3.Loops In c++

In programming, loops are control structures that lets you run a particular block of code repeatedly. It’s very helpful if you wish to carry out the same operation repeatedly without writing duplicate code.

In this chapter we will be going to learn below Loop structures

  1. For Loop
  2. While Loop
  3. do While Loop

For Loop

Use the for loop when you are certain of the number of times you want to loop through a block of code.

loops

Initialization is where we declare the value of a variable and it will be executed only at beginning of the execution of loop .

You define a Condition that determines when the loop should be terminated.

Increment/Decrement :- After every iteration, you specify how the counter variable is modified.

For Loop example for printing numbers from 1 to 5

#include<iostream>

using namespace std;

int main() {

  for (int i = 1; i <= 5; i++) {
    cout << i << " ";
  }
  return 0;
}

Output :- 1 2 3 4 5

Nested For Loops

When we use the loop inside another loop it is nothing but nested loop. It is used for solving complex problem which requires multiple iterations like in Matrix operations.

#include<iostream>
using namespace std;

int main() {

  for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
      cout << i << "/" << j<<" ";
    }
    cout << endl;
  }

  return 0;

}

Output :-
1/1 1/2 1/3 1/4 1/5
2/1 2/2 2/3 2/4 2/5
3/1 3/2 3/3 3/4 3/5
4/1 4/2 4/3 4/4 4/5
5/1 5/2 5/3 5/4 5/5

While Loop

  • A block of code can be run by a loop as long as a predetermined condition is met.
  • Loops are useful because they reduce errors, save time, and improve readability of code.
  • If the initial condition is not true, a “while” loop will not run the code at all.

The while loop iterates over a section of code for as long as a given condition holds true.

While Loop example for printing numbers from 1 to 5

#include<iostream>
using namespace std;

int main() {

  int i = 1;   //Initialisation
  while (i <= 5)   //Condition
 {
    cout << i << " ";
    i++;   // Increment or Decrement
  }
  return 0;
}

Output :- 1 2 3 4 5

Do While Loop

One variation of the while loop is the do/while loop. This loop will run the code block once, then check to see if the condition is true before repeating the loop indefinitely.

The code block is executed prior to the condition being tested, so even if the condition is false, the loop will always run at least once.

#include<iostream>

using namespace std;

int main() {

  int i = 1;
  do {
    cout << i << " ";
    i++;
  }
  while (i <= 5);
  return 0;
}

Output :- 1 2 3 4 5


Zebronics War Gaming Keyboard and Mouse Combo,Gold Plated USB, Braided Cable,Multicolour LEDs/Gaming Mouse with breathing LEDs and 3200 DPI



Leave a Comment