Problem Solving I Chapter 2

You might also like

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

CS221 : Computer Programming I

• Chapter 2: C++ Basics

1
Monolithic Program

• A C++ program is a collection of one or more subprograms


(functions)
• Function
– Collection of related statements that are grouped to
accomplish a task
• Every C++ program has a function called main
• A program that uses a single function (main) to solve a
problem is called monolithic program. Main contains a
collection of statements enclosed in a brace({})

To 2
Anatomy of Monolithic C++
Program

/*program header comment*/


preprocessor directives (if any)
int main ( )
{
statement1 //line Comment
statement2

statement last
return 0 ;
}
3
Anatomy…
Comment : Used to include some explanatory notes at key places
in the program.
Preprocessor directives: Message to the C++ preprocessor. Lines
beginning with # are preprocessor directives.
int main (): This is the function header. C++ programs must
contain one function named main This is where program execution
begins.
The reserved word “int” indicates that main() returns an integer
value.
The parentheses following the reserved word “main” indicate that
main is a function.
The Function Body: A left brace (curly bracket) -- { -- begins the
body of every function. A corresponding right brace -- } -- ends
the function body. 4
Anatomy…

Statements : A set of executable statements.


Each terminated with a semicolon.
indentation is for the convenience of the reader; compiler ignores
all spaces and new line ; the delimiter for the compiler is the
semicolon.

return 0 statement: indicates that main() returns a value of zero to


the operating system which reports normal termination of the
program.

5
Simple C++ Program

Comments
/* This program displays “Hello World” on the monitor
Date Written:……………
Written by ……………. Preprocessor
Directives
*/
#include <iostream.> //This is preprosessor directive Main function
using namespace std;
int main ( ) //this tells the starting point of your program Statements
{
cout << “Hello World” <<endl ; //print the text on monitor
return 0 ; //return to operating system
}
Return Statement
Function Body 6
Comment
Comments are used to document programs. Comments should appear in
a program to:
– Explain the purpose of the program
– Identify who wrote it
– Explain the purpose of particular statements
Any comment in your program is ignored by the compiler.
There are two ways of commenting in C++
• Block Comment - comments that can span several lines. Anything
between the symbol pair /* and the symbol pair */ is a comment. E.g
/*This is a comment that spans
three lines. Note that there is no comment
symbol of any kind on the second line.*/
• Line comment – Comments that span only a single line. Usually used
to comment a single statement. All of the text between the // and the
end of the line is a comment. E.g
y = a + b //This is a line comment 7
Preprocessor Directives

Programmer instructions to the preprocessor (called


preprocessor directives) take the general
form:
# directive tokens
There are two most commonly used preprocessor directives
1. #define directive – Used for macro definition. Takes the
general form
#define identifier tokens
It instructs the preprocessor to substitute tokens for
every occurrence of identifier in the rest of the file. E.g
#define temp 100
This statement instructs the preprocessor to substitute
100 for every occurrence of temp in the rest of the file.
8
Preprocessor…

2. #include directives – used for textual inclusion of a


file in another file. Takes the general form
#include “file path”
It instructs the preprocessor to include the content
of the file in exactly the position where the directive
appears. E. g.
#include “contents.h“
The included file is usually expected to reside in the
same directory as the program file otherwise the full
path to the file should be specified.
9
Using Standard Library functions
• C++ comes with ready made compiled library objects or functions
that you can use in your program.
• Every library has a name and is referred to by a header file.
• These header file contains the description of the objects you are
going to use.
• In order to use these objects the header file for these objects should
be included in your program. In CodeBlock these header files are
located in the directory C:\Program
Files\CodeBlocks\MinGW\lib\gcc\x86_64-mingw32\8.1.0\include\c++
• To include a header file, you use the include preprocessor directives.
Example:
To use the C++ input/output objects, you have to include the “iostream”
file as follows
#include <iostream>
using namespace std;
To use the C++ mathematical objects such as absolute value, square root,
sin, cosine etc, you have to include the “cmath” file as follows
10
#include <cmath>
Using Standard…

Note
• To include C++ standard library function
headers, we use the file to be included
enclosed within <> instead “”. Other file
can be included by using “”.
• It is the way of telling the preprocessor
that we are including a header file of a
standard library
11
Token

A C++ statements are made up of tokens. A token is the smallest


meaningful element of C++ .
It may be a single character or a sequence of characters to form a
single item.
Tokens can be:
• Whitespace
• Names (identifiers)
• Keywords
• Literals
• Numeric constants
• Character constants
• Boolean constants
• String constants
• Punctuation
• Operators
12
White Space
White space in C++ is used to separate tokens in the
source file. It is also used to improve readability of
the source code.

int x; Space is necessary

a = b + c;
Space is optional added only for readability

13
Identifiers
Identifiers allow us to name program objects such as
variable, constant, function, etc.
If we don’t have identifiers that we could use to symbolically
represent data location, we would have to know and use
data addresses to manipulate them.
C++ identifiers rule:
1. The first character must be alphabetic character or
underscore.
Caution: By custom, many of the identifiers in the system
library starts with underscore. So to avoid duplication
when you use also system library, it is recommended that
not to use identifier that start with underscore.
2. The identifier must consist only of alphabetic characters,
digits, and underscore. No other special character.
3. Keywords( or reserved words) can’t be used as identifier.

