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

BUE Lec5-Functions I

Functions lecture will help students of computer science and computer engineering

Uploaded by

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

BUE Lec5-Functions I

Functions lecture will help students of computer science and computer engineering

Uploaded by

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

• Top-down Design.

23COMP02C
• Function Parts.
PROGRAMMING AND
SOFTWARE DESIGN/
• Local vs. Global
23ECE12C
variables.
COMPUTER
• Overloading a PROGRAMMING
function name.

• Default Values. Lecture 5


• Built-in functions.
Functions (User-Defined)

1
Quotes of the Day!

2
1. Top-down Design
• If we look at a big problem as a whole, it may seem
hard to solve because it is so complex.

• Complex problems can be solved using top-down


design, where:
– We break the problem into parts.
– Then break the parts into parts.
– Soon, each of the parts will be easy to do.

3
1. Top-down Design – (cont.)
• A methodology of information processing,
problem solving, and knowledge
representation, that starts at the highest
level of a design concept and proceeds
towards the lowest level.

4
1. Top-down Design – (cont.)
Example
• Problem: we want to automate
sending letters for students who
have passed their absence limits.

5
1. Top-down Design – (cont.)
Example
• Possible solution:
1 Get students list from files
2 Sort according to absence times
3 Select those with more than 3 times
4 Print a letter for each student

6
1. Top-down Design – (cont.)
Example
• Problem: Write a program that
draws this picture of a house.

7
1. Top-down Design – (cont.)
Example
• Possible solution:
1. Draw the outline of the house.
2. Draw the chimney.
3. Draw the door.
4. Draw the windows.
Are there any parts
to divide?

8
1. Top-down Design – (cont.)
Example
• Possible solution:
1. Draw the outline of the house
2. Draw the chimney
3. Draw the door
Call Draw Door Frame
Call Draw Knob

4. Draw the windows

9
1. Top-down Design – (cont.)
Example
• Possible solution:
1. Draw the outline of the house
2. Draw the chimney
3. Draw the door
Draw Door Frame
Draw Knob

4. Draw the windows


Draw Window 1
Draw Window 2
Draw Window 3

10
1. Top-down Design – (cont.)
Example
• Possible solution:
1. Draw the outline of the house.
2. Draw the chimney
3. Draw the door
Call Draw Door Frame
Call Draw Knob
4. Draw the windows
Draw a Window in Location 1
Draw a Window in Location 2
Draw a Window in Location 3
Code/get code for each step.
Code reusability
11
1. Top-down Design – (cont.)
• Top-down is a standard way of writing
programs.
• Programs produced using this method and
using the control structures (sequential,
selection and repetition) are called
structured programs.
• Structured programs are easier to test,
modify, and are also easier for
other programmers to understand.

12
1. Top-down Design – (cont.)
Advantages
• Breaking the problem into parts helps us to
clarify what needs to be done.
• At each step of refinement, the new parts
become less complicated and, therefore,
easier to figure out.
• Breaking the problem into parts allows more
than one person to work on the solution.
• Parts of the solution may turn out to be
reusable.
• Typically, each part will be coded as a
separate function.
13
Functions

• Building blocks of programs in C++:


functions

• I-P-O
– Input – Processing – Output
– Sometimes a function has no input.
– Sometimes a function returns no output.

14
Functions

15
USER-DEFINED FUNCTIONS

16
User-defined Functions

17
2. Programmer-defined Functions
• Three parts in using any function:
1. Function Declaration (Prototype)
• Information for compiler
• To properly interpret calls

2. Function Definition (Body of the function)


• Actual implementation (code) of what the function does

3. Function Call
• Using the function
• Transfers control to function body
• Arguments are plugged in for formal parameters

18
1.Declaration

3.Call

2.Definition

19
2. Programmer-defined Functions – (cont.)
(1) Function Declaration (Prototype)
• Syntax:
return_type Fn_name(parameter list);

• Formal parameters can be of


any type and number.

• A function can return ONLY ONE value


or VOID.

