0% found this document useful (0 votes)
7 views

ITC Lect 12 [Functions-I]

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

ITC Lect 12 [Functions-I]

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Lecture 12: Functions CS 101: Introduction to Computing

Functions - I

Instructor: Muhammad Sajid Ali

Slides prepared by: Prof. Dr. Zahid Halim


Updated by: Dr. Khurram Jadoon

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Introduction
• Suppose we have a program that calculates and displays the
area of a rectangle.
#include <iostream>
using std::cout, std::cin, std::endl;
int main() {
// Calculate the area of a rectangle
double length = 5.0;
double width = 3.0;
double area = length * width;

// Display the result


cout << "Area of the rectangle: " << area << endl;

return 0;
}

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Introduction

• This code works fine for a single calculation, but

– What if you want to calculate the area of multiple


rectangles?

– What if you want to do the same task after some other


steps?

– What if you need to do the same task in one of your other


application?

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Introduction

• You would need to


– duplicate the code each time, leading to repetitive and
potentially error-prone code.

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing
Introduction
#include <iostream>
using std::cout, std::cin, std::endl;
int main() {
// Calculate the area of a rectangle
double length = 5.0;
double width = 3.0;
double area = length * width;
// Display the result
cout << "Area of the rectangle: " << area << endl;

// Calculate the area of a rectangle


double length = 5.0;
double width = 3.0;
double area = length * width;
// Display the result
cout << "Area of the rectangle: " << area << endl;

return 0;
}

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Introduction

• How about
#include <iostream>
using std::cout, std::cin, std::endl;

//Some module name calculateArea

int main() {
// Use module to do the task
return 0;
}

// These modules are called functions in c++

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Introduction

• Divide and conquer


– Construct a program from smaller pieces or components
– Each piece more manageable than the original program

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Program Components in C++