14
Identifiers…
Some important comments about identifier
1. C++ is case sensitive. Two identifiers that differ in case
are treated as different identifiers. E.g.
TEMP ,temp , Temp are three different identifiers.
2. Try to make your identifier descriptive. When the name
contains more than one word, use under score to
separate the words or use camel case notation(capitalize
the first letter of each word except the first). E.g.
sales_tax_rate or salesTaxRate
Example
Which of the following names can be used to name C++
program objects(Valid identifier)?
a a1 1a %sale pi
PI student_name_totalCost sales tax int 15
Keywords
Keywords( or reserved words) are special class of identifier
that have special meaning in C++.
• Each keyword has a predefined purpose in the
language.
• Do not use keywords as variable or constant names!!
Some of the keywords( for exhaustive list of key words use
your reference book) are listed here:
bool, break, case, char, const, continue, do, default, double,
else, extern, false, float, for, if, int, long, namespace, return,
short, signed, static, struct, switch, typedef, true, unsigned,
void, while
Note: All keywords are in lower case
16
Data Types
Data must be stored in memory in order to be manipulated
by your program. Different types of data requires different
amount of memory. It is not going to occupy the same
amount of memory to store a simple number than to store a
single letter or a large number, and they are not going to be
interpreted the same way.
Data type: set of values together with a set of operations.
The set of values constitute the domain for the type.
A type tells the compiler four things
• the amount of memory required to store the data.
• the format of the data, how the bit pattern are interpreted
• the domain or the possible values
• The operation that can be performed on the data
17
Example: Data Format
Int (32 bit) representation
01000000010010001111010111000011
28311552
float
01000000010010001111010111000011
3.14

18
Classification of C++ Data Type
The next figure shows the classification of C++ data type.
Built-in-types: defined by the system.
User-defined-types: defined by the user.
Fundamental types: built in type that can’t be broken down
void type: represent empty data value and operation
Derived Types: derived from the fundamental
Integral types: integers (numbers without a decimal)
Floating-point: decimal numbers

19
Integral Data Type
The Integral type further classified as shown below:

Integral type

Boolean Character Integer


Integer Data Type
The Integer type further classified as shown below:

long long or
signed long long
Or unsigned long long
Integer long long int or Or
signed long long int unsigned long long int

long long

short int long

short or int
unsigned short unsigned int long or unsigned long
signed short Or Or signed long Or
Or unsigned short int signed int Or unsigned long int
short int or long int or
signed short int signed long int
Integer…
C++ supports 4 integer types : short int(or short), int, long int( or long) and long
long( or long long int). Each have a signed and unsigned version. The next table
summarize the integer types

Type Sign Byte Minimum Value Maximum Value C++ implementation


Size

short int signed 2 -32, 768 32, 767 short (or short int)
(short)
unsigned 2 0 65,535 unsigned short
int(PC) signed 2 -32, 768 32, 767 int
unsigned 2 0 65,535 unsigned int
int(main signed 4 -2,147,483,648 2,147,483,647 int
frame) unsigned 4 0 4.294,967,295 unsigned int
long int signed 4 -2,147,483,648 2,147,483,647 long (or long int)
unsigned 4 0 4.294,967,295 unsigned long
Long long signed 8 –9, 223, 372, 036, 9, 223, 372, 036, long long (or long
int 854, 775, 808 854, 775, 807 long int)
unsigned 8 0 18, 446, 744, 073, unsigned long long
709, 551, 615
22
Character Data Type
C++ supports 2 character types : char and wchar_t. Each have a signed
and unsigned version. The next table summarize the integer types
Character

char wchar_t

Type Sign Byte Minimum Maximum Value C++ implementation


Size Value

char signed 1 -128 127 char


unsigned 1 0 255 Unsigned char
wchar_t signed 2 or 4 compiler -32, 768 32, 767 wchar_t
dependent
unsigned 2 or compiler 0 65,535 unsigned wchar_t
dependent
Character…
• Both char and wchar_t can be used to represent a small signed or
unsigned integer umber.
• They can be also used to represent characters (lower and upper
case letters, digits, and special symbol) . A character type contains
the code for the character. This code is a numeric value and depends
on the character coding system being used (i.e., is machine-
dependent). The most common system are:
• ASCII (American Standard Code for Information Interchange)
which uses 7 bits to represent a character
• Extended ASCII (Extended American Standard Code for
Information Interchange) which uses 8 bits to represent a
character
• EBCDIC (Extended Binary Coded Decimal Interchange Code) is
another 8 bits character encoding used mainly on IBM machine.
Character ASCII EBCDIC
A 01000001 (65) 11000001 (193)
a 01100001 (97) 10000001 (129)
24
0 00110000 (48) 11110000 (240)
Bool Data Type
bool (short for boolean) is another smallest integral data
type. A Boolean, bool, can have one of the two values true or
false. It is used to express the results of logical operations.

A bool data takes a byte of memory.


