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

Programming For Engineers Lecture 07 11

The document discusses loops, programming toolkits including decisions and loops, constructing a laboratory stool by making a seat and legs and assembling them, and what functions are including how they allow complicated programs to be divided into manageable components and allow for reusability and avoiding repetition. It provides examples of predefined math functions like pow, sqrt, and floor and shows examples of user-defined functions including their declaration, definition, return types, and calls.

Uploaded by

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

Programming For Engineers Lecture 07 11

The document discusses loops, programming toolkits including decisions and loops, constructing a laboratory stool by making a seat and legs and assembling them, and what functions are including how they allow complicated programs to be divided into manageable components and allow for reusability and avoiding repetition. It provides examples of predefined math functions like pow, sqrt, and floor and shows examples of user-defined functions including their declaration, definition, return types, and calls.

Uploaded by

Malik Adnan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

What we have learned ?

Loops
While
Do while

1
Train your mind……….!!!

2
Programming Toolkit

• Decisions
• Loops
• Sequences
Laboratory Stool
Constructing a laboratory Stool
Constructing a laboratory Stool

• Task: Making a stool


• Subtask:
• Make a seat
• Make legs for the stool
• Assemble them
What are Functions?
• In general, we use (call) functions (aka: modules, methods, procedures, subprocedures,
or subprograms) to perform a specific (atomic) task. In algebra, a function is defined as a
rule or correspondence between values, called the function's arguments, and the unique
value of the function associated with the arguments. For example:

• If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11

• You would say the call f(1) returns the value 7

• 1, 2, and 3 are arguments


• 7, 9, and 11 are the resulting values (or corresponding values)

7
C++ Functions
• C++ functions work in largely the same way. Format of a C++ function call:
• functionName(argumentList)
• where the argumentList is a comma-separated list of arguments (data being sent into
the function).
• In general, function arguments may be constants, variables or more complex
expressions.
• Functions are building blocks
• Also called modules, methods, procedures, or sub-procedures
• Like miniature programs
• Can be put together to form larger program
• One of two principle means of modularization in C++ (other is classes)
8
Why use Functions?
• Divide and Conquer
• Allow complicated programs to be divided into manageable components
• Programmer can focus on just the function: develop it, debug it, and test it
• Various developers can work on different functions simultaneously
• Reusability:
• Can be used in more than one place in a program--or in different programs
• Avoids repetition of code, thus simplifying code maintenance
• Can be called multiple times from anywhere in the program
• Components:
• Custom functions and classes that you write
• Prepackaged functions and classes available in the C++ Standard Library

9
Predefined Functions
• Using predefined functions:
• C++ Standard Library contains many predefined functions to perform
various operations
• Predefined functions are organized into separate libraries
• I/O functions are in iostream header
• Math functions are in cmath header
• Some predefined C++ mathematical functions:
• pow(x,y)
• sqrt(x)
• floor(x)

10
• Power Function - pow(x,y):
• Power function pow(x,y) has two parameters
• pow(x,y) returns value of type double
• pow(x,y) calculates x to the power of y: pow(2,3) = 8.0
• x and y called parameters (or arguments) of function pow
• Square Root Function - sqrt(x):
• Square root function sqrt(x) has only one parameter
• sqrt(x) returns value of type double
• sqrt(x) calculates non-negative square root of x, for x >= 0.0: sqrt(2.25) = 1.5
• Floor Function - floor(x):
• Floor function floor(x) has only one parameter
• floor(x) returns value of type double
• floor(x) calculates largest whole number not greater than x: floor(48.79) = 48.0

11
Math.h
#include < math.h >
double sqrt ( double );

log10 , pow ( xy ) , sin , cos , tan …


Square Root of a Number
• #include <iostream>
• #include <cmath>

• using namespace std;

• int main()
•{
• double number, squareRoot;
• cout << "Enter a number: ";
• cin >> number;

• // sqrt() is a library function to calculate square root


• squareRoot = sqrt(number);
• cout << "Square root of " << number << " = " << squareRoot;
• return 0;
•}

13
14
15
Example:
• n general, function arguments may be constants, • cout << sqrt(49); // because of automatic
variables or more complex expressions type conversion rules
• The pre-defined math function sqrt listed above • // we can send an int where a double is
takes one input value (of type double) and returns expected
its square root. Sample calls:
• // this call returns 7.0
• double x = 9.0, y = 16.0, z;

