C program to print hollow right triangle number pattern

Ex: Write a C program to print hollow right triangle number pattern. How to write a C program to print hollow right triangle number pattern. C program to print hollow right triangle number pattern.

Input from user:
Enter the number:
5

Expected output:
1
12
1  3
1    4
12345





Step by step logic of the given program:

1. Accept input number from user declare variable say no.

2. Run outer for loop from 1 to no:
for(i=1;i<=no;i++)

3. Inside outer for loop run one inner for loop from 1 to i to print it like right triangle:
for(j=1;j<=i;j++)

4. Inside inner for loop, check if condition, to print only first and last number(To print it like hollow triangle):
if(j==1||j==i)
   {
  printf("%d",j); 
   }

5. For last row of the pattern check condition to print all number's:
else if(i==no)
   {
   printf("%d",j);
   }

6. Otherwise print spaces:
else
   {
   printf(" ");
   }

7. For next row print new line(\n): 
printf("\n");





Program:

#include<stdio.h>
void main()
{
 int i,j,no;
 
 printf("Enter the number:\n");
 scanf("%d",&no);
 
 for(i=1;i<=no;i++)
 {
  for(j=1;j<=i;j++)
  {
    if(j==1||j==i)
   {
  printf("%d",j); 
   }
  else if(i==no)
   {
   printf("%d",j);
   }
   else
   {
   printf(" ");
   }
  }
  printf("\n");

 }
}


Above Program's show's the following output:
     
C program to print hollow right triangle number pattern





Another program:

#include<stdio.h>
void main()
{
 int i,j,no;
 
 printf("Enter the number: \n");
 scanf("\n%d",&no);
 
 for(i=1;i<=no;i++)
 {
  for(j=1;j<=i;j++)
  {
    if(i<no&&j==i||i<no&&j==1)
   {
  printf("%d",i);  
   }
  else if(i==no)
   {
   printf("%d",j);
   }
   else
   {
   printf(" ");
   }
  }
  printf("\n");
 }
}

Above program shows the following output:

C program to print hollow right triangle number pattern



No comments:

Post a Comment

If you have any doubts, please discuss here...👇