Programming Noob Programming Noob - 1 month ago 8
C Question

Program doesn't end after if else statement

So guys, I'm very new to programming and the C language, just learning it for fun :) So anyone got any idea why the program doesn't just end after "The voltage is too big" or "Not a valid input"?

printf("Enter the voltage of power supply:");
scanf("%d",&Volt);
if (Volt > 10)
printf("The voltage is too big");
else if (0 > Volt)
printf("Not a valid input");
else
Current=Volt/Resst;

Answer

If an if/else statement block contains more than 1 command (like your last else branch), you need to use curly braces:

if (Volt > 10)
    printf("The voltage is too big");
else if (0 > Volt)
    printf("Not a valid input");
else {
    Current=Volt/Rest;
    printf("...");
}

To avoid errors like this, it is considered best practice to always use curly braces, even if there is only one command in a block:

if (Volt > 10) {
    printf("The voltage is too big");
}
else if (0 > Volt) {
    printf("Not a valid input");
}
else {
    Current=Volt/Rest;
    printf("...");
}
Comments