Thursday, March 9, 2017

For Loop and Varients

In Javascript when we need to do repetitive tasks then we can use a for loop. For example if we need to print the numbers from 1 to 10, without the for loop it would may be look like this:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
console.log("1");
console.log("2");
console.log("3");
console.log("4");
console.log("5");
console.log("6");
console.log("7");
console.log("8");
console.log("9");
console.log("10");

or if we use a variable then it might look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var i = 1;
console.log(i++);
console.log(i++);
console.log(i++);
console.log(i++);
console.log(i++);
console.log(i++);
console.log(i++);
console.log(i++);
console.log(i++);
console.log(i++);

Let us see how it looks if use a for loop:


1
2
3
for (var i = 1; i <= 10; i++) {
  console.log(i)
}

So as you see, using a for loop is very compact and efficient. The for loop has basically 3 parts in it like this:

(this code will not work; it is just for demostration purposes)


1
2
3
for (initialization; condition; step) {
// something to do.
}

Initialization: for loop takes help from a variable to decide how many repetitions it needs to do at the time of running. So, in the initialization we declare a variable where the loop starts. Mostly in simple examples it is declared like a simple variable:

var i = 0;

Condition: The end of the loop is decided by the middle part of the for loop which can be any condition. The loop runs until the condition is true and when the condition is false it just stops and anything what is written after the for loop start getting executing. A simple condition to run a loop for 10 times can be the maximum value of the variable i, so we can write it like "run until i is smaller than 10"; In code we would write it like this:


1
2
3
for ( var i = 0; i < 10; step) {
// body
}

Step: The step part of the for loop decides how the value of the variable i increases or decreases. Since want the loop to start at i = 0; and stop when i exceeds 9 (i < 10) this means we need to put the step for increasing the value of i; which can be written like this:

i = i   + 1;
OR
i +=1;
OR
i++

There are multiple ways to increment a variable by 1; the most common short form used is i++;

so now the full loop becomes this:

1
2
3
for ( var i = 0; i < 10; i++) {
// body
}

this kind of loop is going to make 10 repetitions where the value of i is going to be from 0 to 9;
if we want the value of i from 1 to 10; then we can write it like this:


1
2
3
for ( var i = 1; i <= 10; i++) {
// body
}

Notice that now the condition has changed to less than or equal to (<=), we could have also done it by making it less than 11 (i < 11) so this is up to us how we want it to be defined.

Here is a graphical flow of the execution of for loop:

















To explain, the execution of for loop starts with initializing the variable i and then the condition is checked. If the condition is "true" then the body of the loop is executed and only after then the value of i is incremented.
The point here is that it is possible that the condition is false even before the first execution of the body of the loop in which case the loop just exits after the first time the condition is checked after the initialization of the variable.

Conditions: 
Based on the conditions which can be put in the for loop there can be many variants of the for loop because any expression which can result in true or false can be used as a condition in the for loop.

For example consider this for loop:


1
2
3
4
var nums = [1, 2, 3, 4, 0, 5, 6];
for (var i = 0; nums[i]; i++) {
  console.log(nums[i]);
}

this loop prints the following on the console:
1
2
3
4

The reason this loop prints the above on the console is because when the value of i becomes 4, in the condition part of the for loop the value is evaluated as nums[4] which is actually 0 and since in javascript 0 is equal to false the loop terminates and comes out.

This trick can be applied many times in various situations.

Here are some points to be noticed about for loops:


  • The for loop generally has initialization, condition and increment parts; 
  • The initialization and increment parts can be empty also like this: 

  • 1
    2
    3
    for (; true;) {
    }
    // The above is an infinite loop
    

  • Any condition which can be taken as true or false in javascript can be used as the condition in for loop. 

Here are some practice questions: 
  • Given an array like this: [2, 4, 6, 7, 8, 6, 5, 4], print all the numbers on the console. 
  • Given an array like this: [1, 2, 3, 4, 6, 8, 5, 4, 3, 7], print all numbers which are greater than 5.
  • Given an array like this: [1, 2, 3, 4, 6, 8, 5, 4, 3, 7], print the two numbers for which the sum is a give number X. assume X is 9 and test your program. the output should be 1, 8 (Hint: use nested loops)
  • Given an array like this: [1, 2, 3, 4, 6, 8, 5, 4, 3, 7] print the sum of all the numbers;
  • Given an array like this: [1, 2, 3, 4, 6, 8, 5, 4, 3, 7] print the only odd numbers;
  • Give an array like this: [1, 2, 3, 4, 6, 8, 5, 4, 3, 7] print the sum of odd numbers. 
  • Given a number X; print if the number is prime. 


