0% found this document useful (0 votes)
10 views1,379 pages

Cs201 All PPT Slides

The document is an introduction to programming, focusing on the C language and structured programming methodologies. It covers essential programming concepts such as variables, data types, operators, control structures, and the design recipe for problem-solving. Additionally, it outlines course objectives, policies, and contents, along with examples and exercises to reinforce learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1,379 pages

Cs201 All PPT Slides

The document is an introduction to programming, focusing on the C language and structured programming methodologies. It covers essential programming concepts such as variables, data types, operators, control structures, and the design recipe for problem-solving. Additionally, it outlines course objectives, policies, and contents, along with examples and exercises to reinforce learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1379

Introduction to Programming

Lecture No. 1
Program
“A precise
sequence of
steps to
solve a
particular
problem”
Alan Perlis – Yale University:

“It goes against the grain of modern


education to teach children to program.
What fun is there in making plans,
acquiring discipline in organizing
thoughts, devoting attention to detail
and learning to be self-critical? “
Critical Skills
– Analysis
– Critical
Thinking
– Attention
to Detail
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
– Evaluate and revise the activities in light of
checks and tests
– PAY ATTENTION TO DETAIL
– These skills are useful for
anybody
– All assignments in this course
should follow the these
guidelines
Computers are

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”

“Twas brillig, and the slithy toves


Did gyre and gimble in the wabe “
Course Policy
Policy for the distribution of marks and
examination is as follows
 Assignments 15%

 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

 Structured flowcharts, pseudo-code


Course Contents
 History of C Language
 Variables and expressions in C
 Control structures and functions
 Arrays and Pointers
 Dynamic memory Allocation
Course Contents
 File handling
 Structures and Unions
 Flavor of Object oriented
programming
Introduction to Programming

Lecture 2
Today’s Lecture
 Software Categories
 System Software

 Application Software

 Introduction to ‘C’ Language


 History

 Evolution

 Justification

 Development Environment of ‘C’


There are two main categories of software

 System software

 Application Software
TWAIN

Technology Without An Interesting Name


ANSI C
Tools of the trade

 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;

cout << " x = " ;


cout << x ;

cout << " y = " ;


cout << y ;

cout << " z =x + y = " ;


cout << z ;
}
int x, y, z ;
int x; int y; int z ;
Data Types
1. int
2. short
3. long
4. float
5. double
6. char
Arithmetic operators
Plus +
Minus -
Multiply *

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 ;

cout << “ Please enter the age of student 1: “ ;


cin >> age1 ;

cout << “ Please enter the age of student 2: “ ;


cin >> age2 ;
:
:
TotalAge = age1+ age2 + age3+ age4+ age5+age6+ age7+ age8+age9 + age10 ;
AverageAge = TotalAge / 10 ;

cout<< “The average age of the class is :” << AverageAge ;


}
Quadratic Equation
 In algebra
y = ax2 + bx + c

 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

= (b*b - 4*a*c) /(2 *a) Correct answer


 No expression on the left hand
side of the assignment
 Integer division truncates
fractional part
 Liberal use of
brackets/parenthesis
Interesting Problem

Given a four-digit integer,


separate and print the digits
on the screen
Analysis
 Number = 1234

 Take the remainder of the above number after dividing by 10


Eg 1234 / 10 gives remainder 4
1234 % 10 = 4
 Remove last digit
– 1234/10 = 123.4
– 123 (Truncation due to Integer Division)
 123 %10 gives 3
 Remove last digit
– 123/10 = 12.3
– 12 (Truncation due to Integer Division)
 12 % 10 gives remainder 2
 Remove last digit
– 12/10 = 1.2
– 1 (Truncation due to Integer Division)
 Final digit remains
#include <iostream.h>
Code
main ( )
{
int number;
int digit;
cout << “Please enter a 4 digit integer : ”;
cin >> number;
digit = number %10;
cout <<“The digit is: “ << digit << ‘\n’; // first digit; and then << ‘\n’
number = number / 10;
digit = number % 10;
cout <<“The digit is: “ << digit << ‘\n’;
number = number / 10;
digit = number % 10;
cout <<“The digit is: “ << digit << ‘\n’;
number = number / 10;
digit = number % 10;
cout <<“The digit is: “ << digit;

}
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 Ali’s height is greater then 6 feet


Then
Ali can become a member of the
Basket Ball team
If Statement in C

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;

cout<<“Please enter Amir’s age”;


cin >> AmirAge;
cout<<“Please enter Amara’s age”;
cin >> AmaraAge;

if AmirAge > AmaraAge)


{
cout << “\n”<< “Amir’s age is greater then Amara’s age” ;
}
}
Flow Chart Symbols
Start or stop

Process

Flow line

Continuation mark

Decision
Flow Chart for if statement
Entry point for IF block

IF

Condition

Then

Process

Exit point for IF block

Note indentation from left to right


Example
If the student age is greater than
18 or his height is greater than
five feet then put him on the foot
balll team
Else
Put him on the chess team
Logical Operators

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

Exit point for IF block

Note indentation from left to right


Example
Code

if (AmirAge > AmaraAge)


{
cout<< “Amir is older than Amara” ;
}

if (AmirAge < AmaraAge)


{
cout<< “Amir is younger than Amara” ;
}
Example
Code

if AmirAge > AmaraAge)


{
cout<< “Amir is older than Amara” ;
}
else
{
cout<<“Amir is younger than Amara” ;
}
Make a small flow chart of this
program and see the one to one
correspondence of the chart
and the code
Example
Code

if AmirAge > AmaraAge)


{
cout<< “Amir is older than Amara” ;
}
else
{
cout<<“Amir is younger than or of the same age as
Amara” ;
}
Example
If (AmirAge != AmaraAge)
cout << “Amir and Amara’s Ages
are not equal”;
Unary Not operator !

 !true = false
 !false = true
If (!(AmirAge > AmaraAge))

?
Example

if ((interMarks > 45) && (testMarks >= passMarks))


{
cout << “ Welcome to Virtual University”;
}
Example
If(!((interMarks > 45) && (testMarks >= passMarks)))

?
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

Entry point for WHILE block

Condition is No
While Exit
true?

Process

Exit point for WHILE block


Factorial Definition

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

It executes zero or more


times
Introduction to Programming

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

for ( initialization condition ; termination condition ; increment condition )


{
statement ( s ) ;
}
Example
int counter ;
for( counter = 0 ; counter < 10 ; counter = counter + 1 )
cout << counter;

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

for ( counter = 0 ;counter <= 10 ; counter ++ )


{
…….
continue ;
}
What have we done till now …

 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

 Task: Making a stool


– Subtask:
 Make a seat
 Make legs for the stool
 Assemble them
What we will study today …

 What are functions?


 How are they defined ?
 How are they declared ?
 What values are passed to functions ?
 What values do functions return ?
Function
Function name
{
Body of the
function
}
Function

Two types of functions:


1. Functions that return a value

2. Functions that do not return a value


Function
return-value-type function-name( argument-list )
{
declarations and statements
}
Declaration of Function
return-value-type function-name( argument--type-list) ;
main ( )
{
:
}
Example
int function-name ( int , int , double ) ;

void main ( )
{
….
}
Definition of Function

int function-name ( int i , double j )


{

}
Return Type of Function
Declaration

int square ( int ) ;


Definition

int square ( int i )


{
return ( i * i ) ;
}
Function Call

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

double circleArea ( double radius )


{
return ( 3.1415926 * radius * radius ) ;
}
Calculating ringArea without
using Function
main ( )
{
:
ringArea = ( 3.1415926 * rad1 * rad1 ) – ( 3.1415926 * rad2 * rad2 ) ;

}
Exercises
1. Modify the raise to power function
so that it can handle negative power
of x, zero and positive power of x.

2. For the area of ring function put in


