2lecture 2 C++
2lecture 2 C++
Variable
• In computer programming, a variable is a storage location and an
associated symbolic name (an identifier) which contains some known or
unknown quantity or information, a value. The variable name is the usual
way to reference the stored value; this separation of name and content
allows the name to be used independently of the exact information it
represents. The identifier in computer source code can be bound to
a value during run time, and the value of the variable may thus change
during the course of program execution.
• In computing, a variable may be employed in a repetitive process: assigned
a value in one place, then used elsewhere, then reassigned a new value
and used again in the same way
A 10
• Let us think that I ask you to retain the number 5 in your mental memory,
and then I ask you to memorize also the number 2 at the same time. You
have just stored two different values in your memory. Now, if I ask you to
add 1 to the first number I said, you should be retaining the numbers 6 (that
is 5+1) and 2 in your memory. Values that we could now -for example-
subtract and obtain 4 as result.
The whole process that you have just done with your mental memory is a
similar of what a computer can do with two variables. The same process
can be expressed in C++ with the following instruction set:
a = 5;
b = 2;
a = a + 1;
result = a - b;
• Compilers have to replace variables' symbolic names with the actual
locations of the data. While a variable's name, type, and location often
remain fixed, the data stored in the location may be changed during
program execution.
Data types in C++
Rules for writing variable names
• Assignment statement can also be used for carrying out computation and
assigning values to variables.
General form: result = expression;
For example the following assignment statement:
average = (a + b)/2;
assigns half the sum of a and b to the variable average. The expression is
evaluated and then the value is assigned to the variable result. It is
important to note that the value assigned to result must be of the same type
as result.
• main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
}
Arithmetic operators in C++
Arithmetic operators
• main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
} //end main
Constants
• A quantity that cannot change its value during program execution is called
constant.
Assignments:
• Write a program to assign a value to a
variable year. Calculate no of months and
print on screen.
• Write a program to assign any value to
variables a, b and c. Then calculate sum
and average of a, b, c.
• Write a program to calculate the volume of
cylinder as v=pi r2 h where pi=3.14, r=6,
h=8.