Saturday, February 25, 2017

Switch Case Default - Answers

Javascript - Switch Case Default - Answers

Question #1: Given a number of pizza types like margherita(5.5 euro), napoli (7.5 euro), bruschetta (8.5 euro), funghi (7.5 euro), a customer orders a type of pizza. Write a switch-case-default to print the price of the pizza.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var pizzaType = "bruschetta";

switch (pizzaType) {
  case "magherita":
    console.log(5.5);
    break;
  case "napoli":
    console.log(7.5);
    break;
  case "bruschetta":
    console.log(8.5);
    break;
  case "funghi":
    console.log(7.5)
    break;
}

Question#2: Combine the cases in the question above for pizza napoli and funghi as they have the same price.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var pizzaType = "funghi";

switch (pizzaType) {
  case "magherita":
    console.log(5.5);
    break;
  case "napoli":  // combined cases
  case "funghi":  // combined cases
    console.log(7.5);
    break;
  case "bruschetta":
    console.log(8.5);
    break;
  default:
    break;
}

Qeustion #3: Write a fall through switch-case-default which prints "Bravo!!" for grades in class "A+", "A" and "B+". And for grades "B", "C" and "D" it should print "Good luck for next time".


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var grades = "C";

switch (grades) {
  case "A+":
  case "A":
  case "B+":
    console.log("Bravo!!");
    break;
  case "B":
  case "C":
  case "D":
    console.log("Good luck for next time.");
    break;
  default:
    break;
}

Question#4: Define two values with variables "color" and "variant". Where the variable "color" represents the main color among BLUE, GREEN and RED, and "variant" represents a shade of those colors. For example PINK is a shade of RED. Write a nested switch-case-default to print the shade based on the main color defined by the variable "color".


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var color = "RED"
var variant = "PINK"

switch (color) {
  case 'RED':
    switch (variant) {
      case 'PINK':
        console.log('PINK');
        break;
      case 'MAGENTA':
        console.log('MAGENTA');
        break;
      default:
        break;
    }
    break;
  case 'BLUE':
    switch (variant) {
      case 'SKYBLUE':
        console.log('SKYBLUE');
        break;
      case 'NAVYBLUE':
        console.log('NAVYBLUE');
        break;
      default:
        break;
    }
    break;
  case 'GREEN':
    switch (variant) {
      case 'AQUA':
        console.log('AQUA');
        break;
      case 'TURQUES':
        console.log('TURQUES');
        break;
      default:
        break;
    }
    break;
    deafult:
      break;
}

Friday, February 24, 2017

Switch Case Default

Switch case default is used when we have one single variable which can take different values and each different value requires a different set of operations. Think about it like this:

If you have a number which represents a day of Week, and for each value of this number you need to print the name of the day then you can use switch case default. For example if you have a variable like this:

var numOfDay = 3;

then you are supposed to print which day is the third day of the week. So in this case if you start the Week from Monday then the third day of the week would be Wednesday. If the value of numOfDay is 5, then the Day name would be Saturday.

Now let us write an if else block first to understand the problem:


1
2
3
4
5
6
7
8
9
var numOfDay = 3;

if (numOfDay == 1) console.log("Monday");
if (numOfDay == 2) console.log("Tuesday");
if (numOfDay == 3) console.log("Wednesday");
if (numOfDay == 4) console.log("Thursday");
if (numOfDay == 5) console.log("Friday");
if (numOfDay == 6) console.log("Saturday");
if (numOfDay == 7) console.log("Sunday");

Another way of writing this same piece of code can be using if-else:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
var numOfDay = 4;

if (numOfDay == 1) {
  console.log("Monday");
} else if (numOfDay == 2) {
  console.log("Tuesday");
} else if (numOfDay == 3) {
  console.log("Wednesday");
} else if (numOfDay == 4) {
  console.log("Thursday");
} else if (numOfDay == 5) {
  console.log("Friday");
} else if (numOfDay == 6) {
  console.log("Saturday");
} else if (numOfDay == 7) {
  console.log("Sunday");
}

and now let us write an equivalent switch case default for printing the name of days.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var numOfDay = 3;

switch (numOfDay) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break;
  default:
    console.log("This is not a correct day of week")
}

So in this switch-case-default what you can see is that, we have put a switch on the variable itself,
and then for each possible value of the variable we have a case. So in the case when the value of the variable is 3, the log is printed for the day name "Wednesday".

