Home > Back-end >  Number pattern printing in c
Number pattern printing in c

Time:01-25

I'm newbie to programming. So as an exercise, I'm trying to print a number pattern like below.

0
10
210
3210
43210

I tried the code below.

 #include<stdio.h>
 void main()
 {
    int i ,j,n=5;
    for(i=0;i<=n;i  )
    {
        for(j=0;j>=i;j--)
        {
           printf("%d",i);
        }
        printf("\n");
     }
}

The output am getting after running the code above is:-

10
10
10
10
10

Am just stuck. Not able to solve this question. Can anyone help me please?

CodePudding user response:

There are two loops. The first loop control the line number with range as [0,N). The second loop control the character sequences per line. Each line print out [Line_Number 1] digital numbers. The sequence has a pattern as [Line_Number - Column_Number].

The example code:

#include <stdio.h>
void main() {
  int i, j, n = 5;
  for (i = 0; i < n; i  ) {
    for (j = 0; j < (i   1); j  ) {
      printf("%d", (i - j));
    }
    printf("\n");
  }
}

Build and run:

gcc test.c
./a.out

The output:

0
10
210
3210
43210

CodePudding user response:

You have done a simple mistake for the inner loop-j. Make sure that your outer loop i-loop refers to the number of lines and your printing as printf("%d",i); defines how many lines you want.

#include<stdio.h> 
void main() 
{ 
    int i ,j,n=5; 
    for(i=0;i<n;i  ) 
    {
        for(j=i;j>=0;j--) 
        {
            printf("%d",j);
        }
        printf("\n");
    }
}

Then the output will be:

0
10
210
3210
43210

CodePudding user response:

 #include<stdio.h>
 void main()
 { 
 int i ,j,n=5,t[n];
   for(i=0;i<n;i  )
     {
        t[i]=i;
        for(j=i;j>=0;j--)
           {
              printf("%d",t[j]);                  
           } 
        printf("\n");
     }

try this...

  •  Tags:  
  • Related