> Online tutorial : looping statements in c
Showing posts with label looping statements in c. Show all posts
Showing posts with label looping statements in c. Show all posts

for loop in c


The For Loop




The "for" loop is really nothing new, it is simply a new way of describe the "while" loop. Load
and edit the file named forloop.c for an example of a program with a "for" loop.

Syntax:  for ( [<expr1>] ; [<expr2>] ; [<expr3>] )  <statement>

<statement> is executed repeatedly UNTIL the value of <expr2> is 0.

BEFORE the first iteration, <expr1> is evaluated. This is usually used to
initialize variables for the loop.

AFTER each iteration of the loop, <expr3> is evaluated. This is usually used
to increment a loop counter.
 

Program

main( )
{
int index;
for(index = 0;index < 6;index = index + 1)
printf("The value of the index is %d\n",index);
}

when the above program first  check condition and then loop will continued until the condition will false 
when above program the 
index=0  is initialization of the loop
index<6  is condition of loop
index+1  is the increment of loop
when above program executed until the index value can be 7 and more the program o/p
is
 
output:  The value of the index is 0
The value of the index is 1
The value of the index is 2
The value of the index is 3
The value of the index is 4
The value of the index is 5

while loop in c

The While Loop



The C programming language has several structures for looping and conditional branching. We will cover them all in this chapter and we will begin with the while loop. The while loop continues to loop while some condition is true. When the condition becomes false, the looping is discontinued. It therefore does just what it says it does, the name of the loop being very descriptive.


 Syntax:  while ( <expression> ) <statement>

<statement> is executed repeatedly as long as the value of <expression>
remains non-zero.

The test takes place before each execution of the <statement>.

 Example:

main( )
{
int count;
count = 0;
while (count < 6)
{
printf("The value of count is %d\n",count);
count = count + 1;
}
}
when this program will first check condition and then come to loop.if the loop is incorrect the it should be terminated otherwise go to loop will executed untill the condition occur .
when program executed untill the count<6 and then loop is terminated
output
The value of count is 0
The value of count is  1
The value of count is  2
The value of count is  3
The value of count is  4
The value of count is 5