Você está na página 1de 3

Loop Control Statements: Loop: A loop is defined as a block of statements which are repeatedly executed for certain number

of times. 1) The for loop: The for loop statement comprises of 3 actions. The 3 actions are initialize expression, Test Condition expression and updation expression The expressions are separated by Semi-Colons (;). The loop variable should be assigned with a starting and final value. Each time the updated value is checked by the loop itself. Increment / Decrement is the numerical value added or subtracted to the variable in each round of the loop. Syntax: for(initialize expression; test condition; updation ) { Statement-1; Statement-2; } (i) (ii) The initialization sets a loop to an initial value. This statement is executed only once. The test condition is a relational expression that determines the number of iterations desired or it determines when to exit from the loop. The for loop continues to execute as long as conditional test is satisfied. When the condition becomes false the control of the program exits from the body of for loop and executes next statements after the body of the loop. (iii) The updation(increment or decrement operations) decides how to make changes in the loop. The body of the loop may contain either a single statement or multiple statements.

Print the first five numbers starting from one together with their squares. #include<stdio.h> #include<conio.h>

main( ) { int i; clrscr( ) ; for(i = 1; i <=5; i++) printf(\n Number: %d its Square: %d, i, i*i); getch( ); } Program to display from 1 to 15 using for loop and i=i+1. # include<stdio.h> Output : # include<conio.h> main( ) { The Numbers of 1 to 15 are: 1 2 3 4 int i; clrscr( ); 5 6 7 8 9 10 11 12 13 14 15 printf(\n The Numbers of 1 to 15 are:); for(i=1; i < =15; i=i+1) printf(\n%d , i); getch( ); } Nested for loop: We can also use loop within loops. i.e. one for statement within another for statement is allowed in C. (or C allows multiple for loops in the nested forms). In nested for loops one or more for statements are included in the body of the loop. * ANSI C allows up to 15 levels of nesting. Some compilers permit even more. Two loops can be nested as follows. Syntax: for( initialize ; test condition ; updation) /* outer loop */ { for(initialize ; test condition ; updation) /* inner loop */ { Body of loop; } } The outer loop controls the rows while the inner loop controls the columns. ----------------------------------------for(row =1; row<=rowmax ; ++ row) { Outer loop for (column =1;column<=colmax; ++ column) { Inner loop y = row * column; printf(%4d, y); } printf( \n); } -----------------------------------Program to perform subtraction of 2 loop variables. Use nested for loops.

# include<stdio.h> # include<conio.h> void main( ) { int a, b, sub; clrscr( ); for (a=3; a > =1; a - - ) { for(b=1;b<=2;b++) { sub = a b; printf(a=%d b=%d a-b = %d \n, a,b, sub); } } getch( ); }

Você também pode gostar