0% found this document useful (0 votes)
7 views34 pages

Chapter 6 - Modular Concept

Chapter 6 of IMD238 discusses the modular concept in programming, focusing on functions in C++. It explains the definition, advantages, classifications, and usage of both predefined and independent functions, including function prototypes and parameter passing. The chapter also provides examples of function definitions and calls, highlighting different types of functions based on their return values and parameters.

Uploaded by

Ahmad Nadzrin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views34 pages

Chapter 6 - Modular Concept

Chapter 6 of IMD238 discusses the modular concept in programming, focusing on functions in C++. It explains the definition, advantages, classifications, and usage of both predefined and independent functions, including function prototypes and parameter passing. The chapter also provides examples of function definitions and calls, highlighting different types of functions based on their return values and parameters.

Uploaded by

Ahmad Nadzrin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

IMD238

Programming for Information


Professional

CHAPTER 6:
Modular Concept
INTRODUCTION TO FUNCTION

• A complex problem is often easier


to solve by dividing it into several
smaller parts, each of which can
be solved by itself.
• This is called top-down
programming.
• These parts are called functions in
C++ (also sometimes called
subprograms).
WHAT IS FUNCTION?

• A mini-program containing algorithms to do a


specific task
• A function could be invoked (called) many times
through its name (to execute its task), by the
main function or other functions
• When a function is invoked, the computer will
execute all the instructions in the function from
start to end, and then it goes to the instruction
after the function call
ADVANTAGES OF FUNCTIONS

• Separate the concept (what is done) from the


implementation (how it is done).
• Make programs easier to understand.
• Make programs easier to modify.
• Can be called several times in the same
program, allowing the code to be reused.
FUNCTION INPUT AND OUTPUT

arameters Function Result


FUNCTION CLASSIFICATION

• 2 types of functions :-
• Predefined function or built-in or library function
• Independent function or user-defined function
PREDEFINED FUNCTION

• Functions that are ready-made by the


producer of a compiler and stored in the
header files (.h) called libraries
• To use the predefined function, the
appropriate library file must be included
in the preprocessor directive (# include)
• Common header files are :-
a) iostream.h b) iomanip.h c)
string.h
d) char.h e) math.h f)
stdlib.h
PREDEFINED FUNCTION

• iostream.h

Name Description
cin For console input (keyboard)
cout For console output (screnn)
PREDEFINED FUNCTION

• iomanip.h

Name Description
setw(x) Set field width to x
setfill(x) Set the fill character with x
setprecision(x) Set the floating point precision to x
setiosflags(ios::fixed) Display floating point values in decimal
notation
setiosflags(ios::left) Left justify output

setiosflags(ios::showpoint) Display a decimal point


PREDEFINED FUNCTION

• string.h
Name Description

strcmp(s1, s2) Compares one string to another

strcpy(s1, s2) Copies one string to another

strlen(s) Calculates the length of a string

strcat(s1, s2) Appends one string to another


PREDEFINED FUNCTION

• char.h
Name Description
toupper(c) Converts character c from lowercase to
uppercase letter
tolower(c) Converts character c from uppercase to
lowercase letter
isupper(c) Returns true if c is an uppercase letter
islower(c) Returns true if c is an lowercase letter
isdigit(c) Returns true if c is a digit
isalpha(c) Returns true if c is an alphanumeric character
isspace(c) Returns true if c is a space character
PREDEFINED FUNCTION
#include <iostream.h>
#include <ctype.h>

