This is VERY good code for someone who just started. Even better, you're asking the right questions.
Learn about local variables. These are variables that are declared inside a block (somewhere inside a
{
and
}
pair). All of your variables could be local.
As for efficiency, your if statements could be replaced with a switch statement in this case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
switch (z) {
case 1:
cout << "The sum of " << y << " and " << x << " is " << y + x << "." << endl;
break;
case 2:
cout << " " << y << " minus " << x << " is " << y - x << "." << endl;
break;
case 3:
cout << " " << y << " multiplied by " << x << " is " << y * x << "." << endl;
break;
case 4:
cout << " " << y << " divided by " << x << " is " << y/x << "." << endl;
break;
}
|
The basic format of a switch statement is:
1 2 3 4 5 6 7 8 9
|
switch(expression) {
case value1:
statements;
case value2:
statements;
...
default:
statements;
}
|
It evaluates the expression once. Then if checks the cases and jumps to the statements corresponding to the value of the expression. If it doesn't match any case value, then it executes the statements for the "default" case. Some things to note:
- the expression must evaluate to an integral type (an integer, character, etc)
- the values must be constant expressions, which means they must evaluate to a constant at compile time. Put another way, you should be able reduce it to a constant just by reading the code.
- The default case is optional. If it's missing then none of the code executes.
-
MOST IMPORTANT OF ALL: execution of the statements will "fall through" from one case to the next unless you do something to prevent it. The easiest thing to do is add a break statement which will cause execution to jump to the first statement after the whole switch structure.