I revamped one of my programs which used numerous "else if" statements.
Code:
#include <iostream>
using namespace std;
int addition ( int a, int b );
int substraction ( int c, int d );
int multiplication ( int e, int f);
int division ( int g, int h);
int end ( int k );
int main()
{
int i;
int j = 1;//Might be modified at the end.
int k;
while ( j == 1 ) {//Is used to restart the program once a task is complete.
cout<<"Please choose what type of mathematical operation you want to do:\n 1.Addition\n 2.Substraction\n 3.Multiplication\n 4.Division (might be imprecise)\n Any other number.End program\n";
cin>> i;
cin.ignore();
switch ( i ) {
case 1://This is the addition function.
int a;
int b;
cout<<"Enter the two numbers to be added, pressing enter after each one: ";
cin>> a >> b;
cin.ignore();
cout<<"The result is: "<< addition ( a, b )<<"\n";
break;
case 2://This is the substraction function.
int c;
int d;
cout<<"Enter the two numbers to be substracted, pressing enter after each one: ";
cin>> c >> d;
cin.ignore();
cout<<"The result is: "<< substraction ( c, d )<<"\n";
break;
case 3://This is the multiplication section.
int e;
int f;
cout<<"Enter the two numbers to be multiplicated, pressing enter after each one: ";
cin>> e >> f;
cin.ignore();
cout<<"The result is: "<< multiplication ( e, f )<<"\n";
break;
case 4: {//This is the division section.
int g;
int h;
cout<<"Enter the two numbers to be divided, pressing enter after each one: ";
cin>> g >> h;
cin.ignore();
cout<<"The result is: "<< division ( g, h )<<"\n";
break;
default:
end ( k );
break;
}
}
}
cout<<"Thank you for using this program.\n Press enter to quit.";
cin.get();
}
int addition ( int a, int b )
{
return a + b;
}
int substraction ( int c, int d )
{
return c - d;
}
int multiplication ( int e, int f )
{
return e * f;
}
int division ( int g, int h )
{
return g / h;
}
int end ( int k )
{//This variable is used to modify j.
int j;
cout<<"Would you like to do another operation? Press 1 if you would like to, otherwise press any number: ";
cin>> k;
cin.ignore();
if ( k == 1) {
j = 1;//Translation -> "The loop will start again."
}
else {
j++;//Translation -> "The program will end."
}
}
Normally the user should press a number like 2 when asked if he wants to do another operation, and that would send a little message telling him to press enter to close the program. But it simply restarts the loop. What is wrong with this code?
By the way, sorry for posting the whole code, but I have no clue where the problem is.