Introduction to Loops
Imagine you have a task to print numbers from 1 to 100. How would you do it?
You could write:
std::cout << 1 << std::endl;
std::cout << 2 << std::endl;
std::cout << 3 << std::endl;
// ... and so on up to 100
That would be very tedious and inefficient. Fortunately, there's a better way - loops!
A loop allows us to repeat the same action multiple times without having to write the same code over and over again.
Look at this example:
// Prints numbers 1 to 5
for(int i = 1; i <= 5; i++) {
std::cout << i << std::endl;
}
With just 3 lines of code, we achieved the same thing that would otherwise require 5 lines!
And what's more - we can use the same loop to print any number of numbers, just by changing one value:
// Prints numbers 1 to 100
for(int i = 1; i <= 100; i++) {
std::cout << i << std::endl;
}
Loops are like an automatic machine - you tell it what to do and how many times to repeat it, and it does it for you. Without loops, programming would be very difficult and time-consuming.
In the following lessons, we'll learn different types of loops and how to use them. You'll see that with their help, you can solve even complex tasks simply and elegantly!
Instructions
When you're ready, move on to the next lesson!
Start programming for free
1/9