0
0
C++programming~5 mins

For loop in C++

Choose your learning style9 modes available
Introduction

A for loop helps you repeat a set of instructions many times without writing them again and again.

When you want to count from 1 to 10 and do something each time.
When you need to process each item in a list one by one.
When you want to repeat a task a fixed number of times, like printing a message 5 times.
When you want to sum numbers from 1 to 100 easily.
When you want to run a block of code with a changing number each time.
Syntax
C++
for (initialization; condition; update) {
    // code to repeat
}

initialization runs once at the start.

condition is checked before each loop; if false, loop stops.

update runs after each loop to change the loop variable.

Examples
This loop runs 5 times, with i from 0 to 4.
C++
for (int i = 0; i < 5; i++) {
    // repeat 5 times
}
This loop counts down from 10 to 1.
C++
for (int count = 10; count > 0; count--) {
    // count down from 10 to 1
}
This loop increases i by 2 each time, skipping even numbers.
C++
for (int i = 1; i <= 10; i += 2) {
    // i goes 1, 3, 5, 7, 9
}
Sample Program

This program prints "Hello" followed by numbers 1 to 5, each on a new line.

C++
#include <iostream>

int main() {
    for (int i = 1; i <= 5; i++) {
        std::cout << "Hello " << i << "\n";
    }
    return 0;
}
OutputSuccess
Important Notes

Make sure the loop condition eventually becomes false, or the loop will run forever.

You can use any variable name for the loop counter, not just i.

The update step can add, subtract, or do other changes to the loop variable.

Summary

For loops repeat code a set number of times.

They have three parts: start, condition, and update.

Use for loops when you know how many times to repeat something.