error checking mechanism.
In today’s lecture
 We used functions for breaking complex problems into
smaller pieces, which is a top-down structured approach.
 Each function should be a small module, self contained
and it should solve a well defined problem.
 Variable names and function names should be self
explanatory.
 Always comment your code
Introduction to Programming

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

int functionName ( int , int );


Using Header Files
double pi = 3.1415926;
 It is better to define this value in a header file

 Then simply by including the header file in the


program this value is defined and it has a
meaningful name
#define
 #define pi 3.1415926
 Name can be used inside a program
exactly like a variable
 It cannot be used as a variable

CircleArea = pi * radius * radius

Circumference = 2 * pi * radius
Scope of Identifiers
 Identifier is any name user creates in his/her
program

 Functions are also identifiers

 Labels are also identifiers


Scope of Identifiers
 Scope means visibility

 A variable declared inside a block has


visibility within that block only

 Variables defined within the function has a


scope that is function wide
Example
void functionName ( )
{
{
int i ;
}
…..
}
Identifiers Important Points
 Do not create variables with same
name inside blocks, inside functions
or inside bigger blocks

 Try to use separate variable names to


avoid confusion

 Reuse of variables is valid


File Scope
# include < iostream.h >
int i ;
Global variable
Global Variable
 Can be used anywhere in program
 Can cause logical problems if same variable
name is used in local variable declarations

For good programming

 Try to minimize the use of global variables


 Try to use local variables as far as possible
Visibility of Identifiers
 Global Scope
Anything identified or declared outside of any
function is visible to all functions in that file
 Function level scope
Declaring variables inside a function can be
used in the whole function
 Block level scope
Variables or integers declared inside block are
used inside block
Example: Block Scope
for ( int i = 0 ; i < 10 ; i++ )

 It is block level scope declared in for


loop
 When for is finished “ i ” no longer
exists
Example: Global Scope
#include < iostream.h >
int i ;
void f ( void ) ;
main ( )
{
i = 10 ;
cout<< “ within main i = “ << i ;
f();
}
Example: Global Scope
void f ( void )
{
cout<< “ Inside function f , i =“ << i ;
i = 20 ;
}
Example: Call by Value
#include <iostream.h >
int f ( int ) ;
main ( )
{
int i = 10 ;
cout << “In main i = " << i ;
f(i);
s cout << " Back in main, i = " << i ;
}
Example: Call by Value
int f ( int i )
{
cout << "In function f , i = " << i ;
i *= 2 ;
cout << "In function f , i is now = “ << i
;
return i ;
}
Example : Square of a Number

double square ( double x )


{
return x * x ;
}
main ( )
{
double number = 123.456 ;
cout << “ The square of “ << number << “ is “<< square ( number )

cout << “ The current value of “ << number << “is “ << number ;
}
Math.h
#include < math.h >
double sqrt ( double );

log10 , pow ( xy ) , sin , cos , tan …


Call by Reference
 A function in which original value of the
variable is changed
 To call by reference we cannot pass value,
we have to pass memory address of
variable
 “&” is used to take the address of a
variable
Example: Call by Reference

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

x is a pointer to a variable double


square ( double *x )
{
*x = *x * *x ;
}
Pointers
 Pointers are used to pass address of
variable for reference

 We use “ &x ” to send the address of


“x“

 To receive the address we use “ *x ”


(whatever “ x ” points to)
Recursive Functions
 Special function which can call itself

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

long factorial ( long n )


{
if (n == 1 )
return ( n ) ;
else
return ( n * factorial (n-1) ) ;
}
Exercise
Try to write program for

 Fibonacci series

 Find ‘power of number’ using recursive


technique
Example
The Fibonacci Series
 Set of recursive calls to function
fibonacci
f( 3 )

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 ] ;

 More than one array can be declared on a line


int age [10] , height [10] , names [20] ;

 Mix declaration of variables with declaration of arrays


int i , j , age [10] ;
Referring to Array
Elements

Array name e.g. age


index number

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,0,0,0,0,0,0,0,0,0 } ;

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

– Size should be same


int a [ 10 ] ;
int b [ 10 ] ;
Copying Arrays
To copy from array “ a ” to array “ b ” :

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 ( ) ;

A call goes to ” rand ( ) “ , it generates


a number and returns to x
Modulus “ % ”
It returns the remainder

rand ( ) % 6 = ?
Result has to be between 0 and 5 inclusive

1 + rand ( ) % 6

It will randomly generate number between


1 and 6
Fair Die
If a die is rolled 10/100 million of time , then
on average equal number of 1’s ,equal
number of 2’s , equal number of 3’s etc. will
be generated
Example: Tossing a Coin
It has only two possibilities 0 / 1

rand ( ) % 2 ;
Importance of rand ( )
 It is shipped in every standard library with
compiler

 Most major programming languages give


some kind of random number generator
as a function as part of library

 Writing a random number generator is


itself a field
Array Declaration

data type
name
size
const
const
const int arraySize = 100 ;

 It creates an identifier “ arraySize ” and


assigns a value 100. This is called
integer constant . It is not a variable
 Its value cannot be changed
Introduction to Programming

Lecture 12
Today’s Lecture Includes

 Strings ( character arrays )


 Algorithms using arrays
 Multi-dimensional arrays
char name [ 100 ] ;
\0
In C we have Used
\n New Line

\t Tab Character

\0 Null Character

All C strings are terminated by Null character


Character Array in
Memory

char name [ 100 ] ;


cout << “ Please enter your name ” ;
cin >> name ;
Initializing an Array
Initializing array of integers

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 } ;

For character arrays


char name [ 100 ] = { ‘a’,b’,’c’,’0’,’1’ } ;
char name [ 100 ] = “abc01“ ;
char name [ ] = “Hello World“ ;
Character Arrays
To read name from keyboard and
display it on screen
char name [ 100 ] ;
cout << “ Please enter you
name” ;
cin >> name ;
cout << name ;
Character Arrays
Displaying name on screen using loop

for ( i = 0 ; i < 100 ; i ++ )


{
cout << name [ i ] ;
}
Comparing Two arrays
Condition : Array size should be equal

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

 Determine the length of character


array
Sorting
 Bubble Sort

 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

 Total array size will be 2n and number


can be found in n times

 If 1000 numbers then 10 tries are max


210 = 1024
Is divide and conquer the fastest way, all the
time, of searching for a number in a list ?

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

 Name of the array


 Size of the array
Example 1

Declaration
char name [ 100 ] ;
Function Call

reverse ( name , 100 ) ;


Example 1
Prototype
void reverse ( char [ ] , int ) ;

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

In case of arrays , call by reference is default


X is a variable which is a location in the
memory
Name [ ] is an array
Starting
address - - - - - - - -
Array called Name
Memory

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

function, it is called by reference


Vector
2 Dimensional
3 Dimensional

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

After second outer


loop Input

