
C Programming For Loop
Table of Contents
A loop is used in programming to repeat a specific block. In this chapter you will learn to create for loops in C programming.
A loop is used in programming to repeat a block of code until a conditional becomes false. There are three types of loops in C programming:
1. For Loops
2. While Loops
3. Do while Loops
C for loop
Syntax of C for loops
for (initializationStatement; testExpression; updateStatement)
{
// This code will execute
}
How does the for loop work?
- The initialization Statement executes only once.
- Then the test Expression is executed. If it is false(0), the for loop terminates. But if the value of test expression is True then for the loop code block is executed and the value of update Statement is updated.
- This continues until test Expression returns false.
For loop is usually used if the number of iterations is known beforedhand.
When the value of test Expression is True and when it is False is discussed in the Relational and Logical Operators page.
Example 1: for loop
// C program to output integer from 1 to 5
#include
#include
int main()
{
int i;
clrscr();
for(i=1; i<=5; i++)
{
printf("\n%d",i);
}
getch();
}

Output
1
2
3
4
5
Example 2: for loop
// Program to find sum of first n normal numbers.
// Positive integers 1,2,3...n are known as natural numbers.
#include
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
//For loop ends if value of num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter a positive integer: 10
Sum = 55
Explanation of the above example:
- The value entered by the user is stored in the num variable. Assume, user enters 10.
- The count variable is assigned an initial value of 1 and the test expression is evaluated. Since count <= num (1 is less than 10) is true, the code block of the loop will execute and the value of sum will be equal to 1.
- Then the update Statement ++count will be executed and the value of count will be equal to 2. Test Expression will be executed again. Since 2 is less than 10, the value of test Expression will be true and the loop code block will execute. The value of sum will be equal to 3.
- This process continues until the value of count reaches 11 and the value of sum is delermined.
- Test Expression will return false when the value of count is equal to 11 is not less than of equal to 10. So here the loop will terminate and the following code will be executed. sum will be printed at the end of the loop.
An impressive share! I have just forwarded this onto a coworker who has
been doing a little research on this. And he in fact bought me lunch simply because I found it
for him… lol. So allow me to reword this…. Thank YOU for the meal!!
But yeah, thanx for spending the time to discuss this subject here on your web site.