C++ PROGRAMMING
LANGUAGE
LAB 2
VARIABLES
• Variables represent storage locations in the computer’s memory.
• A way for code to store information by associating a value with a name.
• All variables have a type associated with them, where the type describes the representation of the
variable.
Variable data types
• Integer
• Character
• Float
EXAMPLES OF TYPES IN C++
• int 126
• float
3
• char
-24
EXAMPLES OF TYPES IN C++
• int 1.06
• float
3.0
• char
-2.090
EXAMPLES OF TYPES IN C++
• int 'a'
• float
'&'
• char
'3'
DECLARATION VS INITIALIZATION
Declaration: A declaration introduces a name into a program and specifies
its type, allocate memory for it.
int x; // Declaration of an integer variable named 'x'
Initialization: Initialization is the process of assigning an initial value to a
variable at the time of its declaration or later during the program execution.
It associates a value with a variable name.
x = 5; // initialization of an integer variable named 'x' with the value 5
DEFINE VARIABLES
char c ; // declare a new character variable
c = ‘x’ ; // ‘x’ is assigned to variable c
float d = 1.06; // d is a float, a type used to represent decimal numbers
int a; // declare a new integer variable
a = 5; // initialize the variable value
int a = 12; // ERROR! You do not need the type when re-assigning a variable
a = 13; // this is okay, updates variable value
float a = 4.2; // ERROR! You cannot redefine a variable to be another type
CASE SENSITIVE
• C++ is a case-sensitive programming language, all the keywords must be
in lowercase.
• Case sensitive means that the uppercase and lowercase letters are
considered differently.
int c;
int C; are two different variables!
FUNDMENTAL ARITHMATIC OPERATORS
+ Addition X+Y
- Subtraction X-Y
* Multiplication X* Y
/ Division X/ Y
% Modulus X%Y
EXAMPLE #1
Write a program that takes two integers as input from the
user and calculates their sum.
EXAMPLE #2
Create a program that asks the user to enter two floating-
point numbers and computes their product.
EXAMPLE #3
Develop a program that takes two integers as input,
divides the first number by the second, and prints the
quotient and remainder.
EXAMPLE #4
Create a C++ program that asks the user for a number
and then prints its square and cube.
X2
X3
EXAMPLE #5
Develop a C++ program that asks the user for a radius
and calculates the area of a circle with that radius.
Area of circle = π r2
EXAMPLE #6
Write a program that asks the user to enter the length
and width of a rectangle and then calculates its area and
display it.
Area of rectangle = length x width
EXAMPLE # 7
Create a C++ program that calculates the volume of a
sphere based on the radius provided by the user.
Volume of sphere = 4/3 r π2