For loop
For loop is an alternative to a while loop. The for loop and while loop is used for the same purpose. The only difference between for loop and while loop is the syntax format.
Difference between for loop and while loop
· In a while loop, the initialization of variable, condition applying for the processing of loop (called testing) and, incrementation of the variable, all these three steps are done in a different line.
· In for loop, all the above three steps are done in the same line.
· Example:: look at the red shaded part in both the below programs, you will get the difference.
How does the for loop work?
Let us understand this with the help of an example.
Let us observe the above program
- Step1: The compiler's control will first go to i=0, value will be assigned to the variable i=0.
- Step2: Then the subscript "i" will be compared with 5
if the condition satisfies, the control will go inside the for-loop body.
- Step3: Statements under curly{ } braces are the body of the for loop where the actual operation is performed.
- Step4: after the execution of first iteration of the for-loop "i" will get incremented and, "i" becomes 1. Again the control will go to step2, and the same steps will be repeated till the "i" value becomes 6, and the condition becomes false. When the condition becomes false, the curser will come out of for loop.
Important points
a) We can write i++ as i=i+1 or i+=1.
b) It is mandatory to have two semicolons in the for-statement syntax.#include<stdio.h> int main() { int i; for(i=1;i<=5; ) { printf(“%d “, i); i++; } return 0; } Output: 1 2 3 4 5
Under for statement although the incrementation is done inside the body of for loop, still two semicolons are used.
If we do not write two semi-colons, there will be an error in the program.
#include<stdio.h> int main() { int i; i=1; for(;i<=5; ) { printf(“%d “, i); i++; } return 0;; }
#include<stdio.h> int main() { int i; i=1; for(;i<=5;i++ ) { printf(“%d “, i); } return 0; }
#include<stdio.h> int main() { int i; for(i=1;i<=5;i++); { printf(“%d “, i); } return 0; } Output: 6
Hence the value is now 6. 6 will be printed.
#include<stdio.h> int main() { int i; for(i=0,j=1;i<=5 && j<=5;i++,j++ ) { printf(“i=%d “, i); printf(“j=%d \n“, j); } return 0; } Output: i= 0 j=1 i= 1 j=2 i= 2 j=3
We have also used the && operator.
This states that we can use more than one variable in for loop at the same time.
We can also use logical operators such as (&&)and/or(||).
Nested for loop
As if statements can be nested, similar way For loops can also be nested as well as while loop can be nested.
Example::
#include<stdio.h> int main() { int row, column,i=0; for(row=1;row<=3;row++) { for(column=1;column<=3;column++) { printf(“%d “, i=i+1); } printf(“\n”); } return 0; } output:: 1 2 3 4 5 6 7 8 9 |
See Also:
while loopdo-while loop
break statement
continue statement
Post a Comment
Post a Comment