• z = sqrt(36.0); // sqrt returns 6.0 (gets stored in z) • // in this last one, sqrt(625.0) returns 25.0,
which gets sent as the
• z = sqrt(x);// sqrt returns 3.0 (gets stored in z)
• // argument to the outer sqrt call. This one
• z = sqrt(x + y);// sqrt returns 5.0 (gets stored in z)
returns 5.0, which gets
• // printed
• cout << sqrt(100.0);// sqrt returns 10.0, which
gets printed
• cout << sqrt(sqrt(625.0));

16
User-Defined Functions
• Two types:
• Void functions (nonvalue-returning): no return type, do not return a value
• Value-returning functions: have a data type, return only one value to caller
• When utilizing functions:
• Include correct header file
• Know function name
• Know number of parameters, if any
• Know data type of parameters
• Know data type of value computed by function

17
• Value-returning function used 3 ways:
• Assignment statement
• Output statement
• Argument (actual parameter) in another function call
• Creating functions:

Mnemonic: "ProDeCall":
• Prototype
• Definition
• Call

18
What we will study today …

• What are functions?


• How are they defined ?
• How are they declared ?
• What values are passed to functions ?
• What values do functions return ?
Function
Function name
{
Body of the function
}
Function

Two types of functions:


1. Functions that return a value
2. Functions that do not return a value
Function
return-value-type function-name( argument-list )
{
declarations and statements
}
Function Video

https://www.youtube.com/watch?v=2UqzHffkFbU

23
Declaration of Function
return-value-type function-name( argument--type-list) ;
main ( )
{
:
}
Example
int function-name ( int , int , double ) ;

void main ( )
{
….
}
Definition of Function

int function-name ( int i , double j )


{

}
Return Type of Function
Declaration
int square ( int ) ;

Definition

int square ( int i )


{
return ( i * i ) ;
}
Function Call

int x ;
x = square ( i ) ;
Example : Square of a Number

double square ( double x )


{
return x * x ;
}
main ( )
{
double number = 123.456 ;
cout << “ The square of “ << number << “ is “<< square ( number ) ;
cout << “ The current value of “ << number << “is “ << number ;
}
Example: Function to calculate integer
power ( Xn )
double raiseToPow ( double x , int power )
{
double result ;
int i ;
result = 1.0 ;
for ( i = 1 ; i <= power ; i ++ ) // braces first
{
result * = x ; // result = result *x
}
return ( result ) ;
}
Code
include < iostream.h >
to Call the raisetopow Function
void main ( )
{
double x ;
int i ;
cout << “ Please enter the number “ ;
cin >> x ;
cout << “ Please enter the integer power that you want this number raised to “ ;
cin >> i ;
cout << x << “ raise to power “ << i << “is equal to “ << raiseToPow ( x , i ) ;
}
function returning the max between two
numbers
• #include <iostream> • cout << "Max value is : " << ret << endl;

