How to use while loops In C Language
Approach 1: The while loops check the condition until the condition is false. If the condition is true then enter into the loop and execute the statements.
Example:
C
// C program to print character pattern by // converting number into character #include <stdio.h> 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 printf ( "%c " , character); j++; } printf ( "\n" ); // incrementing character value so that it // will print the next character character++; j = 0; i++; } return 0; } |
Output
A B B C C C D D D D E E E E E
Time complexity: O(R*R)
Here R is given no of rows.
Auxiliary space : O(1)
As constant extra space is used.
Approach 2: Printing pattern by converting given number into character using while loop
Example:
C
// C program to print character pattern by // converting number in to character #include <stdio.h> 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 printf ( "%c " , character); j++; } printf ( "\n" ); // incrementing number value so that it // will print the next character number++; j = 0; i++; } return 0; } |
Output
A B B C C C D D D D E E E E E
Time complexity: O(R*R) where R is given no of rows
Auxiliary space : O(1)
C Program To Print Character Pyramid Pattern
Here, we will build a C Program To Print Character Pyramid Pattern using 2 approaches i.e.
- Using for loop
- Using while loop
Input:
rows = 5
Output:
A B B C C C D D D D E E E E E
Contact Us