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

Introduction To Functions

Uploaded by

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

Introduction To Functions

Uploaded by

U2103097 STUDENT
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

KIG2007 : Computer Programming

Introduction to Functions
Semester 2, Session 2022/2023
Copy-paste coding
#include <iostream>
using namespace std;
Bad coding!!
int main() {
// To find the maximum between 3 and 4
int x = 3, y = 4;
int maxValue = x;// assume x is the largest to start
if (y > maxValue) { // determine whether y is greater than maxValue
maxValue = y; // make y the new maxValue
}
cout << "The maximum between 3 and 4 is " << maxValue << endl;

// To find the maximum between 10 and 7


x = 10, y = 7;
maxValue = x; // assume x is the largest to start
if (y > maxValue) { // determine whether y is greater than maxValue
maxValue = y; // make y the new maxValue
}
cout << "The maximum between 10 and 7 is " << maxValue << endl;
}
With a function
include <iostream>
Function –
using namespace std;
more efficient
int maximum (int x, int y) {
int maxValue = x;// assume x is the largest to start
if (y > maxValue) { // determine whether y is greater than maxValue
maxValue = y; // make y the new maxValue
}
return maxValue;
}

int main() {
cout << "The maximum between 3 and 4 is " << maximum(3, 4) << endl;
cout << "The maximum between 10 and 7 is " << maximum(10, 7) << endl;

return 0;
}
Why define your own functions?
• Divide and conquer
• construct the program from simple, small pieces or components.
Modularize the program into self-contained tasks.
• Avoid repeating codes
• It is easy to copy and paste, but hard to maintain and
synchronize all the copies.
• Software Reuse
• you can reuse the functions in other programs, by packaging
them into library codes.
Global functions
• Do not belong to a particular class
• Have function prototypes placed in header files
• Can be reused in any program that includes the header file and that
can link to the function’s object code
• There’s no need to create any objects before calling the function.

Example:
sqrt in <cmath> header file
sqrt(900.0)
Basics of using functions
1. At the beginning of your program, declare the function.
2. Somewhere in your program, define the function.
3. Other functions can then call the function.
include <iostream>
using namespace std;
Function
declaration int maximum (int x, int y) {
int maxValue = x;
if (y > maxValue) {
Function maxValue = y;
definition }
return maxValue;
}

int main() {
cout << "The maximum between 3 and 4 is "
<< maximum(3, 4) << endl;

return 0; Function
} invocation
1. Function declaration
• Also called function prototype
• Syntax:
return_type function_name (argument1, argument2, …)

Example:
int maximum (int num1, int num2)

• The return_type is a data type indicating what kind of value the


function returns (what it passes back). If the function does not return
a value, use void.
• The (argument1, argument2, …) is a list of zero or more
argument names – separated by commas if there are more than
one – each preceded by the corresponding type. This field may be
empty, which indicates that it takes no arguments.
2. Function definition
• Function definition tells what the function does.
• The braces are required no matter how few statements you have.
• return statement
• must be the same type as the return_type in the declaration
int foo(int x) int foo(int x)
{ {
return "hello"; return x;
} }

• If no values are returned, give the function a void return type.


• Function returns as soon as a return statement is executed
3. Function invocation
• Argument order matters:
• raiseToPower(2,3) is 2^3=8
• raiseToPower(3,2) is 3^2=9

• Refer back to the order during function declaration:

int raiseToPower(int base, int exponent)


raiseToPower ( 2 , 3 )
raiseToPower ( 3 , 2 )
base exponent
Note that…
• Function declarations need to occur before int bar() {
invocations. return 3;
Solution 1: reorder }
function declarations
int foo() { int foo() {
return bar()*2; return bar()*2;
} }

int bar() {
return 3; int bar(); function
} prototype
int foo() {
ERROR – function return bar()*2;
Solution 2: use a
bar() hasn’t been }
function prototype;
declared yet
informs the compiler
you’ll implement it later int bar() {
return 3;
If a function is defined before it is invoked, then }
its definition also serves as the function’s
declaration – separate prototype is unnecessary
Functions with empty parameter lists
• In C++, an empty parameter list is specified by writing either void
or nothing at all in parentheses.
#include <iostream>
using namespace std;

