L2 - Variables & Declarations, Data, and Arithmetic Operations
L2 - Variables & Declarations, Data, and Arithmetic Operations
Data
Arithmetic Operations 1
Ahmed Farhan Ahnaf Siddique
Assistant Professor,
Department of Civil Engineering,
BUET
2
Variables and Their Declarations
#include <iostream>
using namespace std;
int main()
{ // prints "m = 44 and n = 77":
int m, n;
m = 44; // assigns the value 44 to the variable m
cout << "m = " << m;
n = m + 33; // assigns the value 77 to the variable n
cout << " and n = " << n << endl;
return 0;}
➢ Both m and n are declared on the same line
➢ Any number of variables can be declared
together this way if they have the same type
3
Variables and Their Declarations
➢ Every variable in a C++ program must be
declared before it is used.
4
Input Operator
➢ The input operator >> (also called the get
operator or the extraction operator) works like
the output operator <<
#include <iostream>
using namespace std;
int main()
{ // tests the input of integers,floats,and characters:
int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << "m = " << m << ", n = " << n << endl;
double x,y,z;
5
Input Operator
6
Size of Different Data Types
• The number of bites used for data types vary from
compiler to compiler, however we can get this
information by using the sizeof() operator
9
Size of Different Data Types
10
Arithmetic Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (the remainder after division)
#include <iostream>
int main()
14
Precedence and Associativity
15
Precedence and Associativity
#include <iostream>
int main()
cout<<endl<<" 4 * 10 = "<<4*10;
cout<<endl<<" 40 / 6 = "<<40/6;
cout<<endl<<" 6 % 4 = "<<6%4;
cout<<endl<<" 6 % 4 ="<<6%4;
cout<<endl<<" 10 / 2 ="<<10/2;
cout<<endl<<" 4 * 5 ="<<4*5;
17
Precedence and Associativity
18
Precedence and Associativity
4*5/3%4+7/3
19
Assignment Operator
int age;
age = 25;
25 = age;
20
Assignment Operator
a = 5.2;
b = a + 4;
int weight;
weight = 25.5;
cout<<weight;
length = width = 5;
a = b = c / 2.2;
• So, it is effectively
length = 5.5;
length = 7.0;
25
Composite Assignment Operators
#include <iostream>
int main()
int n=22;
n += 9; // adds 9 to n
n -= 5; // subtracts 5 from n
26
Composite Assignment Operators
cout << "After n -= 5, n = " << n << endl;
n *= 2; // multiplies n by 2
n /= 3; // divides n by 3
}
27
Composite Assignment Operators
28
Library Functions
29
Thank You!
30