简体   繁体   中英

Number pattern in C

Can you please help to print the below pattern?

 12345 15
  2345   14
   345     12
    45        9
     5          5

I have tried with this code?

code :

for(i=1;i<=5;i++)
    {
        for(j=1;j<=i;j++)
        {
            printf(" ");
        }
        for(j=i;j<=5;j++)
        {
            printf("%i",j);
            sum = sum + j;
        }

        printf(" ");
        printf("%i",sum);
        printf("\n");
    }

output:

 12345 15
  2345 29
   345 41
    45 50
     5 55

Please help to print the above pattern? Thanks in advance

Well the problem is clear: 29 = 15 + 14.

This means you are forgetting to clear sum when you begin a new line.

for(i=1;i<=5;i++)
    {
    sum = 0; // reset sum when we begin a new line

First problem with logic is that -

for(i=1;i<=5;i++)
{
        sum=0;   // set sum to 0 in every iteration 

You don't do this , therefore you don't get right sum and you get this -

  15+14=29
  29+12=41  // similar for all cases

Solution -

#include <stdio.h>
#include <string.h>

int main(void)
{
     int i,j,sum=0,k=1;
     char p[10];                  // using a char array to print spaces between number ans sun
     memset(p,'\0',sizeof p);     // initialize array elements to null
    for(i=1;i<=5;i++)
     {  
        sum =0;                     // set sum to 0 in every iteration 
        for(j=1;j<=i;j++)
        {
            printf(" ");
        }

       for(j=i;j<=5;j++)
       {
           printf("%i",j);   
           sum = sum + j;
       }
       if(k<10){                    // this is to print space between number and sum 
          memset(p,' ',k);         // include number of space in string 
          printf("%s",p);          // print the string with space
       }
        k=k+2;                         // increment k by 2
        printf("%i",sum);
        printf("\n");
    }
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM