Joesef Constable
Joesef Constable

Reputation: 23

Printing a Diamond of Numbers in C

int print_pattern(){
    int x;
    int y;
    int i;
    //for loop for the bottom and the top, 0 is the top and 1 is the bottom while it stops at anything above 2.
    for (i = 0; i<2;i++){
        //loop to the current number
        for (x=1;x<=input;x+=2){
            // top or bottom, this is the top because i had made the top of the diamond the 0
            // therefore this makes my diamond print the top of the function.
            if ( i == 0){
                //starts for the top of the diamond. and counts the spaces.
                for (y=1; y<=input-x; y++){
                    printf(" ");
                }
                //starts the printing of the diamond.
                for (y=1; y<2*x;y++){
                    printf("%d ", y);
                }
            }
            //bottom of the diamond, which is from the 1. For this spot it take in the one from the for loop to
            // this if statement.
            if (i==1){
                //counting spaces again
                for(y = 1; y<=x; y++){
                    printf(" ");
                }
                //printing again but this is the bottom of the pyramid. #really need to comment more
                for(y = 1; y<(input-x)*2;y++){
                    printf("%d ", y);
                }
            }
            //next line starts when printing out the numbers in the output.
            printf("\n");
        }
    }
}

The output is supposed to look like a diamond of the numbers ending with the odd numberat each row. but it is going +2 number past the input and then also not printing the last line. Which should have a single one.

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

The left is what is expected and the right is what I currently am getting when inputting 5.

Upvotes: 1

Views: 2391

Answers (4)

abelenky
abelenky

Reputation: 64672

Here's the short code for such a diamond.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int w = 9;
    int l;

    for(l=0; l < w; ++l)
    {
        printf("%*.*s\n", abs(w/2 - l)+abs((2*l+1)-(2*l+1>w)*2*w), abs((2*l+1)-(2*l+1>w)*2*w), "123456789");
    }

    return 0;
}

Upvotes: 0

Jeet
Jeet

Reputation: 1046

A JAVA STAR PATTERN PROGRAM FOR DIAMOND SHAPE converted to C Program. Code comment will explain the changes and flow.

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

void myprintf(const char* a) {
    static int iCount = 0;
    if (strcmp(a, "\n") == 0) {
        iCount = 0; //if it is new line than reset the iCount
        printf("\n"); //And print new line
    } else            
        printf(" %d", ++iCount); //Print the value
}

void main() {
    int i, j, m;
    int num = 5; //Enter odd number
    for (i = 1; i <= num; i += 2) { //+=2 to skip even row generation
        for (j = num; j >= i; j--)
            printf(" ");
        for (m = 1; m <= i; m++) 
            myprintf(" *"); //display of star converted to number
        myprintf("\n");
    }
    num -= 2; //Skip to generate the middle row twice
    for (i = 1; i <= num; i += 2) { //+=2 to skip even row generation
        printf("  ");
        for (j = 1; j <= i; j++)
            printf(" ");
        for (m = num; m >= i; m--)
            myprintf(" *"); //display of star converted to number
        myprintf("\n");
    }
}

Output:

               1      
             1 2 3    
           1 2 3 4 5    
             1 2 3      
               1     

Upvotes: 1

M Oehm
M Oehm

Reputation: 29116

Peter Schneider has already raised some valid points in his answer.

Think about what you have to do when you print a diamond of height 5:

  • print 1 centered;
  • print 1 2 3 centered;
  • print 1 2 3 4 5 centered;
  • print 1 2 3 centered;
  • print 1 centered.

Sou you could write a function that prints the numbers from 1 to n centered in a line and call it with n = 1, 3, 5, 3, 1. This can be achieved with two independent loops, one incrementing n by 2, the other decrementing it.

Another approach is to recurse: print the lines as you go deeper, incrementing n by 2 until you reach the target width, at which point you don't recurse, but return and print lines with the same parameters again as you go up. This will print each line twice except the middle one.

Here's a recursive solution:

#include <stdlib.h>
#include <stdio.h>

void print_line(int i, int n)
{
    int j;

    for (j = i; j < n; j++) putchar(' ');
    for (j = 0; j < i; j++) printf("%d ", (j + 1) % 10);
    putchar('\n');
}

void print_pattern_r(int i, int n)
{
    print_line(i, n);                   // print top as you go deeper
    if (i < n) {
        print_pattern_r(i + 2, n);      // go deeper
        print_line(i, n);               // print bottom as you return
    }
}

void print_pattern(int n)
{
    if (n % 2 == 0) n++;                // enforce odd number
    print_pattern_r(1, n);              // call recursive corefunction
}

int main(int argc, char **argv)
{
    int n = 0;

    if (argc > 1) n = atoi(argv[1]);    // read height from args, if any
    if (n <= 0) n = 5;                  // default: 5

    print_pattern(n);

    return 0;
}

Upvotes: 3

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16017

Because you already increment x by 2 in the upper part, you don't need to let the print loop run to y<2*x. It should probably just run to x.

The print loop in the lower part suffers from the fact that y<(input-x)*2 should probably be y<input-x*2 (you want to print 2 less each time).

Generally I'd try to name variables in a more speaking way, like printStartPosition, maxNumToPrint, stuff like that. That makes it easier by a surprising margin to understand a program.

As an enhancement, the two code blocks depending on the i value inside the x loop are structurally very similar. One could try to exploit that and collapse both of them into a function which gets a boolean parameter like "ascending", which increments y when true and decrements it when false. Whether that improves or hinders readability would have to be seen.

Also, keep your variables local if possible.

Upvotes: 5

Related Questions