Looping and Branching (Day-3)
Looping and Branching (Day-3)
Technology
Types of loop:
Syntax:
while(condition)
statement;
Here:
• Statement is a single statement.
• The condition may be any expression, and true is any non-zero value.
• The loop iterates while the condition is true. When the condition becomes
false, program control passes to the line immediately following the loop.
The While Loop
Like with the if statement, you can group multiple statements within the same
while loop by surrounding a group of statements with curly braces.
Syntax:
while(condition) {
statement(s);
}
while(condition) :
statement(s);
endwhile;
The While Loop
Example:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
The For Loop
The for loop allows a statement(s) to be executed a specified number of times.
Syntax:
for ( initialization ; condition; increment /decrement) {
statement(s);
}
The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to put a
statement here, as long as a semicolon appears.
The For Loop
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After
the condition becomes false, the for loop terminates.
The For Loop
Example:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Assignments
1) GENERATE TABLE
generate any number table in for loop with its start and ending point
1+2+3+4+5+6+7+8+9+10=55
3) Factorial Of A Number
The factorial of a positive integer n is equal to 1*2*3*...n.
1) 1 4 9 16 25
2) 1 3 6 10 15 21
3) 50 40 30 20 10
4) 6 12 20 30 42
Assignments
5) Make even odd series b/w 1 to 100 by using single loop
Output should be like:
1 3 5 7 9 11….99
2 4 6 8 10 12…..100