By definition, true has the value 1 when converted to an
integer and false has the value 0. Conversely, integers can be
implicitly converted to bool values: nonzero integers convert
to true and 0 converts to false.
bool, true and false are reserved words.

25
Floating-point Data Type
floting point type

float double Long double

The floating-point types represent floating-point numbers. Floating-point


types come in three sizes: float (single precision),double (double-
precision), and long double(extended precision).
Floating-point types are always signed.
Type Byte Range Precision C++
Size (approximately) Implementation
float(single Precision) 4 10-38 to 1038 7 float
double(double 8 10-308 to 10308 15 double
Precision)
long double(extended 10 10-4932 to 104932 19 long double
precision)
26
Void Data type
The void type has no values and no operation. The set of
values and the set of operations are empty.
It can play the role of a generic type, that is, a type that can
represent any of the other standard types.

27
Variables
Variables are named memory location that have a type such as
integer or character, and consequently, a size, which is
inherited from the their type.
The content of the variable may change through the execution
of the program.

28
Variable Declaration
In C++, all the variables that a program is going to use must be
declared prior to use.
Declaration of a variable serves two purposes:
1. It associates a type and an identifier (or name) with the
variable. The type allows the compiler to interpret
statements correctly. For example in the CPU the instruction
to add two integer values together is different from the
instruction to add two floating-point values together. Hence
the compiler must know the type of the variables so it can
generate the correct add instruction.
2. It allows the compiler to decide how much storage space to
allocate for storage of the value associated with the identifier
and to assign an address for each variable which can be used
in code generation.
29
Variable Declaration…
A variable declaration has the form:
type identifier1, identifier2, …;
type specifies the type of the variables being declared. The
identifier1, identifier2, … is a list of the identifiers of the
variables being declared, separated by commas.
Example
char code;
unsigned int i;
double payRate, price;

30
Variable Initialization
Variables may be initialized at the time of declaration by assigning a value
to them. Initialization gives initial value to variables. There are two ways
of initializing.
type identifier1 = value1, identifier2 = value2; …
type identifier1 (value1) , identifier2 (value2)…;
type identifier1 {value1} , identifier2 {value2}…;

Example:
int i, j, count(0);
float sum = 0.0, product{10};
char ch = ‘a';
bool passed_exam = false;
i, j have no initial value specified, so the program should make no
assumption about their contents.

31
Example-Variable(Real Code)
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
int a, b=0; // declaring variables:
int result;
a = 5;
b = 2;
a = a + 1;
result = a - b;
cout << result<<endl; // print out the result:
system(“pause”);
return 0; // terminate the program:
}
32
Automatic Type Deduction
The auto keyword can be used to let the compiler decide the
data type itself.
The auto keyword specifies that the type of the variable that is
begin declared will automatically be deduced from its initialize
Example
auto i=4; //i is an int
auto x=3.4; //x is double
auto s=sqrt(x);//s is double as the sqrt function returns double

33
Constants
Constants are data values that can’t be changed during
program execution.
Like variables, constants have a type.
C++ has three kinds of constants: literal, defined, and
memory constants.

34
Literal Constants
Literal constants are unnamed constants used to express particular
values within the source code of a program.
Literal constants can be divided in Integer Numerals, Floating-Point
Numerals, Characters, Strings and Boolean Values
1. Integer Literals
They are numerical constants that identify integer decimal values
If the number is with in the range of int, by default its type will be signed
int, otherwise its type will be long int or long long int. You can override
the default value by specifying unsigned(u or U) , long(l or L) and long
long(ll or LL)
12 //its type is int
5123451234567895664545 //its type is long
-31L //its type is long
765432UL //its type is unsigned long
23ULL //its type is unsigned long long
35
Literal…
C++ also allows the use of literal constants of binary numbers(base 2), octal
numbers (base 8) and
hexadecimal numbers (base 16). If we want to express an octal number
we have to precede it with a 0 (zero character). And in order to express
a hexadecimal number we have to precede it with the characters 0x
(zero, x). Example
75 // decimal
0b101 //binary
0113 // octal
0x4b // hexadecimal
2. Floating Point Literals
They express numbers with decimals and/or exponents. The default type is
double. You can override by specifying float(f or F) and long double(l or L).
Example
2.0 //double
6.02e-23 //double
3.1416f //float 36
-6.02e145L //long double
Literal…
3. Character literal
A character literal are enclosed between two single quotes ( apostrophe
). When the character to be represented does not have any graphics
associated with it: that is when it can’t be printed or entered from the
key board, escape character(backslash \) is used.
Example
‘A’ //the character a
‘7’ //the character 7
‘ ‘ //the character space
Some escape sequence for special character
Null character ‘\0’ New line ‘\n’
alert(bell) ‘\a’ form feed ‘\f’
Back space ‘\b’ carriage return ‘\r’
Horizontal tab ‘\t’ single quote ‘\’’
Vertical tab ‘\v’ backslash ‘\\’
37
Literal…
4. String literal
A string literal is a sequence of zero or more characters
enclosed in double quotes. Example
“” //null string
“h” // a string h
“Hello world\n” // Hello world
“\’’Good\” Morning” // “Good” Morning
5. Boolean Literal
The bool type has two predefined literals associated with it:
true and false .

