For Loop in C Porgramming
In programming we often need to perform an action over and over, the mechanism that meets this need is "loop".There are three major loop structure in C: the For Loop, the While Loop and the Do-While Loop.
It is often the case in programming that you want to do something a fixed number of times. For Loop is ideally suited for such case.
Program
void main ( )
{
int num;
for(num=0; num<10; num++)
printf("The Number is %d\n", num);
}
Output
The Number is 0
The Number is 1
The Number is 2
The Number is 3
The Number is 4
The Number is 5
The Number is 6
The Number is 7
The Number is 8
The Number is 9
Structure of For Loop
The parentheses following the keyword For contains loop expression. The "initialize expression", the "test expression", and the "increment expression".
Expression Name
num=0 Initialize expression
num<10 Test expression
num++ Increment expression
The Initialize Expression
The initialize expression, num=0, initializes the num bariable. The initialize expression is always executed as soon as the loop in entered. We can start at any number. in this case we started with 0.
The Test Expression
The second expression, num<10, tests the variable each time the loop to see if num is less than 10. To do this , it makes use of the relational operators, in this case "less than" (<). If the test expression is true(num is less than 0), the body of the loop(the printf( ) statement) will be executed.If the expression becomes false (num is 10 or more), the loop will be terminated and control will pas to the statments following the loop.
The Increment Operator
The third expression, num++, increments the variable num each time the loop is executed. to do this , it uses the increment operator(++).The loop variable in a For loop doesn't have to be increased by 1 each time through the loop. it can also be decreased or changed by some other number, using an expression such that:
num=num+3 or num+=3.
The Body of the For Loop
The statements that will be executed each time round the loop. in our example,
printf("The Number is %d\n", num);
No comments:
Post a Comment