Home > OS >  CS50 week 1 pset (mario)- the user prompt doesn't seem to be working as the #s dont print altho
CS50 week 1 pset (mario)- the user prompt doesn't seem to be working as the #s dont print altho

Time:09-21

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

int main(void)
{
    int n;
    do
    {
        n=get_int("Size: ");
    }
    while (n < 8);
    for (int i = 0; i < n; i  )
    {
       printf("#");
    }
    printf("\n");
}

I want the code to display the number of #s that the user prompts it to, Given that the number prompted is between 1 and 8. Here, the code reprompts the used when the prompt given is less than 8 and displays when its more. Which is the opposite of what I wish to achieve.

Moreover, the code seems to work the way I want it to when I change (n < 8) to (n > 8). Kindly tell me why this occurs.

CodePudding user response:

You need to understand the effect of the conditional that you use.

Have some fun. Try this

#include <stdio.h>
#include <cs50.h> // this is 'subordinate' to <stdio.h>

int main(void)
{
    do // top of loop
    {
        int n;
        n = get_int("Size (0 to 8): "); // inform user of valid range

        for (int i = 0; n <= 8 && i < n; i  ) // inner loop
        {
           printf("#");
        }
        printf("\n");

    } while (n <= 8); // exit loop when 'n' > 8

    printf("Bye-bye\n");
}

CodePudding user response:

The do-while loop will always guarantee an execution once and based on the condition inside the while statement it will repeat.

Given this, what is your condition?

"n < 8"

You are effectively telling your program to repeat the lines inside of the block {} as long as the user input continues to be less than 8.

Review conditional operators and try it out yourself.

Try using if statements such as

if(x < 8)
{
  printf("x is less than 8\n");
}

if(x > 8)
{
  printf("x is greater than 8\n");
}

And look at what executes and why. Ask yourself what are you trying to achieve and then review your code. Remember the computer only does what we tell it to do. Best of luck!

Hint: if its doing the opposite, than maybe you should do the opposite.

  • Related