One thing to notice here is that after every case, there is a break statement which is just before the next case. The reason for this is that the cases in a switch-case-default block fall through downwards. Which means if we don't have a break; after the line number 11: console.log("Wednesday") then Javascript will go through the next case which is case 4 and print the log ("Thursday"). In the case we also don't have any break after case 4 then the case 5 will be executed and this will result in printing all the names which exist after Wednesday until the last log of "This is not a correct day of week".

Try this program:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var numOfDay = 3;

switch (numOfDay) {
  case 1:
    console.log("Monday");
  case 2:
    console.log("Tuesday");
  case 3:
    console.log("Wednesday");
  case 4:
    console.log("Thursday");
  case 5:
    console.log("Friday");
  case 6:
    console.log("Saturday");
  case 7:
    console.log("Sunday");
  default:
    console.log("This is not a correct day of week")
}

Because the above program doesn't have any case with break; this is what it prints.

Wednesday
Thursday
Friday
Saturday
Sunday
This is not a correct day of week

Keep in mind that the cases don't have a block for them defined by { and }. Instead the block is defined just by putting a colon (":") after the case value and the block ends when either the next case starts or the default case starts.

Here are some important facts about switch-case-default:
  1. Default case is NOT mandatory, if you don't need it you can leave it out. 
  2. Default case can exist anywhere in the case sequence and it will still work. 
  3. Case values can be anything like numbers or string values. 
  4. Switch-case-default can be nested inside each other. 

Here are some practice questions:

  • Given a number of pizza types like margherita(5.5 euro), napoli (7.5 euro), bruschetta (8.5 euro), funghi (7.5 euro), a customer orders a type of pizza. Write a switch-case-default to print the price of the pizza.
  • Combine the cases in the question above for pizza napoli and funghi as they have the same price. 
  • Write a fall through switch-case-default which prints "Bravo!!" for grades in class "A+", "A" and "B+". And for grades "B", "C" and "D" it should print "Good luck for next time". 
  • Define two values with variables "color" and "variant". Where the variable "color" represents the main color among BLUE, GREEN and RED, and "variant" represents a shade of those colors. For example PINK is a shade of RED. Write a nested switch-case-default to print the shade based on the main color defined by the variable "color". 


Click here for answers




Saturday, February 18, 2017

Arrays - Answers

Einzelunterricht - Javascript Arrays - Answers


  • Make an array of names of your friends and read the name of the third friend (Hint: index starts at 0)

1
2
var myFriends = ["Marry", "Danial", "John", "Lisa", "Thomas"];
console.log(myFriends[2]); // index is 2 because index starts at 0

  • Make an array of 5 different numbers and print the sum of all the number. 

1
2
3
var num = [100, 23, 45, 67, 43];
var sum = num[0] + num[1] + num[2] + num[3] + num[4];
console.log(sum)

  • Make an array of fruit names and print first fruit and last fruit. Now add a new fruit to the array and check if your code works still without changing (Hint: use array length - 1 to access the last element)

1
2
var fruits = ["Apple", "Orange", "Bananna", "Mango"];
console.log(fruits[0], fruits[fruits.length - 1]);

  • Make an array of your subjects in school and print them in reverse order. 

1
2
var subjects = ["Maths", "Science", "English", "Drawing"];
console.log(subjects.reverse());

  • Make an array of your subjects in school and print them in sorted order. 

1
2
var subjects = ["Maths", "Science", "English", "Drawing"];
console.log(subjects.sort());

  • Make an array of your subjects in school and print them in sorted reverse order. 

1
2
var subjects = ["Maths", "Science", "English", "Drawing"];
console.log(subjects.sort().reverse());
  • Make an array and print the product of it's length and 5, if length is less than 3. If length is more than 3, then print the product of length and 10. 

1
2
3
4
5
6
var grades = ["A", "A+", "B", "B+", "C", "C+"];
if (grades.length < 3) {
  console.log(grades.length * 5);
} else {
  console.log(grades.length * 10);
}

Arrays

Array: Storing many values in one place

When we have some information like the name of the person, age or address of a person, we can store this information like this: 

var name = "Thomas";
var age = "34";
var address = "Hauptstrasse 40, Berlin";

So for each piece of information we can create a variable and store the information in it. 

But the problem happens if we have a lot of same type of information for example names of 10 students in a class. Then creating a variable for each name is not a good way to store the names, because we would have to create 10 variables. 

In Javascript there is a type of variable which can store a lot of similar type of information such as names. For example this: 

var names = ["Julia", "Stephan", "Danial", "Jacob", "Mathilda", "Lisa", "Phillip", "Tao Li", "Marta"];

