|
|
|
|||
|
Lets
have a look on the statement cin
>> age1; cin is the
counter part of the cout. Here cin is the input stream that gets
data from the user and assigns it to the variable on its right side. We know
that the sign >> indicates the direction of the flow of data. In our
statement it means that data comes from user and is assigned to the variable
age1, where age1 is a variable used for storing the age entered for student1.
Similarly we get the ages of all the ten students and store them into
respective variables. That means the age of first student in age1, the age of
second student in age2 and so on up to 10 students. When cin statement is reached in a program, the program stops
execution and expects some input from the user. So when cin >> age1; is executed, the program expects from the user
to type the age of the student1. After entering the age, the user has to
press the 'enter key'. Pressing 'enter key' conveys to the program that user
has finished entering the input and cin
assigns the input value to the variable on the right hand side which is age1
in this case. As we have seen earlier that in an assignment statement, we can
have only one variable on left hand side of the assignment operator and on
right hand side we can have an expression that evaluates to a single value.
If we have an expression on the left hand side of assignment operator we get
an error i.e. x = 2 + 4; is a correct statement but x + y = 3+ 5; is an
incorrect statement as we can not have an expression on the left hand side.
Similarly we can not have an expression after the >> sign with cin. So we can have one and only one
variable after >> sign i.e cin >> x; is a correct statement
and cin >> x + y; is an incorrect statement. Next,
we add all these values and store the result to the variable TotalAge. We
use assignment operator for this purpose. On the right hand side of the
assignment operator, we write the expression to add the ages and store the
result in the variable, TotalAge on left hand side. For this purpose we write the
statement as follow: TotalAge = age1 + age2 + age3 + age4 + age5 + age6
+ age7 + age8 + age9 + age10 ; The
expression on the right hand side uses many addition operators ( + ). As these operators have the same precedence, the
expression is evaluated from left to right. Thus first age1 is added to age2
and then the result of this is added to age3 and then this result is added to
age4 and so on. |
||||
|
|
Previous |
TOC |
Next |
|