void function1(); // function that takes no arguments


void function2(void); // function that takes no arguments

int main() {
function1(); // call function1 with no arguments
function2(); // call function2 with no arguments
}
function1 uses an empty parameter list to
void function1() { specify that the function receives no arguments
cout << "function1 takes no arguments" << endl;
} function2 uses a void parameter list to
specify that the function receives no arguments
void function2(void){
cout << "function2 also takes no arguments" << endl;
}
Default argument
• It’s common for a program to invoke a function repeatedly with the
same argument value for a particular parameter. In such cases, you
can specify that such a parameter has a default argument, i.e., a
default value to be passed to that parameter.
• Default arguments must be the rightmost (trailing) arguments in a
function’s parameter list.
• Default arguments must be specified with the first occurrence of the
function name – typically, in the function prototype.

Example:
int boxVolume(int length = 1, int width = 1, int height = 1);
All three parameters (length, width and height) have been given
default values of 1.
Default argument (Example – 1/2)
#include <iostream>
using namespace std;

// function prototype that specifies default arguments


int boxVolume(int length = 1, int width = 1, int height = 1);

int main() {
// no arguments--use default values for all dimensions length = 1
cout << "The default box volume is: " << boxVolume(); width = 1
height = 1
// specify length; default width and height
cout << "\n\nThe volume of a box with length 10,\n" length = 10
<< "width 1 and height 1 is: " << boxVolume(10); width = 1
height = 1
// specify length and width; default height
cout << "\n\nThe volume of a box with length 10,\n" length = 10
<< "width 5 and height 1 is: " << boxVolume(10, 5); width = 5
height = 1
Default argument (Example – 2/2)
// specify all arguments
cout << "\n\nThe volume of a box with length 10,\n" length = 10
<< "width 5 and height 2 is: " << boxVolume(10, 5, 2) width = 5
<< endl; height = 2
} // end main

// function boxVolume calculates the volume of a box


int boxVolume(int length, int width, int height) {
return length * width * height;
}

Note that default arguments were specified in the


function prototype, so they are not specified in the
function header
Function overloading
• Overloaded functions have
• Same name
• Different sets of parameters

Example: printOnNewLine(3) prints


void printOnNewLine(int x) { “1 Integer: 3”
cout << "1 Integer: " << x << endl;
}
printOnNewLine(2,3) prints
void printOnNewLine(int x, int y) { “2 Integers: 2 and 3”
cout << "2 Integers: " << x << " and " << y << endl;
}

• Function overloading is commonly used to create several functions


of the same name that perform similar tasks, but on different data
types.
Function overloading (Example)
#include <iostream>
using namespace std;

// function square for int values


int square(int x) {
cout << "square of integer " << x << " is ";
return x * x;
}

// function square for double values


double square(double y) {
cout << "square of double " << y << " is ";
return y * y;
}

int main() {
cout << square(7) << endl; // calls int version
cout << square(7.5) << endl; // calls double version
}
C++ standard library header files
• The C++ Standard Library is divided into many portions, each with
its own header file.
• A header file “instructs” the compiler on how to interface with library
and user-written components
• The header files contain definitions of various class types and
functions, as well as constants needed by those functions.
Standard
Explanation
library header
<iostream> Contains function prototypes for the C++ standard input and
output
<iomanip> Contains function prototypes for stream manipulators that
format streams of data
<cmath> Contains function prototypes for math library functions
<fstream> Contains function prototypes for functions that perform input
from and output to files on disk
Case study: Random number generation
• The element of chance can be introduced into computer
applications by using the C++ Standard Library function rand.
• The function rand generates an unsigned integer between 0 and
RAND_MAX* (a symbolic constant defined in the <cstdlib>
header file).
• The function prototype for the rand function is in <cstdlib>.
• To produce integers in the range 0 to 5, we use the modulus
operator (%) with rand: rand() % 6 – This is called scaling.
• We can shift the range of numbers produced by adding a value. e.g.
1 + rand() % 6 produces integers in the range 1 to 6.

