Fun Cation
Fun Cation
91
Functions
• Most computer programs that solve real-world problems include hundreds and even
thousands of lines.
• Experience has shown that the best way to develop and maintain a large program is
to construct it from smaller pieces or modules, each of which is more manageable
than the original program.
92
In Real Life
In Programming
Task 4
Task 1
Function ( )
Function ( )
Task 3
Task 2
Function ( ) Function ( )
93
Why to use Functions ?
• Functions allows to write more manageable units of code.
• Writing functions avoids rewriting the same code over and over.
• Easy maintenance for programs.
Important Tips
1- Don’t try to cram the entire logic in one function. It is a very bad style of
programming.
2- Instead, break a program into small units and write functions for each of these
isolated subdivisions.
94
Calculate and print out The
sum and the Average of 3
student marks.
Task 4
Task 1
Print_out ( )
Get_Marks( )
Task 3
Task 2
Calc_sum( ) Calc_Average ( )
95
Functions
Function Definition
96
Function Types
1. Built in Functions (Ready Made).
• For Example : Math Library Functions <cmath> Like
97
Built in Functions
To correctly use the built in functions we must know well its header (prortotype).
98
#include <iostream>
#include <cmath>
using namespace std;
int main ( )
{
int i = -5 ;
double x = 5.0;
double y = 2.0;
double z = 5.21;
cout << "The absolute value of i is " << abs (i) << "\n \n";
cout << "The power of x to the power y is " << pow (x,y) << "\n \n";
cout << "The Floor for Z is " << floor (z) <<"\n \n";
cout << "The Ceil for Z is " << ceil (z) <<"\n \n";
}
99
Function Types
2. User Defined Functions ( Tailored by Programmers).
Working with user defined functions is done in three steps :
100
Building Functions
1- Function Declaration (Written before The main( ) )
101
User-Defined Functions
• Value-returning functions: have a return type
– Return a value of a specific data type using the return statement
– the returned value can be used in one of the following scenarios:
• Save the value for further calculation
Int result;
Result = sum ( x , y );
106
For Example : write a program that ask the user to Enter 3 integer numbers
and print out their sum and Average.
int main( )
{
int n1 , n2 ;
cout <<"Please Enter 3 integer numbers \n";
cin >>n1 >> n2 ;
cout <<" The sum of the 3 number is " << sum (n1, n2) <<"\n";
}
int sum (int num1 , int num2, int num3 = 90)
{
return num1+ num2+ num3;
}
108
Function Parameters Types
• Value parameter: Reference parameter:
– When passing the address would save memory space and time
110
Function Parameters Types
111