Lesson 2 - Data Types2.1 Integer Variables
The instruction 'int value;' tells the computer to reserve some memory for the storage of an integer value (a whole number), and to give that memory chunk the name 'value'. We could gave chosen alnost any other name for this variable: we are limited only that the name should begin with a letter, should contain only alphanumeric characters, and should not be a word used already to describe the language or a standard object. The instruction 'cin >> value' tells the computer to read in a sequence of keystrokes, to attempt to convert those keystrokes into a number, and to store the number in the reserved memory location called 'value'. The '>>' operator is an instruction to 'cin' to read something, and what it reads must of the type assigned to the variable 'value' which is an integer. The instruction 'cout << value' tells the computer to take the
contents of the variable 'value', format it as a whole number and print
it as a sequence of digits on the console output. When the computer gets
to the expression 'value*123', it performs the necessary arithmetic and
passes the result to cout so that it can be formatted and printed.
|
||
2.2 Floating Point Variables
You will see that in reading a double value, cin now allows a decimal point in the number, and in printing a double value, cout also prints a variable number of decimal digits depending on the value. |
||
2.3 String variables
To use objects of type 'string' the compiler needs to be told what they are and what they do; this is done by the line '#include <string>'. This is an instruction to the compiler to find a definition of the standard string objects. |
||
2.4 Exercisesa. Write a program (arith1.cpp) that reads in two integer numbers and prints their sum and product, as in:arith1 16 7 Sum is 13 Product is 42 arith2 Enter two integer numbers: 6 7 6 + 7 = 13 6 x 7 = 42 average4 Enter number 1: 6 Enter number 2: 3 Enter number 3: 5 Enter number 4: 11 Average is 6.25 loves Enter your name : Mark Enter something you love : ice-cream Mark loves ice-cream. |