*
For GNU C++, the value of RAND_MAX is 2147483647; for Visual Studio, the value of RAND_MAX
is 32767.
Example: Rolling a six-sided die for 20
times
#include <iostream>
#include <iomanip>
#include <cstdlib> // contains function prototype for rand

using namespace std;

int main() {
// loop 20 times
for (int counter = 1; counter <= 20; counter++) {
// pick random number from 1 to 6 and output it
cout << setw(10) << (1 + rand() % 6);

// if counter is divisible by 5, start a new line of output


if (counter % 5 == 0) {
cout << endl; Output:
} 6 6 5 5 6
5 1 1 5 3
}
6 6 2 4 2
return 0; 6 2 3 4 1
}
Randomizing the random number generator
• Function rand actually generates pseudorandom numbers.
• Repeatedly calling rand produces a sequence of numbers that
appears to be random.
• The sequence repeats itself each time the program executes.
• To produce a different sequence of random numbers for each
execution (randomizing), use the C++ Standard Library function
srand.
• Function srand takes an unsigned integer argument and seeds the
rand function to produce a different sequence of random numbers
for each execution.
Randomizing the random number generator
(Example)
#include <iostream>
#include <iomanip>
#include <cstdlib> // contains prototypes for functions srand and rand
using namespace std;

int main() {
int seed = 0; // stores the seed entered by the user

cout << "Enter seed: ";


cin >> seed;
srand(seed); // seed random number generator

for (int counter = 1; counter <= 10; counter++) { // loop 10 times


// pick random number from 1 to 6 and output it
cout << setw(10) << (1 + rand() % 6);

// if counter is divisible by 5, start a new line of output


if (counter % 5 == 0) cout << endl;
}
}
Randomizing the random number generator
• To randomize without having to enter a seed each time, we may use
a statement like
srand(time(0));
• This causes the computer to read its clock to obtain the value for
the seed.
• Function time typically returns the current time as the number of
seconds since January 1, 1970, at midnight Greenwich Mean Time
(GMT). The function prototype for time is in <ctime>.
• To produce random numbers in a specific range use:
number = shiftingValue + rand() % scalingFactor;
where shiftingValue is equal to the first number in the desired range
of consecutive integers and scalingFactor is equal to the width of
the desired range of consecutive integers.
Introducing enum
• Enumeration
• A set of integer constants represented by identifiers
• The values of enumeration constants start at 0, unless specified
otherwise, and increment by 1
• The identifiers in an enum must be unique, but separate
enumeration constants can have the same integer value
• Defining an enumeration
• introduced by the keyword enum and followed by a type name
• comma-separated list of identifier names enclosed in braces
The first value in the preceding
Example: enumeration is explicitly set to 1
enum Months {JAN = 1, FEB, MAR, APR};

Note: Use only uppercase letters in the names of enumeration constants. This makes
these con­stants stand out in a program and reminds the programmer that enumeration
constants are not variables.
Introducing enum (Example – 1/2)
#include <iostream>
#include <cstdlib> // contains prototypes for functions srand and rand
#include <ctime> // contains prototype for function time
using namespace std; the constant CONTINUE has the value 0,
WON has the value 1 and LOST has the
int main() { value 2
// scoped enumeration with constants that represent the game status
enum Status {CONTINUE, WON, LOST}; // all caps in constants

// randomize random number generator using current time


srand(time(0));

Status gameStatus; // can be CONTINUE, WON or LOST


int rollDice; // integer number from the roll of dice

rollDice = 1 + rand() % 6; // generate random number from 1 to 6


Introducing enum (Example – 2/2)
// determine game status based on dice roll
switch (rollDice) {
case 6: gameStatus = WON; // win with 6 on dice roll
break;
case 2: // lose with 2 on dice roll
case 3: // lose with 3 on dice roll
case 1: // lose with 1 on dice roll
gameStatus = LOST;
break;
default: // did not win or lose
gameStatus = CONTINUE; // game is not over
break; // optional at end of switch
}

// display won or lost message


if (gameStatus == WON)
cout << "Player wins" << endl;
else if (gameStatus == LOST)
cout << "Player loses" << endl;
else cout << "Roll again" << endl;
}

You might also like