Now let's try doing something a little less lame. Type in (mult.C), compi le (g++ -o mult mult.C), and run (mult) this program :
// file : mult.C
#include <iostream.h>
main()
{
int x;
int y;
int z;
cout << "Enter a number : ";
cin >> x;
cout << "Enter another number : ";
cin >> y;
z = x * y;
cout << "The product of " << x << " and " << y << " is " << z << endl;
}
Note the int x; int y; int z;. These are variable declarations. In this case, I have declared three integer variables named x, y, and z. These variables can store integer values. There are other types of variables such as float, char, bool and double.
A legal variable name consists of a contiguous string of alphabetic and numeric characters (including the underscore character) which must start with an alphabetic character or the underscore character.
You've seen a similar example of the cout statement in the previous section. But now we deal with cin. When the line that says :
cin >> x;is executed, the program stops and waits for you, the user, the type something in at the keyboard. Whatever you type in will be stored in the variable named ''x''. And since ''x'' is an integer, make sure you type in an integer. The same situation arises with :
cin >> y;
The next new thing we have is :
z = x * y;This is an assignment statement. The values of ''x'' and ''y'' are multiplied together and the result is stored in the variable called ''z''. Variables may be reassigned time and time again - their values may vary - thus the name ''variable''. The ''thing'' to the right of the ''='' (assignment operator) is an arithmetic expression. You can combine arithmetic expressions in many ways - almost all of these ways are very intuitive. Here are some examples of other assignment statements involving arithmetic expressions :
z = 1; z = x; x = x + 2; x = z / y - 3; y = y % x; z = (1 + y) * x; x = (-b + sqrt(b*b - (4*a*c))) / (2*a);
Operator precedence resolves the ambiguity in expressions that aren't parenthesized. Multiplication, division, and modulo (or just mod) (*,/,%) are done first going from left to right. Then addition and subtraction (+,-) are done next going from left to right. These are the standard algebra rules that you grew up with. When in doubt, use parenthesis. Also be careful using division - if you divide an integer by an integer, it will always evaluate to an integer even if it has to be truncated.