Loops are used in programming to repeat a specific block until some end condition is met. There are three loops in C programming:
- for loop
- while loop
- do...while loop
for Loop
The syntax of for loop is:
for (initializationStatement; testExpression; updateStatement) { // codes }
How for loop works?
The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for
loop is executed and the update expression is updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
To learn more on test expression (when test expression is evaluated to nonzero (true) and 0 (false)), check out relational and logical operators.
for loop Flowchart
Example: for loop
// 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; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when n is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); return 0; }