[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

 Analyzing and solving a real world


problem
Array
Manipulation
Example 1
Input
Row 1 1 2 3 Memory
Row 2 4 5 6
Row 3 7 8 9
Row 3 7 8 9
Row 2 4 5 6
Row 1 1 2 3
Output
Addressing Array
Elements

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 ;

Index of Start [0] 1 2 3


[1]
Index of Last Row = maxRows - 1 [2]
Example 2
for ( row = maxRows - 1 ; row >= 0 ; row -- )
{ Decrement Operator
for ( col = 0 ; col < maxCols ; col ++ )

}

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

[0] [1] [2] [2] [1] [0]


1 2 3 3 2 1
4 5 6 6 5 4
7 8 9 9 8 7
Transpose of a Matrix

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

temp = a [ row ] [ col ] ;


a [ row ] [ col ] = a [ col ] [ row ] ;
a [ col ] [ row ] = temp ;
Practical Problem
Problem statement
Given tax brackets and given
employee gross salaries , determine
those employees who actually get less
take home salary than others with
lower initial income
Rule for tax deduction

0 –> 5,000 No tax


5001 – >10,000 5% Income Tax
10,001 – >20,000 10% Income Tax
20,001 and more 15% Income tax
Example
Net salary = Rs 10,000
Tax = 5%
Amount Deducted = 5% of 10,000
= 500
Net amount after deduction = 10,000 - 500
= 9,500
Net salary = Rs 10,001
Tax = 10%
Amount Deducted = 10% of 10,001
= 1,000.1
Net amount after deduction = 10,001 - 1,000.1
= 9,000.9
Storage Requirement
One- dim arrays of integer 0
0
lucky = 0
lucky = 1 0
0
0
0
0
Storage of salary
No of Grow Net Salary
Emp. Salary After Deduction
1 5,000 5,000
2 10,000 9,500
3
4
5
6
7
8
9
10
Interface Requirements
Distribution of the
Program
 Input
 Salary calculation

 Identification of the unlucky

individuals
 Output
Detail Design
Functions in the program

getInput
calculateSalary
locateUnluckyIndividual
displayOutput
Code
#include<iostream.h>

void getinput ( int [ ] [ 2 ] , int ) ;


main ( )
{
const int arraySize = 100 ;
int sal [ arraySize ] [ 2 ] ;
int lucky [ arraySize ] = { 0 } ;
int numEmps ;
cout << “Enter the number of employess “ ;
cin >> numEmps ;
getInput ( sal , numEmps ) ;
}
Code
getInput ( int sal [ ] [2] , int numEmps )
{
for ( i = 0 ; i < numEmps ; i ++ )
cin >> sal [ i ] [ 0 ] ;
}
cs201@vu.edu.pk
Exercise
Suppose you are given a
square matrix of size n x n ,
write a program to determine
if this is an identity matrix
Introduction to Programming

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 ] )

This logic will fail


Code
void locateUnluckyIndividual ( int sal [ ] [ 2 ] , int lucky [ ] , int numEmps )
{
int i , j ;
int grossSalary , netSalary ;
for ( i = 0 ; i < numEmp ; i ++ )
{
grossSalary = sal [ i ] [ 0 ] ;
netSalary = sal [ i ] [ 1 ] ;
for ( j = 0 ; j < numEmp ; j ++ )
{
if ( grossSalary > sal [ j ] [ 0 ] && netSalary < sal [ j ] [ 1 ] )
{
lucky [ i ] = 1 ;
}
}
}
}
Code
void displayOutput ( int sal [ ] [ 2 ] , int lucky [ ] , int numEmps )
{
for ( i = 0 ; i < numEmp ; i ++ )
{
if ( lucky [ i ] == 1 )
{
cout<< “Employee No.” << i+1 << “ is

unlucky, Gross Salary = ” << sal [ i ] [ 0 ]


<< “ Net Salary = ” << sal [ i ] [ 1 ] << “\
n” ;
}
}
Pointers
Pointers
Location
x
60000 10
Address of x
Declaring Pointer to
Integer

int *myptr ;

myptr is pointer to an integer


Declaring Pointers

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 ;

0 and NULL points to nothing


Example
main ( )
{
int numEmp ;
….
funct ( &numEmp ) ;
….
}

void funct ( int *numEmp )


{
cin >> *numEmp ;
}
Declaring pointers

int *ptr1 , *ptr2 , *ptr3 ;


Declaring pointers

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 ;

myptr is a constant pointer to an


integer
const
const int x = 10 ;
const
const int *myptr = &x ;

myptr is a pointer to a constant integer


Array
int a [ 10 ] ;
Starting Address of Array a 1
2
3
4
5
6
7
8
9
10
Introduction to Programming

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

y[0] y[1] y[2] y[3] y[4]

pointer variable yPtr


In this case yptr is a pointer
to integer so now when we
increment yptr it points to
the next integer
Example 1
#include<iostream.h>
main ( )
{
int y [ 10 ] ;
int *yptr = y ;
yptr = y ;
cout << yptr ;
yptr ++ ;
cout << yptr ;
}
yptr = y ;

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

cout << *yptr ;


*yptr += 3 ;
Pointer Arithmetic

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

if ( *y1 > *y2 )


Example
int y [ 10 ] ;
int *yptr ;
yptr = y ;
cout << y [ 5 ] ;
cout << ( yptr + 5 ) ;
cout << *( yptr + 5 ) ;
Example
int que [ 10 ] ;
int y [ 10 ];
int *yptr ;
yptr = y ;
yptr = que ;
location
3000 3004 3008 3012 3016

v[0] v[1] v[2] v[3] v[4]

pointer variable vPtr


Strings
String Initialization
char name [ 20 ] ;
name [ 0 ] = ‘A’ ;
name [ 1 ] = ‘m’ ;
name [ 2 ] = ‘i’ ;
name [ 3 ] = ‘r’ ;
name [ 4 ] = ‘\0’ ;
String Initialization

Strings is always
terminated with \0
String Initialization
char name [ 20 ] = “Amir” ;

Array must be one character


space larger than the number of
printable character which are to
be stored.
Example 4
char string1 [ 20 ] = “Amir”;
char string2 [ 20 ] ;
char *ptrA, *ptrB ;
prtA = string1 ;
prtB = string2 ;
while ( *ptrA != ‘\0’ )
{
*ptrB++ = *ptrA++;
}
*ptrB = ‘\0’ ;
String Copy Function
myStringCopy ( char *destination , const char *source )
{
while ( *source != ‘\0’ )
{
*destination++ = *source++ ;
}
*destination = ‘\0’ ;
}
In Today’s Lecture
 Pointers and Arrays
 Pointer Arithmetic

 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 myName [ ] = “Amir” ;


char *myNamePtr = “Amir” ;
Multi-dimensional Arrays

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

1st row 2nd row 3rd row


1st col 1st col 1st col
Dereferencing array element

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 ++)
{

cout << *( ptr ++ ) << “ ”;


}
cout << endl ;
}
}
Pointer to a
Pointer
Array of Pointers
Array of Pointers

char *myArray [ 10 ] ;
myArray is an array of 10 pointer to
character
Initialization

char *myArray [ ] = { “Amir ” , “ Jahangir ” } ;


Storing Pointers in Array of
Pointers

int *p1 , *p2 , *p3 ;


int *b [ 3 ] ;
b [ 0 ] = p1 ;
b [ 1 ] = p2 ;
b [ 2 ] = p3 ;
Command Line Arguments
argc
argv

‘argc’ stands for a count of the number


of arguments

‘argv’ stands for a vector of arguments


Example 4
main ( int argc , char **argv )
{
cout << argc << "\n“ << *argv ;
}
Example 5
main ( )
{
const char *suit [ 4 ]= { "Spades“ , "Hearts“ , "Diamonds“ ,
"Clubs“ } ;
const char *face [ 13 ] = { "Ace“ , "Deuce“ , "Three“ , "Four",
"Five“ , "Six“ , "Seven“ , "Eight“ ,
"Nine“ , "Ten“ , "Jack“ , "Queen“ , "King" } ;

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 ;

for ( card = 1 ; card <= 52 ; card ++ )


{
do
{
row = rand ( ) % 4 ;
column = rand ( ) % 13 ;
}
while( wDeck[ row ]| column ] != 0 ) ;
wDeck [ row ] [ column ] = card ;
}
}
Deal Function
void deal ( const int wDeck [ ] [ 13 ] , const char *wFace [ ] , const char *wSuit [ ] )
{
int card , row , column ;
for ( card = 1 ; card <= 52 ; card ++ )
{
for ( row = 0 ; row <= 3 ; row++ )
{
for ( column = 0 ; column <= 12 ; column ++ )
{
if ( wDeck [ row ] [ column ] == card )
// Print the face and suit of the card
// break out of loops
}
}
}
}
What we have done today

 Multi-dimensional Arrays
 Pointers to Pointers

 Arrays of Pointers

 Command Line Arguments

 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