38
Defined Constants
Another way to designate a constant is to use the
preprocessor command. Its general format is

#define identifier value

Value will replace the identifier wherever it is found in the


source program during the preprocessing.
For example:
#define PI 3.14159
#define NEWLINE '\n'

39
Memory Constants
C++ provides a capability to define a named constant. We
use the C++ type qualifier const before the definition. The
general syntax is
const type identifier=value;
Note: Const variables must be assigned a value when
declared, and then that value cannot be changed.
For example:
const double PI = 3.14159;
const char NEWLINE = ‘\n’;
const int MYCONST; //invalid!
As a good programming style use upper case identifier for
defined and memory constant.
40
Example - Constant
// Using literal constant
#include <iostream>
using namespace std;
int main ()
{
double radius, circumf;
cout << “Please enter radius: “;
cin >> radius;
circumf = 2 * 3.14159 * radius;
cout << ‘\n’ << “The circumference is: “ << circumf<<endl;
system(“pause”);
return 0;
} 41
Example - Constant
// defined constants: calculate circumference
#include <iostream.>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double radius, circumf;
cout << “Please enter radius: “;
cin >> radius;
circumf = 2 * PI * radius;
cout << NEWLINE << “The circumference is: “ << circumf<<endl;
system(“pause”);
return 0;
42
}
Example - Constant
// memory constants: calculate circumference
#include <iostream>
using namespace std;
const double PI = 3.14159;
const char NEWLINE = ‘\n’;
int main ()
{
double radius, circumf;
cout << “Please enter radius: “;
cin >> radius;
circumf = 2 * PI * radius;
cout << NEWLINE << “The circumference is: “ << circumf<< NEWLINE;
system(“pause”);
return 0;
43
}
C++ Operators
An operator is a language specific syntactical token that
requires an action to be taken.
C++ provides several operators for composing expression:
• Arithmetic
• Increment and decrement
• Relational and equality
• Logical
• Assignment
• Compound Assignment
• Bit-wise Logical
• Conditional
• Comma
• Explicit Type Casting
• Sizeof 44
Arithmetic Operators

C++ provides six basic binary arithmetic operators.


These are summarized in Table below
Operator Name Type Example
- Or + sign unary -x //Gives the negative of the number
stored in x
+ Addition binary 2 + 3.51 //Gives 5.51
- Subtraction binary 2 – 3.51 //Gives -1.51
* Multiplication binary 2*3.51 //Gives 7.01
/ Division binary 21 / 4.0 //Gives 5.25
% Modulo binary 15 % 6 //Gives 3

45
Arithmetic…
• Except for remainder (%), all other arithmetic operators can accept a
mix of integer and real operands. For the modulo operator(%) both
operands must be integral.
• AS a general rule, if both operands are of the same type then the
result will be also of that type.
• Thus, when both operands of the division operator (/) are integers
then the division is performed as an integer division and not the
normal division we are used to. Integer division always results in an
integer.For example:
9 / 2 // gives 4, not 4.5!
-9 / 2 // gives -4, not -4.5!
• It is possible for the outcome of an arithmetic operation to be too
large for storing in a designated variable. This situation is called an
overflow. The outcome of an overflow is machine-dependent and
therefore undefined.
46
Relational Operators
C++ provides seven relational operators for comparing numeric
quantities. These are summarized in Table below. Except the
spaceship operator the result of a relational operation is a Boolean
value that can only be true(1) or false (0), according to its Boolean
result.
Operator Name Example
== Equality 3 == 3 //Gives true
!= Inequality 3 !=3 //Gives false
< Less Than 3<3 //Gives false
<= Less Than or Equal 3.5 <= 3 //Gives false
> Greater Than 3.5 > 3.5 //Gives false
>= Greater Than 3.5 >= 3.5 //Gives true
<=> The spaceship a<=>b gives value less than 0 if a< b
gives value 0 if a ==b
gives value greater than 0 if a>b 47
Relational …

• The operands of a relational operator can be any


expression that evaluates to a number. Characters
are valid operands since they are represented by
numeric values(ASCII code).
• The relational operators should not be used for
comparing c-style strings.

48
Logical Operator
C++ provides three logical operators for combining logical
expression. These are summarized in the table below. Like the
relational operators, logical operators evaluate to 1 or 0.
Operator Type Name Example
! unary Logical Negation !(3>5) //Gives true
&& binary Logical And 3>5 && 2 < 4 //Gives false
|| binary Logical Or 3<5 || 2 > 4 //Gives true

