Can anyone please help with this code ? I can't figure out what's wrong here.
Please also tell me what's the meaning of while(1) and exit(0) as I'm a beginner in C . When I run this program it doesn't work properly in replit.com and if I run it in Turbo C , it shows 2 errors i.e., the exit(0);
#include <iostream>
using namespace std;
int main()
{
int a, b, ch;
while(1)
{
cout << "\t\t1. Add\n\t\t2. Subtract\n\t\t3. Multiplication\n\t\t4. Divide\n\t\t5. Mod\n\t\t6. Exit\n\t\tSelect your option : ";
cin >> ch;
if(ch == 6)
exit(0);
if(ch > 6)
cout << "\nInvalid Selection";
exit(0);
}
cout << "\nEnter any number : ";
cin >> a;
cout << "\nEnter another number : ";
cin >> b;
switch(ch)
{
case 1:
cout << "\nThe addition value is " << a b;
break;
case 2:
if(a > b)
cout << "\nThe subtraction value is " << a - b;
else
cout << "\nThe subtraction value is " << b - a;
break;
case 3:
cout << "\nThe multiplication value is " << a * b;
case 4:
if(a > b)
cout << "\nThe division value is " << a / b;
else
cout << "\nThe division value is " << b / a;
break;
case 5:
cout << "The modulus value is " << a % b;
break;
}
return 0;
}
CodePudding user response:
I am not to familiar with Turbo C , but I think if you type
break;
instead of
exit(0)
it might help.
CodePudding user response:
Exit Success is indicated by exit(0) statement which means successful termination of the program, i.e. program has been executed without any error or interrupt. (https://www.geeksforgeeks.org/exit0-vs-exit1-in-c-c-with-examples/)
While(1) means infinitely while loop.
CodePudding user response:
A debugger is a very handy tool to know how a program is behaving for a given input. You should get into a habit of using it often. And if you don't know what a particular function does, you can always look it up at https://en.cppreference.com/w/
website.
exit()
function causes a program to terminate. For more information have a look here:
https://en.cppreference.com/w/c/program/exit
The main problem with your code is the following condition
if(ch > 6)
cout << "\nInvalid Selection";
exit(0);
Probably you expect exit(0)
to be part of the if condition, but it is not. So the effect of this is that your program always exits irrespective of user input.
What you need is the following:
// If user enter anything greater than or equal to 6 exit the program
if(ch >= 6) {
cout << "\nInvalid Selection";
exit(0);
} else {
// else exit the while loop and continue program execution
break;
}