Sam Waldie
Sam Waldie

Reputation: 25

Values in for loop not changing with incrementation?

So, I have a simple C program which is supposed to output a decreasing number of spaces, and an increasing number of hashmarks in my new line. Here is the code I used to try to accomplished this:

for(x = 0; x < n; x++) {
    for(y = n - 1; y > 0; y--) {
        printf(" ");
    }
    for(int z = 2; z < n + 2; z++) {
        printf("#");
    }

    printf("\n");
}

I expect, based on the code counting down like this, that I should see an output like:

   ##
  ###

However, when I run my code, I get a consistent output of:

   ###
   ###

Any thoughts on where I went wrong in my for loops that might have caused this issue?

Upvotes: 1

Views: 54

Answers (2)

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 8066

Below a cleanest way of doing it. 2 loops:

  • one for the space from 0 to max MINUS row number
  • one for the hashtag from 0 to max MINUS number of space

Code:

int main() {
    int n =10;
    int x, y, z;
    for(x = 0; x < n; x++) {
        for(y = 0; y < n - x - 1; ++y) {
            printf(" ");
        }
        for(z = 0; z < n - y; ++z) {
            printf("#");
        }

        printf("\n");
    }
    return 0;
}

You will get as result:

         #
        ##
       ###
      ####
     #####
    ######
   #######
  ########
 #########
##########  

Upvotes: 1

SergA
SergA

Reputation: 1174

Here:

n = 3;
for(x = 0; x < n; x++) {
    for(y = 0; y < n; y++) {
        printf("%c", (y < (n - x - 1)) ? ' ' : '#');
    }

    printf("\n");
}

Result:

  #
 ##
###

Upvotes: 3

Related Questions