C For Loop
C For Loop
1. for loop
2. while loop
3. do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we
will learn about while and do...while loop.
for Loop
The syntax of the for loop is:
This process goes on until the test expression is false. When the test
expression is false, the loop terminates.
Output
1 2 3 4 5 6 7 8 9 10
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11
is true, the body of for loop is executed. This will print
the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value
of i will be 2. Again, the test expression is evaluated to true,
and the body of for loop is executed. This will print 2(value of i)
on the screen.
4. Again, the update statement ++i is executed and the test
expression i < 11 is evaluated. This process goes on
until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop
terminates.
// Program to calculate the sum of first n natural numbers// Positive integers 1,2,3...n are
known as natural numbers
#include <stdio.h>int main(){
int num, count, sum = 0;
return 0;
}
Run Code
Output
The value entered by the user is stored in the variable num. Suppose,
the user entered 10.
The count is initialized to 1 and the test expression is evaluated.
Since the test expression count<=num (1 less than or equal to 10) is
true, the body of for loop is executed and the value of sum will
equal to 1.
We will learn about while loop and do...while loop in the next
tutorial.