C++ ELSE PROBLEM

#include <stdio.h>
// Begin Main
main ()
{
// Define variables
int num1 = 0;
int num2 = 0;
int result = 0;
int choice = 0;

// Print the menu
printf("Calculator v2.0\n");
printf("------------\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Devide\n");
printf("5. Remainder\n");
printf("----------------\n");
printf("Choice:");

scanf("%d" , &choice);

if ((choice >= 1) && (choice <= 5))
// Print : Enter num1
printf("Enter the first number:");
// Read num1
scanf("%d" , &num1);
// Print : Enter num2
printf("Enter the second number:");
//Read num2
scanf("%d", &num2);

if (choice == 1)
{
// Add num1 and num2
result = num1 + num2;
}
else if (choice == 2)
{
// Subtract num1 and num2
result = num1 - num2;
}
else if (choice == 3)
{
// Multiply num1 and num2
result = num1 * num2;
}
else if (choice == 4 )
{
// Devide num1 and num2
result = num1 / num2;
}
else if (choice == 5)
{
// Remainder num1 and num2
result = num1 %num2;
}

//Print : The result
printf("The result is %d\n", result);


else <---- here the programs says to me else without previous if, idk why thought
{
//Print Error message
printf("Please enter a number from 1 to 5!\n");
}

return 0;


}// End Main






You have
1
2
3
4
5
6
7
8
9
10
11
if (thing)
{
    // ...
}

print_something();

else
{
    // ...
}

The "else" must immediately follow the end of the "if" block.
1
2
3
4
5
6
7
8
if (thing)
{
    // ...
}
else
{
    // ...
}

(Print either inside the if/else-blocks or after all them)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
if (choice == 5)
{
  // statements
} // end of if's block

printf( "Independent statement" );

else // What is before this else? An if?
{
  // statements
}

There is no if before the else. There is printf before the else.


PS. Do not shout.
Registered users can post here. Sign in or register to post.