简体   繁体   中英

Printing number patterns in C

I'm still learning loops and Number pattern in C and I tried to execute this pattern as an exercise:

98765
87654
76543
65432
54321

The maximum number in the pattern is 9 and the minimum number is 1. So I did this:

#include <stdio.h>
   

int main() {
    int i,num,x=9,y,z;

    scanf("%d", &i);

    for (z=1;z <= i; z++) {
        num=x;
        x--;
         
         for (y = 1; y <= i; y++) {
             printf("%d",num);
             num--;
         }
         printf("\n");
    }

    return 0;
     
}

The number of rows and columns should be the same as well. I still need help in figuring out what is lacking.

I didn't understand your question fully, make your question clear first.

But if you want to print a pattern of number with equal num of rows and column and you are taking both the higher number and lower num as input then maybe the code shown here will work for you.

#include <stdio.h>
    
int main() 
{
    int biggerNumber = 9, smallerNumber = 1;
    
    int numberOfRowAndColumn = ((biggerNumber - smallerNumber) / 2) + 1;
    for (int i = 0; i < numberOfRowAndColumn; i++)
    {
        int temporaryVariable = biggerNumber;
        biggerNumber--;

        for (int j = 0; j < numberOfRowAndColumn; j++)
        {
            printf("%d ", temporaryVariable);
            temporaryVariable--;
        }
        printf("\n");
    }
    return 0;
}

And if you want to take numbers of rows and column from user than you can do that too, by just changing one line.

  int numberOfRowAndColumn = ((biggerNumber - smallerNumber) / 2) + 1;

instead of this line just write

 scanf("%d", &numberOfRowAndColumn);

to take input from user.

Hope this helps.

This is the output of code shown above:

9 8 7 6 5 
8 7 6 5 4 
7 6 5 4 3 
6 5 4 3 2 
5 4 3 2 1

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