I am a programming beginner. I made a program that converts integer inputs into roman numerals. It's a nonterminating program, and it can only terminate if the user inputs 5 errors.
int main(){
int i;
for(i = 1; i > 0; i++)
{
int num;
printf("\n\nEnter a positive integer: ");
scanf("%d", &num);
while(num == 0 || num < 0 || num > 3999 || i == 5)
{
if(i == 5)
{
int ch;
printf("\n\nYou have reached 5 retries. Do you wish to continue?\n");
printf("Press 1 to continue.\n");
printf("Press 2 to terminate the program.\n");
scanf("%d", &ch);
if(ch == 1)
{
break;
}
else if(ch == 2)
{
return 0;
}
else
{
printf("Invalid input. The program will now terminate.");
return 0;
}
}
else if(num == 0)
{
printf("Error: Zero is Nulla");
break;
}
else if(num < 0)
{
printf("Error: Input cannot be negative");
break;
}
else if(num > 3999)
{
printf("Error: Input cannot be greater than 3999");
break;
}
else
{
printf("Error: Input should be a positive integer");
break;
}
}
while(num > 0 && num <4000)
{
if (num >= 1000) // 1000 - m
{
printf("m");
num -= 1000;
}
else if (num >= 900) // 900 - cm
{
printf("cm");
num -= 900;
}
else if (num >= 500) // 500 - d
{
printf("d");
num -= 500;
}
else if (num >= 400) // 400 - cd
{
printf("cd");
num -= 400;
}
else if (num >= 100) // 100 - c
{
printf("c");
num -= 100;
}
else if (num >= 90) // 90 - xc
{
printf("xc");
num -= 90;
}
else if (num >= 50) // 50 - l
{
printf("l");
num -= 50;
}
else if (num >= 40) // 40 - xl
{
printf("xl");
num -= 40;
}
else if (num >= 10) // 10 - x
{
printf("x");
num -= 10;
}
else if (num >= 9) // 9 - ix
{
printf("ix");
num -= 9;
}
else if (num >= 5) // 5 - v
{
printf("v");
num -= 5;
}
else if (num >= 4) // 4 - iv
{
printf("iv");
num -= 4;
}
else if (num >= 1) // 1 - i
{
printf("i");
num -= 1;
}
}
}
return 0;}
It stops after 5 user inputs, but I don't want that. I want it to stop after specifically 5 errors. Any help would be appreciated. Thank you
i
is incremented in every iteration of the loop, that is why it stops after 5 iterations (5 user inputs). So:
for
loop, you should have a while(1)
loop.int i;
, make an int error_counter = 0;
before the main loop.if(i == 5)
, you can write ++error_counter; if (error_counter == 5) { ... }
.while(num == 0 || num < 0 || num > 3999 || i == 5)
and while(num > 0 && num <4000)
, you should just use if (num <= 0 || num > 3999) {...} else {...}