I have been trying to solve the problem set 1 in CS50, language C. I've come to this point, but I got stuck in here. I want my code to ask for a new input while(n>=9 || n<=0) but it ends there, instead of asking for a new input. I have already tried return n; but it didn't work at all. You can see the console and the results.
When I asked my code to return 0; I thought it would be asking for a new input. But as it can be seen, it ended up. What I want is it to ask for a new input, instead of stop working.
This is my first time and post in here, so I hope I have described my problem good enough.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Number: ");
while(n>=9 || n<=0)
{
return 0;
}
int i;
for(i=0;i<n;i )
{
int a;
for(a=n-1;a>i;a--)
{
printf(" ");
}
int y;
for(y=0;y<=i;y )
{
printf("#");
}
printf("\n");
}
}
CodePudding user response:
As others suggested, return 0
is an action that terminates the current function you are in, and returns said value. I don't know what is your level of knowledge of C, I'll try to put less informations possible here. Just know that if you write return inside your main(){}
block, the program will ignore all the following code and end the program if that return is executed.
Now as to how to get your desired result
I want my code to ask for a new input while(n>=9 || n<=0)
it seems you just need to put your statement inside the while loop:
int n=0;
while (n>=9 || n<=0)
{
n = get_int("Number: ");
}
in this case you need to declare int n
outside the loop since you will use it later. (I initialized it as 0 to let the program enter the loop).
If you have studied and are able to use "do while" loops, it may be your best choice here. If your program needs to ask for input, and keep asking until input is no longer in the range (n >= 9 || n <= 0)
you might want to try
int n=0;
do
{
n = get_int("Number: ");
} while (n>=9 || n<=0)
This will execute the block of code once for sure, then checks if the while condition is met and loops again. The outcome is you get the statement executed once and then until the condition is no longer met.
CodePudding user response:
Put your code inside while loop to ask it whenever (n >= 9 || n <= 0)
because right now whenever n is greater or equal 9 or less or equal 0 your your program will end because return 0
ends actual function and in your case it is main()
function