Need help with a C++ assignment? Get affordable C++ homework help.

Loops code snippet

Summary

Source code for C/C++ program, showing three types of loops in C/C++.

Source code

C++: loops.cpp

#include <iostream>

 

using namespace std;

 

int main() {

      int i;

 

      // there are three types of loops in C++

      //

      // (1) for loop:

      // for (variable initialization; condition; variable update) {

      //     do smth...

      // }

      cout << "Counting 1 to 10: ";

      for (i = 1; i <= 10; i++) {

            cout << i << " ";

      }

      cout << endl;

 

      // (2) while loop:

      // while (condition) {

      //     do smth...

      // }

      // it continues, while condition is true

      cout << "Counting 1 to 10: ";

      i = 1;

      while (i <= 10) {

            cout << i << " ";

            i++;

      }

      cout << endl;

 

      // (3) do-while loop:

      // do {

      //     do smth...

      // } while (condition);

      // it continues, while condition is true

      // Note. do-while loop executes its body

      // at least one time        

      cout << "Counting 1 to 10: ";

      i = 1;

      do {

            cout << i << " ";

            i++;

      } while (i <= 10);

      cout << endl;

 

      return 0;

}

 

C: loops.c

#include "stdio.h"

 

int main() {

      int i;

 

      /*

            all those three types of loops

            are also available in C

      */

 

      /*

            (1) for loop:

      */

      printf("Counting 1 to 10: ");

      for (i = 1; i <= 10; i++) {

            printf("%d ", i);

      }

      printf("\n");

 

      /*

            (2) while loop:

      */

      printf("Counting 1 to 10: ");

      i = 1;

      while (i <= 10) {

            printf("%d ", i);

            i++;

      }

      printf("\n");

 

      /*

            (3) do-while loop:

      */

      printf("Counting 1 to 10: ");

      i = 1;

      do {

            printf("%d ", i);

            i++;

      } while (i <= 10);

      printf("\n");

 

      return 0;

}

 

Sample run

C/C++

Counting 1 to 10: 1 2 3 4 5 6 7 8 9 10
Counting 1 to 10: 1 2 3 4 5 6 7 8 9 10
Counting 1 to 10: 1 2 3 4 5 6 7 8 9 10