Loops
When you need to repeat a block of code multiple times, use loops in C++. Loops allow you to automate repetitive tasks efficiently.
Main types of loops in C++:
While Loop
The while loop
loops through a block of code as long as a specified condition is true.
// initialization
while(condition){
// code block
// update
}
- Initializes a variable before the loop
- Checks condition each iteration
- Updates variable inside loop body
// Example
int i = 0;
while(i<5){
cout << i << "\n";
i++;
}
/* Output:
0
1
2
3
4
*/
FAQ
\n
is used for adding new lines while displaying the output.
#include<iostream>
using namespace std;
int main(){
// Read N Numbers and find their sum
int n;
cin >> n;
int i = 1; // Track the number of times loop is going to run
int sum = 0;
while(i<=n){
// cout << i << endl;
int num;
cint >> num;
sum = sum + num;
i = i+1;
}
// Final sum
cout << sum << endl;
}
For Loop
The For loop
is very similar to while loop, it combines the 3 steps that have seen in a single line. Both for loop and While Loop can be be used interchangeably and have some performance.
for(inttialization; condition; update){
// code block
}
- Often used when number of iterations is known
- Easier to read than while loops
for(int step=1; step<=5; step=step+1){
// code block
cout << step << endl;
}
#include<iostream>
using namespace std;
int main(){
// Scope of i is restricted and it became local to the loop
// But if we declared it outside as well
int i;
// For loop 1
for(int i=0; i<=5; i=i+1){
cout << i << endl;
}
// For loop 2
for(; \i<=5; ){
cout << i << endl;
i=i+1;
}
cout << "After the loop:" << i << endl;
}
#include<iostream>
using namespace std;
int main(){
// Read N Numbers and find the sum of numbers which are even
int n;
cin >> nn:
int sum = 0;
// For Loop
for(int i=1; i<=n; i++){
int num;
cin >> num;
// Conditional Statement
if(num%2==0){
sum = sum + num;
}
}
cout << "Sum of even numbers:" << sum << endl;
}
FAQ
Both
while
andfor
loops are Entry Controlled Loops.
Do While Loop
The do while
loop is a exit controlled loop.
This loop will execute the code block at-least once, before checking if the condition is true, then it will repeat the loop as the condition is true
do {
// code block
} while(condition);
int i=0;
do {
cout << i << "\n"
i++;
}
while (i < 5)
#include<iostream>
using namespace std;
int main(){
// Do while loops
int money =5;
do{
cout << "Shopping with money: " << money << endl;
money = money - 1;
}
while(money>0);
return 0;
}
/* Output:
Shopping with money: 5
Shopping with money: 4
Shopping with money: 3
Shopping with money: 2
Shopping with money: 1
*/
#include<iostream>
using namespace std;
int main(){
// Read numers until I don't get negatove number
// 10, 2, 54, 22, -9 Stops
int number;
do{
cin >> number;
cout << number;
}
while(number>=0);
}
Nested Loops
You can place a loop inside another loop to create nested loops
. Useful for iterating through multidimensional data.
for(int i=0; i<3; i++) {
for(int j=0; j<5; j++) {
// inner loop
}
}
Break Statement
Break Statement
is used to explicitly terminate the loop based upon a certain condition.
As soon as the break statement
is encountered from within a loop, the loop stops and control returns from the loop immediately to the first statement after the loop.
while(condition1){
if(condition2){
break;
}
}
#include<iostream>
using namespace std;
int main(){
int cal = 0;
int mom_calls_up = 10;
while(cal<50){
cout << "Running and Burning " << cal << endl;
if(cal == mom_calls_up){
break;
}
cal = cal + 1;
}
cout << "Workout complete " << cal << endl;
return 0;
}
NOTE
The
break
statement allows you to terminate the nearest enclosing loop statement immediately.
Break example - Prime checker:
#include<iostream>
using namespace std;
int main(){
int N;
cin >> N;
// Check if the hiven N is prime or not
int i;
for(i = 2; i < N; i++){
// if N is divisible by i
if(N%i==0){
break; // N is divisible - not prime
}
}
if(i==N){
// Loop ended normally
cout << "Prime" << endl;
}
else{
cout << "Not Prime" << endl;
}
return 0;
}
Here break
exits the loop early if a factor is found. After the loop, we can check if it iterated all the way to N to determine if N is prime.
Continue Statement
It is also a control statement, The continue
statement skips the current iteration of a loop but does not terminate the loop. Execution jumps to the next iteration.
while(....){
if(condition){
continue;
}
// Rest of loop body
}
When continue
is executed, the remaining statements in the loop body are skipped and the next loop iteration begins.
Continue example - Skipping multiples of 7:
#include<iostream>
using namespace std;
int main(){
int i = 0;
while(i<=20){
if(i%7==0){
cout << "Mutiple of 7" << endl;
i = i+1;
continue;
}
cout << i << endl;
i++
}
return 0;
}
Here when i
is a multiple of 7 we print a message and use continue
to skip printing i
.
NOTE
The key difference from
break
is thatcontinue
moves to the next iteration rather than terminating the whole loop.