Nt1310 Unit 1 Assignment 1 Free Loop Analysis

760 Words4 Pages

Many times we get some situations where a specific block of codes need to be executed repeatedly. When we are calculating factorial of a number say 7, the multiplication continues to happen with the next smaller number (6,5,4..) and the cycle continues until it reaches 1. It will be great if we can write a set of common code for multiplication only once and get it executed repeatedly until the desired value (here 1) is reached. This set of common codes which gets repeated are collectively called 'loop' in programming language.
10.a WHILE LOOP:
In this loop architecture 'while' is followed by a condition and if it is satisfied, the execution of the loop starts. After execution of each cycle, compiler will check whether the condition under while …show more content…

WHILE LOOP:
In case of this loop, firstly initialization of the value happens.
Then 'do' is followed by braces {} in which statement and increment are written. Immediately after this, the condition is written after 'while'. So the above program can be written using do.. while like this:
#include (-- removed HTML --) main() { int i; i=1; do { printf("%d",i); i=i+1; }while(i<=5);
}
10.d NESTED LOOP:
Nested loops come handy when we are working with multiple variables having different sets of condition. In this case we can use a loop inside another loop. Consider the following program..
#include (-- removed HTML --) main() { int i, j; for(i=1;i<3;++i) { for(j=1;j<=3;++j) printf("\n%d%d",i, j); }
}
The output will be
11
12
13
21
22
23
For the first three numbers i=1 and 'j' changes three times as defined. Later 'i' changes to 2 and the same values of 'j' are repeated. But condition does not allow i=3 and the program stops.
10.e LOOP CONTROL STATEMENTS:
i. …show more content…

It is written simply with a semicolon at the end of the loop. In the first sample program break statement can be used as: for(i=1;;i++) { if(i==6) break; else printf("%d",i); }
Here the for loop will continue to print numbers 1,2,3.. Whenever it finds i=6, the loop breaks and the program stops. ii. continue:
In case there is a 'continue' statement followed by 'if', then the block of codes written after 'continue' will not execute. Suppose we want to print odd numbers between 1 and 10, the loop will be like this : for (i=1;i<=10;i++) { if(i%2==0) continue; printf("\n%d",i);
}
iii. goto:
'goto' statement can discontinue the program execution in the middle and switch it to another section. As it breaks the normal cycle of execution, it is always discouraged to use in programs unless inevitable. Consider the following loop:
for

More about Nt1310 Unit 1 Assignment 1 Free Loop Analysis