• using namespace std;
• return 0;
• •}
• // function declaration •
• int max(int num1, int num2); • // function returning the max between two numbers
• • int max(int num1, int num2) {
• // local variable declaration
• int main () {
• int result;
• // local variable declaration: •
• int a = 100; • if (num1 > num2)
• int b = 200; • result = num1;
• else
• int ret;
• result = num2;
• •
• // calling a function to get max value. • return result;
• ret = max(a, b); •}

32
function example with definition before main()

• #include <iostream> • int main ()


•{
• using namespace std;
• int x=5, y=3, z;
• z = subtraction (7,2);
• int subtraction (int a, int b) • cout << "The first result is " << z << '\n';
•{ • cout << "The second result is " <<
subtraction (7,2) << '\n';
• int r; • cout << "The third result is " << subtraction
• r=a-b; (x,y) << '\n';
• z= 4 + subtraction (x,y);
• return r; • cout << "The fourth result is " << z << '\n';
•} •}

33
Functions with no type. The use of void


The syntax shown above for functions:

•type name ( argument1, argument2 ...) { statements }

•Requires the declaration to begin with a type. This is the type of the
value returned by the function. But what if the function does not
need to return a value? In this case, the type to be used is void,
which is a special type to represent the absence of value. For
example, a function that simply prints a message may not need to
return any value:
34
Void Function example
• // void function example • #include <iostream>
• using namespace std;
• #include <iostream> • void PrintMessage();
• void main(void)
• using namespace std;
•{
• char name[10];
• cout << "What is your first name? ";
• void printmessage () • cin >> name;
•{ • cout << "\n\nHello " << name << endl << endl;
• // Here is the function call
• cout << "I'm a function!"; • PrintMessage();
•} •}
• // Following is the function definition - function heading and code
• void PrintMessage()
• int main () •{
• cout << "********************\n";
•{ • cout << " Welcome to my\n";
• printmessage (); • cout << " wonderful program!\n";
• cout << "********************\n";
•} •}

35
Default Values for Parameters
• 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 instead. Consider the following example −

36
Consider the following example −
• #include <iostream> • int b = 200;
• using namespace std; • int result;
• •
• int sum(int a, int b = 20) { • // calling a function to add the values.
• result = sum(a, b);
• int result;
• cout << "Total value is :" << result << endl;
• result = a + b;

• // calling a function again as follows.
• return (result); • result = sum(a);
•} • cout << "Total value is :" << result << endl;
• int main () { •
• // local variable declaration: • return 0;
• int a = 100; •}

37
Flow of Execution
• Program Execution:

• Begins with first statement in function main()


• Additional functions invoked when called
• Function prototypes appear before function definitions--that is, before function main()
• Compiler translates prototypes first
• Function call invocation:
• Transfer of control to first statement in body of called function
• After function body executed: control passed back to point immediately following function call
• Value-returning function returns value
• After function execution: value that function returns replaces function call statement

38
Call by Value or Reference

https://www.youtube.com/watch?v=ErMKBh1pobg

39
Call By Value
Calling function

Called function
Area of the Ring

Area of Outer Circle ____ Area of Inner Circle = Area of the Ring
Example: Function to calculate
the area of a circle

double circleArea ( double radius )


{
return ( 3.1415926 * radius * radius ) ;
}
Calculating ringArea without
using Function
main ( )
{
:
ringArea = ( 3.1415926 * rad1 * rad1 ) – ( 3.1415926 * rad2 * rad2 ) ;

}
Exercises
1. Modify the raise to power function so that it
can handle negative power of x, zero and
positive power of x.

2. For the area of ring function put in error


checking mechanism.
Example: Call by Value
#include <iostream.h >
int f ( int ) ;
main ( )
{
int i = 10 ;
cout << “In main i = " << i ;
f(i);
s
cout << " Back in main, i = " << i ;
}
Example: Call by Value
int f ( int i )
{
cout << "In function f , i = " << i ;
i *= 2 ;
cout << "In function f , i is now = “ << i ;
return i ;
}
Call by Reference
• A function in which original value of the variable is
changed
• To call by reference we cannot pass value, we have to
pass memory address of variable
• “&” is used to take the address of a variable
Example: Call by Reference

main ( )
{
double x = 123.456 ;
square ( &x ) ;
}
Value of ‘x’ is not passed , but the memory
address of ‘x’ is passed
Example: Call by Reference

x is a pointer to a variable double


square ( double *x )
{
*x = *x * *x ;
}
A FEW POINTS TO REMEMBER
• Value parameters are viewed as constants by the • - Formal parameters appear in the function
function and should never heading and include their data
• appear on the left side of an assignment • type.
statement or in a cin statement.
• - When the formal parameter is a value
• - Reference parameters are modified by the parameter, the argument (actual
function and should appear
• parameter) may be a variable, named or literal
• either on the left side of an assignment
constant, or expression. Note
statement or in a cin statement.
• - Formal and actual parameters are matched
• that type coercion may take place.
according to their relative • - When the formal parameter is a reference
• positions. parameter, the argument (actual
• - Arguments (actual parameters) appear in the • parameter) MUST be a variable of exactly the
function call and do not same data type as the formal
• include their data type. • parameter.

51
Function Overloading

52
• Function refers to a segment that groups code to perform a specific task.

• In C++ programming, two functions can have same name if number and/or type of arguments
passed are different.

• These functions having different number or type (or both) of parameters are known as
overloaded functions. For example:

• int test() { }
• int test(int a) { }
• float test(double a) { }
• int test(int a, double b) { }

53
• Here, all 4 functions are overloaded functions because argument(s) passed to these
functions are different.

• Notice that, the return type of all these 4 functions are not same. Overloaded functions
may or may not have different return type but it should have different argument(s).

• // Error code
• int test(int a) { }
• double test(int b){ }
• The number and type of arguments passed to these two functions are same even though
the return type is different. Hence, the compiler will throw error.

54
Example 1: Function Overloading
• #include <iostream> • return 0;
• using namespace std; •}

