Loops in C and C++

CC++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to understand loops in C and C++.

Looping in programming is used when we have to execute a given block code again and again. It takes in the approach for writing the same code line again and again and promoted DRY code practice.

Example

For loop

 Live Demo

#include <iostream>
using namespace std;
int main(){
   for (int i = 1; i <= 10; i++){
      cout << "Hello World\n";
   }
   return 0;
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

While loop

 Live Demo

#include <iostream>
using namespace std;
int main(){
   int i = 1;
   while (i < 6){
      cout << "Hello World\n";
      i++;
   }
   return 0;
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World
raja
Published on 01-Apr-2020 10:05:30
Advertisements