The for loop is a control structure in C++ that allows you to execute a block of code repeatedly. It is used when you know the number of times you want to execute a block of code. The for loop is one of the most commonly used loops in C++ programming.
The syntax of the for loop is as follows:
for (initialization; condition; increment/decrement) { // code to be executed }
The initialization statement is executed only once at the beginning of the loop. It is used to initialize the loop counter variable. The condition statement is evaluated at the beginning of each iteration of the loop. If the condition is true, the loop continues to execute. If the condition is false, the loop terminates. The increment/decrement statement is executed at the end of each iteration of the loop. It is used to update the loop counter variable.
Here is an example of a for loop that prints the numbers from 1 to 10:
for (int i = 1; i <= 10; i++) { cout << i << " "; }
In this example, the loop counter variable i is initialized to 1. The loop continues to execute as long as i is less than or equal to 10. The loop counter variable i is incremented by 1 at the end of each iteration of the loop. The output of this code will be:
1 2 3 4 5 6 7 8 9 10
You can also use the for loop to iterate over arrays. Here is an example of a for loop that prints the elements of an array:
int arr[] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) { cout << arr[i] << " "; }
In this example, the loop counter variable i is initialized to 0. The loop continues to execute as long as i is less than 5. The loop counter variable i is incremented by 1 at the end of each iteration of the loop. The output of this code will be:
1 2 3 4 5
The for loop can also be used to iterate over strings. Here is an example of a for loop that prints the characters of a string:
string str = "hello"; for (int i = 0; i < str.length(); i++) { cout << str[i] << " "; }
In this example, the loop counter variable i is initialized to 0. The loop continues to execute as long as i is less than the length of the string. The loop counter variable i is incremented by 1 at the end of each iteration of the loop. The output of this code will be:
h e l l o
The for loop is a powerful tool in C++ programming. It allows you to execute a block of code repeatedly, making it easier to write efficient and effective programs.