Logical Negation
If its operand is true or non-zero it produces false, and if it is false or zero it
produces true.
Logical And
Produces false if one or both of its operands evaluate to false or zero. Otherwise, it
produces true.
Logical Or
Produces false if both of its operands evaluate to false or zero. Otherwise, it 49
produces 1.
Logical…
Note
• we talk of zero and nonzero operands (not zero and 1). In general, any
nonzero value can be used to represent the logical true, whereas only
zero represents the logical false. The following are, therefore, all valid
logical expressions:
!20 // gives 0 10 || 5.5 // gives 1
10 && 5 // gives 1 10 && 0 // gives 0
• In evaluating logical && expression, if the left part is evaluated to
false, there is no need to evaluate the second expression. A similar
thing happens with || expressions. If the first of two expressions
joined with the || operator is true, then you know the entire
expression is true, no matter whether the second expression is true or
false. The C++ language operates in a “short circuit mode”, i.e., if the
truth value of the whole expression can be determined by evaluating
the left expression of && or ||, C++ does not bother to evaluate the
right expression. But this may not be true for other languages.
E.g 1 > 2 && 7 < 3 // the expression 7 < 3 will not be evaluated
1 < 7 || 5 < 4 //the expression 5 < 4 will not be evaluated 50
Assignment Operator
The assignment operator(=) is used for storing a value at some
memory location (typically denoted by a variable).
The part at the left of the assignment operator (=) is
known as the lvalue (left value) and the right one as the rvalue (right
value).
The lvalue has to be a variable whereas the rvalue can be either a
constant, a variable, the result of an operation or any combination of
these.
In an assignment statement, first the expression on the right-hand side of
the equal sign is evaluated
and then the variable on the left-hand side of the equal sign is set equal to
this value.
SYNTAX
Variable = Expression;
EXAMPLES
distance = rate * time;
a=5 //assign 5 to the variable a
5=a // invalid assignment left side should be an lvalue
51
Increment/Decrement Operators
The auto increment (++) and auto decrement (--) operators provide a
convenient way of, respectively, adding and subtracting 1 from a numeric
variable. These are summarized in the table below. The examples assume
the following variable definition:
int k = 5;
Operator Name Example
++ Prefix increment Y = ++k + 3 //k will be 6 and y will be 9
++ Postfix increment Y = k++ + 3 //k will be 6 and y will be 8
-- Prefix decrement Y = --k + 3 //k will be 4 and y will be 7
-- Postfix decrement Y = k-- + 3 //k will be 4 and y will be 8
i++, ++i are identical to i= I + 1
i--, --i are identical to i= I - 1
Both operators can be used in prefix and postfix form. The difference is
significant. When used in prefix form, the operator is first applied and the
outcome is then used in the expression. When used in
the postfix form, the expression is evaluated first and then the operator
52
Bitwise Operators
C++ defines several bitwise operators that can be applied to the
integer types:long long, long, int, short, char. These operators act
upon the individual bits of their operands.
1. Bitwise NEGATION(~) is a unary operator which reverses the
bits in its operands.
2. Bitwise AND(&) compares the corresponding bits of its
operands and produces a 1 when both bits are 1, and 0
otherwise.
3. Bitwise OR (|) compares the corresponding bits of its
operands and produces a 0 when both bits are 0, and
1otherwise.
4. Bitwise EXCLUSIVE OR(^ ) compares the corresponding bits of
its operands and produces a 0 when both bits are 1 or both
bits are 0, and 1 otherwise 0.

53
Bitwise…
5. The bitwise LEFT SHIFT (<<) moves the data left a specified number
of bits. Any bits that are shifted out the left side disappear. New bits
coming in from the right are zeros.
Shifting left by n places is the same as multiplying by 2n.
6. The bitwise RIGHT SHIFT (>>) does the same thing in the other
direction. When a variable is shifted to the right, C++ needs to fill the
space on the left side with something. For signed variables, C++
uses the value of the sign bit. For unsigned variables, C++ uses zero
These are summarized in Table below. In the table below, The
examples assume the following variable definition:

54
Bitwise…
These are summarized in Table below. In the table below, The examples assume
the following variable definition:
int cl = 0x45; //00000000000000000000000001000101 (69)
int c2 = 0x71; //00000000000000000000000001110001 (113)

Operator Name Example


~ Bitwise Negation Y = ~c1 //Y will be 0xFFFFFFBA
& Bitwise And Y = c1 & c2 //Y will be 0x41
| Bitwise Or Y = c1 | c2 //Y will be 0x75
^ Bitwise Exclusive Or Y = c1 ^ c2 //Y will be 0x34
<< Bitwise Left Shift Y = c1 << 4 //Y will be 0x450
>> Bitwise Right Shift Y =( -c1) >> 4 //Y will be 0xFFFFFFFB

55
Exercise
How can we set the bit at bit position 4 of unsigned int variable n?
How can we unset the bit at bit position 4 of unsigned int variable
n?
How can we toggle the bit at bit position 4 of unsigned int variable
n?
How can we test if the bit at bit position 4 of unsigned int variable
is off?

56
Compound Assignment

When we want to modify the value of a variable by performing an


operation on the value currently stored in that variable we can use
compound assignment operators. Its general format is:
variable operator = expression
which is equivalent to
variable = variable operator (expression)
Where variable is a valid variable, operator is an arithmetic or
bitwise operators, and expression is a valid arithmetic or bitwise
expression.
Example
sum /= 2.0; is equivalent to sum= sum/2;
n &= 0xF2F2 is equivalent to n = n & 0xF2F2;
x *= y + 3; is equivalent to n = x * (y + 3);