20
2. Programmer-defined Functions – (cont.)
(1) Function Declaration (Prototype)

…………..
}

21
2. Programmer-defined Functions – (cont.)
(2) Function Definition (Body)
• Syntax:
return_type Fn_name(parameter_list)
{
// your code goes here
}
• Implementation of the function.
• Placed after main() or instead of declaration.
• Returned value type, and formal parameters
type, order and number should match the
function declaration.

22
2. Programmer-defined Functions – (cont.)
(2) Function Definition

Formal parameters: Variable names


referring to data in definition

A return statement sends


data back to caller and can
return only one value.
23
1. Definition of the function is placed after
main() and declaration before main().

24
2. Definition of the function is placed instead
of declaration (before main()).

25
2. Programmer-defined Functions – (cont.)
(3) Function Call
• To execute its body. If it is a void
function(i.e function
Fn_name(arguments_list); returns nothing)
result = Fn_name(arguments_list);
If the function returns A VALUE OF THE
SAME TYPE AS RESULT
• A function to execute must be called in a way or
another in the main function.
• Arguments type, number and order should match
the function declaration.

26
2. Programmer-defined Functions – (cont.)
(3) Function Call
Arguments can be
literals, variables,
expressions, or
combination

Call can be placed in


an expression or a
cout statement
(if not void function)

27
2. Programmer-defined Functions – (cont.)

Example 1 – void function


• A void function does not return a value.
• When being called, it cannot be used in
expressions, or in assignment statements.

• void function with void parameters


• void function with parameters

28
// declaration
1.void welcome ();

2. void main()
3. {
4. cout << "Main\n";
// call
5. welcome (); // No expression or assignment statement
13. cout << "after calling\n";
14. } // end main
// definition
6. void welcome ()
7. {
8. int repeat;
9. cin >> repeat;
10 for (int i = 1; i <= repeat; i++)
11. cout << "Hi\tWelcome to my game!\n";
12. } // end welcome
29
// declaration Example 2
double sum (double x, double y, double z);

void main()
{
double A, B, C, result;
A = 1; B = 2; C = 3; //cin >> A >> B >> C;
// processing
A++;
// call
result = sum (A, B, C); // call by value
// output
cout << "In main, B: " << B << " and Result: "<< result << endl;
} // end main

// definition
double sum (double A, double B, double C)
{
B = B + 2;
cout << "In function sum, B: " << B << endl;
return A + B + C;
} // end sum

30
2. Programmer-defined Functions – (cont.)
(5) Parameters vs Arguments
• Formal parameters
– In function declaration
– In function definition’s header

Parameters: "Variables names"


used to refer to data in
definition or declaration
(optional) 31
2. Programmer-defined Functions – (cont.)
(5) Parameters vs Arguments
• Actual arguments
– In function call

Calling by value

32
2. Programmer-defined Functions – (cont.)
Function call (by value)
arguments_list

parameters_list

33
2. Programmer-defined Functions – (cont.)
Keep in mind: Calling/Passing by value
1. The value of the argument (not the
variable) that is plugged in for the formal
parameter.
2. Arguments are plugged in for formal
parameters in the order they appear in the
function call.
3. When an argument is plugged in for a
formal parameter, it is plugged in for ALL
instances of this parameter that occur in the
function body.
34
35
2. Programmer-defined Functions – (cont.)
(6) Local Variables
– Declared inside body of given function
– Available only within that function
• Can have variables with same names
declared in different functions
– Scope is local: "that function is its scope"
• Local variables preferred
– Functions should declare whatever local
data needed to “do their job”.

36
2. Programmer-defined Functions – (cont.)
Local Variables

• Local variables are


declared within a
scope.

• A function can
declare its own local
variables as needed.

37
2. Programmer-defined Functions – (cont.)
Local Variables
• Can have variables
with same names
declared in
different functions
• Same name BUT
they are totally
different locations
in memory.

38
Exercise

Write a program that uses a function


to take three arguments and returns
true if the three arguments are
ascendingly ordered, otherwise it
returns false.

