Why does my function for multiplication not work?

Hello, I am a new programmer looking to learn c++. I was learning about functions, so I decided to play around with it and make a very VERY basic calculator. If you were to take a look and run it, you would realize that the function for multiplication divides rather than multiply. (Also, I tried adding a "default case to my switch statement, but it always went to the default no matter the input)and sorry I used goto statements...




#include <iostream>

using namespace std;


int add(int X,int Y) // Function for addition
{
int R;
R = X + Y;
return R;
}
int subtract(int X, int Y) //Subtraction
{
int R;
R = X - Y;
return R;
}
int mult(int X,int Y) // Multiplication <---- This is the problem
{
int R;
R = X * Y;
return R;
}
int divide(int X, int Y) // and division
{
int R;
R = X / Y;
return R;
}


int main(){
int num1, num2, operation, Remainder, Z;

start:

cout << "Select a number:" << endl;
cin >> num1;
cout << "Input another number:" << endl;
cin >> num2;
oper:
cout << "Input an operation \n1.) Add \n2.) Subtract \n3.) Multiply ***This function is out of order*** \n4.)Divide" << endl;
cin >> operation;

switch (operation)
{
case 1:
Z = add(num1, num2);
case 2:
Z = subtract(num1, num2);
case 3:
Z = mult(num1, num2);
case 4:
Z = divide(num1, num2);
Remainder = num1 % num2; // For some reason if I use the "default" case, it ALWAYS runs that instead
}

cout << "The result is: " << Z << endl;
if (operation == 4)
cout <<"Remainder: "<< Remainder << endl;
cout << "\n\n\n\n\n" << endl;
goto start;

cin.ignore();
cin.get();
return 0;
}
Last edited on
Ignore that "oper:", It was a typo
All you need to do is put a break; statement after each case.
Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
switch (operation)
{
case 1:
Z = add(num1, num2);
break;

case 2:
Z = subtract(num1, num2);
break;

case 3:
Z = mult(num1, num2);
break;

case 4:
Z = divide(num1, num2);
Remainder = num1 % num2;	
break;
}


The break statement causes the program to execute the next statement outside the switch statement. Without a break statement, every statement from the matched case label to the end of the switch statement, including the default clause, is executed.

Hope that helps :)
Oooh I completely forgot about break. Thank you that does help :)
Topic archived. No new replies allowed.