Computer Programming 02
Computer Programming 02
PROGRAMMING
Lecture 02
(Data Types and Operators)
Declaration Examples:
double average, m_score, total_score;
double moon_distance;
int age, num_students;
int cars_waiting;
int myVariable;
cin >> myVariable;
Waits for user input, then stores input in myVariable
= (assignment operator)
Assigns value to a variable
Binary operator (has two operands)
Example:
sum = variable1 + variable2;
1 //example
2 // program to add two numbers
3 #include <iostream>
4
5 int main()
6 {
7 Use
int integer1, integer2, sum; stream extraction
// declaration
8 operator with standard input
9 stream to//obtain
cout << "Enter first integer\n"; user•input.
prompt Notice how cin is used to get user input.
10 cin >> integer1; Calculations can //be performed
read in output
an General
integer form statements: alternative for
is cin>>identifier;
11 cout << "Enter secondlines 13 and 14:// prompt
integer\n"; • Cin is an I stream object
12 cin >> integer2; • streams input from standard input
// read an integer
13 cout << "Sum is " <<
sum = integer1 + integer2;
• uses
// integer1 thesum
>> (input
+ integer2
assignment of << operator)
std::endl;
• Note that data entered from the keyboard
14 cout << "Sum is " << sum << endl; // print sum
must be compatible with the data type of the
15 variable
•Variables can be output using cout << variableName.
16 return• 0;
Generl//form
indicate endl flushes the buffer and prints a
that program ended successfully
is cout<<expression;
17 } newline.
• An expression is any c++ expression(stringConcatenating,
constant, identifier,
chaining or
formula or function call) cascading stream insertion
• Cout is an o stream object
• streams output to standard output operations.
• uses the << (output) operator
OUTPUT OF PROGRAM
17. return 0;
18. }
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s
20 - 4 / 5 * 2 + 3 * 5 % 4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
number_of_bars = number_of_bars + 3;
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
c then becomes 6
Cout<<c prints c =5
Cout<<c++ prints c =5 then increment c by 1 to 6
Cout<<c prints c =6
Cout<<c prints c =5
Cout<<++c first increment c by one to to 6 then prints c =6
Cout<<c prints c =6