Computer >> Computer tutorials >  >> Programming >> C programming

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


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 −

#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) −

#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