Topic 2: Type, Operators and Expressions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

TOPIC 2: TYPE, OPERATORS AND EXPRESSIONS

 At the end of this topic, students should be able


to:
◦ write simple computer programs in C++.
◦ use simple input and output statements.
◦ familiar with the fundamental data types.
◦ use arithmetic operators.
◦ use the increment, decrement and assignment operators.
◦ to write simple decision-making statements.
 C++ Programming structure
 Print a line of text - cout
 Definitions of variables - Data types and sizes
 C++’s keywords
 Obtain value from users - cin
 Type conversions
 Arithmetic operators
 Assignment operators
 Increment and decrement operators
 Conditional expression
 Logical operators
C++ Programming Structure
1 /* A first program in C++ */
2
3 #include <iostream> /* and */ indicate comments – ignored by compiler
4
5 using namespace std;
6
7 int main() /* function main begins program execution */
8{
9 cout<< “Welcome to c++!\n”;
10
11 return 0; /* indicate that program ended successfully */
12 } /* end function main */

Welcome to c++!
c++!

 Comments
◦ Text surrounded by /* and */ is ignored by the C++ compiler
◦ Used to describe program
1 /* A first program in C++ */
2 #include directive tells the compiler to read the file
3 #include <iostream> iostream
4
5 using namespace std;
6 Tells the compiler to locate names such as cout
7 int main() /* function main begins program execution */ in the “standard name space”
8{
9 cout<< “Welcome to c++!\n”;
10
11 return 0; /* indicate that program ended successfully */
12 } /* end function main */

Welcome to c++!
c++!

 #include <iostream>
◦ # - Preprocessor directive
 Tells computer to load contents of a certain file
◦ <iostream>
 The file contains the definition for the stream input/output package
 Eg. Cout – print the string on the screen
1 /* A first program in C++ */
2
3 #include <iostream>
4
5 using namespace std;
6
7 int main() /* function main begins program execution */
8{
9 cout<< “Welcome to c++!\n”; Left brace declares beginning of main function
10
11 return 0; /* indicate that program ended successfully */
12 } /* end function main */
 int main()
◦ C++ programs contain one or more functions, exactly one of
which must be main
◦ Parenthesis used to indicate a function
◦ int means that main "returns" an integer value
◦ Braces ({ and }) indicate a block
 The bodies of all functions must be contained in
braces
Print a Line of Text - cout

1 /* A first program in C++ */


2
3 #include <iostream>
4
5 using namespace std;
6
7 int main() /* function main begins program execution */
8{
9 cout<< “Welcome to c++!\n”; Statement tells C++ to perform an action
10
11 return 0; /* indicate that program ended successfully */
12 } /* end function main */
Welcome to c++!
c++!
cout<< “Welcome to c++!\n”;
◦ Instructs computer to perform an action
 Specifically, prints the string of characters within
quotes (" ")
◦ Entire line called a statement
 All statements must end with a semicolon (;)
◦ Escape character (\)
 Indicates that cout should do something out of
the ordinary
 \n is the newline character
General form for cout function:

cout<< “string to be printed\n”;


Some Common Escape Sequences

Escape sequence Description

\n Newline. Position the cursor at the beginning of the next line.


\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.
\" Double quote. Insert a double-quote character in a string.
1 /* A first program in C++ */
2
3 #include <iostream>
4
5 using namespace std;
6
7 int main() /* function main begins program execution */
8 {
9 cout<< “Welcome to c++!\n”;
10
return statement ends the function
11 return 0;
12 }
Right brace declares end of main function
Welcome to c++!
c++!

 return 0;
◦ A way to exit a function
◦ return 0, in this case, means that the program
terminated normally
1 /* A first program in C++ */
2
3 #include <iostream>
4
5 using namespace std;
6
7 int main() /* function main begins program execution */
8 { cout statement starts printing from where the
9 cout << “Welcome to”; last statement ended, so the text is printed on
10 cout <<c++!\n”;
one line.
11
12 return 0; /* indicate that program ended successfully */
13 } /* end function main */

Welcome to c++!
c++!
1 /* A first program in C++ */
2
3 #include <iostream>
4
5 using namespace std;
6
7 int main() /* function main begins program execution */
8 {
9 cout << “Welcome\n to \n c++!\n”;
10
11 return 0; /* indicate that program ended successfully */
12 } /* end function main */

Welcome
to
c++!
c++!
1 /* A first program in C++ */
2
3 #include <iostream>
4
5 using namespace std;
6
7 int main() /* function main begins program execution */
8 {
9 cout << “Welcome “<<endl;
10 cout << “to c++!\n”;
10
11 return 0; /* indicate that program ended successfully */
12 } /* end function main */
Welcome
to c++!
c++!
int integer1; Variables – a location in
int integer2;
memory where a value
can be stored for use by
int sum;
the program
An identifier that can
consists of letters, digits,
Data types – and underscore (_) that
int means that does not begin with a
these variables digit
will hold any Case sensitive
integer values
General form for definitions of variables:
datatype variable;

OR
datatype variable1, variable2,……,
variable n;

Eg.
int integer1, integer2, sum;
C++’s Keywords

 Keywords
◦ Special words reserved for C++
◦ Cannot be used as identifiers or variable names

Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
 int - stores integers (-32767 to +32768)
 unsigned int – 0 to 65535
 char – holds 1 byte of data (-127 to 128)
 unsigned char – holds 1 byte (0 to +255)
 long – usually double int (signed)
 unsigned long – positive double int
 float – floating point variable
 double – twice of a floating point variable
