Reputation: 13
This is my code. I failed to use the break keyword after the printf function in order to break out of the loop. When I enter a negative number or zero, it doesn't prompt me again to re-enter.
#include <stdio.h>
#include <cs50.h>
int get_positive_int(void);
int main (void)
{
get_positive_int();
}
int get_positive_int(void)
{
int i;
i = get_int("Integer: ");
while (true)
{
if (i<1)
{
return i;
}
else
{
printf("%i", i);
}
}
}
Upvotes: 0
Views: 938
Reputation: 15042
The algorithm in the function get_positive_int()
is wrong:
You need to place i = get_int("Integer: ");
inside of the while
loop.
Your if
condition:
if (i < 1)
is wrong as that would return i
if i
is a negative integer or 0
. If you want to return i
when i
is a positive integer or 0
you should use if(i >= 0)
.
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
after the call to maintain the occurrence of a read error. But if you want to only return INT_MAX
then, you do not need to do so and can omit it since this would fit to the conditional statement ``if(i >= 0)` and its body.
The code is then:
int get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
else if (i >= 0)
{
return i;
}
printf("%i", i);
}
}
Side note: If you don´t want to count 0
as positive integer, you need to have i >= 1
as the condition of the if
statement.
As you said in the comments you only want to continue if i
is a positive integer and exit if i
is a negative characters or 0
:
void get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i < 1)
{
return;
}
printf("%i\n", i);
}
}
Note that in this case, the return type of get_positive_int
shall be void
instead of int
and it should omit to return i
as it is not necessary to return any value from the function.
Upvotes: 2