How to print the numbers in different formats using C program?

CServer Side ProgrammingProgramming

Problem

What is the logic in C language to print the numbers in different formats like pyramid, right angle triangle?

Solution

To print the numbers or symbols in different model we can take the help of for loop in the code.

Example1

Following is the C program to print pyramid −

 Live Demo

#include<stdio.h>
int main(){
   int n;
   printf("Enter number of lines: ");
   scanf("%d", &n);
   printf("\n");
   // loop for line number of lines
   for(int i = 1; i <= n; i++){
      // loop to print leading spaces in each line
      for(int space = 0; space <= n - i; space++){
         printf(" ");
      }
      // loop to print *
      for(int j = 1; j <= i * 2 - 1; j++){
         printf(" * ");
      }
      printf("\n");
   }
   return 0;
}

Output

Enter number of lines: 8
                  *
                * * *
              * * * * *
            * * * * * * *
          * * * * * * * * *
         * * * * * * * * * * *
        * * * * * * * * * * * * *
      * * * * * * * * * * * * * * *

Example 2

Following is a program to display numbers in the form of right angled triangle (pattern) −

 Live Demo

#include <stdio.h>
void main(){
   int i,j,rows;
   printf("Input number of rows : ");
   scanf("%d",&rows);
   for(i=1;i<=rows;i++){
      for(j=1;j<=i;j++)
         printf("%d",j);
      printf("\n");
   }
}

Output

Input number of rows : 10
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
raja
Published on 08-Mar-2021 13:16:19
Advertisements