03-data-types-and-variables
03-data-types-and-variables
9
Numerical integer types
int
• They can store a whole number value, such as 7 or 1024.
Floating-point types
float
• They can represent real values, such as 3.14
or 0.01
Size of a data type
• Use sizeof() function to check the size
Answer
• Result which can vary from machine to machine/
Compilers
Data type selection
Memory allocation
Define Variables in C++
• Tell the compiler where and how much to create the
storage for the variable
data_size
age
Local variable
Variables in a program
Exercise 3.3
• Write a C++ program to calculate and display total
amount of the given unit price and quantity of
an item.
Answer
Constant variables
• Constants are declared like variables with
the addition of the const keyword
23
Type Casting
• A way to convert a variable from one data type to
another data type
• Use cast operator
– (type_name) expression
– (int) float_value
C++ Memory concept
• Variable names correspond to location in the
computer’s memory
• Every variable has a name, a type, a size and
a value
• A memory cell is never empty. But its initial
contents may be meaningless to your program.
• The current contents of a memory cell are destroyed
whenever new information is placed in that cell.
Garbage values
Input / Output
Standard Streams
• cin is the standard input, normally the keyboard.
• To input data from keyboard use the word ‘cin’,
followed by the ‘Extraction’ operator (>>)
– cin >> x;
• Wait for a value to be entered at the keyboard
and (when enter is pressed) will put that value
into variable ‘x’.
Exercise 3.4
• Write a C++ program to read two numbers from
keyboard and display the total.
Answer
Exercise 3.5
Create a C++ program to calculate and display total
amount of given unit price and quantity of the some
item.
Answer
Input
33
Wait until key press
34
Read value of the key press
35
Change the courser position
36
Output
• To output data onto the screen, use the word
‘cout’, followed by the ‘insertion’ operator
(<<).
Change the output Format
• Adjusting field widths
• Use the width() member function to set the field
width to display a value.
– cout.width(10)
Example
Floating-point notation
Example
Floating-point Precision
• Sets the decimal precision to be used to format
floating-point values on output operations.
– precision(number);
Example
Exercise 3.6
Write a C++ program to read price of the 3 items and
print the total
Answer
Examples
1. Write a C++ program to read 3 integer numbers
and find the total and average