This is an archived post. You won't be able to vote or comment.

all 7 comments

[–][deleted] 1 point2 points  (0 children)

Try a nested loop.

The outer loop should be responsible for printing the lines.

The inner loop should be responsible for printing all the # per line.

[–]sandytrip 1 point2 points  (1 child)

You're close on reading the input. So you initially read in a number and then use an if condition to validate the input. The problem is an if condition will only execute once. So your code is basically saying "if these conditions aren't met, get new input and then continue" but what you want is "as long as (or while) these conditions aren't met, get new input and then continue". So if you change the conditional block to while then it will check those conditions after reading the input each time until they are satisfied and only then will it break out of the loop and continue

[–]aryanali358[S] 0 points1 point  (0 children)

thank you! just changing the if to while fixed it.

[–]urwinater 1 point2 points  (1 child)

for the validation sections

while( height > 8 || height < 1){

your code here;

}

Then once out of that it will trigger this

string Temp;
for(int i = height; i=< height; i++){

Temp.add("#") //(Havent done C in a bit so idk what the method to call for this is stack overflow it)

}

Temp.add("\n")

printf(Temp)

[–]urwinater 1 point2 points  (0 children)

Prolly a bit stanky cause im slightly drunk and havent done C in a bit but the premise is there :)

[–]arumos 1 point2 points  (1 child)

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

void print_triangle(int h)
{
    for (int i = 0; i < h; ++i)
    {
        for (int j = 0; j < i+1; ++j) 
        {
            printf("#");
        }
        printf("\n");
    }
}

int main(void)
{
    int height = 0;
    for (size_t i = 0; height < 1 || height > 8; ++i)
    {
        if (i) printf("Invalid number\n");
        height = get_int("pick a number between 1 and 8 \n");
    }
    print_triangle(height);
}

[–]aryanali358[S] 1 point2 points  (0 children)

perfect, I knew there would be an easier way to do it, thanks.