Looping Construct or Statements. Introduction of looping constructs In looping,a sequence of...
-
Upload
cody-rogers -
Category
Documents
-
view
241 -
download
0
Transcript of Looping Construct or Statements. Introduction of looping constructs In looping,a sequence of...
Looping Construct or Statements
Introduction of looping constructs
In looping ,a sequence of statements are executed until some condition for termination of the loop are satisfied.A program loop consists of two segments, (i) Body of the loop (ii) Control statementA looping construct includes the following four terms: (i) Initialization (ii) Condition (iii) Updation (iv) Body
Looping construct
C supports three types of looping constructs:while loopdo….while loopfor loop
While loop
The while loop is an entry-controlled loop construct.The general syntax of while loop is:
initialization;
while (test-condition)
{
body of the loop;
updation;
}
An example of while loop
/*To print numbers from 1-10*/
#include<stdio.h>
void main()
{
int i=1; /*initialization*/
while( i<=10) /*condition- check */
{
printf( “%d \n”, i ); /*body of while loop*/
i++; /*updation*/
}
}
Do….While loop
The do…while loop is an exit controlled loop construct.The general syntax of while loop is:
initialization;
do
{
body of the loop;
}
while (test-condition) ;
For loop
The for loop is an entry-controlled loop.The general syntax of the for statement is:
The initialization is an assignment statement that sets the loop control variable, before entering the loop.The conditional test is a relational expression, which determines, when the loop will exit.
for( initialization; condition; updation)
{
body of the loop;
}
Nested loop
Nesting of loop means one loop defined within another loop.The nesting may continue upto 15 levels or more i.e. compiler dependent.For exam.:
for( i=1; i<10; ++i)
{
--------------
for( j=1;j!=5;++j)
{
------------
}
}
An example of nested loop
/*To print “*” in triangle form */
#include<stdio.h>
void main()
{ int i, j;
for( i=0; i<5; i++)
{
for( j=0; j<i; j++)
{
printf( “*” );
}
printf( “*” );
printf( “\n”);
}
}
Thanks…..