39
#include <iostream>
using namespace std;

bool isInOrder (int, int, int); // declaration

void main()
{
int n1, n2, n3;
cout << " Enter three numbers\n";
cin >> n1 >> n2 >> n3;

bool check = isInOrder( n1, n2, n3); // call

if (check)
cout << "In order\n"; If(isInOrder( n1, n2, n3))
else
cout << "Not arranged\n";

bool isInOrder( int a, int b, int c) // definition


{ Change the program to return
if (a <= b && b <= c) true whether they are ASC or
return true; NOT.
else
return false; Can be omitted...why?☺
} 40
Exercise

Write a program that reads the


employee salary and uses a function
to calculate the taxes according to
the following rules.

Salary Tax
2000 - 3999 5%
Between 4000 and 6000 7%
More than 6000 10%

41
#include <iostream>
using namespace std;

float CalcTax (float salary);

void main()
{
float empSal;
cout << "Enter the salary\n";
cin >> empSal;

float tax = CalcTax (empSal);

if (tax != -1)
cout << tax << endl;
else
cout << "Invalid salary\n";
} 42
Salary Tax
2000 - 3999 5%
Between 4000 and 6000 7%
More than 6000 10%
float CalcTax (float sal)
{
if (sal >= 2000 && sal < 4000)
return sal * 0.05;
else if (sal >= 4000 && sal <= 6000)
return sal * 0.07;
else if (sal > 6000)
return sal * 0.1;
else
return -1; // there is a problem
}

43
2. Programmer-defined Functions – (cont.)
(7) Global Constants/Variables
– Declared outside all functions, hence
defined for all functions below it.

44
2. Programmer-defined Functions – (cont.)

Constant needed in the


two functions

45
Constant is global to
all functions below
its declaration

46
Constant global to
all functions below
its declaration

What if we declared a
local variable with the
same name as a global
one?

47
48
2. Programmer-defined Functions – (cont.)
(8) Overloading a Function Name
• Having more than one function
with the same name
• How does the compiler know?
– By number of parameters
– By type of parameters
– NOT by return value
• Should be used with care!
49
2. Programmer-defined Functions – (cont.)
(8) Overloading a Function Name
How does the
compiler know?
By number of parameters

50
double avg(double, double); How does the
double avg(double, double, double); compiler know?
double avg(int, int);
By type of parameters
int main() or number of parameters
{
double A=1, B=2, C=3;
int X=1, Y=2, Z=3;
cout<<"Integer avg="<< avg (X,Y) << endl;
cout<<"Double avg= "<< avg (A,B) << endl;
cout<<"Double avg= "<< avg (A,B,C) << endl;
return 0;
}
double avg (double n1, double n2, double n3)
{ return (n1+n2+n3)/3.0; }

double avg (int n1, int n2) What if avg was called with
{ return (n1+n2)/2.0; } two different arguments type?
Try it at home and tell me
double avg (double n1, double n2) next lecture ☺
{ return (n1+n2)/2.0; }
51
Default Parameter Values
• When you define a function, you can
specify a default value for each of the last
parameters. This value will be used if the
corresponding argument is left blank when
calling to the function.

• This is done by using the assignment


operator and assigning values for the
arguments in the function definition.

• If a value for that parameter is not passed


when the function is called, the default
given value is used, but if a value is
specified, this default value is ignored and
the passed value is used.
52
#include <iostream>
using namespace std;
int sum (int a, int b = 20)
{
int result;
result = a + b;
return (result);
}
void main ()
{
int a = 100; int b = 200; int result;

result = sum(a, b); //calling with 2 arguments


cout << "Total value is :" << result << endl;

result = sum(a); //calling with 1 argument


cout << "Total value is :" << result << endl;
} 53
54
EXAMPLE
int add(int x=10, int y=5)
{
return x+y;
}
void main()
{
//10
cout<<add(3,7);
cout<<add(7); //12
cout<<add(); //15
}
55
56

You might also like