void main()
{ char letter;
cout<<"Enter a charater: ";
cin>>letter;

if (isalpha)
{ if (isdigit(letter))
cout<<"The character is a digit\n";
else if (isupper(letter))
{ cout<<"The character is an uppercase.\n"
<< "The lowercase is "
<< char(tolower(letter)) <<endl;
}
else
{ cout<<"The character is an lowercase.\n"
<<"The uppercase is " <<
PREDEFINED FUNCTION

• math.h
Name Description

pow(x,y) Return x raised to the power of y

sqrt(x) Square root of x


ceil(x) Round up value – Returns the smallest
integral value that is not less than x.
floor(x) Round down value - Returns the
largest integral value that is not
greater than x.
PREDEFINED FUNCTION

#include <iostream.h>
#include <math.h>

void main()
{
int number;
cout<<"Enter a number: ";
cin >> number;

cout<<"The square root of number " <<number<< " is " <<


sqrt(number)<<endl;
cout<<number <<" raised to the power of 3 is " <<
pow(number,3);
}
PREDEFINED FUNCTION

• stdlib.h
Name Description

abs(i) Converts to the absolute value of i

rand() Generate a random positive integer between 0 and


RAND_MAX(32767)
srand() Initialize random number generator where seed
represent the starting point for the rand function
PREDEFINED FUNCTION

#include <iostream.h>
#include <stdlib.h>
#include <iomanip.h>

void main()
{
unsigned seed;
float randValue;
cout<< "Enter the value of seed ";
cin>>seed;
srand(seed);
cout<<"\n 5 random generated numbers are:\n";
for (int i= 1; i<=5; i++)
{
randValue = rand();
cout<<setw(8) <<randValue <<endl;
}
}
INDEPENDENT FUNCTION
• Known as user-defined / programmer-defined functions
• Whose tasks are determined by programmer
• Tasks are define within the program in the function is used

• The function can be written:


• In the same file as main() or
• Compiled independently in separate file
• To apply this method, the file that contains the function definitions
must be included:

Syntax form:
#include “<filename>.cpp”
E.G
#include”myfile.cpp”
PROGRAM STRUCTURE USING
INDEPENDENT FUNCTION
#include <iostream.h>
Function prototype declarations;

Void main() 1. Function Prototype


{ declaration
variable declarations;
statements [including function calls]; 2. Function Call
}
3. Function Definition
Function definitions(s)
{
statements;
}
FUNCTION PROTOTYPE
DECLARATIONS
• Independent functions must be declared first
before they can be used in a program. A
function declaration specifies:

• The return value


• The name of the function
• The order and type of parameters
FUNCTION PROTOTYPE
DECLARATIONS (CONT.)
• C++ syntax form
• returnType funcName (type parameter_list);

returnType funcName Type parameter_list


•Indicates the type •Is the name of the •Tells the calling
of value that function function type of data
function will return •It can be any value
• Int, float, names but the •Tell the order of the
double, char, name convention values
long void must follow the •If contains more than
•Void is used for rules in naming one parameter –
function that not the identifier separated by comma
return any value •Parameter_list also
known as arguments.
FUNCTION PROTOTYPE
EXAMPLE
void display();
• declares the functions display() does not receive any
argument and does not return any argument to the calling function

int findSum(int, int);


• Declares that the function findSum() expects to receive two
integer arguments and will return an integer value to the calling
function

float swap(float, float, int, char);


• declares that the function swap() requires 4 arguments –
two float, one integer, one char. This function will return a floating-
point value
FUNCTION DEFINITION

• Function definition is a description of subprogram that


contains:
• Function Header
• Function Body

• A function is written once in the program and can be


used by any other function in the program

• The function definition is placed either before the


main() or after the main()
SYNTAX FORM OF FUNCTION
DEFINITION
ReterunType funcName (type parameter_list)
{
declaration(s); Function Header
--defines the return type,
statement(s); function name and list of
parameters.
return expression; --similar to function
prototype, except that the
}
header does not end with
Function Body semicolon.
--contains declaration of Example:
local variables and
executable statements int sum3Num(int a, int b, int c)
{
int total = a+B+C;
return total;
}
FUNCTION CALL

• Function call is made to execute the statements in the


Function Definition.

• When a function is called, the program control is passed


to the called function and the statements inside the
function will be executed to the end until control is
passed back to the calling function.

• Function call specifies the function name and the values


of the parameter.
FUNCTION CALL SYNTAX

Syntax:
Function-Name(actual parameters);

Example of function calls

findMin(num1, num2);
getSum(firstNum, secNum);
AFTER COMPLETING A
FUNCTION CALL
• Two possibilities:
• Function call that returns no value
• Does no return any value to the calling function.

• Function call that returns a value


• Return value after the execution in the called function is
completed.
• 4 ways for calling function
• 1 In an arithmetic expression
• 2 In a logical expression
• 3 In an assignment statement
• 4 In an output statement
PARAMETERS
• Two types of parameters:
• Format parameter – define at the function header
• Actual parameter – define at function call that consists of parameter,
variable or expression.

Place at: Formal Parameter

void calcSum(int num1, int num2, int num3)


{
Function cout<<“Total: “ << num1 +num2 +num3;
Definition
}

void main()
{ Actual Parameter
Function
int x = 4;
call
calSum(10, 8, x+3);
}
RULES FOR PARAMETER
PASSING
• The type of actual must be the same with the formal
parameter.

• The order of parameter must the same (first actual


parameter corresponds to the first formal
parameter).

• The number of actual parameter must be the same


with the number of formal parameter.
EXAMPLE OF PARAMETER
PASSING
Example

Void main()
{ Function
statement; Call
…………. Actual Parameter
int num1 = 10; 10 20 30
int net_total = sum3Num(num1, 20, 30);
cout<<net_total;
}
Formal Parameter a=10 b=20 c=30
Function sum3Num
int sum3Num(int a, int b, int c) Total = 10+20+30
{
int total = a+b+c;
return total;
} 60
Types of Independent
Functions
1. Function with no return value and no parameter

Function Prototype Function Call Function Definition

void display(); { …. void display()


….. {
display(); cout << “This is only a title of the program”<< endl;
….. }
}

void calcAreaCircle(); { …. void calcAreaCircle()


…. { double radius;
cin >> radius;
calcAreaCircle(); area = radius * radius * 3.142;
….. cout << “The area of circle is “<< area;
} }
2. Function with no return value and has a parameter

Function Prototype Function Call Function Definition

void average(int, int); { int x, y; void average(int a, int b)


cin >> x >> y; { int avg;
average(x, y); avg = (a + b)/2;
….. cout << “The average is “ << avg;
} }

void factorial(int); { int x; void factorial(int a)


factoria(x); { int result=1;
…. while (a > 0)
} { result = result * a;
a = a – 1;
}
cout << “The factorial of “ << a << “is “ << result;
}
3. Function with return value and no parameter

Function Prototype Function Call Function Definition

float areaCircle(); { double area; Float areaCircle()


area = { double radius;
areaCircle(); cin >> radius;
cout << “Area is A = 3.142 * radius * radius;
“ << area; return A;
} }
4. Function with return value and has a parameter

Function Prototype Function Call Function Definition

int factorial(int); { int x, fac; int factorial(int a)


cin >> x; { int result=1;
fac = while (a > 0)
factorial(x); { result = result * a;
cout << fac; a = a – 1;
} }
return result;
}

int average(int, int); { int x, y; int average(int a, int b)


cin >> x >>y; { int purata;
cout << “The purata = (a + b)/2;
average of the 2 return purata;
numbers is “ << }
average(x, y);
}
5. Function with return value and has a reference
parameter
 reference parameter – used to return values as a return output to
called function.
 it is used where more than one value or variable need to be returned to
the called function.

Function Prototype Function Call Function Definition

void swap(int &, int { int x, y; void swap(int &a, int &b)
&); cin >> x >>y; { int temp;
swap(x, y); temp = a;
} a = b;
b = temp;
}

void calc(int, int, int { int x, y, total; Void calc(int a, int b, int &jum, float &purata)
&, float &); float avg; {
cin >> x >>y; jum = a + b;
calc(x, y, total, purata = jum/2;
avg); }
}

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