Monday, April 7, 2014

LOOP STATEMENT FOR

The for loop in C is simply a shorthand way of expression a while statement.For example,suppose you have the following code in C:

x=1;
while(x<=10)
{
printf("%d
",x);

x++;
}
you convert this into for loop as follows:
for(x=1;x<=10;x++)
{
printf("%d
",x);

}
               
 Note that the while lop contains an initialization step(x=1),a test step (x<=10),and an increment step(x++).The for loop lets you put all three parts into one line.In the for loop also the condition is tested at the entry level.The body of the above for loop executes 10 times.Here, the control variable is initialized first and then it is executed.If the test condition is true, the body of the loop s executed;otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.After the body of the loop has been executed,the control is transferred to the for statement,where the control variable is updated and then retested.The loop continues till the condition remains true.
The syntax of the for loop is as follows:
for(initialization; condition; updation)
{

body of the loop;

}

  A for loop can also be nested.The problem of printing 1 once and 2 twice can be written using nested for loops as follows:

#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=10;i++)
{
for(j=0;j<=i;j++)      ------------->INNER LOOP
printf("%d",i);

printf("
");

}
}  

The inner for loop has only one statement and the outer for loop has two statements.If the body of the loop contains only one statement,there is no need for curly braces to enclose the body of the loop.
The problem which is solved using while loop can also be solved using a for loop.It is a good programming practice to use for loop where the number of times of repetition is known precisely.The for loop is a definite repetition loop where we know in advance exactly how many times the loop will be executed.The while loop is preferred when the number of repetitions is not known before the loop begins executing.

eg:
#include<stdio.h>
void main()
{
char ch;
int count=0;
ch=getchar();
while(ch!=
)            /*condition*/

{
count++;
ch=getchar();
}
printf("The number of characters entered:%d
",count);

}


In the above example the number of times the loop will be executed is not known until the user presses the enter key in the keyboard.Once the variable ch obtains its value as the new line character (Enter key pressed),the test condition fails and the control is transferred to the next statement immediately after the body of the while loop.For this problem,the while loop is preferred since the number of characters to be entered by the user is not known precisely.In the above program, the function getchar() is used to read a character at a time from the keyboard and it is a pre-defined function.
  

Related Posts by Categories

0 comments:

Post a Comment