Write a C program to visualize a pattern using nested for loop.

Function Main
    Declare Integer i
    Declare Integer j
    Declare Integer n
    Output "Enter a number: "
    Input n
    For i = 1 to n
        For j = 1 to i
            Output "* "
        End
        Output ""
    End
End

#include <stdio.h>
int main() 
{
    int i;
    int j;
    int n;
    printf("Enter a number:");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) 
    {
        for (j = 1; j <= i; j++) 
        {
            printf("* "); // output * pattern or number or symbol
        }
        printf("\n");
    }
    return 0;
}
Enter a number: 5

*
* *
* * *
* * * *
* * * * *

More Examples:

// This code show us left, right, inverted pattern, if we can organized it.
#include <stdio.h>
 
int main()
{
  int i, j, k, rows;
 
  printf("Enter the no. of rows: ");
  scanf("%d", &rows);
 
  for (i = 1; i <= rows; i++)
  {
    // for (j = i; j <= rows; j++) 
      // printf("  ");
 
    for (k = 1; k <= i; k++)
      printf(" %d", k);
 
    printf("\n");
  }
 
  return 0;
}

Enter a number: 5 

 1                                                                              
 1 2                                                                            
 1 2 3                                                                          
 1 2 3 4                                                                        
 1 2 3 4 5                                                                                

#include <stdio.h>  
  
int main()  
{  
      
    int i, j, rows, k = 0;  
    printf (" Enter a number of rows:");  
    scanf ("%d", &rows);   
      
    for ( i =1; i <= rows; i++)  
    {  
        for ( j = 1; j <= rows - i; j++)  
        {  
            printf ("  ");   
        }  
        // use for loop where k is less than equal to (2 * i -1)  
        for ( k = 1; k <= ( 2 * i - 1); k++)  
        {  
            printf ("%d ", k); }
        printf ("\n");  
    }  
    
} 

 Enter a number of rows:5                                                       
        1                                                                       
      1 2 3                                                                     
    1 2 3 4 5                                                                   
  1 2 3 4 5 6 7                                                                 
1 2 3 4 5 6 7 8 9                                                                                

Though it is a Java hollow pattern, it helps us very much in printing hollow patterns in C Program.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.