57
Conditional operator
The conditional operator is a ternary operator the takes three
operand. Its general format is:
condExpr? expr1 : expr2
Where condexpr is any conditional expression, and expr1 and
expr2 are valid expression.
First the conditional expression is evaluated, which is treated as a
logical condition. If the result is nonzero then expr1 is evaluated
and its value is the final result. Otherwise, expr2 is evaluated and
its value is the final result.
Example 1:
int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
int min = (m < n ? m++ : n++); //result?
58
Comma Operator

Multiple expressions can be combined into one expression


using the comma operator. The comma operator is a binary
operator that takes two operands. It first evaluates the left
operand and then the right operand, and returns the value of
the latter as the final outcome.
Example:
a = 2 , 3 , 4; // a will be assigned 4
a = (b=3, b+2); //result?
Example
int m=6, n=2, min;
int mCount = 0, nCount = 0;
//...
min = (m < n ? mCount++, m : nCount++, n); //result?
59
Sizeof() Operator

This operator accepts one parameter, which can be either a


type or a variable itself and returns the size in bytes of
that type or object. Its general format is:
sizeof(type or variable);
Example
int a, b,c;
double x;
a = sizeof (char); //a?
b= sizeof(float); //b ?
c = sizeof(x); //?
The value returned by sizeof is a constant, so it is always
determined before program execution.
60
Explicit type Casting Operator
C++ permits explicit type conversion of variables or
expressions using the type cast operator. The following two
versions are equivalent:
(type – name) expression // C notation
type – name (expression) // C++ notation
Examples:
average = sum / (float) i; //C notation
average = sum / float (i); //C++ notation
Example
int i;
float f = 3.14;
i = (int) f; //i contains?
C++ provides another operator for type casting: Static cast. Its
syntax is
static_cast < type > (expression);
Example
static_cast <int> (3.5 * 6.9 / x);
61
Expression

Expression is a sequence of operands and operators that


reduce to a single value. Example
5 + 3 * x;
If the variable x contains 2, the expression reduces to a single
value 11.
y=5 + 3*x;
y is assigned 11 and the expression reduces to a single value
11.
An operand is the one that receives the operator action. It
can be a constant or a variable.
62
Expression

You can specify the order of operations in a complex


expression by inserting parentheses. If you omit parentheses,
the computer will follow rules called precedence rules that
determine the order in which the operations are performed.
Operators in higher levels take precedence over operators in
lower levels.
The associativity determines the order in which operators
with the same precedence are evaluated in a complex
expression.

63
Operator Precedence
Precedence Operator Description Associativity
1 () Function call Left to right
[] Array reference
-> Indirection reference
:: Scope access
. Direct reference
2 ++ - - Unary Postfix Left-to right
3 ++ - - ~ ! sizeof Unary Prefix Right-to left
+ - Unary Sign
4 (type) , static_cast < type > type casting Right-to left
6 */% multiplicative Left-to right
7 + - additive Left-to right
8 << >> shift Left-to right
9 < > <= >= relational Left-to right
10 == != equality Left-to right 64
Operator Precedence

Precedence Operator Description Associativity


11 & bitwise AND Left-to right
12 ^ bitwise XOR Left-to right
13 | bitwise OR Left-to right
14 && logical AND Left-to right
15 || logical OR Left-to right
16 ?: conditional Right-to left
17 = *= /= %= += -= >>= <<= &= ^= |= assignment Right-to left
18 , comma Left-to right

65
Example

Assume the following variable definition:


int n=1, p=2, q=3;
What is the result of the following expression?
1. n <= p + q && n >= p - q || n == 0
2. ++n * q-- / ++p - q
3. n | p & q ^ p << 2 + q
4. p < q ? n < p ? q * n - 2 : q / n + 1 : q - n

66
Type of Expression

Expressions may be of the following six types:


1. Constant expressions
consist of only constant values. Examples:
(1.5 - 3.5) * 4 + 22
2. Integral expressions
Integral expressions are those which produce integer
results after implementing all the automatic and explicit
type conversions.
m+n-5
m * n – 5 + int(m/n)
where m and n are integer variable
67
Type of Expression

3. Float expressions
Float expressions are those which, after all conversions,
produce floating – point results. Examples:
x * y / 10.0 //double
5 + float(10) //float
where x and y are integer variable
4. Relational expressions
Relational expressions yield results of type bool which
takes a value true(1) or false(0). Examples:
x <= y
a+b == c+d
68
Type of Expression

5. Logical expressions
Logical expressions combine two or more relational
expressions and produce bool type results. Examples:
a>b && x==10
x==10 || y==5
6. Bitwise expressions
An expression that involves one or more bitwise operator
and produce an integral value. Examples:
!a << 4
a&b

69
Side Effects

When the very act of evaluating an expression changes the


value of data in memory, we say the evaluation has a side
effect.
Thus, evaluating an assignment expression has the side effect
of changing the assignee’s value.
x=y + 2.5*y; // the expression has a side effect
y=--a + (3 + b) /2 – c++; //The expression has three side effects
y*x + 3.5 //?

Note: In C++, if an expression variable is modified more than