cin obtains a value from the user
and assigns it to integer1

cin obtains a value from the user


and assigns it to integer2
cin >> integer1; tells cin the location in
cin >> integer2; memory which the
variable integer1 is
stored

tells cin the location in


memory which the
variable integer2 is
stored
General form for input using cin:

Cin >> variable;


Assigns a value to sum
Sum = integer1 + integer2

Assignment Operator
To print the sum:

cout << “Sum is =”<< sum;

OR

cout << “Sum is =”<< integer1 + integer2;


Definitions of variables

cin obtains a value from the user


and assigns it to integer1

cin obtains a value from the user


and assigns it to integer2

Assigns a value to sum


 Arithmetic calculations
◦ Use * for multiplication and / for division
◦ Integer division truncates remainder
 7 / 5 evaluates to 1
◦ Modulus operator(%) returns the remainder
 7 % 5 evaluates to 2
 Operator precedence – similar to mathematics rules
◦ multiplication before addition
◦ use parenthesis when needed
◦ Eg. Find the average of three variables a, b and c
 Do not use: a + b + c / 3
 Use: (a + b + c ) / 3
Arithmetic Algebraic
C opetration C expression
operator expression

Addition + f+7 f + 7
Subtraction – p–c p - c
Multiplication * bm b * m

Division / x
x y or or x ÷ y
y x / y

Remainder % r mod s r % s
Precedence of Arithmetic Operators.

Operator(s) Operation(s) Order of evaluation (precedence)


( ) Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost pair is
evaluated first. If there are several pairs of
parentheses “on the same level” (i.e., not nested),
they are evaluated left to right.
* Multiplication Evaluated second. If there are several, they are
/ Division evaluated left to right.
% Remainder
+ Addition Evaluated last. If there are several, they are
- Subtraction evaluated left to right.
 Assignment operators abbreviate assignment expressions
c = c + 3;
can be abbreviated as c += 3; using the addition assignment
operator
 Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
 Examples of other assignment operators:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Assignment Sample
Explanation Assigns
operator expression
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
12
+= 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

Arithmetic Assignment Operators


 Dangerous error
◦ Does not ordinarily cause syntax errors
◦ Any expression that produces a value can be used in control
structures
◦ Nonzero values are true, zero values are false
◦ Example using ==:
if ( payCode == 4 )
cout << "You get a bonus!\n" ;
 Checks payCode, if it is 4 then a bonus is awarded
 Example, replacing == with =:

if ( payCode = 4 )
cout << "You get a bonus!\n" ;

 This sets payCode to 4


 4 is nonzero, so expression is true, and bonus
awarded no matter what the payCode was

◦ Logic error, not a syntax error


 lvalues - expressions that can appear on the left side of an
equation
◦ Their values can be changed, such as variable names
 x = 4;
 rvalues - expressions that can only appear on the right side of
an equation
◦ Constants, such as numbers
 Cannot write 4 = x;
 Must write x = 4;
◦ lvalues can be used as rvalues, but not vice versa
 y = x;
 Increment operator (++)
◦ Can be used instead of c+=1
 Decrement operator (--)
◦ Can be used instead of c-=1
 Preincrement
◦ Operator is used before the variable (++c or --c)
◦ Variable is changed before the expression it is in is evaluated
 Postincrement
◦ Operator is used after the variable (c++ or c--)
◦ Expression executes before the variable is changed
 If c equals 5, then
cout << ++c ;  Prints 6

cout << c++ ; Prints 5 then



increase c by 1  6
 When variable not in an expression
++c;
cout << c ;
Has the same effect as

c++;
cout << c ;
Operator Sample expression Explanation

++ ++a Increment a by 1, then use the new value of a in the


expression in which a resides.
++ a++ Use the current value of a in the expression in which a
resides, then increment a by 1.
-- --b
--b Decrement b by 1, then use the new value of b in the
expression in which b resides.
-- b-- Use the current value of b in the expression in which b
resides, then decrement b by 1.

Increment and Decrement Operators


c is printed, then incremented

c is incremented, then printed


 Executable statements
◦ Perform actions (calculations, input/output of data)
◦ Perform decisions
 Eg. "pass" or "fail" given the value of a test grade
 if control statement
◦ If a condition is true, then the body of the if statement
executed
 0 is false, non-zero is true
◦ Control always resumes after the if structure
Standard algebraic C equality or
Example of
equality operator or relational Meaning of C condition
C condition
relational operator operator

Equality operators
= == x == y x is equal to y

≠ != x != y x is not equal to y
Relational operators

> > x > y x is greater than y

< < x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y


Checks if num1 is equal to num2

Checks if num1 is not equal to num2

Checks if num1 is less than num2


Checks if num1 is greater than num2

Checks if num1 is less than or equal to num2

Checks if num1 is greater than equal to num2


 && ( logical AND )
◦ Returns true if both conditions are true
 || ( logical OR )
◦ Returns true if either of its conditions are true
 ! ( logical NOT, logical negation )
◦ Reverses the truth/falsity of its condition
◦ Unary operator, has one operand
 Useful as conditions in loops
Expression Result
true && false false
true || false true
!false true
expression1 expression2 expression1 && expression2

0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1

Truth table for the && (logical AND) operator


expression1 expression2 expression1 || expression2

0 0 0
0 nonzero 1
nonzero 0 1
nonzero nonzero 1

Truth table for the logical OR (||) operator


expression !expression

0 1
nonzero 0

Truth table for operator ! (logical negation)

You might also like