The loop Control Structure Flashcards
3 Methods to loop:
- For statement
- While Statment
- do-while
while statement:
initialise loop counter (index variable);
while (Condition [to test loop counter or any Exp] )
{ body of while;
loop counter increment / decrement;
}
loop counter can be float as well, u can incre or decree them by a float value.
Default scope of while
1 statement right after it.
Output? int i = 1; while ( i<= 32767 ) { printf("hi"); i++ }
Indefinite.
when is 32767 and reaches increment, it wants to become 32768 which falls out of int range so instead it becomes -32768 and it satisfies the while condition, this will keep on happening.
OutPut? int i = 1; while ( i<= 10 ); { printf("hi"); i++ }
Indefinite int i = 1; while ( i<= 10 ) ; { printf("hi"); i++ } No output but control keeps rotating as i is not incremented.
Compound Assignment Operator:
+= , -=, *=, /=, %=.
While(i++ < 10)
post increment operator. Performs i < 10 and then i becomes i + 1, for the body of loop for tht cycle and next check.
++i
First ‘i’ gets incremented and then its Exp is evaluated.
The for loop:
for ( initialise counter ; test counter ; increment counter)
{
excute statements;
}
Initialization, testing & increment incorporated in for statement.
those three can be any expressions, remember the flow of control.
Working of For:
set counter value, test condition execute the body and then increment.
Default Scope of For:
Immediately next statement after it.
is this Valid:
for ( ;i++ >10; ){
}
Note semicolons are necessary.
here the comparison is done then the value is incremented and then body of the loop is executed.
Nesting for loops.
For each value of outer loop, inner loop will take all values.
Multiple Initialisations in the for loop.
for ( i = 1 , j = 0 ; j < 2 ; i++, j++ ) {statement;}
test expression can be only one but u can use logical operators to link more conditions.
hence ; are used in for statement so , allow us to use multiple initialisation n increment.
The odd Loop
When we unaware how many times to loop
use of do-while.