int isdigit ( int c ) ;


isalpha ( ) Function

int isalpha ( int c ) ;


isalnum ( ) Function

int isalnum ( int c ) ;


islower ( ) Function

int islower ( int c ) ;


isupper ( ) Function

int isupper ( int c ) ;


tolower ( ) Function

int tolower ( int c ) ;


toupper ( ) Function

int toupper ( int c ) ;


getchar ( ) ;
cout << “Please enter a character string then press enter”;
while ( ( c = getchar ( ) ) != ‘\n’ )
{
if ( islower ( c ) )
lc ++ ;
else if ( isupper ( c ) )
uc ++ ;
else if (isdigit ( c ) )
dig ++;
else if ( isspace ( c ) )
ws ++ ;
else if ( ispunct ( c ) )
pun ++ ;
else
oth ++ ;
}
String Conversion Functions

double atof ( char * str )


int atoi (char * str )
long atol (char * str )
atoi ( ) Function
char str [ ] ;
int age ;
age = atoi ( str ) ;
atof ( ) Function

12.89
atof ( ) Function
char str [ ] ;
double dVar ;
dVar = atof ( str ) ;
int main (int agrc, char **agrv )

‘argc’ stands for a count of the number of


arguments

‘argv’ stands for a vector of arguments


String Functions
String Manipulation Functions
Function prototype Function description
char *strcpy( char *s1, Copies string s2 into array s1. The value of s1 is
const char *s2 ) returned.
char *strncpy( char *s1, Copies at most n characters of strings2 into array s1.
const char *s2, size_t n) The value of s1 is returned.

int strcmp( const char *s1, Compares strings1 to s2


const char *s2 ); Returns a negative number ifs1 < s2, zero if s1 == s2
or a positive number ifs1 > s2
int strncmp( const char *s1, Compares up to n characters of strings1 to s2
const char *s2, size_t n ); Returns values as above

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 * strncpy ( char *s1 , char *s2 , int n ) ;

char * strcat (char *s1 , char *s2 ) ;

char * strncat ( char *s1 , char *s2 , int n ) ;


strcmp ( ) Function

int strcmp (const char *s1 , const char *s2 ) ;


strncmp ( ) Function

int strncmp ( const char *s1 , const char *s2 , int n ) ;


strlen ( ) Function

int strlen ( const char *s ) ;


Search Functions
Search Functions
Function prototype Function description

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

 Any data that you key in by keyboard


while a program is running is also
volatile
File Handling

 Text files handling

 Binary files handling


Steps to handle file
 Open the File

 Read / Write the File

 Close the File


Streams
Header File for File
Handling

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;

We can also write:


myfile >> var1 >> var2 ;
Close the File

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” ) ;

if ( !myFile ) // Error check


{
cout << “Your file could not be opened”;
}
------
myFile.close ( ) ;
Output File Modes
 Create a new file
 Overwrite an existing file
 Append some text
 Randomly accessing a file
Syntax
fStream fileVar ( “fileName” , mode ) ; // Generic syntax
Opening
Mode

ifstream myfile ( “myfile.txt” , ios :: in ) ;


Opening
Mode

ofstream myfile ( “myfile.txt” , ios :: out ) ;


List of File Handling Modes

ios :: in open for reading (default for ifstream)


ios :: out open for writing (default for ofstream)
ios :: app start writing at end of file (APPend)
ios :: ate start reading or writing at EOF of file (ATEnd)
ios :: trunc truncate file to zero length if it exists (TRUNCate)
ios :: nocreate error when opening if file does not already exist
ios :: noreplace error when opening for output if file already exists
ios :: binary open file in binary (not text) mode
 Append
ofstream myfile (“myfile.txt” , ios :: app ) ;
 Random Access
ofstream myfile ( “myfile.txt” , ios :: ate ) ;
 Truncate
ofstream myfile ( “myfile.txt” , ios::trunc ) ;
myfile.eof ( )

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 ) ;

ofstream myOnputFile ( “myfile.txt” , ios :: out ) ;


int i ;
i=0;

int i = 0 ;
Open file

ifstream myInputFile ( “myfile.txt” ) ;


Open file

ofstream myOnputFile ( “myfile.txt” ) ;


strtok ( )
getline ( ) function
Syntax of getline function
Numbers of
Character characters to
array be read

myfile.getline (char *s, int n, char delim);


delimiter
Syntax of getline function
Input
Hello World

myfile.getline ( arrayString , 20 , ’W’ ) ;

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

 open ( file_name , mode ) ;


 close ( ) ;
ifstream myFilePtr ;
myFilePtr.open ( “myFile” , ios :: in ) ;
Output File Stream
 ios :: app
 ios :: trunc
 ios :: ate
Read/write a character

get ( ) Read a character


put ( ) Write a character
Number of Delimiter
characters to read

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

filePtr.seekg ( long Num , ios :: origin ) ;


seekg ( )
seekg ( 10L , ios :: beg ) ;
seekg (10L , ios :: cur ) ;
seekg ( 10L , ios :: end ) ;
Example 1
#include<fstream.h>
main ( )
{
int length ;
ifstream inFile ( “myFile.txt” ) ;
inFile.seekg ( 0L , ios :: end ) ;
length = inFile.tellg ( ) ;
}
File
Name city Date-of-Birth
: : :
Jamil Ahmed Sukkur 10-10-1982
: : :

Rawalpindi
Merge Method
Original file Empty file

This is a text
data And needs
To be replaced NOT
seekg ( )

seekg ( 2201L , ios :: beg ) ;


fstream

fstream myFile ( “Sample.txt” ,


ios :: in | ios :: out ) ;
OR Function
A B Output
0 0 0
0 1 1
1 0 1
1 1 1
Example 2
This is an Apple

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

read ( char *buff , int count ) ;

Area in memory
Number of bytes to
be written

write ( char *buff , int count ) ;


Example 3
char str [ 10000 ] ;
myInputFile.read ( str , 10000 ) ;
myOuputFile.write ( str , 10000 ) ;
seekg ( )

seekg ( 0L , ios :: end ) ;


seekg ( )

seekg ( -1L , ios :: end ) ;


seekg ( )

seekg ( -2L , ios :: cur ) ;


Address of the
integer ‘i’ Number of bytes
to be written

myOutputFile.write ( &i , 4 ) ;
sizeof ( ) ;
Address of the
integer ‘i’ Size of integer

myOutputFile.write ( &i , sizeof ( i ) ) ;


for ( i = 0 ; i < 100 ; i ++ )
{
myOutputFile.write ( &i , sizeof ( i ) ) ;
}
myOutputFile.close ( ) ;
Introduction to Programming
Lecture 20
In the Last Two Lectures

 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

Student s1 = { “Amara”,“cs201”,“19”, “2002” } ;

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

cout << s1.name ;


cout << s1.course ;
cout << s1.age ;
cout << s1.year ;
Assignment of structures

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

Bit1 Bit2 Bit1 & Bit2


1 1 1
1 0 0
0 1 0
0 0 0
Bitwise AND Operator Example
3 2 1 0
………… 2 2 2 2
12 = 1 1 0 0
&
8 _______________
= 1 0 0 0
1 0 0 0

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

Hence the result x = 12


Bitwise OR Operator
Example 2
x=8|1

1 0 0 0
|
0 0 0 1
_____________
1 0 0 1

Hence the result x = 9


Bitwise Exclusive OR
Operator
Truth table for Exclusive OR operation
A B A^B
1 1 0
1 0 1
0 1 1
0 0 0
Example: Exclusive OR
Operator
X=8^1
1 0 0 0
0^ 0 1
0_____________
Result x = 9 1 0 0 1