• void display(int); • void display(int var) {


• void display(float); • cout << "Integer number: " << var << endl;
• void display(int, float); •}

• int main() { • void display(float var) {


• cout << "Float number: " << var << endl;
• int a = 5; •}
• float b = 5.5;
• void display(int var1, float var2) {
• display(a); • cout << "Integer number: " << var1;
• display(b); • cout << " and float number:" << var2;
• display(a, b); •}

55
• Output • Here, the display() function is
called three times with different
type or number of arguments.
• Integer number: 5
• Float number: 5.5
• The return type of all these
• Integer number: 5 and float functions are same but it's not
number: 5.5 necessary.

56
Write a Program to compute absolute value which
Works both for integer and float
• #include <iostream> • int absolute(int var) {
• using namespace std;
• if (var < 0)
• int absolute(int); • var = -var;
• float absolute(float); • return var;
• int main() { •}
• int a = -5;
• float b = 5.5;
• float absolute(float var){

• cout << "Absolute value of " << a << " = " << absolute(a) • if (var < 0.0)
<< endl;
• var = -var;
• cout << "Absolute value of " << b << " = " << absolute(b);
• return 0; • return var;
•} •}

57
• Output • int absolute(int var) {
• if (var < 0)
• Absolute value of -5 = 5 • var = -var;
• Absolute value of 5.5 = 5.5 • return var;
• In the above example, two functions absolute() •}
are overloaded. • When absolute() function is called with float as an
argument, this function is called:

• Both functions take single argument. However,


one function takes integer as an argument and • float absolute(float var){
other takes float as an argument. • if (var < 0.0)
• var = -var;
• When absolute() function is called with integer • return var;
as an argument, this function is called: •}

58
Header Files

#include <iostream.h>
Prototype
Assignment List with
Return value
data type

int functionName ( int , int );


Using Header Files
double pi = 3.1415926;

 It is better to define this value in a header file

 Then simply by including the header file in the


program this value is defined and it has a
meaningful name
#define
• #define pi 3.1415926
• Name can be used inside a program exactly
like a variable
• It cannot be used as a variable

CircleArea = pi * radius * radius

Circumference = 2 * pi * radius
Scope of Identifiers
• Identifier is any name user creates in his/her program

• Functions are also identifiers

• Labels are also identifiers


Scope of Identifiers
• Scope means visibility

• A variable declared inside a block has visibility


within that block only

• Variables defined within the function has a scope


that is function wide
Example
void functionName ( )
{
{
int i ;
}
…..
}
Identifiers Important Points
• Do not create variables with same name
inside blocks, inside functions or inside bigger
blocks

• Try to use separate variable names to avoid


confusion

• Reuse of variables is valid


File Scope
# include < iostream.h >
int i ;
Global variable
Global Variable
• Can be used anywhere in program
• Can cause logical problems if same variable name
is used in local variable declarations

For good programming

• Try to minimize the use of global variables


• Try to use local variables as far as possible
Visibility of Identifiers
• Global Scope
Anything identified or declared outside of any function is visible to all
functions in that file
• Function level scope
Declaring variables inside a function can be used in the whole
function
• Block level scope
Variables or integers declared inside block are used inside block
Example: Block Scope
for ( int i = 0 ; i < 10 ; i++ )

• It is block level scope declared in for loop


• When for is finished “ i ” no longer exists
Example: Global Scope
#include < iostream.h >
int i ;
void f ( void ) ;
main ( )
{
i = 10 ;
cout<< “ within main i = “ << i ;
f();
}
Example: Global Scope
void f ( void )
{
cout<< “ Inside function f , i =“ << i ;
i = 20 ;
}
In today’s lecture
• We used functions for breaking complex problems into smaller
pieces, which is a top-down structured approach.
• Each function should be a small module, self contained and it
should solve a well defined problem.
• Variable names and function names should be self explanatory.
• Always comment your code

You might also like