Website For Developers

For Loop in C++



Loops are the iterative structure that means they repeats a statement or a set of statements for a several times.
There are three types of loops in C++:
1) for loop
2) while loop
3) do while loop


for loop

• for loop in C++ is used when the number of iteration is fixed.
• for loop is also called counter controlled loop.
• The body of the loop is executed only if the given condition is true.
• When the condition is false, loop is terminated and cursor move to next line.
• It is the most frequently used loop by all the programmers.

Syntax

for (initialization; condition; increment/decrement) {
// for loop body
}

Initialization specifies the starting value or initial value of the loop. It can be one or more starting values in the loop.

Condition specifies the condition of the loop on which the loop will be executed. It is given in relational expression.

Increment/Decrement specifies the change in counter variable after each statement is executed. We can use many variables and separated them with the help of comma.

for loop in C++ example

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  for(int i = 1; i<=5; i++) {
    cout<< "Loop iteration: "<< i<< endl;
  }
  getch();
  return 0;
}

Output

Loop iteration: 1
Loop iteration: 2
Loop iteration: 3
Loop iteration: 4
Loop iteration: 5



Q# Display "Hello World" five times by using for loop in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  for(int i = 0; i<5; i++) {
    cout<< "Hello World"<< endl;
  }
  getch();
  return 0;
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World


Q# C++ Program to display multiplication table of 2

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  for(int i = 1; i<=10; i++) {
    cout<< "2 * 1 = "<< i*2<< endl;
  }
  getch();
  return 0;
}

Output

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20


Q# C++ Program to check whether the number is prime or not

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int i, number, flag = 0;
  cout<< "Enter Number: ";
  cin>> number;
  for(int i = 2; i<=number/2; i++) {
    if (number%i == 0) {
      cout<< number<< " is not Prime Number"<< endl;
      flag = 1;
      break;
    }
  }
  if (flag == 0) {
    cout<< number<< " is a Prime Number"<< endl;
  }
  getch();
  return 0;
}

Output

Enter Number: 19
19 is a Prime Number