[go: up one dir, main page]

0% found this document useful (0 votes)
18 views39 pages

Lecture 5

Uploaded by

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

Lecture 5

Uploaded by

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

CPE 224

FUNCTIONS
Outline

Introduction to functions
C library functions
Function call
User defined functions
Examples
OBJECTIVES
• To learn how to design, develop and manage
large programs

• To understand what and how functions work

• To distinguish between C library function from


user defined functions

• To understand what function calls are and their


types

• To solve real life problems with functions


INTRODUCTION TO FUNCTIONS
• Real-world problems are very complex, hence
they can not be solved by programming
techniques earlier discussed (looping, selection
etc).

• Splitting large programs into more manageable


smaller pieces call (MODULES) was identified
to be the best way to develop and maintain large
programs.

• The technique is known as DIVIDE and


CONQUER
INTRODUCTION TO FUNCTIONS

• Divide and Conquer


Advantages of using modules
• Modules can be written and tested separately

• Modules can be reused

• Large projects can be developed in parallel

• Reduces length of program, making it more


readable

• Promotes the concept of abstraction

• A module hides details of a task


Functions
• Functions also referred to as Modules

• It is used to perform specific tasks in order to achieve a


desired solution

• Functions help to Modularize a program

• Helps in:
▫ Manageable program development (Divide and
conquer)
▫ Software reusability (abstraction)
▫ Avoid code repetition
Functions Definitions
• Every c program starts with main () function
• Additional functions are called or invoked when the program
encounters function names
• Functions could be;
• Pre-defined library functions (e.g., printf, sin, tan) or
Programmer-defined functions (e.g., my_printf, area)
• Assume that printf function was not there. How difficult your
life would be? Every time you want to print something, you
have to write several sets of instructions (that printf uses
internally) to perform this task.
▫ May take arguments
▫ May return a single value to the calling function
▫ May change the value of the function arguments (call by
reference)
Functions Definition

return_type function_name (parameters list)


{
declarations;
statements;
}
int my_add_func(int a, int b)
{
int sum;
sum = a + b;
return (sum);
}
Function Definition

 Function-name: any valid identifier

 Return-value-type: data type of the result (default


int)
• void – indicates that the function returns nothing

 Parameter-list: comma separated list, declares


parameters
• A type must be listed explicitly for each parameter
unless, the parameter is of type int
Function Definition

▫ Declarations and statements: function body (block)


 Variables can be declared inside blocks (can be
nested)

▫ Returning control
 If nothing returned
 return;
 or, until reaches right brace

 If something returned
 return expression;
FUNCTION PROTOTYPE
▫ Function Prototype describes how a function is
called
▫ Function implementation
▫ int my_add_func(int a, int b)
▫ Function Call
▫ result = my_add_func(5, X);
▫{ Function parameters
▫… Formal parameters
▫} Actual parameter
Formal parameters must match with actual parameters
in order, number and datatype.
If the type is not the same, type conversion will be
applied
Function Prototype
• Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after use in
program
– The function with the prototype
int maximum( int, int, int );
• Takes in 3 ints
• Returns an int
• Promotion rules and conversions
– Converting to lower types can lead to errors
PRE-DEFINED FUNCTIONS
we have been using several pre-defined functions! :
EXAMPLE
//program to print the sine of an angle
#include <stdio.h>
#include <math.h>
int main(void) {
double angle;
printf (“Input angle in radians: \n“);
scanf(“%f”, &angle);
printf(“Sine of the angle is %f\n“, sin(angle));
return 0;
}
HEADER FILES
• Header files
– Contain function prototypes for library functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
• Custom header files
– Create file with functions
– Save as filename.h
– Load in other files with #include "filename.h"
– Reuse functions
RANDOM NUMBER GENERATION
Some pre-defined functions we have discussed
are:
main
printf
scanf
RANDOM AND PSEUDO-RANDOM NUMBERS
rand (uniform random numbers)
srand (for may be 7 random numbers)

READ OTHER FUNCTIONS IN C AND HOW


THEY WORK
Generating a specified range of RNs
[a b]
1. Generate a RN between 0 and 8
• x = rand() % 9;

2. Generate a RN between 10 and 17


• x = 10 + rand() % 8;
int rand_int(int a,int b)
{
return rand()%(b-a+1) + a;
}
Types of functions
• Functions with no arguments and no return
values.

• Functions with arguments and no return values.

• Functions with arguments and return values.

• Functions that return multiple values.

• Functions with no arguments and return values.


