C++ for loop
Created By: chatGPT
For loops in C++ are used to iterate over a range of values. The general syntax includes initialization, a condition, and an increment or decrement operation. Here's how you can structure a for loop:
for (initialization; condition; increment) {
// code to be executed in each iteration
}
Let's look at a simple example that prints numbers from 1 to 5. In this example, we will initialize a variable, check if it is less than or equal to 5, and then increment it in each iteration.
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
std::cout << i << std::endl;
}
return 0;
}
In this code:
- We include the iostream library to use
std::cout
. - The for loop begins with
int i = 1
, meaning we start counting from 1. - The condition
i <= 5
keeps the loop running untili
exceeds 5. - The statement
i++
incrementsi
by 1 with each iteration. - Inside the loop, we output the value of
i
. When you run this program, you will see the numbers 1 through 5 printed on separate lines.
You can also use a for loop with arrays. Here's an example where we iterate through an array of integers and compute their sum.
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
int length = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < length; i++) {
sum += arr[i];
}
std::cout << "Sum: " << sum << std::endl;
return 0;
}
In this example:
- We declare an array
arr
containing five integers. - We initialize a variable
sum
to 0 to hold the total. - We determine the length of the array using
sizeof(arr) / sizeof(arr[0])
. - The for loop iterates from 0 to
length - 1
, adding each element ofarr
tosum
. - Finally, the total sum is printed out.