once in an expression, the result is undefind.
70
Mixed Expression
An expression that involves more than one data type is called
mixed expression.
When the operands of an operator are of different type, the
operands must be converted so that they are the same type. There
are two rules.
1. Rule in evaluating expression(Implicit type conversion)
• If the two values are both floating types– float, double, or long
double– but of different precision, the type of the value with
lower precision is implicitly promoted to the type of the value
with higher precision.
• If the values are both integral type,
 Integer types smaller than int are promoted to int when an
operation is performed on them
 Then the operand with the type of lesser integer
conversion rank is converted to the type of the operand
with greater rank.

71
Mixed…

• If one of the value is a floating point type and the other is an


integral type, the integral type is implicitly converted to the
floating type.
2. Rule for conversion of Assignment Expression
In evaluating assignment expression, if the expression on the right
side when evaluated is not the same as the type on the left of the
operator, the value of the right expression is implicitly converted to
the type of the left-side variable.
Example:
float e=2.53;
int r;
r = 250 + e*10; //the type of the evaluated expression?
//type assigned to r
72
Mixed…

The left expression evaluates to a float. The left variable is an int


type. The value of the right expression will be converted to the
left type. What value is stored in r?

Note: As long as the size of the variable on the left of the


assignment operator is the same or larger than the size of the
expression value, the conversion is safe. Otherwise an invalid
result may be stored on the left variable.

Reading Assignment: Read about wrapping signed integer

73
Statements

• Statements represent the lowest-level building blocks of a


program.
• Each statement represents a computational step which has a
certain side-effect.
• Statements are useful because of the side-effects they cause,
the combination of which enables the program to serve a
specific purpose.
A statement can be simple or compound.
A simple statement is a computation terminated by a semicolon.
Example:
int i; // declaration statement
++i; // this has a side-effect
double d = 10.5; // declaration statement
d + 5; // useless statement!
74
Statements
A null statement is the simplest statement that consists of just a
semicolon. Example:
; // null statement
It has an application in some loop construction.
A compound or block statement Is a sequence of single
statements between braces, as shown in this example:
{
statement1;
statement2;
.
.
last statement;
}
Compound statement allow us to put multiple statements in
places where otherwise only single statements are allowed.

75
Input and Output

A program is a data processor. It takes input data, process


data and create output. Therefore your program, to do a
useful job, it must be connected to input and output devices.

76
Stream, Data Source and
Destination
A stream is an abstract representation of an input
or output
A stream is an abstract channel or conduit where
data are passed to data destination from data
source.
Input(data source): A stream that flows from an
input device ( i.e.: keyboard, disk drive, network
connection) to main memory(or your program)
Output(data destination): A stream that flows from
main memory(or your program) to an output
device ( i.e.: screen, printer, disk drive, network 77
connection)
Data Source

data source:

input device device driver input library

our program

output library device driver output device

data destination:
78
Standard Streams

C++ automatically defines four standard streams called console


input, console output, console error, and console log.
The console input is associated with the standard input
(keyboard). It is named as cin.
The console output, console error, and console log are connected
to the standard output (monitor). They are named as cout, cerr
and clog respectively.
The difference between console error and console log is that
console error is unbuffered; that is the error is displayed on the
console in immediately after it is written, while the console log is
buffered, therefore, it does not display on the console until the
buffer is full.
79
Using the Standard Streams

To perform input–output, we must make the standard library


iostream object available to our program. We do that by
using the include preprocessor directive
#include <iostream>
Code Block or Dave
using namespace std;
Or
Turbo
#include <iostream.h>

Among other things the header file iostream contains the


declaration of cin, cout, cerr, and clog. By including this file
you make this objects available to your program.
80
Writing data to Standard Output

The insertion operator(<<) can be used with cout to write the


standard output. The general syntax is:
cout << expression or manipulator << expression or manipulator…;
Where expression is the expression to be evaluated and displayed
and manipulator is used to format the output.
The operator << returns their left operand as their result,
enabling multiple output operations to be combined into one
statement.
Example
cout << “Hello world\n”; //prints “Hello World” on the screen
cout << “Hello world” << endl; //prints “Hello World”
cout << "Hello, I am " << age << " years old and my
postal code is " << pincode;
81
Example
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
double sale;
char first;
num1 = 4;
cout << "num1 = " << num1 << endl;
num2 = 4 * 5 - 11;
cout << "num2 = " << num2 << endl;
sale = 0.02 * 1000;
cout << "sale = " << sale << endl;
first = 'D';
cout << "first = " << first << endl;
return 0;
}

82
Writing…
Some manipulator to use
Manipulator Scope Use
endl One time New line
fixed permanent Displays a floating number in fixed
format.
scientfic permanent Display in scientific format
showpoint permanent Shows decimal in floating point values
cout.setf(ios::left) permanent Right justify text in width area
cout.setf(ios::right) permanent Right justify text in width area
setw(…) One time Set width of output fields
setprecision(…) permanent Sets number of decimal for floating point
setfill(…) permanent Specifies fill character.

83
Writing…
Additional manipulators in the iomanip header file
Manipulator Scope Use
setw(…) One time Set width of output fields
setfill(…) permanent Specifies fill character.
right permanent Sets right alignment
left permanent Sets left alignment
fixed Permanent Display floating numbers in scientific format
scientific Permanent Display floating numbers in scientific format
setprecision(…) permanent Sets number of decimal for floating point
oct,hex, dec Permanent number base to be used in displaying integers