So this variable "names" is called an Array which can store all the names in it. 

To access the names we can use the index starting from 0. So to read the value "Julia" we can write names[0]. To read the name "Stephan" we can write names[1]. Similarly we can read any name by using it's index value. So for example to read Marta we can use names[8]. 

This array of names in Javascript has some functions which can be used to print the entire list at once like this: 

names.join(' - ');

The above line will print this: 

"Julia - Stephan - Danial - Jacob - Mathilda - Lisa - Phillip - Tao Li - Marta" 

the Symbol we give in the join function is used to put together all the names in the result. so if we write this: 

names.join(' QQQ ');

This will print this: 
"Julia QQQ Stephan QQQ Danial QQQ Jacob QQQ Mathilda QQQ Lisa QQQ Phillip QQQ Tao Li QQQ Marta" 

So this symbol can be anything like character or number or special symbol like # or $;

Size of the array can be check by using the array.length so for example you can write names.length to check the number of names. 

To print the items in an array you can use array.sort() like this: 

names.sort();

this will give you the following; 

["Danial","Jacob","Julia","Lisa","Marta","Mathilda","Phillip","Stephan","Tao Li"]

To print the items of an array in reverse (from last to first) use the array.reverse();

names.reverse();

this will give you the following:

["Marta","Tao Li","Phillip","Lisa","Mathilda","Jacob","Danial","Stephan","Julia"]

Here are some examples to practice: 

  • Make an array of names of your friends and read the name of the third friend (Hint: index starts at 0)
  • Make an array of 5 different numbers and print the sum of all the number. 
  • Make an array of Fruit names and print first fruit and last fruit. Now add a new fruit to the array and check if your code works still without changing (Hint: use array length - 1 to access the last element)
  • Make an array of your subjects in school and print them in reverse order. 
  • Make an array of your subjects in school and print them in sorted order. 
  • Make an array of your subjects in school and print them in sorted reverse order. 
  • Make an array and print the product of it's length and 5, if length is less than 3. If length is more than 3, then print the product of length and 10. 

Conditional Operators (if-else)

Testing a conditions with if and else. 


if (<something to check>) {
// something to do
}

In javascript a condition can be checked using "if" statement:
For example if we have two numbers like this:

var number1 = 7;
var number2 = 5;

and if we need to check if "number1" is greater than "number2" then we can write it in an "if" statement like this:

if (number1 > number2)

Now after checking the numbers if we want to do something if number1 is greater (which means the condition is true) then we write a block for if condition like this:

if (number1 > number2) {
    // something to do here in this block
}

The part in curly braces is called the "if block" which gets executed if the the number1 was really greater than number2. which in our case actually is (7 > 5)

In case the number1 was not bigger, then this condition would not have been successful (true) and in this case either we do nothing or if we want we can do something in the else block like this :

Highlighted in red is the else part of if and else blocks.

if (number1 > number2) {
    // something to do here in this block
else {
    // do something in else block
}

So for example if the numbers were like this:

var number1 = 4;
var number2 = 5;

then then else block would be executed because the condition of if state would be not successful.

Here are some examples to practice:

  • Take two numbers and check if they are equal, if not, print "numbers are not equal". 
  • Take two numbers and print the smaller number. 
  • Take two numbers and print the sum of them if first number is greater, or print the product of them if second number is greater. Print "numbers are equal" if they are equal. 
  • Given a number x, print its ranges in tens. For example if the number is 45, print "Range is 40 to 50". 

Conditional Operators (if-else) Answers

  • Take two numbers and check if they are equal, if not, print "numbers are not equal". 

1
2
3
4
5
6
7
var x = 5;
var y = 7;
if (x === y) {
  console.log("Numbers are equal");
} else {
  console.log("Numbers are not equal");
}

  • Take two numbers and print the smaller number. 

1
2
3
4
5
6
7
var x = 5;
var y = 7;
if (x < y) {
  console.log(x);
} else {
  console.log(y);
}

  • Take two numbers and print the sum of them if first number is greater, or print the product of them if second number is greater. Print "numbers are equal" if they are equal. 

1
2
3
4
5
6
7
8
9
var x = 9;
var y = 7;
if (x > y) {
  console.log(x + y);
} else if (x < y) {
  console.log(x * y);
} else {
  console.log("numbers are equal");
}

  • Given a number x, print its ranges in tens. For example if the number is 45, print "Range is 40 to 50". 

1
2
3
4
var x = 34;
var lower = Math.floor(x / 10) * 10;
var higher = Math.ceil(x / 10) * 10;
console.log("Range is between " + lower + " and " + higher);