For loops
COS1511 - Introduction To Programming I · Learning C++
For Loops
A for loop is a control structure that allows you to repeat a block of code a specific number of times. It is very useful when you know in advance how many times you want to execute a statement or a block of statements. A for loop consists of three main parts: initialization, condition, and increment or decrement.
Structure of a For Loop
The basic structure of a for loop in C++ is as follows:
for (initialization; condition; increment) {
// code to be executed
}1. **Initialization**: This part is executed only once at the beginning of the loop. It is typically used to declare and initialize a loop control variable.
2. **Condition**: Before each iteration, the condition is evaluated. If it is true, the loop body is executed. If it is false, the loop terminates.
3. **Increment/Decrement**: This part is executed after each iteration of the loop body. It is used to update the loop control variable.
Example of a For Loop
Let’s look at a simple example that prints the numbers from 1 to 5:
#include
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}
return 0;
}In this example:
- The initialization part is
int i = 1, which declares an integer variableiand sets it to 1. - The condition is
i <= 5, which means the loop will continue as long asiis less than or equal to 5. - The increment part is
i++, which increases the value ofiby 1 after each iteration.
Remember: In C++, the ++ operator increments the variable by 1. You can also use -- to decrement a variable by 1.
Common Mistakes with For Loops
Students often make mistakes with for loops. Here are some common errors:
Watch out: Ensure that the loop control variable is updated correctly. If you forget to increment or decrement it, you may create an infinite loop.
Nesting For Loops
You can also nest for loops, which means placing one for loop inside another. This is useful when you want to work with multidimensional data structures, such as arrays.
Example of Nested For Loops
Here is an example that prints a multiplication table for numbers 1 to 3:
#include
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << i * j << " ";
}
cout << endl;
}
return 0;
}In this example:
- The outer loop iterates over the variable
i, which goes from 1 to 3. - The inner loop iterates over the variable
j, which also goes from 1 to 3. - For each value of
i, the inner loop executes completely, printing the products ofiandj.
Using For Loops with Arrays
For loops are often used to iterate over arrays. This allows you to access each element of the array easily.
Example of a For Loop with an Array
Consider the following example, which calculates the sum of elements in an array:
#include
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "Sum: " << sum << endl;
return 0;
}In this example:
- The array
numberscontains five integers. - The for loop iterates from 0 to 4 (5 iterations), accessing each element of the array using the index
i. - The sum of the elements is calculated and printed.
Break and Continue Statements
Inside a for loop, you can use the break statement to exit the loop prematurely or the continue statement to skip the current iteration and proceed to the next one.
Using Break
Here is an example that uses the break statement:
#include
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
return 0;
}In this example, the loop will stop executing when i equals 5, so it will only print numbers 1 to 4.
Using Continue
Here is an example that uses the continue statement:
#include
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
cout << i << endl;
}
return 0;
}This example prints only odd numbers from 1 to 10. When i is even, the continue statement skips the rest of the loop body and proceeds to the next iteration.
Summary
- A for loop is used to repeat a block of code a specific number of times.
- The structure of a for loop includes initialization, condition, and increment/decrement.
- You can nest for loops to work with multidimensional data.
- For loops are commonly used with arrays to access and manipulate elements.
- The break statement exits the loop, while the continue statement skips the current iteration.
Check your understanding
- What are the three main parts of a for loop?
- Write a for loop that prints all even numbers from 2 to 20.
- Explain the difference between the break and continue statements.
- How would you use a for loop to sum the elements of an array?