X=9^1 0 0 ^0 1
_____________
Result x = 8 1 0 0 0
NOT Operator

Truth table for 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

 << shift left


 >> shift right
Left & Right Shift
Operator
Unsigned int i = 4 ;
i << 1 ; shift left
i >> 1 ; shift right
Left shift
1 0 1 1 0 0 0 1

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

&= Bitwise AND Assignment Operator


Operato
|= Bitwise OR Assignment Operator
^= Bitwise Exclusive OR Assignment
Operator
Assignment Operator

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

Bit wise AND & (Binary


Bit wise OR | (Binary)
Bit wise Exclusive OR ^ (Binary)
NOT ~ (unary
 Sequential Construct
 Decision Construct
 Loop Construct
If-statement
if ( condition )
{
statement ( s ) ;
}
If-else
if ( condition )
{
statement ( s ) ;
}
else
{
statement ( s ) ;
}
if ( a > b && c < d )
Nested if
statements
if ( condition )
{
statement ( s ) ;

if ( condition )
{
statement ( s ) ;
}
statement ( s ) ;
}
While Loops
while ( a > b )
{
statement ( s ) ;
}
While Loops

While loop executes


zero or more times
Do - while
do
{
statement ( s ) ;
}
while ( condition ) ;
Do - while
Do-while loop
executes
one or more times
For Loops
for ( i = 0 ; i < 10 ; i ++ ; )
{
statement ( s ) ;
}
 i=i+1;
 i += 1 ;

 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>

Consol Input Output


#include <conio.h>
#include <conio.c>
int getche ( ) ;
Get Character
With Echo
#ifdef __cplusplus
extern "C" {
#endif
--
--

#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

#define MAXSTUDENT 100


int Student [ MAXSTUDENT ] ;
Problem statement

Find the average age of


the students in your class
int numstd ;
Example 2
int *iPtr , *sPtr ;
cout << "Enter the number of students " << endl ;
cin >> numstd ;
iPtr = malloc ( numstd * ( sizeof ( int ) ) ) ;
if ( iPtr == NULL )
{
cout << "Error on malloc " ;
return 1 ;
/* Use a nonzero return to indicate an error has occurred */
}

// 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
}

double squareroot ( double x )


{
// body of the function
}
Example 4
main ( )
{
double i , x ;
int j = 5 , k ;
i = squareroot ( 10.5 ) ;
cout << i << endl ;
k = squareroot ( j ) ;
cout << k << endl ;
}
Example
F ( int a , int b ) ;
F ( int a , int b , int c ) ;

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

The instances of the


class are called Objects.
Structure of a class
class name_of_class
{

// 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 :

// private data and functions

public :

// public data and functions


};
Date Class
class Date
{
int day ;
int month ;
int year ;
};
main ( )
{
Date mydate ;
mydate.month = 10 ; // illegal
}
Date Class
class Date
{
private :
int day , month , year ;
public :
setMonth ( ) ;
print ( ) ;
};
main ( )
{
Date mydate ;
mydate.setMonth ( 10 ) ;
mydate.print ( ) ;
}
Separation of Interface
from the Implementation.
Example 3
class Date
{
public :
void display ( ) ;
Date ( int day , int month , int year )
private:
int day , month , year ;
};
Example 3
void Date :: display ( )
{
cout << day << “/ " << month << “/ " << year ;
}
Scope Resolution
Operator
Example 3
main ( )
{
Date mydate ;
mydate.display ( ) ;
}
Example
class Date
3: Modified
{
public :
Date ( int month , int day , int year ) ;
void display ( ) ;
setDay ( int ) ;
setMonth ( int ) ;
setYear ( int ) ;
private :
int month , day , year ;
};
Example 3: Modified
main ( )
{
Date mydate ;
mydate.setDay ( 10 ) ;
}
Example 3: Modified
void Date :: setDay ( int i )
{
day = i ;
}
Example 3: Modified
main ( )
{
Date date1 , date2 , date3 ;
date1.setMonth ( 10 ) ;
date2.display ( ) ;
}
Constructor
Example 3: Modified

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.

The argument list can:


– Either vary in the number of
arguments
– Or vary in the type
Example
class Date
{
public :
Date ( int month = 1 , int day = 1 , int year = 1
private :
int month , day , year ;
};
Example
main ( )
{
Date mydate ( ) ;
}
Example
main ( )
{
Date mydate ( “01-Jan-2002” ) ;
}
Memory Allocation Inside
a Constructor
Utility
Functions
Friend
Functions
Destructor
~
Rules of
Destructor
1. Destructors cannot be
overloaded
2. Destructors take no arguments
3. They don’t return a value
class Date
Example 1
{
public :
Date ( ) ;
Date ( int month , int day , int year ) ;
~Date ( ) ;
setMonth ( int month ) ;
setDay ( int day ) ;
setYear ( int year ) ;
int getDay ( ) ;
int getMonth ( ) ;
int getYear ( ) ;
setDate (int day, int month, int year ) ;
private:
int month , day , year ;
};
Example 1
main ( )
{
Date mydate ( 35 , 13 , 2000 ) ;
}
Example 1
main ( )
{
Date mydate ;
mydate.setDate ( 21 , 01 , 1979 ) ;
}
Example 1
main ( )
{
Date mydate ( 21 , 01 , 1979 ) ;
}
What Happens in Memory
Functions
setMonth ( int month ) ;
setDay ( int day ) ;
setYear ( int year ) ;
int getMonth ( ) ;
int getDay ( ) ;
int getYear ( ) ;

int month ; int month ; int month ;


int day ; int day ; int day ;
int year ; int year ; int year ;
Example 2
main ( )
{
Date date1 , date2 , date3 ;
date1.setMonth ( 3 ) ;
date2.setDay ( 23 ) ;
}
Destructors
~className ( ) ;
Destructors
~Date :: Date ( )
{
cout<< “Object Destroyed” ;
}
Constructors
Date :: Date ( )
{
cout << “Date Object Created” ;
}
Constructors without
Arguments
Date :: Date ( )
{
cout<< “Default constructor
without arguments called ” ;
}
Constructors with
Arguments

Date :: Date ( int month , int day , int year )


{
cout<< “A constructor with paramerters ” ;
}
Introduction of Programming
Lecture 28
Today’s Lecture
 How memory allocation is done in
C++
 How is it different from C style
 Advantages of memory allocation in
C++
 Uses of memory allocation
– Classes
– Objects
Pointers to a
data structure
Pointers to a
class
->
Memory Allocation
malloc ( ) ;
calloc ( ) ;
realloc ( ) ;
malloc ( 10 * ( sizeof ( int ) ) ) ;
free ( )
new
new int ;
Example

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 ;

dptr is a pointer to an object of type date


dptr = new Date ;
Example
main ( )
{
Date mydate ;
cout<< sizeof
( mydate ) ;
}
Example

int *iptr ;
iptr = new int [ 10 ] ;
Example
Date *dptr ;
dptr = new Date [ 10 ] ;
Example
Date date1 , *dptr ;
date1.setDate ( ) ;

dptr = new Date ;


dptr ->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
{
--

friend functionName ( Argument_list ) ;


--
};
Friend Function
 Friend functions are NOT the members of
the class
 The class itself declare it’s friend
functions
 The prototype of these functions are
written inside the class and the key word
friend is appended before the function
name
 Friend functions have access to private
and public members of the class
Example
class myClass
1
{
friend increment ( myClass , int ) ;
private:
int topSecret ;
public:
myClass ( )
{ topSecret = 100 ; }
void Display ( )
{ cout<< “The value of topSecret is
“ << topSecret ; }
};
Example 1
void Increment ( myClass A , int i )
{
A.topSecret += i ;
}
Example 1
main ( )
{
myClass x ;
x.Display ( ) ;
Increment ( x , 10 ) ;
x.Display ( ) ;
}
Example 1: Output

The value of topSecret is 100

The value of topSecret is 110


Example 2
class myClassTwo ;
class myClassOne
{
private :
int topSecret ;
public :
void Display ( ) ;
myClassOne ( )
{ topSecret = 100; }
friend AddBoth ( myClassOne , myClassTwo )
};
Example 2
class myClassTwo
{
private:
int topSecret ;
public:
void Display ( ) ;
myClassTwo ( )
{ topSecret = 200 ; }
friend AddBoth ( myClassOne , myClassTwo ) ;

};
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 ;

cout << “The value of topSecret in myClassTwo object


is”<< B.topSecret ;

cout << “The sum of topSecret values in “


<< “myClassOne and myClassTwo object is ”
<< A.topSecret + B.topSecret ;
}
Example 3
class otherClass ;
class classOne
{
private :
int topSecret;
public :
void Display ( ) ;
classOne ( )
{ TopSecret = 100 ; }
friend otherClass ;
};
Straight Line

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" } ;

void valfunc ( b ) ; // Call by value

void ptrfunc ( * b ) ; // Call by pointer

void reffunc ( & b ) ; // Call by reference


Example 4
void main ( )
{
valfunc ( b ) ; // Passing the variable itself
ptrfunc ( & b ) ; // Passing the address of the variable

reffunc ( b ) ; // Passing a reference to the variable

}
struct b
Example 4
{
int serno ;
char text [ 1000 ] ; // A lot of chars
} b = { 123 , "This is a BIG structure" } ;

void valfunc ( b ) ; // Call by value

void ptrfunc ( const * b ) ; // Call by pointer

void reffunc ( const & b ) ; // Call by reference


Difference Between
References and Pointers
main ( )
{
int i ;
int & refi = i ;
cout << “The address of the
reference is ” << & refi ;
cout << & i ;
}
Dangling
Reference
References as Return Values
int mynum = 0 ; // Global variable
int & num ( )
{
return mynum ;
}
void main ( )
{
int i ;
mynum = 100 ;
i = num ( ) ;
num ( ) = 200 ;
}
int & i ;
double & f ;
char & c ;
a=b=c;
a=b;
cout << “The values of the
integer is ”<< i << endl ;
Introduction to Programming
Lecture 31
Operator
Overloading
Today’s Lecture
– Operators
– Syntax for overloading
operators
– How to overload operators ?
Complex
Number
complex c1 , c2 , x ;
x = cadd ( c1 , c2 ) ;
x = cadd ( cadd ( a , b ) , c ) ;

Operators
The complete list of C++ operators that are
overloaded is as follows
+ - * / % ^ &
| ~ ! = < > +=
-= *= /= %= ^= &= |=
<< >> >>= <<= = = != <=
>= && | | ++ - - -> * ,
-> [ ] ( ) new new[ ] delete delete
[]
a+b
Date.day
Example
Return_type operator + (Argument_List)
{
// Body of function
}
a*b+c;
x=y+z;
Example
class Complex
{
private :
double real ;
double imag ;
public :
// member function
}
Example
Complex c1 , c2 ;
c1 = c2 ;

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

Complex operator += ( Complex & c )


Example
Complex Complex :: operator += ( Complex & c )
{
real += c.real ;
imag += c.imag ;
}
Example
Complex operator + ( Complex & c1 , Complex & c2 )
{
Complex temp ;
temp.real = c1.getreal ( ) + c2.getreal ( ) ;
temp.imag = c1.getimag ( ) + c2.getimag ( ) ;
return temp ;
}
class String
Example
{
private :

char s [ 30 ] ;

public :

String ( )
{
strcpy ( s , "" ) ;
}

// Declaration (prototype) of overloaded sum operator

String operator + ( String c ) ;


};
Example
String String :: operator + ( String c )
{
String temp ;
strcpy ( temp.s , "" ) ;
strcat ( temp.s , s ) ;
strcat ( temp.s , c.s ) ;
return temp ;
}
Introduction to Programming
Lecture 32
In Last Lecture
– What is operator overloading ?
– Overload operators
We also saw the
– Binary Operators
– Unary Operators
– Member and Non-member
operators
Example

Complex operator - ( Complex c ) ;


Example
Complex Complex :: operator - ( Complex c )
{
Complex Temp ;
Temp.real = real - c.real ;
Temp.imag = imag - c.imag ;
return Temp ;
}
Example

void operator -= ( Complex c ) ;


Example
void Complex :: operator -= ( Complex c )
{
real -= c.real ;
imag -= c.imag ;
}
Date operator + ( int i ) ;
Example
Date Date :: operator + ( int days )
{
Date Temp ;
int toHold ;
int daysInThisMonth = 0 ;
daysInThisMonth = daysInMonth ( month ) ;
toHold = days ;
Example
if ( ( day + days ) >= daysInThisMonth )
if ( ( day + days ) >= daysInThisMonth )
{
Temp.month = month + 1 ;
if ( Temp.month > 12 )
{
Temp.day = 1 ;
Temp.month = 1 ;
Temp.year = year + 1 ;
}
else
Example
{
toHold = day + days ;
if ( toHold > daysInThisMonth )
{
Temp.day = toHold - daysInThisMonth ;
}
Temp.year = year ;
}
}
else
Example
{
Temp.day = days + day ;
Temp.month = month ;
Temp.year = year ;
}
return Temp ;
}
Unary
Operator
i ++
i --
date += 1 ;
Same as
date ++ ;
Date operator++ ( ) ;
Unary Member
Operator
Example
void Date :: operator ++ ( )
{
if ( day == daysOfMonth ( day , month , year ) )
{
if ( month < 12 )
{
day = 1 ;
month ++ ;
}
else
{
day = 1 ;
month = 1 ;
year ++ ;
}
else
day ++ ;
}
Example
Date Date :: operator + ( int days )
{
days = 5
Date Temp ;
for ( i = 1 ; i < days ; i ++ )
++ Temp ;
return Temp ;
}
Code
Reuse
Comparison Operator
<
>
<=
>=
==
bool
bool operator > ( Date d ) ;
Example

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

 new and delete operators

 Overloading of Arrays Operator


Arrays of Object
Date mydate [ 10 ] ;
int intArray [ 10 ] = { 1 , 2 , 3 , 4 , 5 ,
6 , 7 , 8 , 9 , 10
};
Date mydate [ 10 ] = {
Date ( 21 , 01 , 1979 ) ,
Date ( 21 , 02 , 1979 ) ,
Date ( 21 , 03 , 1979 ) ,
Date ( 21 , 04 , 1979 ) ,
Date ( 21 , 05 , 1979 ) ,
Date ( 02 , 06 , 1979 ) ,
Date ( 02 , 07 , 1979 ) ,
Date ( 02 , 08 , 1979 ) ,
Date ( 02 , 09 , 1979 ) ,
Date ( 02 , 10 , 1979 )
};
Example
Fill the array
for ( int i = 0 ; i < arraySize ; i ++ )
{
cin >> c [ i ] ;
}
Example
Print in Reverse order

for ( int i = arraySize ; i >= 0 ; i -- )


{
cout << c [ i ] ;
}
Incorrect code
Example
Print in Reverse order

for ( int i = ( arraySize – 1 ) ; i >= 0 ; i -- )


{
cout << c [ i ] ;
}
Example
void Date :: display ( )
{
char * monthName [ ] =
{
"zero", "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November" , "December"
};
cout << monthName [ month ] << ' ' << day << ", " << year
<< endl ;
}
Date mydate [ 10 ] ={
Date ( 21 , 01 , 1979 ) ,
Date ( “01-Jan-2002” ) ,
Date ( 21 , 03 , 1979 ) ,
Date ( “01-Feb-2002” ),
Date ( 21 , 05 , 1979 ) ,
Date ( 02 , 06 , 1979 ) ,
Date ( 02 , 07 , 1979 ) ,
Date ( 02 , 08 , 1979 ) ,
Date ( 02 , 09 , 1979 ) ,
Date ( 02 , 10 , 1979 )
};
String myString [ 5 ] = {
"First line of message\n" , "Second line
of message\n",
String ( "Third line of message\n" ) ,
String ( '-' , 25 ) ,
String ( )
};
String * text ;
text = new String [ 5 ] ;
String myString [ 5 ] = {
"First line of message\n",
"Second line of message\n",
String ( "Third line of
message\n" ) ,
String( '-', 25 ),
String ( )
};
Default
Constructor
String * text ;
text = new String [ 5 ] ;
delete text ;
// Incorrect syntax for
// deleting array
delete [ ] text ;
Example
int * iPtr ;
iPtr = new int [ 10 ] ;
delete iPtr ;// bad usage
delete [ ] iPtr ;
delete [ ] text ;
Overloading new Operator

void * operator new ( size_t size )


{
void * rtn = calloc ( 1 , size ) ;
return rtn ;
}
Overloading delete Operator

void operator delete ( void * ptr )


{
free ( ptr ) ;
}
Overloading new
Operator for Date class

void * Date :: operator new ( size_t size ) ;


Example
int iArray [ 10 ] ;
int i ;
for ( i = 0 ; i < 100 ; i ++ )
{
iArray [ i ] = i ;
}
Example
int iArray [ 10 ] ;
int i ;
for ( i = 0; i < upperLimit ; i ++)
{
iArray [ i ] = i ;
}
[]
int iArray [ 5 ] ;
int & operator [ ] ( int index ) ;
#define MAXNUM 10
int iArray [ MAXNUM ] ;
Overloaded Array Operator [ ]
int & IntArray :: operator [ ] ( int index )
{
int dummy = 0 ;
if ( (index > ( MAXNUM – 1 ) )
{
cout << "Error: invalid index call.\n“ ;
return dummy ;
}
else
return array [ index ] ;

}
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 )

More than one Integer type to express


counts in streams
character is read
<<
cout.put (char c ) ;
#include <iostream.h>
iomanip.h
cerr
clog
Buffered
Input/Output
Buffer
flush
“\n”
cout << endl ;
caux
cprn
cout << “The value of the first
integer is” << i ;
Stream
Insertion
Operator
ostream & ostream :: operator << ( char * text )
Stream
Extraction
Operator
Example
int i , j ;
cin >> i >> j ;
cin.getline ( char * buffer , int buff_size , char delimiter = ‘\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

char name1 [ 30 ] , name2 [ 30 ] ;


cin >> name1 >> name2 ;
In Today’s Lecture
We learnt
 Input / Output Stream

cin , cout , cerr , clog


 How to create our own object
 Overload Stream Operators
Introduction to Programming
Lecture 36
#include <iostream.h>
#include <fstream.h>
iomanip.h
 cin.eof ( ) ;
 cin.fail ( ) ;
 cin.bad ( ) ;
 cin.good ( ) ;
 cin.clrear ( ) ;
Manipulators
Stream
Manipulators
float PI = 3.1415926 ;
endl
cout << endl ;
cout << flush ;
Manipulator
With Arguments
Inline
Manipulator
cout.flush ( ) ;
Number System
 Binary
 Decimal

 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 ;

cout << setbase ( 16 ) << x <<endl ;


cout << setbase ( 10 ) << x <<endl ;
cout << setbase ( 0 ) << x <<endl ;
} Same as setbase (10)
Input Output state flags

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

cout.setf ( ios :: showbase ) ;


showbase
cout.setf ( ios :: showbase ) ;
cout.setf ( ios::dec , ios :: basefield ) ;
cout << x << '\n' ; // Outputs 77
cout.setf ( ios :: oct , ios :: basefield ) ;
cout << x << '\n' ; // Outputs 077
cout.setf ( ios :: hex , ios :: basefield ) ;
cout << x << '\n' ; // Outputs 0x77
ios :: scientific
cout.setf ( ios :: scientific ) ;
Scientific Notation
+/-

1.2334e +09
Fixed Point Notation
ios :: fixed
ios :: uppercase
What we learnt so far..

 Input Output Stream


 And their
Manipulations in C++
Introduction to Programming
Lecture 37
Operator
Overloading
Operator Overloading

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 )

Reference to the output Object of the


stream class
Definition
ostream & operator << ( ostream & output , vehicle d )
{
output<< d.seats ;
output<<d.tires ;
-------
return output ;
}
cout << d ;
cout << “The description of the vehicle is \n” << d ;
Example
class Matrix
{
private :

int rows , cols ;


int elements [ 3 ] [ 3 ] ;
public :

Matrix ( int rows = 3 , int cols = 3 ) ;


friend ostream & operator << ( ostream & output , Matrix m ) ;
};
Example
ostream& operator << ( ostream & output , Matrix m )
{
for ( int i = 0 ; i < m.rows ; i ++ )
{
for ( int j = 0 ; j < m.cols ; j ++ )
{
output << m.elements [ i ] [ j ] ;
}
}
return output ;
}
int i ;
cin >> i ;
Matrix x ;
cin >> x ;
Example
class Matrix
{
private :
int rows, cols ;
int elements [ 3 ] [ 3 ] ;
public :
Matrix ( int rows = 3 , int cols = 3 ) ;
friend ostream & operator << ( ostream & output , Matrix m ) ;
friend istream & operator >> ( istream & input , Matrix m ) ;
};
Example
istream & operator >> ( istream & input , Matrix & m )
{
cout<< “Please enter the values of the matrix” ;
for ( int i = 0 ; i < m.rows ; i ++ )
{
for ( int j = 0 ; j < m.cols ; j ++ )
{
cout << “Please enter the values of elements ” << i << “,” << j ;
input >> m.elements [ i ] [ j ] ;
}
}
return input;
}
Example

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

ostream & bell ( ostream & output )


{
return output << '\a' ;
}

// Takes the cursr to next line

ostream & endLine ( ostream & output )


{
return output << '\n' << flush ;
}

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

 Parameter Less Manipulation


 Static Data
Introduction to Programming
Lecture 39
Copy
Constructor
Review
 Pointers
 References

 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

2. Write assignment operator

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 ” ;
}

Person :: Person ( char * name , char * address ,int day ,


int month , int year ) : Date ( month , day , year )
{
cout << “Inside Person constructor” ;
}
Destructor
~ Date ( )
{
cout << “Inside Date destructor ” ;
}
~ Person ( )
{
cout << “Inside Person destructor” ;
}
class Column
Example
{
private :
int size ;
public :
Column ( )
{
cout << "Column Created" << endl ;
}

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
{

friend class outer ;


// Data members
};
// Data members
// Member functions
};
ReturnType className :: functionName ( )

}
{
// 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

Aij+ Bij = Cij


Addition of two Matrices
Size of two matrices must be
same

Number of rows and columns


must be identical for the
matrices to be addable
Example
1 2 3 3 6 8
-2 -4 -5
-2 2 0
= 5 6 7 - 7 4 7
0 0 10 9 10 11 9 10 1

Cij = Aij - Bij


Adding a Scalar to
the Matrix
Ordinary number
added to every
element of the
matrix
Subtracting a Scalar
from a Matrix
Ordinary number
subtracted from
every element of the
matrix
Division of Matrix
by a Scalar

Divide every element


of Matrix by a scalar
number
Example
Let :
X be a Scalar number
A be a Matrix

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

Number of columns of the 1st Matrix


=
Number of rows of the 2nd Matrix
Rules regarding Matrix
Multiplication
 First matrix has
– M rows
– N columns

 Second matrix has


– N rows
– P columns

 Resultant matrix will have


– M rows
– P columns
Transpose of a
Matrix

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

Size of matrix change after transpose

A A
T

3 ( Rows ) * 4 ( Columns ) 4 ( Rows ) * 3 ( Columns )


Before After
Next Phase of
Analysis
• Determine the Constants
• Memory Allocation
• What is it’s user interface
Interface
Interface
Constructor : Parameters are
 Number of rows
 Number of columns

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

A=B ( Member Operator )


Interface

>> Extraction Operator : Friend Operator

<< Stream Insertion Operator : Friend Operator


Copy Constructor
 Copy Constructor
 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

int getRows ( void ) const ;


int getCols ( void ) const ;

// Input output functions for Matrix class

const Matrix & input ( istream & is = cin ) ;


const Matrix & input ( ifstream & is ) ;

void output ( ostream & os = cout ) const ;


void output ( ofstream & os ) const ;
Class Matrix

// 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

Matrix operator + ( Matrix & m ) const ;


Matrix operator + ( double d ) const ;
friend Matrix operator + ( double d , Matrix & m ) ;
const Matrix & operator += ( Matrix & m ) ;
i += 3 ;
i=i+3;

A += B ; // A and B are Matrices


A–B
Where A and B
are both matrices
d is a variable
‘A’ is an
of type double
object of a
class Matrix

A–d;
d is a ‘a’ is an
variable of object of a
type double class Matrix

d–A;
Class Matrix
// Minus Operator

Matrix operator - ( Matrix & m ) const ;


Matrix operator - ( double d ) const ;
friend Matrix operator - ( double d , Matrix & m ) ;
A*B;
Where A and B are both matrices
‘A’ is an d is a variable
object of a of type double
class Matrix

A*d;
d is a
variable of ‘a’ is an
type double object of a
class Matrix

d*A;
Class Matrix
// Multiplication Operator

Matrix operator * ( const Matrix & m ) ;


Matrix operator * ( double d ) const ;
friend Matrix operator * ( const double d , const Matrix & m ) ;
‘A’ is an d is a variable
object of a of type double
class Matrix

A/d;
Class Matrix
// Division Operator

Matrix operator / ( const double d ) ;


Example
// Stream Insertion and Extraction Operator

cin >> m ;

// Where m is a matrix
Class Matrix
// Stream Insertion and Extraction Operator

friend istream & operator >> ( istream & , Matrix & ) ;


friend ifstream & operator >> ( ifstream & , Matrix & ) ;

friend istream & operator << ( istream & , Matrix & ) ;


friend ifstream & operator << ( ifstream & , Matrix & ) ;
Class Matrix

const Matrix & operator = ( const Matrix & m ) ;


const Matrix & transpose ( void ) ;
Class Matrix
Matrix :: Matrix ( int row , int col ) // Default Constructor
{
numRows = row ;
numCols = col ;
elements = new ( double * ) [ numRows ] ;
for ( int i = 0 ; i < numRows ; i ++ )
{
elements [ i ] = new double [ numCols ] ;
for ( int j = 0 ; j < numCols ; j ++ )
elements [ i ] [ j ] = 0.0 ;
}
}
Matrix A ( B ) ;
Matrix A = B ;
Class Matrix
Matrix :: Matrix ( const Matrix & m )
{
numRows = m.numRows ;
numCols = m.numCols ;
elements = new ( double * ) [ numRows ] ;
for ( int i = 0 ; i < numRows ; i ++ )
{
elements [ i ] = new double [ numCols ] ;
for ( int j = 0 ; j < numCols ; j ++ )
elements [ i ] [ j ] = m.elements [ i ] [ j ] ;
}
}
Class Matrix
Matrix :: ~ Matrix ( void )
{
delete [ ] elements ;
}
Class Matrix
int Matrix :: getRows ( ) const
{
return numRows ;
}

int Matrix :: getCols ( ) const


{
return numCols ;
}
Class Matrix
void Matrix :: output ( ostream & os ) const
{
// Print first row with special characters
os.setf ( ios :: showpoint ) ;
os.setf ( ios :: fixed , ios :: floatfield ) ;
os << ( char ) 218 ;
for ( int j = 0 ; j < numCols ; j ++ )
os << setw ( 10 ) << " “ ;
os << ( char ) 191 << "\n" ;
Class Matrix
// Print remaining rows with vertical bars only
for ( int i = 0 ; i < numRows ; i ++ )
{
os << ( char ) 179 ;
for ( int j = 0 ; j < numCols ; j ++ )
os << setw ( 10 ) << setprecision ( 2 ) << elements [ i ] [ j ] ;
os << ( char ) 179 << "\n" ;
}
Class Matrix
// Print last row with special characters
os << ( char ) 192 ;
for ( int j = 0 ; j < numCols ; j ++ )
os << setw ( 10 ) << " " ;
os << ( char ) 217 << "\n" ;
}
Class Matrix
void Matrix :: output ( ofstream & os ) const
{
os.setf ( ios :: showpoint ) ;
os.setf ( ios :: fixed , ios :: floatfield ) ;
os << numRows << " " << numCols << "\n" ;
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < numCols ; j ++ )
os << setw ( 6 ) << setprecision ( 2 ) << elements [ i ] [ j ] ;
os << "\n" ;
}
}
Class Matrix
const Matrix & Matrix :: input ( istream & is )
{
cout << "Input Matrix size: " << numRows << " rows by " << numCols << " columns \n" ;
for ( int i = 0 ; i < numRows ; i ++ )
{
cout << "Please enter " << numCols << " values separated by spaces for row no." << i+1 << ": " ;
for ( int j = 0 ; j < numCols ; j ++ )
{
cin >> elements [ i ] [ j ] ;
}
}
return * this ;
}
Class Matrix
const Matrix & Matrix :: input ( ifstream & is )
{
int Rows , Cols ;
is >> Rows ;
is >> Cols ;
if ( Rows > 0 && Cols > 0 )
{
Matrix temp ( Rows , Cols ) ;
* this = temp ;
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < numCols ; j ++ )
{
is >> elements [ i ] [ j ] ;
}
}
}
return * this ;
}
Class Matrix
const Matrix & Matrix :: transpose ( )
{
if ( numRows == numCols ) // Square Matrix
{
double temp ;
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = i + 1 ; j < numCols ; j ++ )
{
temp = elements [ i ] [ j ];
elements [ i ] [ j ] = elements [ j ] [ i ] ;
elements [ j ] [ i ] = temp ;
}
}
}
Class Matrix
else
{
Matrix temp(numCols, numRows);
for ( int i = 0 ; i < numRows ; i ++ )
{
for ( int j = 0 ; j < numCols ; j ++ )
{
temp.elements [ j ] [ i ] = elements [ i ] [ j ] ;
}
}
* this = temp ;
}
return * this ;
}
Introduction to Programming
Lecture 45
Assignment Operator

A=B
Class Matrix

const Matrix & operator = ( const Matrix & m ) ;


Assignment Operator

(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

ifstream & operator >> ( ifstream & is , Matrix & m )


{
m.input ( is ) ;
return is ;
}
Class Matrix
ostream & operator << ( ostream & os , Matrix & m )
{
m.output ( ) ;
return os ;
}

ofstream & operator << ( ofstream & os , Matrix & m )


{
m.output ( os ) ;
return os ;
}
main ( )
{
Matrix m ( 3 , 3 ) ;
m.output ( ) ;
………
}
Template for Matrix
Class
Rules for Programming

• 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

There are three kinds of Loops in C Language :


– while
– do – while
– for
Classes and
Objects
Classes and Objects

Object.member
Garbage
Collection
Truth
Table
Structured Query Language

SQL
Optimizer

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy