Cs201 All PPT Slides
Cs201 All PPT Slides
Lecture No. 1
Program
“A precise
sequence of
steps to
solve a
particular
problem”
Alan Perlis – Yale University:
STUPID
Humans are even
more…….
Think Reuse
Area of the Ring
Inner Circle
Outer Circle
Area of Outer Circle ____ Area of Inner Circle = Area of the Ring
Think Reuse
Think User Interface
Comments liberally
What is the probability that she gets
exactly three letter right i.e. three
Letters into their correct envelopes.
Logical Error
Lewis Carol: “Through the Looking Glass”
Group discussion 5%
Midterm 35 %
Final 45 %
Books
Deitel & Deitel :– C++ How to Program
Kernighan and Ritchie:-
The C Programming Language
Course Objectives
Objectives of this course are three fold
1. To appreciate the need for a
programming language
2. To introduce the concept and usability
of the structured programming
methodology
3. To develop proficiency in making useful
software using the C language
Course Contents
To achieve our first two objectives we
will be discussing
Basic Programming constructs and
building blocks
Structured programming
Lecture 2
Today’s Lecture
Software Categories
System Software
Application Software
Evolution
Justification
System software
Application Software
TWAIN
Editor
Interpreter and Compilers
Debuggers
Integrated Development Environment
(IDE)
It contains
Editor
Compilers
Debugger
Linkers
Loaders
Program is created in the
Editor Disk editor and stored on disk.
Preprocessor program
Preprocessor Disk processes the code.
Compiler creates
Compiler Disk object code and stores
it on disk.
Linker Disk Linker links the object
code with the libraries
Primary Memory
Loader
Loader puts program
in memory.
Disk ..
..
..
Primary Memory
CPU takes each
CPU instruction and
executes it, possibly
storing new data
..
..
values as the program
..
executes.
Introduction to Programming
Lesson 3
#include <iostream.h>
main ( )
{
cout << “ Welcome to Virtual University “;
}
Variable
Variable X
Variable
Pic of the memory
25
name
10323 of the
variable
Variable
Variable starts with
1. Character
2. Underscore _ (Not Recommended)
Variable
Small post box
X
Variable
Variable is the name of a location in
the memory
e.g. x= 2;
Variable
In a program a variable has:
1. Name
2. Type
3. Size
4. Value
Assignment Operator
=
x=2
X
2
Assignment Operator
L.H.S = R.H.S.
X+ 3 = y + 4 Wrong
Z = x +4
x +4 = Z Wrong
X = 10 ; X 10
X = 30 ;
X 30
X = X + 1;
X
10 + 1
= 11
X
Data type
int i ; ->
Declaration line
i
#include <iostream.h>
main ( )
{
int x ;
int y ;
int z ;
x = 10 ;
y = 20 ;
z=x+y;
Divide /
Modulus %
Arithmetic operators
i+j
x*y
a/b
a%b
% = Remainder
5%2=1
2%2=0
4/2=2
5/2=?
Precedence
Highest: ()
Next: *,/,%
Lowest: +,-
Introduction to Programming
Lecture 4
Key Words of C
main
if
else
while
do
for
Memory
x=2+4;
= 66 ;
Memory
a b
x=a+b;
x
#include <iostream.h>
main ( )
{
int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10 ;
int TotalAge ;
int AverageAge ;
In C
y = a*x*x + b*x + c
a*b%c +d
a*(b%c) = a*b%c
?
Discriminant
b2 - 2a
4c
= b*b - 4*a*c /2 *a Incorrect
answer
Solution
}
Special Character Newline
\n
Introduction to Programming
Lecture 5
In the Previous Lecture
Basic structure of C program
Variables and Data types
Operators
‘cout’ and ‘cin’ for output and input
Braces
Decision
If Statement
If condition is true
statements
If (condition)
statement ;
If Statement in C
If ( condition )
{
statement1 ;
statement2 ;
:
}
If statement in C
if (age1 > age2)
cout<<“Student 1 is older
than student 2” ;
Relational Operators
< less than
<= less than or equal to
== equal to
>= greater than or equal to
> greater than
!= not equal to
Relational Operators
a != b;
X = 0;
X == 0;
Example
#include <iostream.h>
main ( )
{
int AmirAge, AmaraAge;
AmirAge = 0;
AmaraAge = 0;
Process
Flow line
Continuation mark
Decision
Flow Chart for if statement
Entry point for IF block
IF
Condition
Then
Process
AND &&
OR ||
Logical Operators
If a is greater than b
AND c is greater than d
In C
if(a > b && c> d)
if(age > 18 || height > 5)
if-else
if (condition)
{
statement ;
-
-
}
else
{
statement ;
-
-
}
if-else Entry point for IF-Else block
IF
Condition
Then
Process 1
Else
Process 2
!true = false
!false = true
If (!(AmirAge > AmaraAge))
?
Example
?
Nested if
If (age > 18)
{
If(height > 5)
{
:
}
}
Make a flowchart of this nested if
structure…
In Today’s Lecture
Decision
– If
– Else
Flowcharts
Nested if
In the last lecture
Conditional Construct
if
if-else
Loop - Repetition
structure
Example
int sum ;
sum = 1+2+3+4+5+……..+10 ;
cout << sum ;
Find the Sum of the first 100
Integer starting from 1
?
while
while ( Logical Expression )
{
statements;
:
}
int sum ;
sum = 0 ;
int sum = 0; ( Optional )
Example
int sum , number ;
sum = 0 ;
number = 1 ;
while ( number <= 1000 )
{
sum = sum + number ;
number = number + 1 ;
}
cout << “ The sum of the first 1000 integer starting from 1 is ” << sum ;
while (number <= UpperLimit)
Example
int sum, number , UpperLimit ;
sum = 0 ;
number = 1 ;
cout << “ Please enter the upper limit for which you want the sum ” ;
cin >> UpperLimi t;
while (number <= UpperLimit)
{
sum = sum + number ;
number = number +1 ;
}
cout << “ The sum of the first ” << UpperLimit << “ integer is ” << sum ;
if ( number % 2 == 0 )
{
sum = sum + number ;
number = number + 1 ;
}
Example
sum = 0;
number = 1;
cout << “ Please enter the upper limit for which you want the sum ”;
cin >> UpperLimit;
while (number <= UpperLimit)
{
if (number % 2 == 0)
{
sum = sum + number;
number = number + 1;
}
}
cout << “ The sum of all even integer between 1 and ” << UpperLimit << “ is” <<
sum;
2 * ( number / 2 ) ;
?
int Junk ;
Junk = 1 ;
while ( Junk <= UpperLimit ) ( infinite loop ) X
{
sum = sum + number ;
number = number + 1 ;
}
Flow Chart for While Construct
WHILE Statement
Condition is No
While Exit
true?
Process
n! = n*(n-1)*(n-2)*(n-3)…………*3*2*1
Example: Factorial
#include <iostream.h>
main ( )
{
int number ;
int factorial ;
factorial = 1 ;
cout << “Enter the number of Factorial” ;
cin >> number ;
while ( number >= 1 )
{
factorial = factorial * number ;
number = number – 1 ;
}
cout << “Factorial is” << factorial ;
}
Property of While
Statement
Lecture 7
while loop
while (condition)
{
statements;
:
}
statements;
While loop executes zero
or more times. What if we
want the loop to execute
at least one time?
do-while
Do while loop execute on
or more times
Syntax of do-while loop
do
{
statements ;
}
while ( condition ) ;
Example-Guessing game
char c ;
int tryNum = 1 ;
do
{
cout << "Please enter your guess by pressing a character key from a to z “ ;
cin >> c ;
if ( c == 'z‘ )
{
cout << "Congratulations! you guessed the right answer“ ;
tryNum = 6 ;
}
else
tryNum = tryNum + 1 ;
} while ( tryNum <= 5 ) ;
Flow chart for do-while loop
Do-while
Process
false
condition Exit
true
Relational Operators
char c ;
int tryNum , maxTries ;
tryNum = 1 ;
maxTries = 5 ;
cout << "Guess the alphabet between a to z “ ;
cin >> c ;
while ( ( tryNum <= maxTries ) && ( c! = ‘z‘ ) )
{
cout << "Guess the alphabet between a
to z “ ;
cin >> c ;
tryNum = tryNum + 1 ;
}
for Loop
For loop
Output
0123456789
Table for 2
2x1=2
2x2=4
2x3=6
:
:
2 x 10 = 20
Example - Calculate Table for 2
#include <iostream.h>
main ( )
{
int counter ;
for ( counter = 1 ; counter <= 10 ; counter = counter + 1 )
{
cout << "2 x " << counter << " = " << 2* counter << "\n“ ;
}
}
Output
2 x1 = 2
2x2=4
2x3=6
:
:
2 x 10 = 20
Flow chart for the ‘Table’ example
Start
counter=1
While
No Exit
counter <=10?
yes
Print 2*counter
Counter =
counter + 1
Stop
Example: Calculate Table- Enhanced
#include <iostream.h>
main ( )
{
int number ;
int maxMultiplier ;
int counter ;
maxMultiplier = 10 ;
cout << " Please enter the number for which you wish to construct the table “ ;
cin >> number ;
for ( counter = 1 ; counter <= maxMultiplier ; counter = counter + 1 )
{
cout << number <<" x " << counter<< " = " << number * counter << "\
n“ ;
}
}
Always think re-use
Don’t use explicit constants
Increment operator
++
counter ++ ;
same as
counter = counter + 1;
Decrement operator
--
counter -- ;
same as
counter = counter - 1
+=
counter += 3 ;
same as
counter = counter + 3 ;
-=
counter -= 5 ;
same as
counter = counter – 5 ;
*=
x*=2
x=x*2
/=
x /= 2
x=x/2
Compound Assignment
Operators
operator=
%=
x %= 2 ;
same as
x=x%2;
Comments
Write comment at the top
program to show what it does
Write comments that mean some
thing
In today’s lecture
Do - while
– Executes the code at least ones
For loop
– Executes at least zero times
Short hand operators
– Incrementing
– Decrementing
Compound assignment operator
Introduction to Programming
Lecture No. 8
In the last lecture
Loops
– While
– Do while
– For
Operators
– Increment / Decrement
– Compound Assignment Operators
Example: Program to calculate
the average marks of class
int sum;
int students ;
int average ;
sum = 0 ;
students = 0 ;
do
{
cin >> grade ;
sum += grade ;
students ++ ;
}
while (grade >= 0) ;
average = sum / students ; A Flaw in the code
cout << average ;
Multi-way decision
if Statements
if ( grade ==‘A’ )
cout << “ Excellent ” ;
if ( grade ==‘B’ )
cout << “ Very Good ” ;
if ( grade ==‘C’ )
cout << “ Good ” ;
if ( grade ==‘D’ )
cout << “ Poor ” ;
if ( grade ==‘F’ )
cout << “ Fail ” ;
if else
if ( grade ==‘A’ )
cout << “ Excellent ” ;
else
if ( grade ==‘B’ )
cout << “ Very Good
”;
else
if ( grade ==‘C’ )
cout << “ Good ” ;
else
if ( grade ==‘D’ )
cout << “ Poor ” ;
if else
if ( grade == ‘A’ )
cout << “ Excellent ” ;
else if ( grade == ‘B’ )
…
else if …
…
else …
switch statement
switch statements
switch ( variable name )
{
case ‘a’ :
statements;
case ‘b’ :
statements;
case ‘c’ :
statements;
…
}
switch statements
switch ( grade)
{
case ‘A’ :
cout << “ Excellent ” ;
case ‘B’ :
cout << “ Very Good ” ;
case ‘C’ :
…
…
}
switch statements
case ‘A’ :
cout << “ Excellent ” ;
…
…
Example
switch ( grade)
{
case ‘A’ :
cout << “ Excellent ” ;
case ‘B’ :
cout << “ Very Good ” ;
case ‘C’ :
cout << “Good ” ;
case ‘D’ :
cout << “ Poor ” ;
case ‘F’ :
cout << “ Fail ” ;
}
break;
Example
switch ( grade )
{
case ‘A’ :
cout << “ Excellent ” ;
break ;
case ‘B’ :
cout << “ Very Good ” ;
break ;
case ‘C’ :
cout << “Good ” ;
break ;
case ‘D’ :
cout << “ Poor ” ;
break ;
case ‘F’ :
cout << “ Fail ” ;
break ;
}
default :
default :
cout << “ Please Enter Grade
from ‘A’ to ‘D’ or ‘F’ “ ;
Flow Chart of switch statement
switch (grade)
case ‘A’ :
Display
“Excellent”
case ‘B’ :
Display
“Very Good”
…
Default :
“……..”
if ( amount > 2335.09 )
statements ;
Whole Number
short
int
long
case ‘A’ :
case ‘ 300 ‘ :
case ‘ f ‘ :
break ;
if (c == ‘z’ )
{
cout << “ Great ! You have made the correct guess “ ;
break ;
}
continue ;
continue
while trynum <= 5 ;
{
….
….
continue ;
}
continue in ‘for’ loop
Sequential Statements
Decisions
– if , if else , switch
Loops
– while , do while , for
goto
Unconditional Branch of Execution
Structured Programming
Sequences
Decisions
Loops
Minimize the use of break
Minimize the use of continue
Never use goto
Guide lines for structured
programming
Modular
Single entry - single exit
Rules for Structured
Flowchart
Rule 1 : Use the simplest flowchart
Rule 2 : Any rectangle can be replaced by
two rectangles.
Rule 3 : Any rectangle can be replaced with
structured flowcharting constructs.
Rule 4 : It says, rule 2 and rule 3 can be
repeated as many times as needed
Next Milestones
Data Structures
– Arrays
Character Strings
Pointers
Introduction to Programming
Lecture 9
Programming Toolkit
Decisions
Loops
Sequences
Laboratory Stool
Constructing a laboratory Stool
Constructing a laboratory
Stool
void main ( )
{
….
}
Definition of Function
int x ;
x = square ( i ) ;
Example: Function to calculate
integer power ( Xn )
double raiseToPow ( double x , int power )
{
double result ;
int i ;
result = 1.0 ;
for ( i = 1 ; i <= power ; i ++ ) // braces first
{
result * = x ; // result = result *x
}
return ( result ) ;
}
Code to Call the raisetopow
Function
include < iostream.h >
void main ( )
{
double x ;
int i ;
cout << “ Please enter the number “ ;
cin >> x ;
cout << “ Please enter the integer power that you want this number raised to “ ;
cin >> i ;
cout << x << “ raise to power “ << i << “is equal to “ << raiseToPow ( x , i ) ;
}
Call By Value
Calling function
Called function
Area of the Ring
Inner Circle
Outer Circle
Area of Outer Circle ____ Area of Inner Circle = Area of the Ring
Example: Function to calculate
the area of a circle
}
Exercises
1. Modify the raise to power function
so that it can handle negative power
of x, zero and positive power of x.
Lecture 10
Today's Lecture Includes
Header Files
Scope of Variables
Functions
– Call by value
– Call by reference
Header Files
#include <iostream.h>
Prototype
Assignment List
Return value
with data type
Circumference = 2 * pi * radius
Scope of Identifiers
Identifier is any name user creates in his/her
program
cout << “ The current value of “ << number << “is “ << number ;
}
Math.h
#include < math.h >
double sqrt ( double );
main ( )
{
double x = 123.456 ;
square ( &x ) ;
}
Value of ‘x’ is not passed , but the
memory address of ‘x’ is passed
Example: Call by Reference
x10 = x * x9
x9 = x * x8
x8 = x * x7
……
xn = x * xn-1
Recursive Functions: Factorial
n! = n * (n-1) * (n-2) …….. 3 * 2 * 1
5! = 5 * 4 * 3 * 2 * 1
4! = 4 * 3 * 2 * 1
5! = 5 * 4!
0! = 1
Recursive Functions: Factorial
Fibonacci series
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Management Issues of
Computer
There are two issues inside a computer
Memory overhead
Stack overhead
Programming Options
Elegant code
where price is not too high
Efficient code
where price is too high
What have we Done Today …
Header Files
– Nice mechanism of putting all prototypes
and definitions of global constants etc.
Scope of variables
Functions
– Call by value
– Call by reference
Recursion
Introduction to Programming
Lecture 11
ARRAYS
Arrays
They are special kind of data type
They are like data structures in which
identical data types are stored
In C each array has
– name
– data type
– size
They occupy continuous area of
memory
Storage of an array in memory
Name memory
C[0] 24
C[1] 59
C[2] 35
C[3] ...
C[4] ...
C[5] ...
C[6] ...
C[7] ...
C[8] ...
C[9] ...
Index
Declaration of Arrays
arrayType arrayName[numberOfElements ];
For example ,
int age [ 10 ] ;
age [ 4 ]
Example1: Using Arrays
for ( i = 0 ; i < 10 ; i ++ )
{
cin >> age [ i ] ;
}
Example 2
totalAge = 0 ;
for ( i = 0 ; i < 10 ; i ++ )
{
totalAge + = age
[i];
}
Initializing an Array
int age [ 10 ] ;
for ( i = 0 ; i < 10 ; i ++ )
{
age [ i ] = 0 ;
}
Initializing an Array
int age[ 10 ] = { 0 } ;
Initializing an Array
int age [ ] =
{ 1,2,3,4,5,6,7,8,9,10 } ;
for ( i = 0 ; i < 10 ; i ++ )
‘ i ‘ will have value from 0 to 9
Example: 3
#include < iostream.h >
main ( )
{
int c [ 100 ] ;
Example: 3
int z , i = 0 ;
do
{
cin >> z ;
if ( z != -1 )
c[ i ] = z ; assignment statement
Example 3
i ++ ;
} while ( z != -1 && i < 100 ) ;
cout << “ The total number of positive
integers entered by user is “ << i -1;
}
Copying Arrays
– Data types should be
identical
b[0]=a[0];
b[1]=a[1];
b[2]=a[2];
b[3]=a[3];
………
………
b [ 10 ] = a [ 10 ] ;
Copying Arrays
for ( i =0 ; i < 10 ; i ++ )
b[i]=a[i];
Example: 4
Take the sum of squares of 10 different
numbers which are stored in an array
int a [ 10 ] ;
int arraySize =10 ;
int sumOfSquares = 0 ;
for ( i = 0 ; i < arraySize ; i ++ )
{
sumOfSquares = sumOfSquares + a [ i ] * a [ i ] ;
}
Example 5
int z ;
int a [ 100 ] ;
for ( i = 0 ; i < 100 ; i ++ )
{
a[i]=i;
}
cout << “ Please enter a positive integer “ ;
cin >> z ;
int found = 0 ;
Example 5
for ( i =0 ; i < 100 ; i ++ )
{
if ( z == a [ i ] )
{
found = 1 ;
break ;
}
}
Example 5
if ( found == 1 )
cout << “ We found the integer at position ” << i
;
else
cout << “ The number was not found” ;
rand ( )
# include < stdlib.h >
0 - 32767
Calling rand ( )
x = rand ( ) ;
rand ( ) % 6 = ?
Result has to be between 0 and 5 inclusive
1 + rand ( ) % 6
rand ( ) % 2 ;
Importance of rand ( )
It is shipped in every standard library with
compiler
data type
name
size
const
const
const int arraySize = 100 ;
Lecture 12
Today’s Lecture Includes
\t Tab Character
\0 Null Character
int c [ 10 ] = { 1,2,3,4,5,6,7,8,9,10 } ;
int c [ ] = { 1,2,3,4,5,6,7,8,9,10 } ;
int equal = 0 ;
int num1 [ 100 ] , num2 [ 100 ] ;
for ( i = 0 ; i < 100 ; i ++ )
{
if ( num1 [ i ] != num2 [ i ] )
{
equal = 1 ;
break ;
}
}
if ( equal ==1 )
cout << “ The arrays are not equal” ;
else
cout << “ The arrays are equal” ;
Comparing Two Arrays
AZMAT HAMEED
Azmat Hameed
Exercise
Input your name and display it in
reverse order
Quick Sort
Brute-Force
Technique
[0] 4
[1] 23
[2] 9
[16] 1
[99] 67
Swapping
[0] 66
Memory
[1] 44
Location
[2] 33
66
[16] 3
[99] 100
Swapping Two
Numbers
int num [ ] ;
int x ;
x = num [ 0 ] ;
num [ 0 ] = num [ 15 ] ;
num [ 15 ] = x ;
Binary Search Algorithms
Divide and Conquer rule
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4
Binary Search Algorithm
If we think about it , it is
logn log2
1
2 Linear Search ?
3
Binary Search ?
Suppose they are Random
100 Suppose they are Ordered
Suppose they are mixed-up
Functions and Arrays
Sending Arrays into
Another Functions
Declaration
char name [ 100 ] ;
Function Call
Definition
void reverse ( char characters [ ] , int arraySize)
{
reverse the character string;
}
Example 1
main ( )
{
cin >> name [ ] ;
reverse ( character [ ] , arraySize ) ;
cout << name [ ] ;What will it
Show ?
}
Call by Reference
& Address Operator
* Pointer Operator
name
Example 2
void f ( int [ ] , int ) ;
main ( )
{
int numbers [ 100 ] ;
f ( numbers , 100) ;
for ( int i = 0 ; i < 100 ; i ++)
cout << numbers [ i ] ;
}
Example 2
void f ( int x [ ] , int arraySize )
{
int i ;
for ( i = 0 ; i < arraySize ; i ++)
x[i]=i;
}
f(x[3]);
Executed with call by
value, not by reference
Whenever a variable is passed , it
is passed by value
Whenever you pass an array to
Dot Product
Vector Product
Matrix
Rows
Columns
Two Dimensional
Array
int x [ 2 ] [ 3 ] ;
Example 3
int maxRows = 2;
int maxCols = 3 ;
int matrix [ 2] [ 3 ];
int row , col ;
for ( row = 0 ; row < maxRows ; row ++ )
{
for ( col = 0 ; col < maxCols ; col ++ )
{
cout << “Please enter value of ”<< row << “ “ <<
col;
cin >> matrix [ row ] [ col ] ;
}
}
After first outer loop
Input
[0]
5 2 9
[0] 5 2 9
[1] 7 0 4
Three Dimensional
Arrays
int x [ ] [ ] [ ] ;
Introduction to Programming
Lecture 13
Today’s Lecture
Manipulation of Two dimensional
arrays
a [rowIndex ] [ columnIndex ]
Example 1
int row ;
int col ;
const maxRows = 3 ;
const maxCols = 3 ;
int a [ maxRows ] [ maxCols ] ;
Example 1
for ( row = 0 ; row < maxRows ; row ++ )
{
for ( col = 0 ; col < maxCols ; col ++ )
{
cout << “Please enter value of element number
”<<row<< “,” << col ;
cin >> a [ row ] [ col ] ;
}
}
Example 2
maxRows = 3 ;
maxCols = 3 ;
Row 1 1 2 3 Row 3 7 8 9
Row 2 4 5 6 Row 2 4 5 6
Row 3 7 8 9 Row 1 1 2 3
Example 2: Formatted
Output
cout << “The original matrix is” ;
for ( row = 0 ; row < maxRows ; row ++ )
{
for ( col = 0 ; col < maxCols ; col ++ )
{
cout << a [ row ] [ col ]<<
; ‘\t‘ ;
}
} 15 42
Example 2: Formatted
Output
for ( row = 0 ; row < maxRows ; row ++ )
{
for ( col = 0 ; col < maxCols ; col ++ )
{
cout << a [ row ] [ col ] << ‘\t’ ;
}
cout << ‘ \n ’ ;
}
15 42 26 7
Exercise
Enter the values in a matrix and print
it in reverse Column order
1 2 3
4 5 6
7 8 9
Square Matrix
Number of rows are equal to number of columns
rows
arraySize = cols
Square Matrix
a ij = a ji
i = rows
j = columns
Square Matrix
int a [ row ] [ col ] ;
int arraySize ;
for ( row = 0 ; row < arraySize ; row ++ )
{
for ( col = 0 ; col < arraySize ; col ++ )
{
//Swap values
}
}
Swap Mechanisms
individuals
Output
Detail Design
Functions in the program
getInput
calculateSalary
locateUnluckyIndividual
displayOutput
Code
#include<iostream.h>
Lecture 14
Code
calculateSalary ( int sal [ ] [ 2 ] , int lucky [ ] , int numEmps )
{
for ( i = 0 ; i < numEmps ; i ++ )
{
// netSalary = grossSalary – tax
if ( sal [ i ] [ 0 ] <= 5000 )
{
sal [ i ] [ 1 ] = sal [ i ] [ 0 ] ;
}
Code
else
{
if ( sal [ i ] [ 0 ] <= 10000 )
{
sal [ i ] [ 1 ] = sal [ i ] [ 0 ] -
0.05*sal [ i ] [ 0 ] ;
}
Code
else
{
if ( sal [ i ] [ 0 ] <= 20000 )
{
sal [ I ] [ 1 ] = sal [ I ] [ 0 ] -
0.1 * sal [ I ] [ 0 ] ;
}
Code
else
{
sal [ i ] [ 1 ] = sal [ i ] [ 0 ] - 0.15 * sal [ i ] [ 0 ] ;
}
}
}
}
if ( sal [ i ] [ 0 ] >= 0 && sal [ i ] [ 0 ] <= 5000 )
{
sal [ i ] [ 1 ] = sal [ i ] [ 0 ] ;
}
if ( sal [ i ] [ 0 ] > 5000 && sal [ i ] [ 0 ] < 10000 )
{
sal [ i ] [ 1 ] = sal [ i ] [ 0 ] - 0.05 * sal [ i ]
[0];
}
... … …
if ( grossSalary > sal [ i ] [ 0 ] && netSalary < sal [ i ] [ 1 ] )
int *myptr ;
double *x ;
char *c ;
Example
int *ptr ;
int x ;
x = 10 ;
ptr = &x ;
Dereferencing
Operator *
*ptr is read as
“The value of what ever ptr points to”
z = *ptr * 2 ;
Initializing Pointers
ptr = &var ;
ptr = 0 ;
ptr = NULL ;
int *ptr , x ;
Declaring pointers
int *ptr , x , a [ 10 ] ;
Bubble Sort
5 1 1 1
1 5 3 2
3 3 5 3
6
6 6 4
2
9 2 5
9
2 4 6
4
4 8 8
8
8 9 9
Swapping
Swap
temp = x ;
x=y;
y = temp ;
Example
main ( )
{
int x = 10 , y = 20 , * yptr , * xptr ;
yptr = &y ;
xptr = &x ;
swap ( yptr , xptr ) ;
}
Example
swap ( int *yptr , int *xptr )
{
………
}
const
int *const myptr = &x ;
Lecture 15
In Today’s Lecture
Pointers and Arrays Manipulations
Pointers Expression
Pointers Arithmetic
Multidimensional Arrays
Pointer String and Array
Pointers and Arrays
int y [ 10 ] ; Starting Address of Array y 0
[0]
1
[1]
2 [2]
3 [3]
4 [4]
5 [5]
6 [6]
7 [7]
8 [8]
9 [9]
The name of the array is like a
pointer which contain the
address of the first element.
Declaration of a Pointer Variable
int y [ 10 ] ;
int *yptr ;
yptr is a pointer to integer
yptr = y ;
Declaration of a Pointer Variable
0
[0]
1
[1]
2 [2]
y[3] 3 [3]
4 [4]
5 [5]
6 [6]
7 [7]
8 [8]
9 [9]
int y [ 10 ] ;
int *yptr ;
yptr = y ;
yptr ++ ;
location
3000 3004 3008 3012 3016
is same as
yptr = &y [ 0 ] ;
……..
yptr = &y [ 2 ] ;
Example 2
#include<iostream.h>
main ( )
{
int y [ 10 ] ;
int *yptr ;
yptr = y ;
cout << yptr ;
yptr ++ ;
cout << *yptr ;
}
Example 3
main ( )
{
int x = 10 ;
int *yptr ;
yptr = &x ;
cout << yptr ;
cout << *yptr ;
*yptr ++ increment
; whatever yptr points to
}
Pointer Arithmetic
*yptr + 3 ; This Is an Expression
yptr = &x ;
yptr ++ ;
Pointer Arithmetic
int x =10 ;
int *yptr ;
yptr = &x ;
*yptr += 3 ;
yptr += 3 ;
Decrementing
*yptr --
Pointer Arithmetic
int *p1 ,*p2;
…..
p1 + p2 ;
Error
Pointer Arithmetic
int y [ 10 ] , *y1 , *y2 ;
y1 = &y [ 0 ] ;
y2 = &y [ 3 ] ;
cout << y2 - y1 ;
Pointer Arithmetic
int y [ 10 ] ;
int *yptr ;
yptr = y [ 5 ] ;
cout << *( yptr + 5 ) ;
Pointer Comparison
if ( y1 > y2 )
if ( y1 >= y2 )
if ( y1 == y2 )
Pointer Comparison
Strings is always
terminated with \0
String Initialization
char name [ 20 ] = “Amir” ;
Manipulation of Arrays
String Arrays
Introduction to Programming
Lecture 16
In Today Lecture
Conclude the last discussion
Multi-dimensional Arrays
Pointers to Pointers
Example 1
char multi [ 5 ] [ 10 ] ;
Multi-dimensional Array in Memory
Placed sequentially in the memory
[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3] [4]
1 2 3 4 10 7 9 11 14 10 17 25 39 45 58
multi [ 2 ] [ 3 ]
*multi
?
Example 2
#include<iostream.h>
main ( )
{
char multi [ 5 ] [ 10 ] ;
cout << multi << endl ;
cout << *multi ;
cout << **multi ;
}
multi + 3
*( multi + 3 )
*( multi + 3 ) + 3
*(*( multi + 3 ) + 3 )
main ( )
Example 3
{
int multi [ 5 ] [ 6 ] ;
int row , col ;
int *ptr ;
ptr = *multi ;
for ( row = 0 ; row < 5 ; row ++ )
{
for ( col = 0 ; col < 10 ; col ++ )
{
multi [ row ] [ col ] = row * col ;
}
}
Example 3
for ( row = 0 ; row < 5 ; row ++ )
{
for ( col = 0 ; col < 10 ; col ++)
{
char *myArray [ 10 ] ;
myArray is an array of 10 pointer to
character
Initialization
int deck [ 4 ] [ 13 ] = { 0 } ;
srand ( time ( 0 ) ) ;
shuffle ( deck ) ;
deal ( deck , face , suit ) ;
}
Shuffle Functions
void shuffle ( int wDeck [ ] [ 13 ] )
{
int row , column , card ;
Multi-dimensional Arrays
Pointers to Pointers
Arrays of Pointers
Comprehensive Example
Introduction to Programming
Lecture 17
String Handling
String Manipulation Functions
Character
ASCII
1 byte = 8 bits
Example 1
#include<iostream.h>
main ( )
{
int i ;
char c ;
for( i = 0; i < 256 ; i ++ )
{
c=i;
cout << i << “\t” << c <<endl ;
}
}
Header File
ctype.h
#include<ctype.h>
ctype Functions
int isdigit ( int c ) int isspace ( int c )
int isalpha ( int c ) int iscntrl ( int c )
int isalnum ( int c ) int ispunct ( int c )
int isxdigit ( int c ) int isprint ( int c )
int islower ( int c ) int isgraph ( int c )
int isupper ( int c )
int tolower ( int c )
int toupper ( int c )
isdigit ( ) Function
12.89
atof ( ) Function
char str [ ] ;
double dVar ;
dVar = atof ( str ) ;
int main (int agrc, char **agrv )
char *strcat( char *s1, Appends string s2 to array s1. The first character of
const char *s2 ) s2 overwrites the terminating null character of s1.
The value of s1 is returned.
char *strncat( char *s1, Appends at most n characters of strings2 to array s1.
const char *s2, size_t n ) The first character ofs2 overwrites the terminating
null character of s1. The value of s1 is returned.
int sum ;
int sum_even ;
int sum_odd ;
myStrcpy ( ) ;
String Manipulation
Functions
char * strcpy (char *s1 , const char *s2 ) ;
char *strchr( const char *s, Locates the first occurrence of characterc in string s. If c is found, a pointer to c in
int c ); s is returned. Otherwise, a NULL pointer is returned.
size_t strcspn( const char Determines and returns the length of the initial segment of strings1 consisting of
*s1, const char *s2 ); characters not contained in string s2.
size_t strspn( const char Determines and returns the length of the initial segment of strin
g s1 consisting only
*s1, const char *s2 ); of characters contained in strings2.
char *strpbrk( const char Locates the first occurrence in strings1 of any character in strings2. If a character
*s1, const char *s2 ); from string s2 is found, a pointer to the character in string s1 is returned. Other-
wise, a NULL pointer is returned.
char *strrchr( const char *s, Locates the last occurrence ofc in string s. If c is found, a pointer to c in string s is
int c ); returned. Otherwise, a NULL pointer is returned.
char *strstr( const char *s1, Locates the first occurrence in strings1 of string s2. If the string is found, a pointer
const char *s2 ); to the string in s1 is returned. Otherwise, a NULL pointer is returned.
char *strtok( char *s1, const A sequence of calls to strtok breaks string s1 into “tokens”—logical pieces such
char *s2 ); as words in a line of text—separated by characters contained in strings2. The first
call contains s1 as the first argument, and subsequent calls to continue tokenizing
the same string contain NULL as the first argument. A pointer to the current token is
returned by each call. If there are no more tokens when the function is called,NULL
is returned.
This is a test
““ wrong
‘‘ right
NULL
Introduction to Programming
Lecture 18
File
Types of Files
Text Files
Executable Programs
Memory is volatile
fstream.h
Header File for File
Handling
#include <fstream.h>
Input File Stream
ifstream
Output file stream
ofstream
Example 1
#include <fstream.h>
ifstream myFile ;
myFile.open ( “payRoll.txt” ) ;
Fully Qualified Path Name
C:\myProg\payRoll.txt
Access file data
myfile >> var1;
myFile.close ( ) ;
Process : Open
myfile.open ( “payRoll.txt” ) ;
myFile payRoll.txt
Process: Close
myfile.close ( “payRoll.txt” ) ;
payRoll.txt
myFile
X
Example 1
ifstream myFile ;
myFile.open ( “myFile.txt” ) ;
while ( !myfile.eof ( ) )
{
myfile >> varName ;
}
get ( )
char ch ;
myFile.get ( ch ) ;
Example 2
while ( !myFile.eof ( ) )
{
myFile.get ( ch ) ;
cout << ch ;
}
put ( )
outputFile.put ( ch ) ;
ifstream myInputFile ( “myfile.txt” , ios :: in ) ;
int i = 0 ;
Open file
Output
Hello
File
Amir 1000
Amara 1002
strtok ( string , delimiter )
Example
char * namePtr , *salaryPtr , arr [ 30 ] ;
double fSalary = 0.0 ;
inFile.getline ( arr , 30 , ‘\n’ ) ;
namePtr = strtok ( arr , " " ) ;
salaryPtr = strtok ( NULL , " " ) ;
fSalary = atof ( salaryPtr ) ;
:
Introduction to Programming
Lecture 19
Random Access Files
Files
getline(str,10, ‘\n’) ;
File Positions
File Position Pointer
tellg ( ) Function
myFile.tellg ( ) ;
Returns a whole number which tell you the position
of the next character to be read from the file
tellp ( ) Function
myFile.tellp ( ) ;
Returns a whole number which tell you the position o
the next character to be written in a file
For Positioning in the file
seekg ( ) ;
seekp ( ) ;
seekg ( )
Number of
characters to move Starting point
to
Rawalpindi
Merge Method
Original file Empty file
This is a text
data And needs
To be replaced NOT
seekg ( )
This is a Sample
get ( ) and put ( ) character
in a file
myInputFile.get ( c ) ;
myOutputFile.put ( c ) ;
read ( ) and write ( )
Functions
Area in memory
Number of bytes to
be read
Area in memory
Number of bytes to
be written
myOutputFile.write ( &i , 4 ) ;
sizeof ( ) ;
Address of the
integer ‘i’ Size of integer
File Handling
– Sequential Files
– Random Access Files
Today’s Lecture
Structures
Unions
Structure
?
Structure definition
Keyword
Structure
struct Student name
}
char name [ 60 ] ;
char address [ 100 ] ; Data of the structure
double gpa ;
};
Student s1 , s2 , s3 ;
Structure Name
}Variable Names
Structure
struct address
{
char streetAddress [ 100 ] ;
char city [ 30 ] ;
char country [ 30 ] ;
}
Structure
struct Student
{
char name [ 60 ] ;
address add ;
double gpa ;
} s1 , s2 , s3 ;
Example 1
struct Card
{
char *suit ;
char *value ;
};
Structures
Variables of type structure
Pointers to Structure
Array of Structure
Structures
Student s [ 100 ] ;
Student *sPtr ;
Structures
Student stdnt1 , stdnt2 ;
stdnt1 + stdnt2 ; //Wrong
Structures
Student s1 , s2 ;
s1 = s2 ;
Example 2
struct Student
{
char name [ 64 ] ;
char course [ 128 ] ;
int age ;
int year ;
};
Initializing Structures
Name
year
Course age
name
Initializing Structures
s1.name ;
s1.course ;
s1.age ;
s1.year ;
Initializing Structures
s1.age = 20 ;
s1.name = “Abbas Ali ” ; //Wrong
strcpy ( s1.name , “Abbas Ali ” ) ;
Accessing structure members
Student s1 , s2 ;
s2 = s1 ;
Passing Structures
to Functions
Passing Structures to Functions
Call by value
Call by Reference X
int Square ( int x ) ;
x = Square ( 10 ) ;
Structures
Simple Variable of type
Structure
Pointer to Structure
Arrays of Structures
Function that returns a
Structure
Pass the Structure to functions
Pointers to Structure
Pointers to Structure
Student *sPtr , s1 ;
sPtr = &s1 ;
Pointers to Structure
sPtr.name ;
Wrong
Pointers to Structure
*sPtr.name ;
Pointers to Structure
*( sPtr ).name ;
Pointers to Structure
*sPtr ->name ;
Same as
s1.name
Arrays of Structures
Arrays of Structure
Student s [ 100 ] ;
s [ 0 ].name ;
s [ 1 ].name ;
s [ 2 ].name ;
.
.
.
s [ 99 ].name ;
sizeof ( s1 ) ;
Example 3
struct Student
{
char firstName [ 30 ] ;
char lastName [ 30 ] ;
char course [ 15 ] ;
char rollNo [ 10 ] ;
int age ;
float gpa ;
};
Example 3
Student s [ 10 ] ;
for ( int i = 0 ; i < 10 ; i ++ )
{
cout << “Please enter the student's last name : " ;
cin >> s [ i ].lastName ;
cout << “Please enter the student's first name : " ;
cin >> s [ i ].firstName ;
cout << " Please enter the student's course : " ;
cin >> s [ i ].course ;
cout << " Please enter the student's Roll No. : " ;
cin >> s [ i ].rollNo ;
cout << " Please enter the student's grade : " ;
cin >> s [ i ].grade ;
cout << " Please enter the student's age : " ;
cin >> s [ i ].age ;
cout << " Please enter the student's GPA : " ;
cin >> s [ i ].gpa ;
}
Example 4
Student getData ( ) ;
Return
Type
Function
Name
Example 4
ifstream inFile ( “myText.txt” ) ;
void main ( )
{
Student s1 ;
s1 = getData ( ) ;
inFile.close ( ) ;
}
Example 4
Student getData ( )
{
Student tempStudent ;
inFile >> tempStudent.firstName ;
inFile >> tempStudent.lastName ;
inFile >> tempStudent.course ;
inFile >> tempStudent.rollNo ;
inFile >> tempStudent.age ;
inFile >> tempStudent.gpa ;
return tempStudent ;
}
Union
Union
union intOrChar
{
int i ;
char c ;
};
Union
Memory
Both Variable
i occupy the
same space in
memory
Union
union intOrDouble
{
int ival ;
double dval ;
};
Union
Memory
iVal
Both Variable
dVal
occupy the
same space in
memory
Union
intOrDouble u1 ;
u1.ival = 10 ;
cout << u1.ival ;
cout << u1.dval ; incorrect value
Union
u1.dval = 100.0 ;
cout << u1.ival ; incorrect value
Example 5
char c ;
int x ;
x = ‘a’ ;
cout << x ;
x = x * 256
cout << x ;
:
Example 5
x = x +’b’ ;
cout << x ;
Example 5
Union iandc
{
char c [ 4 ] ;
int x ;
};
Today we studied
Structures
Unions
Introduction to Programming
Lecture 21
Today’s Lecture
Bit manipulation
Bit operators
Logical Operators
AND &&
OR ||
Bit manipulation operators
& Bitwise AND Operator
| Bitwise OR Operator
^ Bitwise Exclusive OR Operator
~ NOT Operator
<< Left Shift Operator
>> Right Shift Operator
Bitwise AND Operator
Truth table for AND operation
Hence x = 12 & 8 = 8
Example
#include <iostream.h>
main ( )
{
int number = 12 ;
if ( number & 0x8 )
cout << "Bit number four is set" << endl ;
else
cout << "Bit number four is not set" << endl ;
}
Bitwise OR Operator
Truth table for OR operation
A B A|B
1 1 1
1 0 1
0 1 1
0 0 0
Bitwise OR Operator
Example 1
X = 12 | 8
1 1 0 0
|
1 0 0 0
_____________
1 1 0 0
1 0 0 0
|
0 0 0 1
_____________
1 0 0 1
X=9^1 0 0 ^0 1
_____________
Result x = 8 1 0 0 0
NOT Operator
A ~A
0 1
1 0
NOT Operator
x=8
~ ( 1000 ) = 0111
= 7
Bit Flags
Read Write And Execute
Exclusive OR Operator
Example
unsigned int a , b , c ;
a = 112 ;
b = 32 ;
c=a^b;
c = ( a ^ b ) ^ b ; the result is a
c = ( a ^ b ) ^ a ; the result is b
Raid
Redundant Array of Inexpensive Devices
Hot Plug
Example
Swapping two integers without
a temporary storage
unsigned int a = 12 ;
unsigned int b = 8 ;
a=a^b;
b=b^a;
a=a^b;
Unsigned integer
unsigned int i , j , k ;
Left Shift
A number 1
Shift left
Right Shift
A number 10
Right shift
10
01
Left & Right Shift
Operator
Right shift
1 0 1 1 0 0 0 1
Introduction to Programming
Lecture 22
Review
Bit wise Manipulation
and
Assignment Operator
a =a+1;
a += 1 ;
Bit Manipulation Operators
a &= b ;
Same as
a=a&b;
Assignment Operator
a |= b ;
Same as
a=a|b;
Assignment Operator
a ^= b ;
Same as
a=a^b;
Design Recipes
Analyze a problem statement, typically
expressed as a word problem
Express its essence, abstractly and with
examples
Formulate statements and comments
in a precise language
Evaluate and revise the activities in the
light of checks and tests.
PAY ATTENTION TO DETAIL
Variables
Symbolic Names
x
i
BasicPay
HouseRent
Data types
Whole numbers:
– int, short, long, unsigned
Real Numbers (with decimal points)
– float, double
Character data
– char
int = 4 bytes
char = 1 byte
ASCII Table
Arrays
Collection of same data types
Arithmetic Operators
Plus +
Minus -
Multiply *
Divide /
Modulus %
Modulus Operator
a%b;
7%2=1;
100 % 20 = 0 ;
Compound
Arithmetic Operators
+=
-=
*=
/=
%=
Compound
Arithmetic Operators
a=a+b;
a += b ;
Logical Operators
AND &&
OR ||
Comparison Operators
a<b;
a <= b ;
a == b ;
a >= b ;
a>b;
a = b;
if ( a = b )
//Wrong
//Logical Error
a>b;
a >= b ;
Bit wise Operators
if ( condition )
{
statement ( s ) ;
}
statement ( s ) ;
}
While Loops
while ( a > b )
{
statement ( s ) ;
}
While Loops
i ++ ;
Switch Statement
break ;
continue ;
Functions
Call by value
Call by reference
Arrays
Arrays
int a [ 10 ] ;
a[0];
:
a[9];
Pointers
Pointers
Memory address of a
variable is stored
inside a pointer
Files and their
Input / Output
systems
Introduction to Programming
Lecture 23
Preprocessors and
Header files
Today’s Lecture
Preprocessor Directives
Header Files
Macros
Preprocessor
#include <iostream.h>
#
#include
#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <stream.h>
5:10 to 5:23
5:24 to 5:41
Re-locatable
Executable
MyHeader.h
#include “MyHeader.h”
#include <iostream.h>
#define
#define PI 3.141592
Preprocessor Directives
#if
#else
#endif
#elif
#ifdef
#ifndef
#error
Preprocessor Directives
#ident
#import
#line
#machine
#system
#warning
Example
#ifdef PI
# define PI
# ifdef PI
# define DEBUG
# ifdef DEBUG
Conditional
Compilation
Macro Translation
#undef DEBUG
#include <conio.h>
#ifdef __cplusplus
}
#endif
Macro
Example 1
#define SQUARE ( X ) X * X
main ( )
{
int i = 5 , j ;
:
j = iSQUARE
*i; (i);
}
Example 2
#define SQUARE ( X ) X * X
main ( )
{
int i = 5 , j = 10 , k ;
:
k = iSQUARE
+ j * i +( ji ;+ j ) ;
}
Example 3
#define SQUARE(X) (X)*(X)
main ( )
{
int i = 5 , j = 10 , k ;
( i + j ) *( (i i++j j) ); ;
k = SQUARE
}
Overhead
Code Bloat
Example 4
#define PI 3.14159
#define CIRCLEAREA ( X ) (PI( *PIX)**X( X ) * ( X ) )
main ( )
{
float radius ;
cout << “ Enter radius of Circle Area : ” ;
cin >> radius ;
cout << “ Area of Circle Area is ”
( ( PI ) * ( radius
<< CIRCLEAREA 2 *) radius
( radius* () radius
; ); ));
}
Header Files
Header File
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
In Next Lecture
Memory Allocation
Introduction to Programming
Lecture 24
Today’s Agenda
Memory Allocation
– Dynamic memory allocation
– Advantages/disadvantages of
Dynamic and static memory
allocation
– Common programming errors while
using Dynamic memory allocation
Static Memory
Allocation
int i , j , k ;
char s [ 20 ] ;
Compile Time
Allocation
Dynamic Memory
Allocation
Heap
Pointers
void
Pointer
int *i ;i is a pointer to an integer
char *s ;
void *ptr ;
Cast
void *ptr ;
( int * ) ptr ;
NULL
Space in terms of
numbers of elements
calloc ( n , m ) ;
Space in terms of size
each of elements
calloc ( 1000 , sizeof ( int ) ) ;
( int * ) calloc ( 1000 , sizeof ( int ) ) ;
void * calloc ( size_t n , size_t el-size ) ;
Example 1
int *iPtr ;
iPtr = ( int * ) calloc ( 1000 , sizeof ( int ) ) ;
if ( iPtr == NULL )
exit ( ) ;
void * malloc ( n )
Number of
bytes required
malloc (1000 *sizeof ( int ) ) ) ;
malloc ( n ( sizeof ( float ) ) ) ;
Static Memory
Allocation
// a while loop to read the ages of the student and place them in the
memory
sPtr = iPtr ;
sPtr++ ;
free ( iPtr ) ;
realloc(void *iPtr, size_t size);
Unreferenced
Memory
Memory
Leaks
Example
main ( )
{
funct ( ) ;
}
funct ( )
{
int *iPtr ;
iPtr = malloc ( 1000 * ( sizeof ( int ) ) ) ;
// used the memory
}
Dangling
Pointers
Example
int *ptr1 , *ptr2 ;
ptr1 = malloc (1000 * ( sizeof ( int ) ) ) ;
ptr2 = ptr1 ;
---
free ( ptr1 ) ;
Multi-tasking
Review
Dynamic Memory Allocation
– Efficient usage of computers
resources
– Have to do memory
management
Introduction to Programming
Lecture 25
Introduction to C++
language
In Coming Lectures
– C++ Features
– Classes
– Object
Today’s Lecture
Default Function Arguments
Inline Functions
Classes
Rules for Structured
Programming
Do Modular programming
– Write small function
– Every function should perform
a specific well defined task
Function should obey single entry
single exit rule
Liberally Comment
the code
Object Oriented
Language
Early 1980's
Bjarne Stroustrup
at Bell Labs
C with Classes
C++
Java
Default Function
Arguments
power ( x , n ) ;
void f ( int i , double x ) ;
void f ( int i =1 , double x = 10.5 )
{
--
}
Example 1
void f ( int i = 1 , double x = 10.5 )
{
cout<<“i = ”<<i;
cout<<“ x = “<< x<<endl;
}
Example 1
main ( )
{ Output
f(); i = 1 x = 10.5
f(2); i = 2 x = 10.5
f ( 2 , 12 ) ; i = 2 x = 12
}
void f ( double x=10.5 , int i ) ;
The declaration of
variables inside the code
while ( condition )
{
// body of the while loop
}
{
int i ;
---
}
Scope of Variable
When you declare a
variable inside the block
then the variable exists in
that block.
Example 2
for ( int i = 0 ; i < 3 ; i++ )
{
int temp = 22 ;
cout << "\n i = " << i << "temp = " << temp ;
}
cout << "i = " << i ;
Inline
functions
inline
Example 2
#define SQUARE ( X ) X * X
main ( )
{
int i = 5 , j = 10 , k ;
:
k = iSQUARE
+ j * i +( ji ;+ j ) ;
}
Example 3
#define SQUARE ( X ) ( X ) * ( X )
main ( )
{
int i = 5 , j = 10 , k ;
( i + j ) *( (i i++j j) ); ;
k = SQUARE
}
Example 3
#define MAX ( A , B ) ( ( A ) > ( B ) ? ( A ) : ( B ) )
inline f ( int a, int b )
{
if ( a > b )
return a ;
return b ;
}
void main ( )
{
int i , x , y ;
x = 23 ; y = 45 ;
i = MAX ( x++ , y++ ) ; // Side - effect : larger value incremented twice
cout << "x = " << x << " y = " << y << '\n' ;
x = 23 ; y = 45 ;
i = f ( x++ , y++ ) ; // Works as expected
cout << "x = " << x << " y = " << y << '\n' ;
}
Function
Overloading
Operator
Overloading
Overloading
Using the same name to
perform multiple tasks or
different task depending on
the situation
double Intsquareroot ( int i ) ;
double Doublesquareroot ( double x ) ;
Example 4
int squareroot ( int i )
{
// body of the function
}
main ( )
{
-----------
F(1,2); // F ( int a , int b ) ; is called
F ( 1 , 2 , 3 ) ; // F ( int a , int b , int c ) ; is called
-----------
}
int f ( int a ) ;
double f ( int a ) ;
Name Mangling
Introduction to Programming
Lecture 26
Today’s Lecture
– Classes
– Object
struct
Class
A class has
– data
– functions
Class
A Class is a user defined
data type.
Object
// definition of a class
}
Example 1
struct Date
{
int day ;
int month ;
int year ;
};
Date mydate ;
mydate.month = 1 ;
mydate.day = 21 ;
mydate.year = 1979 ;
Example 2
class Date
{
int day ;
int month ;
int year ;
};
Example 2
main ( )
{
Date mydate ;
/* manipulate the data members
mydate.day ;
mydate.month ;
mydate.year ;
*/
}
Example 2
class Date
{
int day ;
int month ;
int year ;
};
Example 2
main ( )
{
Date mydate;
mydate.month = 10 ; // Error
}
Private
Default visibility of
all data and function
inside a class is
private
Public
class Date
{
private :
public :
class Date
{
public :
Date ( int month , int day , int year ) ;
void display ( ) ;
private :
int month , day , year ;
};
Date :: Date ( int month , int day , int year )
{
// Body of the function
}
Example 3: Modified
main ( )
{
Date mydate ( 1 , 1 ,2002 ) ;
mydate.display ( ) ;
}
Date :: Date ( int day , int month , int year = 2002 )
Example 3: Modified
main ( )
{
Date mydate ( 1 , 1 ,2002 ) ;
Date mydate ( 1 , 1 ) ;
}
Introduction of Programming
Lecture 27
Today’s Lecture
– Classes and objects
– Constructors
– Destructors
– Member functions
– Member data
Function
Oriented
Object Oriented
Multiple
Media
Classes
Objects
Constructors
Data Hiding
Encapsulation
Constructor
Bugs
The majority of programming
problems occur because of the
use of un-initialized data.
Constructor
Name of the constructor is same
as the name of the class
It does not return any thing, not
even void
Example
class Date
{
int month ;
int day ;
int year ;
public:
Date ( int day = 1 , int month = 1 , int year =
1)
};
Function
Overloading
Rules of function
overloading
When ever we overload a function,
the name of the function remain the
same but argument list changes.
int * iptr ;
iptr = new int ;
Example
new char ;
new double ;
delete
Example
int * iptr ;
iptr = new int ;
delete iptr ;
Example
int * iptr ;
iptr = new int [ 10 ] ;
Example
new data_type [ Number_of_locations ] ;
new double [ 10 ] ;
Example
int *iptr ;
iptr = new int [ 10 ] ;
delete iptr ;
Example
Date *dptr ;
int *iptr ;
iptr = new int [ 10 ] ;
Example
Date *dptr ;
dptr = new Date [ 10 ] ;
Example
Date date1 , *dptr ;
date1.setDate ( ) ;
dptr.setDate ( ) ; Wrong
Protected
Destructor
Allocate enough space for
the new data
Populate that space
Delete the previous space
Point the new space to the
pointer pointing to the
original data
char *name =new char [ string_length ]
delete [ ] name
delete [ ] pointer_name
Example
main ( )
{
Date mydate ( “01-12-2002” ) ;
mydate.display ( ) ;
}
Messages
Method
Introduction to Programming
Lecture 29
Private
Public
Encapsulation
Data Hiding
Friend
Friend Function
Friend Function
class Date
{
--
};
Example 2
main ( )
main ( )
{
myClassOne A ;
myClassTwo B ;
A.Display ( ) ;
B.Display ( ) ;
AddBoth ( A , B ) ;
}
Example 2
int AddBoth ( myClassOne A , myClassTwo B )
{
cout << “The value of topSecret in myClassOne object
is” << A.topSecret ;
y = mx + c
Slope Intercept
on y axis
Straight Line
class straightLine
{
double slope , intercept ;
// member function
};
Quadratic
y = ax +bx + c
2
Quadratic
class quadratic
class quadratic
{
private :
double a , b , c ;
// member function
};
Limitations
It is NOT Transitive
It is NOT Associative
Introduction to Programming
Lecture 30
In Today’s Lecture
– References
– Differences
Between References
and Pointers
Reference
&
int & i ; ‘i’ is a reference to an integer
int * i ; ‘i’ is a pointer to an integer
int i ;
int & j = i ;
main ( )
Example 1
{
int i ;
int & j = i ;
i = 123 ; Output
cout << i << endl ; 123
cout << j << endl ; 123
i++ ;
cout << i << endl ; 124
cout << j ; 124
}
Example 2
void swap ( int x , int y )
{
int temp = x ;
x=y;
y = temp ;
}
Example 2
main ( )
{
int x , y ;
x = 10 ;
y = 20 ;
swap ( x , y ) ;
cout << x << y ;
}
Example 2
main ( )
{
int x , y ;
x = 10 ; y = 20 ;
swap ( & x , & y ) ;
cout << x << y ;
}
swap ( int * i , int * j ) ;
Example 2
void swap ( int * i , int * j )
{
int * temp = i ;
*i=*j;
* j = * temp ;
}
Example 3
void swap ( int & i , int & j )
{
int temp = i ;
i=j;
j = temp ;
}
Example 3
main ( )
main ( )
{
int x , y ;
x = 10 ;
y = 20 ;
swap ( x , y ) ;
cout << x << y ;
}
const
Example 4
struct b
{
int serno ;
char text [ 1000 ] ; // A lot of chars
} b = { 123, "This is a BIG structure" } ;
}
struct b
Example 4
{
int serno ;
char text [ 1000 ] ; // A lot of chars
} b = { 123 , "This is a BIG structure" } ;
Is equivalent to
c1.real = c2.real ;
c1.imag = c2.imag ;
Complex operator + ( Argument_ list ) ;
Example
Complex Complex :: operator + ( Complex c )
{
Complex temp ;
temp.real = real + c.real ;
temp.imag = imag + c.imag ;
return temp ;
}
Complex x , y , z ;
z=x+y;
z=x+d;
Complex Complex Double
Number Number Precision
Number
Complex operator + ( double d ) ;
z=x+y;
z=x+d;
Example
Complex Complex :: operator + ( Complex c )
{
Complex temp ;
temp.real = real + d ;
temp.imag = imag ;
return temp ;
}
z=d+x;
Complex Complex
Number Double
Precision Number
Number
Friend
Function
User Defined
Data types
<<
Example
main ( )
{
Complex c1 ( 1 , 2 ) , c2 ( 3 , 4 ) , c3 ;
c3 = c1 + c2 ;
c1.display ( ) ;
c2.display ( ) ;
c3.display ( ) ;
}
Complex operator + ( Complex & c ) ;
C is a reference to a
complex number
i += 2 ;
i=i+2;
c1 += c2 ;
Example
char s [ 30 ] ;
public :
String ( )
{
strcpy ( s , "" ) ;
}
Date d1 , d2 ;
if ( d1 > d2 )
Example
Date date ;
date + 5 ;
Example
5 + date ;
Interface
Introduction to Programming
Lecture 33
In Today’s Lecture
Operator overloading
Assignment operator
A “this” pointer
Operator over loading using this pointer
Conversion function
Assignment
Operator
a=b;
Member Wise
Assignment
Member Wise Copy
Example
class String
{
char buf [ 100 ] ;
public:
String ( ) ;
~ String ( ) ;
...
};
Example
main ( )
{
String s1 ( “This is a test” ) ;
String s2 ;
s2 = s1 ;
…
…
}
s2 = s1 ;
Example
void String :: operator = ( String & s1 )
{
delete buf ;
buf = new char [ s1.buf + 1 ] ;
strcpy ( buf , s1.buf ) ;
}
Assignment Operator
int i , j , k ;
i=5;
j = 10 ;
k = 15 ;
i=j;
k=i;
i=j=k;
k=i=j;
k = i = ++ j ;
this pointer
this pointer
buf ;
this -> buf ;
( * this ).buf ;
int i ;
i = i ; // nothing happens
String s [ 1000 ] = { “This is a Test” } ;
s=s;
Self
Assignment
Example
main ( )
{
String s , * sPtr ;
sPtr = & s ;
.
.
.
s = * sPtr ;
}
Example
void String :: operator= ( String & other )
{
if ( this == & other )
return ;
--------
}
Example
String & String :: operator = ( String & other )
{
if ( this == & other )
return * this ;
delete buf ;
buf = new char [ other.length + 1 ] ;
strcpy ( buf , other.buf ) ;
return * this ;
}
s3 = s2 = s1 ;
cout << a << b << c ;
Example
Date d1 , d2 ;
d2 = d1 ++ ;
d2 = d1 + 1 ;
Example
Date date1 , date2 ;
date2 = date1 + 1 ;
date2 = date1 ++ ;
Example
main ( )
{
int i ;
float x ;
x=i;
i=x;
}
Example
main ( )
{
Date d ;
?
int i ;
d=i;
}
Example
main ( )
{
int i ;
float x ;
x = ( float ) i ;
}
Conversion
Function
Date ( )
{
// body of function
}
double x = 1 / 3 ; Output: 0.33333
x*3; Output:
0.99999
Common Business
Oriented Language
Introduction to Programming
Lecture 34
In Today’s Lecture
Arrays of objects
Interaction of Arrays with Free Store
}
Example
class IntArray
{
private :
int length ;
int * iPtr ;
public :
IntArray ( int i ) ;
...
};
main ( )
Example
{
IntArray i ( 10 ) ;
int j ;
for ( j = 0 ; j < 10 ; j ++ )
i[j]=j;
}
Example
int & IntArray ::operator [ ] ( int index )
{
int dummy = 0 ;
if ( ( index < 0 ) || ( index >= length ) )
{
cout << "Error : index out of range.\n" ;
return dummy ;
}
else
return array [ index ] ;
}
Example
IntArray :: IntArray ( int i )
{
int * iPtr ;
iPtr = new int ( i ) ;
length = i ;
}
Today’s lecture
Arrays of objects
Dynamically allocating arrays using new
operator
Usages and overloading new and delete
Operator
Array subscripting [ ] Operator
Introduction to Programming
Lecture 35
Input/Output
Streams
File
Input/Output
Stream
scanf ( ) ;
printf ( ) ;
Stream
Stream is an ordered
sequence of bytes
Stream
Input/Output
Input stream object
cin
Output stream object
cout
Stream Operators
>>
<<
Example
int i ;
char c ;
cin >> i ;
cin >> c ;
Every stream has:
– A source
– A destination
State
Example
int i , j ;
cin >> i >> j ;
cout << i / j ;
Formatted
Input / Output
Member Functions
cin.get ( ) ;
c = cin.get ( ) ;
cin.get ( char c ) ;
cin.read ( char * buffer , streamsize n )
100
cin.unget ( ) ;
cin.peek ( ) ;
cout.put ( char ch ) ;
cout.write ( char * str , int n ) ;
Example
char name [ 60 ] ;
cin >> name ;
cout << name ;
Example
Octal
Hexadecimal
Example
int i = 10 ;
cout << i ;
10
Example
#include <iostream.h>
#include <iomanip.h>
main ( )
{
int i = 10 ; Output
cout << oct << i << endl ; 12
cout << hex << i<< endl ; A
cout << dec << i << endl ; 10
}
White
Space
WS
Manipulator
setw
Example
#include <iostream.h>
#include <iomanip.h>
main ( )
{
int i = 5 ;
cout << “The value of i is = ” ;
cout << setw ( 4 ) << i << endl ;
}
setfill
cout << setfill ( ‘*’ ) ;
A Character
Example
#include<iostream.h>
#include<iomanip.h>
Main ( )
{
int i = 4000 ;
cout << setfill ( ‘*’ ) << setw ( 10 ) << i << endl ;
}
Set Precision
Manipulator
Example
#include<iostream.h>
#include<iomanip.h>
main ( )
{
float number = 6.67076632 ;
cout << setprecision ( 2 ) << number <<
endl ;
}
Example
#define PI 3.1415926
main ( )
{
cout << PI << endl ;
cout << setprecision ( 2 ) << PI << endl ;
}
setbase
Example
#include <iostream.h>
#include <iomanip.h>
main ( )
{
int x = 10 ;
cout << setbase ( 8 ) << x <<endl ;
IOS Flags
width ( ) ;
cin.width ( 7 ) ;
cout.width ( 10 ) ;
cout.precision ( 2 ) ;
Example
#include <iostream.h>
#include <iomanip.h>
main ( )
{
int i = 10 , j = 20 ;
cout << setw ( 7 ) << i <<endl ;
cout << j ;
}
Formatting Manipulation
ios :: adjustfield
ios :: left
ios :: right
ios :: left | ios :: right , ios :: adjustfield
cout.setf ( ios :: left , ios :: adjustfield ) ;
Set Flag
cout.fill ( ‘*’ ) ;
cout.fill ( '0' ) ;
Formatting Manipulation
cout.fill ( '0' ) ;
cout << setw ( 10 ) << number << endl ;
cout.setf ( ios :: hex ) ;
7ff
0111 1111 1111
showbase
showbase
1.2334e +09
Fixed Point Notation
ios :: fixed
ios :: uppercase
What we learnt so far..
Stream Insertion /
Extraction
int i ;
cin >> i ;
int a , b , c ;
a+b+c;
cin >> i >> j ;
Friend
Function
Member
Operators
Object.data
Object.function ( )
Stream Insertion Operator
int i = 5 , j = 10 , k = 15 ;
cout << i << j << k ;
Return type:
Reference to the output stream
Operator
}
}
ostream & operator << ( ostream & output , vehicle A )
Matrix m ;
m.getMatrix ( ) ;
m.displayMatrix ( ) ;
Example
Matrix m ;
cin >> m ;
cout << m ;
Introduction to Programming
Lecture 38
Today’s Lecture
User Define Manipulator
Static key word
User Define
Manipulators
Example
int i = 10 ;
cout << setwidth ( 7 ) << i <<endl ;
Parameter Less
Manipulators
cout << manipulator << otherdata ;
ostream & manipulatorName ( ostream & os ) ;
Definition
ostream & manipulatorName ( ostream & os )
{
return os << userDefinedManipulator ;
}
User Defined Manipulators
// Tab A Short Example
ostream & tab ( ostream & output )
{
return output << '\t' ;
}
// bell
void main ( )
{
cout << "Virtual " << tab << "University" << bell << endLine ; // Use of Mainpulator
}
Static
Static
Are variables which exist for a
certain amount of time which is
longer than an ordinary automatic
variable.
Global
Example
int i ;
void myfunction ( void )
{
int i ;
for ( i = 0 ; i < 10 ; i ++ )
cout << i << endl ;
}
Automatic
Variable
State
static int i ;
static int i = 0 ; //Initialization
.........
i = 0 ; //Ordinary Assignment Statement
void f ( void )
Example
{
static int i = 0 ;
i ++ ;
cout << “Inside function f value of i : ” << i << endl ;
}
main ( )
{
int j ;
for ( j = 0 ; j < 10 ; j ++ ) ;
f();
}
Example
class Truck
{
char a ;
public :
Truck ( char c )
{
a=c;
cout << "Inside constructor for object " << a << endl ;
}
~ Truck ( )
{
cout << "Inside destructor for object " << a << endl ;
}
};
Example
Truck a ( 'A' ) ;
main ( )
{
Truck b ( 'B' ) ;
f();
g();
cout << “Function g has been called " << endl ;
}
Example
void f ( )
{
Truck c ( 'C' ) ;
}
void g ( )
{
static Truck g ( 'G' ) ;
}
Example
Output
Inside constructor for object A
Inside constructor for object B
Inside constructor for object C
Inside destructor for object C
Inside constructor for object G
function g has been called
Inside destructor for object B
Inside destructor for object G
Inside destructor for object A
Static Data
Member Inside
A Class
File
Scope
class Truck
Example
{
public :
int wheels ;
int seats ;
};
main ( )
{
Truck A ;
A.seats ;
}
Scope Resolution Operator
::
Truck :: nameOfStaticDatamember = values ;
Example
class SavingsAccount
{
private :
char name [ 30 ] ;
float accountNumber ;
float currentBalance ;
static float profitRate ;
// ...
public :
SavingsAccount ( ) ;
//...
};
SavingsAccount :: profitRate = 3.0 ;
SavingsAccount A ;
A.profitRate ; // bad usage
A.profitRate = 4.0 ; // bad usage
SavingsAccount :: profitRate ;
Example
class Student
{
public :
static int howMany ;
Student ( ) { howMany ++ ; }
~ Student( ) { howMany -- ; }
void displayHowMany ( )
{
cout << "Number of students are " << howMany ;
}
};
int Student :: howMany = 0 ;
Dynamic
What we covered today
Memory Allocation
Pointers
A pointer is a special type of
variable that contain a memory
address
Void Pointer
Pointer to an Integer
Pointer to a Character
Pointer to a Float
Pointer to Objects
References
&
const
Dynamic
Memory
Allocation
Native Operator
new
delete
Dynamic Memory Allocation
int *p ;
p = new int ;
delete p ;
Dynamic Memory Allocation
int *p ;
p = new int [ 10 ] ;
delete [ ] p ;
Example
class Matrix
{
private :
int * m ;
int row , col ;
public :
Matrix ( int rows , int cols )
{
m = new int [ rows * cols ] ;
}
};
delete [ ] m ;
Assignment
int i = 0 ;
//Initialization
int i ;
i = 0 ; //Assignment
Matrix m1 , m2 ;
……
m2 = m1 ;
//Assignment Statement
Member to
Member
Assignment
m2 = m1
Pointing to the same
int *m of m1
region in memory
0xefffdad0
mx
int *m of m2
0xefffdad0
Pointing to the same
int *m of m1
region in memory
0xefffdad0
mx
int *m of m2
0xefffdad0
Copy
Constructor
Call by
value
Shallow
Deep Copy
Copy
Matrix ( Matrix & ) ;
class String
Example
{
char * c ;
public :
void copy ( char * s ) ;
String ( char * data ) ;
void print ( ) ;
// etc.
};
Example
String s1 ( “test1” ) ;
String s2 = s1 ;
s1.copy ( “this is a test” ) ;
s2.print ( ) ;
int i ;
i = 10 ;
i=i;
Matrix m2 ( m1 ) ;
Matrix m2 = m1 ;
Rules
For dynamic memory allocation
1. Define copy constructor
3. Provide destructor
What have we covered today
Review of pointers
– Dynamic memory allocation
new
Delete
For memory allocation in classes we must provide
– Constructor
– Copy constructor
– Assignment operator
– destructor
Introduction to Programming
Lecture 40
Class
Class is a user
defined data type.
Data
Hiding
Public
Interface
Yes you can use user
defined data type as a
member of the class
Class can contain
objects.
Example
class Date
{
private :
int month , day , year
;
public :
// member functions
};
Example
class Person
{
private :
char * name ;
char * address ;
Date dateOfBirth ; // member object
public :
// public member functions . . .
};
Person :: Person ( char * name , char * address , int day , int month , int year )
{
dateOfBirth.setDay ( dy ) ;
dateOfBirth.setMonth ( mn ) ;
dateOfBirth.setYear ( yr ) ;
// statement ( s ) ;
}
Initializer
List
Person :: Person ( char * name ,
char * address , int day, int month, int year )
: Date ( int month , int day , int year )
Constructor
Date :: Date ( int day , int month , int year )
{
cout << “Inside Date constructor ” ;
}
void display ( ) ;
void set ( int ) ;
~ Column ( )
{
cout << "Column destroyed" << endl ;
}
};
class Row
Example
{
private :
int size ;
Column col ;
public :
void set ( int ) ;
Row ( )
{
cout << "Inside Constructor for object Row" << endl ;
}
~ Row ( )
{
cout << "Row destroyed" << endl ;
}
void display ( ) ;
};
class Matrix
Example
{
private :
Row row ;
int size ;
public :
Matrix ( )
{
cout << "Matrix Created" << endl << endl ;
}
~ Matrix ( )
{
cout << "Matrix destroyed" << endl << endl ;
}
void display ( ) ;
};
Example
main( )
{
Matrix m ;
m.display ( ) ;
}
Output
Column Created
Inside Constructor for object Row
Matrix Created
….
Matrix Destroyed
Row Destroyed
Column Destroyed
Code
Reuse
const Date dateOfBirth ;
Structure inside
a structure
Class inside
a class
class Outer
Example
{
…….
class Inner1
{
private :
// Data members
//data functions
public :
// Data members
//data functions
};
//data members
//data functions
};
Class inside a class
Inner2
Inner1
Outer
Friend
Example
class Outer
{
public :
class Inner ;
friend class Inner ;
class Inner
{
}
{
// Statement ( s ) ; definition
}
Outer :: Inner :: Inner ( )
{
// definition
}
class Outer
Example
{
class Inner1
{
class Inner2
{
class Inner3
{
// Data members and functions
// and perhaps more inner classes
};
// Data members and functions
};
// Data members and functions
}; 48:
};
Introduction to Programming
Lecture 41
Templates
Types of Templates
Function Templates
Class Templates
Swap Function
void swap ( int & i , int & j )
{
int temp ;
temp = i ;
i=j;
j = temp ;
}
Function
Overloading
Function Templates
template < class T >
return_type function_name ( argument_list )
Example
int reverse ( int x )
{
return ( - x ) ;
}
double reverse ( double x )
{
return ( - x ) ;
}
Example
template < class T >
T reverse ( T x )
{
return (- x ) ;
}
Example
main ( )
{
int i ;
…….
reverse ( i ) ;
}
Example
main ( )
{
int i ;
…
reverse ( i ) ;
…
double y ;
…
reverse ( y ) ;
}
Code
Reuse
Example
template < class T >
template < class T >
void swap ( T & x , T & y )
{
T temp ;
temp = x ;
x=y;
y = temp ;
}
int a , b ;
char a , b ;
swap ( a , b ) ;
Example
template < class T >
void swap ( T & x , T & y )
{
T temp ;
temp = x ;
x=y;
y = temp ;
}
template < class T , class U >
Example
template <class T>
T larger ( T x, T y )
{
T big ;
if ( x > y )
big = x ;
else
big = y ;
return ( big ) ;
}
Example
main ( )
{
int i = 5 , j = 7 ;
double x = 10.0 , y = 15.0 ;
cout << larger ( i , j ) << endl ;
cout << larger ( x , y ) << endl ;
// cout << larger ( i , y ) ; Error
}
Example
template <class T>
void inverse ( T & x , T & y )
{
T temp ;
temp = x ;
x=y;
y = temp ;
}
Example
template <class T>
T inverse ( T x )
{
return ( - x ) ;
}
Example
main ( )
{
int i = 4 , j = 8 ;
inverse ( i , j ) ;
inverse ( i ) ;
}
Example
template <class T>
T reverse ( T x )
{
return ( - x ) ;
}
void main ( )
{
double a = 10.75 ;
reverse ( a ) ;
reverse <int> ( a ) ;
}
Example
template <class T , class U>
T reverse ( U x )
{
return ( - x ) ;
}
main ( )
Example
{
double a = 8.8 ;
reverse ( a ) ;
reverse <int> ( a ) ;
reverse <int , double> ( a ) ;
reverse<double , double> ( a ) ;
reverse<double , int> ( a ) ;
}
Example
class PhoneCall
{
private :
int lengthOfCall ;
char billCode ;
public :
PhoneCall ( const int i , char b ) ;
PhoneCall ( PoneCall & p ) ;
PhoneCall PhoneCall :: operator - ( void ) ;
void display ( void ) ;
};
Example
template <class T>
T reverse ( T x )
{
return ( - x ) ;
}
Example
PhoneCall reverse ( PhoneCall x )
{
return (- x ) ;
}
Example
PhoneCall PhoneCall :: operator - ( void )
{
PhoneCall temp ( * this ) ;
temp.billCode = 'C' ;
return ( temp ) ;
}
main ( )
Example
{
PhoneCall a ( 10 , ‘S’ ) ;
a.display ( ) ;
a = reverse ( a ) ;
a.display ( ) ;
}
Introduction to Programming
Lecture 42
template <class T>
Template
Classes
Stack
Last In
First Out
template <class T>
class ClassName
{
definition
}
Member function
template <class T>
Class_Name <T> :: Function_Name (Arguments)
{
// body of function
}
Class_Name :: Function_Name ( Arguments )
{
// body of function
}
Example
template <class T>
class Number
{
private :
T MyNumber ;
public:
Number ( T n ) ;
display ( ) ;
}
Example
Number <int> x ;
Number <double> y ;
Non Type
Parameters
template <class T , int elements>
int x [ 100 ] ;
Static
Member
Variables
Number <int> x ;
Example
class PhoneCall
{
private :
int lengthOfCall ;
char billCode ;
public :
PhoneCall ( const int i , char b ) ;
PhoneCall ( PoneCall & p ) ;
PhoneCall PhoneCall :: operator - ( void ) ;
void display ( void ) ;
};
Example
PhoneCall PhoneCall :: operator -( void )
{
PhoneCall temp ( * this ) ;
temp.billCode = 'C' ;
return ( temp ) ;
}
Friend
Function
‘a’ is a 2 is an
object of a integer value
class
a+2;
a+2;
should be same
as
2+a;
friend f ( ) ;
friend f ( x <T> & ) ;
friend f ( X <int> & ) ;
friend class Y ;
friend A :: f ( ) ;
friend A :: f ( X< T > & )
template <class T>
Example
class Stack
{
private :
int size ;
T array [ ] ;
public :
Stack ( ) ;
void push ( T ) ;
T pop ( ) ;
bool isEmpty ( ) ;
bool isFull ( ) ;
// Etc.
};
Example
Stack <int> x ;
Stack <double> x ;
Last In
First Out
Queue
Link List
First In
First Out
STL
Standard
Template Library
Introduction to Programming
Lecture # 43
Math Library
Complex number
Matrix
Quadratic equation and their solution
…………….…
Design Recipe
To design a program properly, we must :
– Analyze a problem statement, typically
expressed as a word problem
– Express its essence, abstractly and with
examples
– Formulate statements and comments in a
precise language i.e. code
– Evaluate and revise the activities in light
of checks and tests and
– PAY ATTENTION TO DETAIL
Matrix
• Matrix is nothing but a two
dimensional array of numbers
• Normally, represented in the
form of :
• Rows
• Columns
Example
1 2 3 4
A= 5 6 7 8
9 10 11 12
Three Rows
Four Columns
i & j are two Integers
i representing the Row number
j representing the Column number
Operations Performed with Matrix
• Addition of two matrices.
• Addition of a scalar and a matrix
• Subtraction of two matrices
• Subtraction of a scalar from a matrix
• Multiplication of two matrices
• Multiplication of a scalar with a matrix
• Division of a scalar with a matrix
• Transpose of a matrix
Interface
Addition of two Matrices
C = Aij
ij
X
Multiplication of a scalar with a Matrix :
Example
Let :
X is a Scalar number
A is a Matrix
X*A
X * A ij = Cij
Multiply two
Matrices
(1)(2)+(2)(1) (1)(4)+(2)(2)
1
5
2
6 *
2
1
4
2 = (5)(2)+(6)(1) (5)(4)+(6)(2)
Rules Regarding
Matrix Multiplication
Interchange of rows
and columns
Transpose of a Matrix
Example
1 2 3 1 5 9
5 6 7 2 6 10
9 10 11 3 7 11
Transpose of a Non
Square Matrix
A A
T
Display function
Plus operator : member operator of the class
Subtraction operator : member operator of the
class
Plus operator : friend of the class
Subtraction operator : friend of the class
Plus Operator
A+X
X+A
Subtraction Operator
A-X
X–A
Interface
Multiplication Operator : Member of the Class
Multiplication Operator : Friend of the Class
Division Operator : Member of the Class
Transpose Function : Member of the Class
Assignment Operator : Member of the Class
+= , -= : Members of the Class
Multiplication Operator
A*X
X*A
Assignment Operator
Memory Allocation
Memory Deallocation
Introduction to Programming
Lecture 44
Class Matrix
class Matrix
{
private :
int numRows , numCols ;
double ** elements ;
};
Class Matrix
class Matrix
{
private :
int numRows , numCols ;
double ** elements ;
public :
Matrix ( int = 0 , int = 0 ) ; // Default constructor
Matrix ( const Matrix & ) ; // Copy constructor
~ Matrix ( ) ; // Destructor
Class Matrix
// Utility functions of Matrix class
// Plus Operator
Matrix operator + ( Matrix & m ) const ;
Matrix operator + ( double d ) const ;
d is a variable
‘A’ is an object of a of type double
class Matrix
A+d;
d is a ‘a’ is an
variable of object of a
type double class Matrix
d+A;
Class Matrix
// Plus Operator
A–d;
d is a ‘a’ is an
variable of object of a
type double class Matrix
d–A;
Class Matrix
// Minus Operator
A*d;
d is a
variable of ‘a’ is an
type double object of a
class Matrix
d*A;
Class Matrix
// Multiplication Operator
A/d;
Class Matrix
// Division Operator
cin >> m ;
// Where m is a matrix
Class Matrix
// Stream Insertion and Extraction Operator
A=B
Class Matrix
(A=B)=C
Self Assignment
A=A
Class Matrix
const Matrix & Matrix :: operator = ( const Matrix & m )
{
if ( &m != this)
{
if ( numRows != m.numRows || numCols != m.numCols )
{
delete [ ] elements ;
elements = new ( double * ) [ m.numRows ] ;
for ( int i = 0 ; i < m.numRows ; i ++ )
elements [ i ] = new double [ m.numCols ] ;
}
Class Matrix
numRows = m.numRows ;
numCols = m.numCols ;
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < numCols ; j ++ )
{
elements [ i ] [ j ] = m.elements [ i ] [ j ] ;
}
}
}
return * this ;
}
Addition Operator
+
Addition Operator
A+B
Both A and B are Matrices
Class Matix
Matrix Matrix :: operator + ( Matrix & m ) const
{
// Check for conformability
if ( numRows == m.numRows && numCols == m.numCols )
{
Matrix temp ( * this ) ;
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < numCols ; j ++)
{
temp.elements [ i ] [ j ] += m.elements [ i ] [ j ] ;
}
}
return temp ;
}
Matrix temp ( * this ) ;
return temp ;
}
8:50
+= Operator
+= Operator
A += B
Class Matrix
const Matrix & Matrix :: operator += ( Matrix & m )
{
* this = * this + m ;
return * this ;
}
Class Matrix
Matrix Matrix :: operator + ( double d ) const
{
Matrix temp ( * this ) ;
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < numCols ; j ++ )
{
temp.elements [ i ] [ j ] += d ;
}
}
return temp ;
}
Class Matrix
Matrix operator + ( double d , Matrix & m )
{
Matrix temp ( m ) ;
for ( int i = 0 ; i < temp.numRows ; i ++ )
{
for ( int j = 0; j < temp.numCols ; j ++ )
{
temp.elements [ i ] [ j ] += d ;
}
}
return temp ;
}
13:00
*
Operator
Class Matrix
Matrix Matrix :: operator * ( const Matrix & m )
{
Matrix temp ( numRows , m.numCols ) ;
if ( numCols == m.numRows )
{
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < m.numCols ; j ++ )
{
temp.elements [ i ] [ j ] = 0.0 ;
for ( int k = 0 ; k < numCols ; k ++ )
{
temp.elements [ i ] [ j ] += elements [ i ] [ k ] * m.elements [ k ] [ j ] ;
}
}
}
}
return temp ;
}
Class Matrix
Matrix Matrix :: operator * ( double d ) const
{
Matrix temp ( * this ) ;
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < numCols ; j ++ )
{
temp.elements [ i ] [ j ] *= d ;
}
}
return temp ;
}
Matrix / d
Check d = 0 ?
<< Insertion Operator
>> Extraction Operator
Where m is an object of the class Matrix
cin >> m
Class Matrix
istream & operator >> ( istream & is , Matrix & m )
{
m.input ( is ) ;
return is ;
}
Class Matrix
• Sequences
• Decisions
• Loops
Variable
Variable is a name
for a value
Pointer
Pointer is the address
of a location in the
memory
Arrays
Decisions Or
if ( condition ) if ( condition )
{ {
statement ( s ) ; statement ( s ) ;
} }
Or else if ( condition )
if ( condition )
{ {
statement ( s ) ; statement ( s ) ;
} }
else
{
statement ( s ) ;
}
Repetition Structure
Object.member
Garbage
Collection
Truth
Table
Structured Query Language
SQL
Optimizer