Learning Sections show
For Loop in C
Example
#include<stdio.h> // Include the standard input-output library
int main() {
// For loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
// Print the current value of i
printf("Number: %d\n", i);
}
// End of the main function
return 0;
}
Explanation:
The for
loop in C is a control flow statement that allows code to be executed repeatedly based on a given condition. It consists of three parts: initialization, condition, and increment/decrement.
In this example:
#include<stdio.h>
: Includes the standard input-output library which allows us to use theprintf
function.int main()
: The main function where the program execution begins.for (int i = 1; i <= 5; i++)
: Thefor
loop starts with the initialization of the variablei
to 1. The loop continues to execute as long as the conditioni <= 5
is true. After each iteration, the value ofi
is incremented by 1.printf("Number: %d\n", i);
: Prints the current value ofi
to the console.return 0;
: Ends the main function and returns 0 to the operating system, indicating that the program ended successfully.
In summary, the for
loop is a versatile control flow statement that is commonly used for iterating over a range of values. It is particularly useful when the number of iterations is known beforehand.