How to use while loops In C++

Input:

rows=5

Output:  

A 
B C 
D E F 
G H I J 
K L M N O 

Approach 1: 

The while loops check the condition until the condition is false. If the condition is true then it enters into the loop and executes the statements. 

C++




// C++ program to print the continuous
// character pattern using while loop
#include <iostream>
using namespace std;
 
int main()
{
 
    int i = 1, j = 0;
   
    // input entering number of rows
    int rows = 5;
   
    // given a character
    char character = 'A';
   
   
    // while loops checks the conditions until the
    // condition is false if condition is true then enters
    // in to the loop and executes the statements
    while (i <= rows) {
       
        while (j <= i - 1) {
           
            // printing character to get the required
            // pattern
            cout << character << " ";
          
            j++;
           
            // incrementing character value so that it
            // will print the next character
            character++;
        }
        cout << "\n";
 
        j = 0;
        i++;
    }
    return 0;
}


Output

A 
B C 
D E F 
G H I J 
K L M N O 

Approach 2:

Printing pattern by converting given number into character using while loop. 

C++




// C++ program to print continuous
// character pattern by converting
// number in to character
#include <iostream>
using namespace std;
 
int main()
{
 
    int i = 1, j = 0;
   
    // input entering number of rows
    int rows = 5;
   
    // given a number
    int number = 65;
   
    // while loops checks the conditions until the
    // condition is false if condition is true then enters
    // in to the loop and executes the statements
    while (i <= rows) {
        while (j <= i - 1) {
           
            // converting number in to character
            char character = char(number);
           
            // printing character to get the required
            // pattern
            cout << character << " ";
           
            j++;
           
            // incrementing number value so that it
            // will print the next character
            number++;
        }
        cout << "\n";
 
        j = 0;
        i++;
    }
    return 0;
}


Output

A 
B C 
D E F 
G H I J 
K L M N O 

Time complexity: O(n2) where n is given no of rows

Space complexity: O(1)



C++ Program To Print Continuous Character Pattern

Here we will build a C++ Program To Print Continuous Character patterns using 2 different methods i.e: 

  1. Using for loops
  2. Using while loops

Input:

rows = 5

Output:  

A 
B C 
D E F 
G H I J 
K L M N O 

Similar Reads

1. Using for loop

Approach 1:...

Using while loops:

...

Contact Us