Chapter 2 Computer Programmingodp
Chapter 2 Computer Programmingodp
[ECEg-1052]
Chapter Two:
Fundamental of C++ Programming
3
Cont’d...
Programming languages (PL)is:
➔
Language used to interact with the computer.
➔
A special purpose and limited language.
➔
A sets of rules and symbols used to construct a computer program.
Three types of programming languages
1. Machine languages
2. Assembly languages
3. High-level languages
4
2.1.1 Machine languages
Provides program instructions in bits.
Strings of numbers giving machine specific instructions.
Uses binary code
Machine-dependent
Not portable
5
Cont’d...
To see how instructions are written in machine language, suppose you
want to use the equation:
wages = rate * hours
In machine language, you might need the following sequence of
instructions to calculate weekly wages:
Suppose that the binary code
➔
100100 stands for load, 100100 010001
➔
100110 stands for multiplication, and 100110 010010
➔
100010 stands for store. 100010 010011
6
2.1.2 Assembly languages
English-like abbreviations representing elementary computer operations.
Uses mnemonics
Machine-dependent
Not usually portable
Assemblers: A program that translates a program written in assembly
language into an equivalent program in machine language.
Using assembly language instructions, you can write the equation to
calculate the weekly wages as follows:
LOAD rate
MULT hours
STOR wages 7
2.1.3 High-level languages
Similar to everyday English, use mathematical notations
➔
translated via compilers
Machine independent
Portable (but must be compiled for different platforms)
Basic, FORTRAN, COBOL, Pascal, C, C++, C#, and Java are all high-level
languages.
In C++, you write the weekly wages equation as follows:
wages = rate * hours;
8
2.2 Algorithm and Flow Charts
2.2.1 Algorithm
A typical programming task can be divided into two phases:
1. Problem solving phase
➔ Produce an ordered sequence of steps that describe solution of
problem this sequence of steps is called an algorithm.
2. Implementation phase
➔ Implement the program in some programming language
9
Cont’d...
10
Cont’d...
Example 1: Write an algorithm to determine a student’s final grade and indicate
whether it is passing or failing. The final grade is calculated as the average of
four marks.
Pseudocode:
3. if average is below 50
Print “FAIL”
else
Print “PASS” 11
Cont’d...
Detailed Algorithm
Step 1: Input M1,M2,M3,M4
Step 2: GRADE ← (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
12
2.2.2 Flow Charts
A flowchart is a graphical representation of an algorithm.
Play a vital role in the programming of a problem and are quite helpful in
understanding the logic of complicated and lengthy problems.
Once the flowchart is drawn, it becomes easy to write the program in any
high level language.
Often we see how flowcharts are helpful in explaining the program to
others.
Hence, it is correct to say that a flowchart is a must for the better
documentation of a complex program.
13
Cont’d...
14
Cont’d...
Flow Chart
START
Input
Lft
Lcm Lft x 30
Print
Lcm
STOP
16
Cont’d...
Steps: Sum := x + y
1. input x, y A := sum/2
3. sum = x + y Write A
5. output average
17
Cont’d...
Example 4: Draw a flowchart to find the sum of first 50 natural numbers.
18
Cont’d...
Example 5: Write an algorithm and draw a flowchart that will read the two sides
of a rectangle and calculate its area.
Pseudocode
• Input the width (W) and Length (L) of a rectangle
• Calculate the area (A) by multiplying L with W
• Print A
Algorithm
Step 1: Input W,L
Step 2: A←L x W
Step 3: Print A
19
3.3 Basic Program Structure
Program:
// A simple C++ program
#include <iostream>
using namespace std;
int main (){
cout << "Programming is great fun!";
return 0;
}
Program output:
Programming is great fun!
20
Cont’d...
Comments
The first line of the above program:
// A simple C++ program
is an example of comment line.
The two slash signs (//) marks the beginning of a comment.
Comments allow the programmer to insert notes or descriptions embedded
within the source code.
21
Cont’d...
C++ supports to insert two ways comments:
1. Single line comment: uses two slash signs (//).
// line comment
2. Multi-line comment: uses /* ……….*/.
/* block
Comment */
22
Cont’d...
Examples:
// This is a single line comment
/* You can write
your comment in
a multiple lines */
23
Cont’d...
Preprocessor directives
The second line:
#include <iostream>
is a preprocessor directive.
When a line begins with a pound sign (#) it indicates it is a preprocessor
directive.
Think of a preprocessor as a program that “sets up” your source code for
the compiler.
24
Cont’d...
The #include directive causes the preprocessor to include the contents of
another file in the program.
Here, iostream standard header file is included.
The iostream file contains codes that allows a C++ program to display
output on the screen and read input from the keyboard.
This program uses cout to display screen output, so the iostream file
must be included.
25
Cont’d...
The main Function
The third line of the above program:
int main ()
Corresponds to the beginning of the main function declaration.
A function can be thought as a group of one or more programming
statements that collectively has a name.
Here, the name of the function is main.
26
Cont’d...
The main function is the point by where all C++ programs begin their
execution.
The int indicates the main function returns an integer value back to the
operating system when it finished executing.
Parenthesis () include arguments within them. Here, no parameter is
included.
27
Cont’d...
The content of the main function is enclosed between curly brackets
({ }).
The above example contains two instruction statements:
cout << "Programming is great fun!";
return 0;
which tells the computer to display
Programming is great fun!
on the screen and terminate the program
28
Cont’d...
A semicolon (;) marks the end of a complete statement in a C++
program.
Comments are ignored by a compiler, so the semicolon is not required
at the end of a comment.
Also the beginning of a function, like int main(), and a preprocessor
directives donot need semicolon at the end.
29
Cont’d...
Exercise
Write a program that will display your name. on the screen. Place a
comment with today’s date at the top of the program.
30
3.2 Define and Declare Variables, Data Types, Constants
31
Cont’d...
Example
//This program has a variable
#include<iostream> Output of the program
using namespace std; The value of the number is number
int main() { The value of the number is 5
int number; The value of the number is 7
number=5;
cout<<"The value of the number is "<<"number"<<endl;
cout<<"The value of the number is "<<number<<endl;
number=7;
cout<<"The value of the number is "<<number<<endl
}
Each variable needs an identifier.
Example:- number, a, b, result, etc. 32
Cont’d...
Identifiers
An identifier is a programmer-defined names that represent some
elements of a program.
Variable names are examples of identifiers.
Keywords or Reserved Words
Variables , function names , labels ….
33
Cont’d...
Some rules that must be followed with all identifiers.
The first character must be one of the letters a through z, A through Z, or an
underscore character (_).
After the first character you may use the letters a through z or A through Z, the
digits 0 through 9, or underscores.
Uppercase and lowercase characters are distinct.
➔
This means ItemsOrdered is not the same as itemsordered.
34
Cont’d...
Examples
Valid Identifiers: Invalid Identifiers:
dayOfWeek, Data-Rec,
my+name,
MYNAME,
4student,
myname,
12,
x,
%change,
x1, 3x,
x_1, myfirst.c
_count,
student4 35
Cont’d...
Another rule is that you should not use any keyword of the C++ language to
define your own identifier.
Examples:
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default,
delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, for, friend,
goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public,
register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch,
template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t
36
Cont’d...
Additionally, alternative representations for some operators do not
have to be used as identifiers since they are reserved words under some
circumstances:
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Also some specific reserved keywords may be used for the compiler .
Example: far, huge and near as key words.
37
Cont’d...
Data Types
Used to tell the type of data to be stored since storing a simple number,
a letter or a large number is not going to occupy the same space in
memory.
Two types
Fundamental and derived data types
Examples
char, short, long, int, float, double, long double, bool, wchar_t
38
Cont’d...
Name Bytes* Description Range*
char 1 character or integer 8 bits length. signed: -128 to 127
unsigned: 0 to 255
short 2 integer 16 bits length. signed: -32768 to 32767
unsigned: 0 to 65535
long 4 integer 32 bits length. signed:-2147483648 to 2147483647
unsigned: 0 to 4294967295
long double 10 long double precision floating point 1.2e + / - 4932 (19 digits)
number.
bool 1 Boolean value. It can take one of two true or false
values
wchar_t 2 Wide character. It is designed as a type wide characters
to store international characters of a 39
two-byte character set.
Declaration of variables
Format:
Type Identifier;
For example:
int a;
float mynumber;
int var1;
A declaration introduces a variable’s name (such as var1) in to a program
and specifies its types(such as int).
40
Cont’d...
To declare several variables of the same type, you can declare all of them in the
same line separating the identifiers with commas.
For example:
int a, b, c;
is the same as
int a;
int b;
int c;
41
Cont’d...
Integer data types (char, short, long and int) can be signed or unsigned.
For example:
unsigned short NumberOfSons;
signed int MyAccountBalance;
By default, if we do not specify signed or unsigned it will be assumed
that the type is signed, therefore in the second declaration we could have
written:
int MyAccountBalance;
42
Initialization of variables
When you want a variable to store a concrete value the moment that is
declared.
Format: type identifier = initial_value ;
Example:
int a = 0;
int age = 6;
int day = 2, month = 3, year = 2006;
char x= ’B’;
43
Cont’d...
Additionally to this way of initializating variables (known as c-like), C++
has added a new way to initialize a variable: by enclosing the initial
value between parenthesis ():
type identifier (initial_value) ;
For example:
int a (0);
Both ways are valid and equivalent in C++.
44
Cont’d...
A variable can be declared any where in the C++ program but before
reference.
C++ allows initialization of a variable at run time and this is called
dynamic initialization.
Example: Some where in your program
float avg;
avg=sum/count or
float avg=sum/count;
45
Scope of variables
All the variables that we are going to use must have been previously
declared.
Variables can be global variables or local variables.
Global variables can be referred to anywhere in the code, within any
function, whenever it is after its declaration.
The scope of the local variables is limited to the code level in which they
are declared.
46
Cont’d...
In C++, the scope of a local variable is given by the block in which it is
declared (a block is a group of instructions grouped together within curly
brackets {} signs).
If it is declared within a function it will be a variable with function
scope.
If it is declared in a loop its scope will be only the loop, etc...
47
Cont’d...
#include <iostream>
Using namespace std;
Int integer;
Char char;
global variables
Int main(){
Int age;
Float number;
local variables
48
Constants
A constant is any expression that has a fixed value.
They can be divided in
➔
Integer constants,
➔
Floating-Point constants,
➔
Characters and
➔
Strings.
49
Integer constants
1776
707
-273
75
To express an octal number we must precede it with a 0 character (zero
character).
EX: 0113
And to express a hexadecimal number we have to precede it with the
characters 0x (zero, x).
EX: 0x4b
50
Cont’d...
For example, the following literal constants are all equivalent to each
other:
75 // decimal
0113 // octal
0x4b // hexadecimal
All of them represent the same number: 75 (seventy five) expressed as a
radix-10 number, octal and hexadecimal, respectively.
51
Floating Point Constants
They express numbers with decimals and/or exponents.
They can include a decimal point, an e character (that expresses "by ten
at the Xth height", where X is the following integer value) or both.
3.14159 // 3.14159
6.02e23 // 6.02 x 1023
1.6e-19 // 1.6 x 10-19
3.0 // 3.0
52
Characters and strings
There also exist non-numerical constants, like:
'z'
'p'
"Hello world"
"How do you do?"
to represent a single character - single quotes (') and to express a string
of more than one character - double quotes (").
53
Cont’d...
Notice this:
x
'x'
x refers to variable x,
'x' refers to the character constant 'x'.
54
Escape sequence
Used to give more control to the output display.
Written by having a control character precede by an inverted slash(\).
Example:
'\n'
'\t'
"Left \t Right"
55
Commonly Used Escape Sequences
Escape Sequence Description
\n Newline Cursor moves to the beginning of the next line
\r Return Cursor moves to the beginning of the current line (not the next line)
56
Cont’d...
To express any character by its numerical ASCII code
●
For octal (radix-8) --- use an inverted slash (\)
●
For hexadecimal (radix-16) --- use \x
For example:
●
Octal: \23 or \40
●
Hexadecimal: \x20 or \x4A
DEC OCT HEX
A 65 101 41
B 66 102 42
! 33 041 21
= 61 075 3D 57
Cont’d...
To display A
●
\101 // octal
●
\x41 // hexadecimal
For example:
cout<<“\101 ”<<endl;
cout<<“\x41”<<endl;
Output:
A
A
58
Cont’d...
Constants of string of characters can be extended by more than a single
code line if each code line ends with an inverted slash (\):
"string expressed in \
two lines"
59
Defined constants (#define)
Example:
61
Cont’d...
Example: Write a C++ program to add two integers.
// Addition program
#include <iostream>
Using namespace std; Output:
int main (){ Enter first integer:
int num1;
12
int num2;
int sum; Enter second integer:
cout<<"Enter first integer:\n" ; 34
cin>>num1;
cout<<"Enter second integer: \n";
Sum is 46
cin>>num2;
sum=num1+num2;
cout << “Sum is " << sum;
return 0;
} 62
3.3 Operators, expressions and statements
An expression can be defined as the combination of operators and
operands which yields a single value.
The operand is a constant or variable value which is manipulated in an
expression.
The operator defines the method by which its operands will interact.
A statement ends in a semicolon (;) and contains keywords, expressions,
and other statements.
63
Cont’d...
An operator is a symbol that tells the computer to perform
certain mathematical (or) logical manipulations.
Operators used in programs to manipulate data and variables.
64
1. Arithmetic operators
Are operators to add (+), subtract (-), multiply (*), divide (/), and mod (%).
mod gives remainder of division.
Example:
cout<<6%8<<endl;
if a = 11;
cout<<8%8<<endl;
b = 3;
cout<<10%8<<endl;
c = a % b;
Output: 6
»c = 2; 0
2
65
2. Relational operators
Are used to evaluate a comparison between two expressions.
== Equal
!= Different(Not equal)
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
The result of a relational operation is a bool value that can only be true
or false, according to the result of the comparison.
66
Cont’d...
/*A program to display values of true and false state */
#include <iostream>
using namespace std; Output
int main () { value1 is 1
bool value1, value2; value2 is 0
int x=5, y=10;
value1=(x<y);
value2=(y==x);
cout << "value1 is " << value1;
cout << "\n value2 is " << value2;
return 0;
}
67
Cont’d...
we can use numeric constants, any valid expression, including variables.
Example: 5 < 4 → would return false.
If a=2, b=3 and c=6,
➔
(a == 5) would return false.
➔
(a*b >= c) would return true since (2*3 >= 6).
➔
((b=2) == a) would return true. Be aware.
•
The first (=) is an assignation operator and the other (==) is a relational operator of
equality.
68
3. Logical operators
C++ has the following three logical operators.
&& (logical AND),
|| (logical OR),
! (logical NOT).
Truth table for AND and OR operations:
First Operand a Second Operand b Result a && b Result a || b
true true true true
true false false true
false true false true
false false false false
Example:
( (5 == 5) && (3 > 6) ) returns false ( true && false ).
( (5 == 5) || (3 > 6)) returns true ( true || false ).
69
4. Assignment operators
Used to assign the result of an expression to a variable and the symbol
used is ‘= ‘
It is of 3 types:
A. Simple assignment
B. Multiple assignment
C. Compound assignment
70
A. Simple assignment
The assignation operator serves to assign a value to a variable.
Example:
a = 5; assigns the integer value 5 to variable a.
a = 2 + (b = 5); is equivalent to:
b = 5;
a = 2 + b;
71
B. Multiple assignment
Example:
a = b = c = 5;
assigns 5 to the three variables a, b and c.
72
C. Compound assignment
+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=
value += increase; is equivalent to
value = value + increase;
Example:
Sum+=N; //Sum=Sum+N;
a -= 5; //a = a - 5;
a /= b; //a = a / b;
price *= units + 1; //price = price * (units + 1);
73
5. Auto increment / decrement
(+ + / - - )
Used to add /subtract 1 from their operands
There are 2 types
1. Prefix auto increment / decrement
74
1. Prefix auto increment / decrement
Adds /subtracts 1 to the operand & result is assigned to the variable on
the left.
Example:
a = 5; a=5;
b=++a; b=--a;
75
2. Postfix auto increment / decrement
First assigns the value to the variable on the left & then
increments/decrements the operand.
Example:
a = 5; a=5;
b=a++; b=a--;
Results: b=5, a=6 b=5, a=4;
a=a+1 can be written as ++a, a++ or a+=1.
a=a-1 can be written as a--, --a or a -= 1.
76
Cont’d...
Example:
// Program to demonstrate increment and decrement operators.
#include<iostream>
Using namespace std;
int main(){
int var1=10,var2=1;
cout<<"var1 is "<<var1<<" and var2 is "<<var2<<endl;
var1++;
var2--;
cout<<"var1 is "<<var1<<" and var2 is "<<var2<<endl;
77
Cont’d...
++var1;
--var2;
cout<<"var1 is "<<var1<<" and var2 is "<<var2<<endl;
int var3, var4;
var3=++var1; Output:
var4=var1++;
cout<<"var1 is "<<var1<<endl;
cout<<"var3 is "<<var3<<endl;
cout<<"var4 is "<<var4<<endl;
return 0;
}
78
6. Conditional operator (?)
Format:
condition ? result1 : result2;
■ If condition is true the expression will return result1, if not it will return
result2.
Example:
a=10;
b=15;
x = (a>b) ? a : b;
in this example x will be assigned the value of b.
79
7. Bitwise operators
Bitwise operators: ( &, |, ^, ~, <<, >> )
Modify variables considering the bits that represent the values that they
store, that means, their binary representation.
a. bitwise and ( & )
a=8 1000 b. bitwise or ( | )
80
Cont’d...
c. bitwise Xor (^ ) : If one is 0 and the other is 1, then resulting bit is 1, if
both are same then result is 0.
a=8 1000
b=3 0011
1011
d. one’s complement ( ~ )
81
Cont’d...
e. bitwise shift operators:
(1) (<<) shift left – shifts bits to left
Ex: a=8, b=2; //a= 00001000
c=a<<b; //c=00100000
(2) (>>) Shift right – shifts bits right
Ex: a=8, b=2; //a= 00001000
c=a>>b; //c=00000010
82
Explicit type casting operators
Allow to convert a datum of a given type to another.(we use parenthesis
() ).
Example:
int i;
float f = 3.14;
i = (int) f; //i=3
Or i = int ( f ); //i=3
83
sizeof()
Accepts one parameter, that can be either a variable type or a variable
itself and returns the size in bytes of that type or object:
Example:
a = sizeof (char);
b = sizeof (int);
84
Priority of operators
When making complex expressions with several operands, we may have
some doubts about which operand is evaluated first and which later.
There is an established order with the priority of each operator.
See table on next slides (from greatest to lowest priority).
85
Cont’d...
Priority Operator Description Associativity
1 :: scope Left
2 () [ ] -> . sizeof Left
++ -- increment/decrement
Complement to one
~
(bitwise)
! unary NOT
3 Right
Reference and
&*
Dereference (pointers)
= += -= *= /= %=
12 Assignation Right
>>= <<= &= ^= |=
88
Cont’d...
Example: Output:
#include<iostream>
Using namespace std;
580
int main(){ 15
int a=20, b=30, c=40, d,e,f;
0
d=a+a*b-c;
e=a*b/c;
f=(a*(b/c));
cout<<d<<endl;
cout<<e<<endl;
cout<<f<<endl;
return 0;
}
89
Cont’d...
Note: a=20, b=30, c=40
d=a+a*b-c;
a*b ---- a add ---c subtracted //* preced + and -
e=a*b/c;
a*b ---- division by c //left associtivity
f=(a*(b/c));
b/c---- a multiplied to result //parenthesis
90
3.4 Communication through console
The console is the basic interface of computers, normally it is the set
composed of the keyboard and the screen.
In the iostream C++ library, two data streams:
➔
cin for input and
➔
cout for output.
91
Output (cout)
The cout with the overloaded operator << (known as insertion
operator) is used.
Example:
cout << "Output sentence";
93
Cont’d...
The insertion operator (<<) may be used more than once in a same
sentence:
cout << "Hello, " << "I am " << "a C++ sentence";
Print the message
Hello, I am a C++ sentence on the screen.
94
Cont’d...
The utility of repeating the insertion operator (<<) is demonstrated
when we want to print out a combination of variables and constants or
more than one variable:
Example:
cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;
Hello, I am 24 years old and my zipcode is 90064
95
Cont’d...
cout does not add a line break after its output unless we explicitly
indicate it, therefore, the following sentences:
cout << "This is a sentence.";
cout << "This is another sentence.";
will be shown followed in screen:
This is a sentence.This is another sentence.
96
Cont’d..
So, in order to perform a line break on output we must explicitly order it
by inserting a new-line character, that in C++ can be written as \n:
cout << "First sentence.\n ";
cout << "Second sentence.\nThird sentence.";
produces the following output:
First sentence.
Second sentence.
Third sentence.
97
Cont’d...
Additionally, to add a new-line, you may also use the endl manipulator.
For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
would print out:
First sentence.
Second sentence.
98
Input (cin)
Is done by applying the overloaded operator of extraction (>>) on the
cin stream.
This must be followed by the variable that will store the data that is
going to be read.
Example:
int age;
cin >> age;
Declares the variable age as an int and then waits for an input from cin
(keyborad).
99
Cont’d...
You can also use cin to request more than one datum input from the user:
cin >> a >> b;
is equivalent to:
cin >> a;
cin >> b;
100
Cont’d...
// i/o example
#include <iostream>
Using namespace std;
int main (){
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ‘.’;
return 0;
}
101
Thank You !
102