Functions with no arguments and no
return values
#include<stdio.h> void doNothing( )
void doNothing( ); {
void main( ) int i;
{ for(i=0; i<5; i++){
doNothing( ); printf(“I do nothing\n”);
} }
}
Functions with arguments and no
return values.
void add(int x, int y)
{
int result;
result=x+y;
printf(the sum is %d\n”, result);
}
#include<stdio.h>
void add(int x, int y);
void main( )
{
Add(35, 25);
}
Functions with arguments and
return value
int add(int x, int y)
{
int result;
result=x+y;
return (result);
}
#include<stdio.h>
int add(int x, int y);
void main( )
{ int z;
Z=add(35, 25);
printf(“the sum is %d\n”, Z);
}
Functions that return multiple
values
#include<stdio.h>
void calc(int x, int y, int *add, int *sub)
{
*add=x+y;
*sub=x-y; sum=31, sub=9
}
main( ) {
int a=20, b=11, p, q;
calc(a,b, &p, &q);
printf(“sum=%d, sub=%d”, p,q);
}
Functions with no arguments and
return values
#include<stdio.h>
int send( )
}
int N;
printf(“Enter a number:”);
scanf(“%d”, &N);
return (N);
}
void main( ) {
int z;
z=send( );
printf(“you just entered %d\n”, z);
Calling Functions: Call by Value and Call by
Reference
• Used when invoking functions
• Call by value
– Copy of argument passed to function
– Used when function does not need to modify argument
• Call by reference
– Passes original argument
– Changes in function affects original
– Only used with trusted functions
Function call by value example
#include<stdio.h>
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
printf(" values before swap m = %d \n and n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \n values after swap m = %d\n and n = %d", a, b);
}
Call by reference example
#include<stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \n and b = %d", *a, *b);
}
CLASS WORK

1. Write a function to compute maximum


and minimum of two numbers.
2. Write a function that takes score as
parameter, computes and returns letter
grade based on the scale below.
• 80-100A
• 60-79B
• 40-59C
• 0-39D
FUNCTION SCOPE
Scope refers to the portion of the program in
which
• It is valid to reference the function or variable
• The function or variable is visible or accessible
• Same variable names can be used in different
part of functions

Two types of scopes


 LOCAL SCOPE
GLOBAL SCOPE
SCOPE
 Local scope
• local variable is defined within a function or a
block and can be accessed only within the
function or block that defines it
 Global scope
• A global variable is defined outside the main
function and can be accessed by any function
within the program file.
SCOPE RULES
• File scope
– Identifier defined outside function, known in all functions
– Used for global variables, function definitions, function
prototypes
• Function scope
– Can only be referenced inside a function body
– Used only for labels
• Block scope
– Identifier declared inside a block
• Block scope begins at declaration, ends at right brace
– Used for variables, function parameters (local variables of
function)
G vs L
#include <stdio.h>
int z = 2; int main()
void function1() {
{ int a = 3;
int a = 4; z = z + a;
printf("Z = %d\n",z); function1();
z = z+a; printf("Z = %d\n",z);
} z = z+a;
return 0;
}
• Output
• Z=?
• Z=?
Recursion
• If a function calls itself, it becomes a recursive
function . Clearly, the calling function and called
function are same here

void function() {

function(); // Recursive call as function calls
itself……
}
int main() {
function(); // Normal Call…
}
Recursion
• If a function keeps calling itself, stack might get
full due to number of calls and the result would
be a stack overflow.
EXAMPLES

• Example: factorials
▫ 5! = 5 * 4 * 3 * 2 * 1
▫ Notice that
 5! = 5 * 4!
 4! = 4 * 3! ...
▫ Can compute factorials recursively
▫ Solve base case (1! = 0! = 1) then plug in
 2! = 2 * 1! = 2 * 1 = 2;
 3! = 3 * 2! = 3 * 2 = 6;
int factorial(int n) {
if(n <= 1){
return 1;
}
else
return ( n * factorial(n-1) ); // Recursive call…
}
int main() {
int number;
int result;
printf(“Enter a number:\t”);
scanf(“%d”, &number);
result = factorial(number);
printf(“Factorial of %d is %d…\n”, number, result);
}
EXAMPLES 2

int fact(int k)
{ note :k!=k*(k-1)!
if (k == 0)
return 1;
else
return k*fact(k-1);
}
Example Using Recursion: The
Fibonacci Series
Sequence {f0,f1,f2,…}. First two values (f0,f1) are
1, each succeeding number is the sum of previous
two numbers.
• 1 1 2 3 5 8 13 21 34
• F(0)=1, F(1) = 1
• F(i) = F(i-1)+F(i-2)

• Can be solved recursively:


• fib( n ) = fib( n - 1 ) + fib( n – 2 )
• Fibonacci series: 1, 1, 2, 3, 5, 8...
fibaonacci function Code
#include<stdio.h>
long fibonacci(long n);
int main(){
long x;
x=fibonacci(1);
return x;
}
//fibonacci function
long fibonacci(long n){
if (n==0 || n==1){
return n;
}
else
return fibonacci(n-1)+fibonacci(n-2);
}
fibonacci
fibaonacci function Code 2

int fibonacci(int k)
{
int term;
term = 1;
if (k>1){
term = fibonacci(k-1)+fibonacci(k-2);
}
return term;
}

You might also like