C++ language

adplus-dvertising
Loops in C++
Previous Home Next

A Loop is a block of code for repeating a statement one and more times Until Some Way of ending the loop Occur. Repetition is depend on the loop condition. when you need to execute a block of code or repeat a statement continuously Until a known Or Unknown Condition , for known number of repetition we use of for loop and for unknown we use of while or do while loop.

Typically in a for loop, repeated as long as an expression is true (a while loop) or repeated until an expression becomes false in a do while loop.

Type of loops In C++:-

  1. For Loop
  2. While Loop
  3. Do while loop
  4. Nested loop
  1. 1. For loop:- For loop in c++ is used to repeat statement continuously for a specific number of time.
  2. Examples-
    #include<iostream>
    using namespace std;
    int main()
    int i;
    for (i = 0; i < 20; i++)
    {
    cout << "Hello" << "\n";
    cout << "There" << "\n";
    }
    return 0;
    }
    
  3. While Loop- In While loop repeat statement until a certain condition is met. That Means we use While if you don’t know how many times a loop must run.
  4. Examples:-
    #include<iostream>
    using namespace std;
    {
    int i=0;
    while (i < 4)
     {
    cout << i++;
    
      }
    }
    
  5. Do- while Loop:-Do while is basically similar to while loop. The do-while loop is usually preferred over a while-loop when the statement needs to be executed at least once.
  6. Example:-
    #include <iostream>
    using namespace std;
    int main()
    {
    int x;
    x = 2;
    do {
    cout<<"Hello, world!\n";
    } while ( x != 2 );
    cin.get();
    }
    
  7. Nested Loop:- Nested loop means Place loop inside another loop it is called nesting of loops, So use of one loop in another loop is nested loop.
  8. Example:-
    #include <stdio.h>
    #include <conio.h>
    void main ()
    {
    int= i, j;
    clrscr ();
    for (j=1; j<=4; j++)    
    {
    for (i=1; i<=5; i++)   // Nesting of loop
    {
    	printf (*);
    }
    printf ("/n");
    }
    }
    
Output
*****

*****

*****

*****
Previous Home Next