84
Example
//Example: using manipulator
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int age = 55;
weight = 89.3456;
cout<<fixed<< setprecision(2);
cout <<left<< setw(20) <<“Name” << ‘\t’ <<“setw(3) <<“Age” << ‘\t’ << setw(10) << “Weight”<<
endl; // Heading
cout << setw(20) << “Kebede Samson” << “\t” << setw(3) << age << ‘\t’<< right << setw(10) <<
weight << endl ;
age = 25; weight = 58.7895;
cout << left<< setw(20) << “Hirut Lemma” << “\t” << setw(3) << age << ‘\t’ << right << setw(10)
<< weight << endl;
age = 45; weight = 75.4378;
cout <<left << setfill(‘*’) << setw(20) << “Dawit Moges” << “\t” << setw(3) << age << ‘\t’ << right
<< setw(10) << setprecision(3)<< weight << endl;
return 0;
}

85
Reading data from Standard Input
The extraction operator(>>) can be used with cin to read formatted
data(the standard data types) from the standard input(keyboard). The
general syntax is:
cin >>var1 >>var2,…;
Where var1, var2, … are variables of any standard types.
When a program reaches a cin statement, it waits for input to be entered
from the keyboard.
The input to cin is buffered. That means the data you type don’t get sent
to the program until you press Enter.
When reading data into a char variable
>> skips leading whitespace, finds and stores only the next character
Reading stops after a single character
To read data into an int or double variable
>> skips leading whitespace, reads + or - sign (if any), reads the
digits (including decimal for float type)
Reading stops on whitespace or non-digit character
86
Reading…
Example:
int n;
char ch;
float f;

statement input effect


cin >>ch A ch=‘A’
cin >>ch AB ch=‘A’, B is held in buffer for latter input
cin >>n 44 n=44
cin >>n 44.35 n=44, .35 is held in buffer for latter input
cin >>f 44.35 f=44.35
cin >>f 44 f=44.0
cin >> ch >> n >>f; A 35 45.36 ch=‘A’, n=35. f=45.36
cin >> n >> ch>>f; 35A45.36 ch=‘A’, n=35. f=45.36
87
Character Input/Output
Character input functions reads one character a time from the keyboard.
Character output functions write one character a time on the screen.
cin.get(): reads the next character from the keyboard and returns its value
through a reference parameter. It can read any character including
whitespace and control characters.
Syntax: cin.get(<character variable name>);
Example:
cin.get(ch); // ch is a character variable to receive the character
cin.put(): writes one character, specified as a parameter, to screen
Syntax: cin.put(<character value>);
Example:
cin.put(ch); //ch is a character variable containing the character to be
written

88
Class Exercise
1. A modern shopkeeper wanted a program that calculates the selling
price of an item given its cost. He expected to gain 15% of the cost as
a profit. The shopkeeper expected you to write this program.
– Identify the input.
– Identify the output.
– Identify the process to change the input to the output (the solution).
– Write the algorithm.
– Translate its algorithm to a C++ code.
– The profit factor is to be literal constant.
2. Modify the above program so that the profit factor is to be declared as
defined constant.
3. Modify the above program so that the profit factor is to be declared as
memory constant.

89
Class Exercise...
4. Write a program that prompts a user to enter the number of second
elapsed for an event and converts this to m hours, n minute and p
seconds. For example if the user enter 7840, the program display
2:10:40.
5. Write a program that prompts a user for an integer value in the range
0 to 32767 and then prints the individual digits of the number on a
line with four spaces between the digits. The first line is to start with
the left most digit and prints all five digits; the second line is to start
with the second digit from the left and print four digits, and so forth.
For example if the user enters 1234, the output looks like
0 1 2 3 4
1 2 3 4
2 3 4
3 4
4
90
Class Exercise...
6. Write a program that asks for a person’s height and weight then
computes the body mass index (BMI) to tell whether the person is
underweight, balanced or overweight. BMI is computed as weight in
kilogram divided by square of height in meters (BMI = weight /
(height)2). An underweight person’s BMI is assumed to be less than 20,
while an overweight persons’ BMI is above 25. A BMI between 20 and
25 is assumed to be a balanced person.
7. Write a program that exchange two integer variables without using a
temporary variable.

91
Assignment
Write a program to create a customer’s bill for a company. The company sells only
five different products: TV, VCR, Remote Controller, CD player and Tape Recorder.
The unit prices are $400.00, $220.00, $300.00, and $150.00 respectively. The tax
rate is 8.25 % of the sale. The program must prompt and read the quantity sold for
each product and produce an output shown below (you may need to use
manipulator functions, IOS class).
QTY DESCRIPTION UNIT TOTAL
PRICE PRICE
_ _____________ _____ _________
XX TV 400.00 XXXX.XX
XX VCR 220.00 XXXX.XX
XX REMOTE CTRLR 35.20 XXXX.XX
XX CD PLAYER 300.00 XXXX.XX
XX TAPE RECORDER 150.00 XXXX.XX
__________
SUBTOTAL XXXX.XX
TAX XXX.XX
TOTAL XXXX.XX
92

You might also like