Jordan
Jordan

Reputation: 15

Nested For Loop Problems in C

Im trying to understand and figure out how to make a pyramid going left to right.

I have the computer asking for the height, it is only 1-8

Im trying to make that pyryamid look something like this depending on the height

I have a squared being made. Heres the code

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int getHeight;

    do
    {
        //asks height
        getHeight = get_int("Height: ");
    }
    //If the height is greater then 8 then ask for the Height again
    while(getHeight > 8);


    //
    for(int row = 0; row < getHeight; row++)
    {
        for(int colums = 0; colums < getHeight; colums++)
        {
            printf("#");
        }
        printf("\n");
    }


}**

Upvotes: 0

Views: 36

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

It looks like your inner loop is wrong. It iterates up to getHeight but should only iterate up to (and including) row:

for(int row = 0; row < getHeight; row++)
{
    for(int colums = 0; colums <= row; colums++)
    { //                       ^^^^^^

Each iteration of the outer loop will increase row. The inner loop will make one more iteration over colums every time row increases.

Output if the user enters 8:

#            // row 0, columns 0-0
##           // row 1, columns 0-1
###          // row 2, columns 0-2
####         // row 3, columns 0-3
#####        // row 4, columns 0-4
######       // row 5, columns 0-5
#######      // row 6, columns 0-6
########     // row 7, columns 0-7

Upvotes: 2

Related Questions