• Programs written by
• combining new functions with “prepackaged”
functions in the C++ standard library.
• The standard library provides a rich collection
of functions.
• The standard library provides a rich collection of
functions.
• Input/output (getline, read etc.)
• Common mathematical calculations (pow, sqrt,
exp, etc.)
• String manipulations(strcpy, strcat, etc.
• Many more

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing9

3.2 Program Components in C++


• Functions are invoked by a function call
– A function call specifies the function name and provides
information (as arguments) that the called function
needs
– Boss to worker analogy:
A boss (the calling function or caller) asks a worker
(the called function) to perform a task and return (i.e.,
report back) the results when the task is done.

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Program Components in C++

• Function definitions
– Only written once
– These statements are hidden from other functions.
– Boss to worker analogy:
The boss does not know how the worker gets the job done; he just
wants it done

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Math Library Functions

• Math library functions


– Allow the programmer to perform common mathematical
calculations
– Are used by including the header file <cmath>
• Functions called by writing
functionName (argument)

• Example
cout << sqrt( 900.0 );
– Calls the sqrt (square root) function. The preceding statement
would print 30
– The sqrt function takes an argument of type double and returns
a result of type double, as do all functions in the math library

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Math Library Functions

• Function arguments can be


– Constants
sqrt( 4 );
– Variables
sqrt( x );
– Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Predefined Functions

Ghulam Ishaq Khan


C++ Programming: Institute
From Problem Analysisof Engineering
to Program Sciences
Design, Fourth Edition and Technology, Topi 13
Lecture 12: Functions CS 101: Introduction to Computing

Predefined Functions (continued)

Ghulam Ishaq Khan


C++ Programming: Institute
From Problem Analysisof Engineering
to Program Sciences
Design, Fourth Edition and Technology, Topi 14
Lecture 12: Functions CS 101: Introduction to Computing

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Predefined Functions (continued)


• Example sample run:

Ghulam Ishaq Khan


C++ Programming: Institute
From Problem Analysisof Engineering
to Program Sciences
Design, Fourth Edition and Technology, Topi 16
Lecture 12: Functions CS 101: Introduction to Computing

Functions

• Functions
– Allow the programmer to modularize a program
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local variables
• Parameters
– Local variables passed when the function is called that provide the
function with outside information

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Functions
• Function Prototypes

• Function Calling

• Function Definition

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Function Prototypes
• Function prototype
– Function name
– Parameters
• Information the function takes in
– Return type
• Type of information the function passes back to caller (default int)
• void signifies the function returns nothing
– Only needed if function definition comes after the function call in
the program
• Example:
int maximum( int, int, int );
– Takes in 3 ints
– Returns an int

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Function Definitions
• Create customized functions to
– Take in data
– Perform operations
– Return the result

• Format for function definition:


return-value-type function-name( parameter-list ){
declarations and statements
}
• Example:
int square( int y)
{
return y * y;
}

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


1 // Fig. 3.3: fig03_03.cpp
21
2 // Creating and using a programmer-defined function Outline
3 #include <iostream.h>
4
1. Function
Notice how parameters and prototype

7
return value are declared in
8 int square( int ); // function the function prototype
prototype
2. Loop
9
10 int main() 3. Function
11 { definition
12 for ( int x = 1; x <= 10; x++ )
13 cout << square( x ) << " ";
14
15 cout << endl;
16 return 0; The function square is
17 } called for x = 1, 2, … 10
18
19 // Function definition
20 int square( int y )
Function definition
21 {
22 return y * y;

23 }

1 4 9 16 25 36 49 64 81 100

 2000 Prentice Hall, Inc. All rights reserved. Program Output


1 // Fig. 3.4: fig03_04.cpp

2 // Finding the maximum of three integers

3 #include <iostream>

5 using std::cout;

6 using std::cin;

7 using std::endl;

9 int maximum( int, int, int ); // function prototype

10

11 int main()

12 {

13 int a, b, c;

14

15 cout << "Enter three integers: ";

16 cin >> a >> b >> c;

17

18 // a, b and c below are arguments to

19 // the maximum function call

20 cout << "Maximum is: " << maximum( a, b, c ) << endl;


21

22 return 0;

23 }
24

25 // Function maximum definition

26 // x, y and z below are parameters to

27 // the maximum function definition


28 int maximum( int x, int y, int z )

29 {

30 int max = x;

31
32 if ( y > max )

33 max = y;

34

35 if ( z > max )
36 max = z;

37

38 return max;

39 }

Enter three integers: 22 85 17


Maximum is: 85

Enter three integers: 92 35 14


Maximum is: 92

Enter three integers: 45 19 98


Maximum is: 98
19 // Function maximum definition 24
20 // x, y and z below are parameters to
Outline
21 // the maximum function definition
22 int maximum( int x, int y, int z )
3. Function
definition
23 {
24 int max = x;
Initially, max is equal to x
25

26 if ( y > max )
If y is greater than max,
27 max = y;

28
y becomes the new max
29 if ( z > max )
now
Finally, if z is greater than
30 max = z;

31
max,
32 return max;
z becomes the new max
33 }

Enter three integers: 22 85 17


Maximum is: 85
Program Output
Enter three integers: 92 35 14
Maximum is: 92

Enter three integers: 45 19 98


Maximum is: 98

 2000 Prentice Hall, Inc. All rights reserved.


Lecture 12: Functions CS 101: Introduction to Computing

Header Files

• Header files
– Contain function prototypes for library functions
– <cstdlib> , <cmath>, etc.
– Load with #include <filename>
• Example:
#include <cmath>

• Custom header files


– Defined by the programmer
– Save as filename.h
– Loaded into program using
#include "filename.h"

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Random Number Generation


• rand function
i = rand();
– Load <cstdlib>
– Generates a pseudorandom number between 0 and RAND_MAX
(usually 32767)
• A pseudorandom number is a preset sequence of "random" numbers
• The same sequence is generated upon every program execution
• srand function
– Jumps to a seeded location in a "random" sequence
srand( seed );
srand( time( 0 ) ); //must include <ctime>
– time( 0 )
• The time at which the program was compiled
– Changes the seed every time the program is compiled, thereby
allowing rand to generate random numbers

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 12: Functions CS 101: Introduction to Computing

Random Number Generation

• Scaling
– Reduces random number to a certain range
– Modulus ( % ) operator
• Reduces number between 0 and RAND_MAX to a number between 0
and the scaling factor
– Example
i = rand() % 6 + 1;
• Generates a number between 1 and 6

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


1 // Fig. 3.7: fig03_07.cpp

2 // Shifted, scaled integers produced by 1 + rand() % 6

3 #include <iostream>

5 using std::cout;

6 using std::endl;

8 #include <iomanip>

10 using std::setw;

11

12 #include <cstdlib>

13

14 int main()

15 {
Notice rand() % 6 . This returns a
16 for ( int i = 1; i <= 20; i++ ) { number between 0 and 5 (scaling).
17 cout << setw( 10 ) << ( 1 + rand() % 6 ); Add 1 to get a number between 1 and
18
6.
19 if ( i % 5 == 0 )

20 cout << endl;

21 }

22

23 return 0;
Executing the program again
24 }
gives the same "random" dice
rolls.
5 5 3 5 5
2 4 2 5 5
5 3 2 2 1
5 1 4 6 4
1 // Fig. 3.9: fig03_09.cpp

2 // Randomizing die-rolling program

3 #include <iostream>

5 using std::cout;

6 using std::cin;

7 using std::endl;

9 #include <iomanip>

10

11 using std::setw;

12

13 #include <cstdlib>

14

15 int main()

16 {

17 unsigned seed;

18

19 cout << "Enter seed: ";

20 cin >> seed;

21 srand( seed );

22

23 for ( int i = 1; i <= 10; i++ ) {

24 cout << setw( 10 ) << 1 + rand() % 6;

25

26 if ( i % 5 == 0 )

27 cout << endl;

28 }

29

30 return 0;

31 }  2000 Prentice Hall, Inc. All rights reserved.


Enter seed: 67
1 6 5 1 4
5 6 3 1 2

Enter seed: 432


4 2 6 4 3
2 5 1 4 4

Enter seed: 67
1 6 5 1 4
5 6 3 1 2

Notice how the die


rolls change with the
seed.
Lecture 12: Functions CS 101: Introduction to Computing

References
Dietal and Dietal : How to Program C++
3rd Edition

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi

You might also like