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

Chap v. Functions2015-16

The document discusses functions in C/C++. It explains that functions enable modular programming by breaking programs into smaller pieces that perform specific tasks. Functions can receive input parameters and return output. Variables declared within functions are local to that function. Well-defined functions make programs more readable and maintainable by avoiding repeated code blocks and enabling easy debugging and modification. The document provides examples of function definitions, prototypes, parameters, and calls.

Uploaded by

thierrymuhirwa5
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)
41 views

Chap v. Functions2015-16

The document discusses functions in C/C++. It explains that functions enable modular programming by breaking programs into smaller pieces that perform specific tasks. Functions can receive input parameters and return output. Variables declared within functions are local to that function. Well-defined functions make programs more readable and maintainable by avoiding repeated code blocks and enabling easy debugging and modification. The document provides examples of function definitions, prototypes, parameters, and calls.

Uploaded by

thierrymuhirwa5
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/ 39

FUNCTIONS

• A function in C(++) is a small “sub-program” that performs a particular task, and

supports the concept of modular programming design techniques.

• In modular programming the various tasks that your overall program must
accomplish are assigned to individual functions and the main program basically
calls these functions in a certain order.
 Main program is mainly a wiring together of function calls.

1
Functions

• Functions
 Enable you to break a program into smaller pieces (modularization).
 Each function performs a specified task. It may receive input data and
return output data.
 All variables declared inside functions are local variables
• Known only in that function
 Parameters
• Communicate information between functions

2
Functions

• The functions are used for the following reasons:


 Don’t have to repeat the same block of code many times in your code.
Make that code block a function and call it when needed.
 Function portability
 Easy to debug
 Easy to modify and expand
 For a large programming project, you will code only a small fraction of the
program.
 Make program self-documenting and readable.

3
Start with an example

• Imagine that many different times in a program you have to find


the maximum of two numbers:

if ( a > b ){
bigger = a;
}
else{
bigger = b;
}
• While this may not seem like a lot of code, it can get very ugly and
make the program difficult to follow. It would be much nicer to say something
like:
bigger = imax(a,b); 4
C functions, cont.

• The purpose of a C(++) function is to allow the programmer to move


snippets of code outside of the main program and call them by an
intuitive name. These functions can then be reused in any program
where they are needed.

5
Predefined functions
• C Standard library functions or simply C Library functions are inbuilt

functions in C programming.
• Function prototype and data definitions of these functions are written in their

respective header file.


 For example: If you want to use printf function, the header file stdio.h should
be included.

#include <stdio.h>
int main()
{ /*If you write printf() statement without including header
file, this program will show error. */
printf(“This is a c program”); }
6
Predefined functions
• There are many library functions available in C(++) programming to help the
programmer to write a good efficient program.

 Suppose, you want to find the square root of a number


• You can write your own piece of code to find square root but, this process
is time consuming and the code you have written may not be the most
efficient process to find square root.
• But, in C programming you can find the square root by just using sqrt()
function which is defined under header file < math.h >

7
Predefined functions
Ex.: Math header functions (methods)

8
USER DEFINED FUNCTIONS
• In order to use functions, the programmer must do three things
 Define the function
 Declare the function
 Use the function in the main code (function call).
• The following
is the general program format:

9
Function prototype
• The general format for a prototype is simple:
 Return-type function_name(arg_type arg1,………..arg_type argN);
arg_type just means the type for each argument -- for instance, an int, a
float, or a char. It's exactly the same thing as what you would put if you
were declaring a variable.
• There can be more than one argument passed to a function or none at all (where
the parentheses are empty), and it does not have to return a value.
• Functions that do not return values have a return type of void

10
Function definition

• The general form of a function definition in C is as follows:


return _type function_name(parameter (s))
{
local declaration
function implementation
function return
}

11
Function definition
• If the function returns a value then the type of that value must be specified in
return-type. For the moment this could be int, float or char. If the function does not
return a value then the return-type must be void.

• The function-name follows the same rules of composition as identifiers.


• The parameter-list lists the formal parameters of the function together with
their types.
• The local-definitions are definitions of variables that are used in the function-
implementation. These variables have no meaning outside the function.

• The function-implementation consists of C executable statements that


implement the effect of the function.

12
Function definition
Function with no return type and no parameter

• Many of the programs we have seen use only main function. But as your
program get bigger you can improve their readability by subdivide them in
different functions
Example:
void hello(void)
{
printf (“Hello, every body”);
}

13
Function definition
Function with no return type and no parameter

• In programming, when you use a function, it said that “ you call ” that function.
The following program calls the function hello:

# include <stdio.h>
void hello(void);
{
printf(“Hello, every body\n”);
}
void main(void)
{
hello();
}

14
Function definition
Function with no return type and no parameter
• To well understand, we modify the main party of the program
# include <stdio.h>
void hello(void); // Function prototype
int main(void)
{
printf(“Ready to call the function\n”);
hello();
printf(“return to the main program\n”);
return 0;
}
// function definition
void hello(void)
{
printf(“Hello every body\n”);
}
15
Function definition
Declaring variables within function definition
# include <stdio.h>
void three_hello(void);
{
int compter; //variable
for(compter=1; compter<=3; compter++)
printf(“Hello, every body\n”);
}
void main(void)
{
three_hello ();
}

16
The main Function
• For C, the main function of a program is the first instruction that the program
execute.
 All what you can do in the main function, you also can do it in any other
function (variable declaration, using instruction if, while, and even call other
function). Ex:

# include <stdio.h> void main(void)


void hello(void); {
{
three_hello ();
printf(“Hello, every body\n”);
}
}
void three_hello(void);
{
int compter;
for(compter=1; compter<=3; compter++)
hello();
} 17
Parameters & arguments
• The term parameter (sometimes called formal parameter) is often used to refer
to the variable as found in the function definition, while argument (sometimes
called actual parameter) refers to the actual input passed.

• We have already transmitted argument to the function printf:

printf(“Hello every body\n”);

• The function three_hello would be powerful if you could specify the number the
message will be displayed.

18
Parameters & arguments
• To use an argument, the function have to indicate the type and the name of the
argument

• Example:
repeat_hello(int message_number)
{
// instruction of the function
}
 When any function for ex. Main have to call the function repeat_hello, it
must specify (define) a value for the argument

 Ex: repeat_hello(2); // displays the message 2 times


repeat_hello(10); // displays the message 10 times
……

19
Parameters & arguments
The following program shows the topic

# include <stdio.h>
void main(void)
void hello(void)
{
{
printf(“display 2
printf(“Hello every body\n”)
times\n”);
}
repeat_hello(2);
void repeat_hello(int nbr)
printf(“display 5 times\
{
n”);
int cpmt; //variable
repeat_hello(5);
for(cpmt =1; cpmt <= nbr; cpmt++)
}
hello();
}

20
Using many arguments

void funct_any (int nbre, float othernbre, char letter)


{
//Instruction of the function
}

When a program call the function, it must provide the values for each argument.:

funct_any(20,18.6, ‘A’);

21
Function with return value
• To return a integer value, a function must have been defined as :

int my_function(int value)


{
// instruction of function
}
Ex: function cube
int cube(int value)
{
return (value* value* value);
}

22
Function with return value
• The function use return to send the result to the caller
• The returned value can be assigned to a variable or directly used as an argument of
another function:

 result = cube(5);
 printf (“the cube of 5is %d\n”, cube(5));
• Program using cube function:
# include <stdio.h>
int i_cube(int value)
{
return (value*value*value);
}
void main()
{
printf(“the cube of 3 is %d\n”, i_cube(3));
printf(“the cube of 5 is %d\n”, i_cube(5));
} 23
Recursion Function
• Recursion is a programming technique that allows the programmer to express
operations in terms of themselves
• In C, this takes the form of a function that calls itself.

• A useful way to think of recursive functions is to imagine them as a process being


performed where one of the instructions is to "repeat the process".

This makes it sound very similar to a loop because it repeats the same
code, and in some ways it is similar to looping.

24
Recursion Function
Every recursion should have the following characteristics.

1. A simple base case which we have a solution for and a return value. Sometimes
there are more than one base cases.
2. A way of getting our problem closer to the base case. I.e. a way to chop out part
of the problem to get a somewhat simpler problem.
3. A recursive call which passes the simpler problem back into the function.

Let's write the factorial function recursively.

int myFactorial( int n)


{
if(( n== 1)||(n==0))
return 1;
else
{
return (n* (myFactorial(n-1)));
}
}
25
Recursion Function
Exercices
1. Exponentiation, Multiplication, division

2 Write a recursive function that computes the sum of all numbers from 1 to n,
where n is given as parameter.
//return the sum 1+ 2+ 3+ ...+ n
int sum(int n)

3. Write a recursive function that finds and returns the minimum element in an
array, where the array and its size are given as parameters.
//return the minimum element in a[]
int findmin(int a[], int n)

26
Data visibility

• Extremely important!
 Function can only "see" three types of variables:
 Those declared locally within the function
 Those passed into the function through it arg list
 "Global variables" defined outside of any function
We have not yet used global variables
 Any variables defined in other functions (even main) that are not
passed into another function are NOT visible to that function, and it can
not see or manipulate their values!
This behavior is crucial to achieving code modularity.

27
Parameter passing methods

• In all the function prototype and definition examples we have


seen thus far, parameters are specified as if they were simple
variables, and the process of parameter passing is comparable
to the process of assigning a value to a variable:
 Each parameter is assigned the value of its corresponding argument

 Although the value of a parameter may change during the course of a


function, the value of the corresponding argument is not affected by
the change to the parameter
Passing by value

• The process described on the previous slide, and illustrated in


all examples thus far, is called passing by value - this is the
default method for parameter passing
• When arguments are passed by value:
 a copy of each argument value is passed to its respective parameter

 the parameter is stored in a separate memory location from the


storage location of the argument, if the argument has one
 Any valid expression can be used as an argument
Example – swap function
Suppose we want to write a function that swaps two values: that is, value a is
replaced by value b, and value b is replaced by the original value of a. The
function below is an attempt to achieve this goal.
The function appears to work correctly. The next step is to
void swap (int a, int b)
{ write a program that calls the function so that we can test
int tmp = a; it:
a = b;
b = tmp; int main()
} {
int a=2, b=6;
printf(“Before swap, a = %d and b = %d\n”,a,b);
Output: swap(a,b);
Before swap, a=2 and b=6 printf(“After swap, a = %d and b = %d\n”,a,b); return 0;
After swap, a=2 and b=6 }
What went wrong?

• In the swap function, parameters a and b were passed the values of


variables x and y via the function call swap(x, y);
• Then the values of x and y were swapped

• When the function returned, a and b were no longer in memory, and x


and y retained their original values
• Remember, when you pass by value, the parameter only gets a copy of the
corresponding argument; changes to the copy don’t change the original
Building a better swap function: introducing
reference parameters

• C(++ ) offers an alternative parameter-passing method called pass-by-


reference
• When we pass by reference, the data being passed is the address of the
argument, not the argument itself
• The parameter, rather than being a separate variable, is a reference to the
same memory that holds the argument – so any change to the parameter
is also a change to the argument
Revised swap function

We indicate the intention to pass by reference by appending the address of


operator (*) to the data type of each reference parameter. The improved
swap function illustrates this:
The reference designation (*) means that x
void swap (int *x, int *y) and y are not variables, but are instead
{ references to the memory addresses passed to
int tmp = *x; them
*x = *y;
*y = tmp; If we had the same main program as before,
} the function call:
swap(a,b);
indicates that the first parameter, x, is a
reference to a, and the second parameter, y, is
a reference to b
How pass-by-reference works

• In the example on the previous slide, x and y referenced the


same memory that a and b referenced
• Remember that variable declaration does two things:
– Allocates memory (one or more bytes of RAM, each of which has a
numeric address)
– Provides an identifier to reference the memory (which we use instead
of the address)
• Reference parameters are simply additional labels that we
temporarily apply to the same memory that was allocated
with the original declaration statement
• Note that this means that arguments passed to reference
parameters must be variables or named constants; in other
words, the argument must have its own address
Limitations of pass by value

• Recall that a function can have either one return value or no return value

• If we want a function’s action to affect more than one variable in the


calling function, we can’t achieve this goal using return value alone –
remember, our options are one or none
• The next example illustrates this problem
Returning multiple values

• The return statement only allows you to return 1 value. Passing output variables by
reference overcomes this limitation.

int divide(int numerator, int denominator, int *remainder) {


*remainder = numerator % denominator;
return numerator / denominator;
}
int main()
{
int num = 14;
int den = 4;
int rem;
int result = divide(num, den, &rem);
printf(“%d * %d + %d= %d\n”, result, den, rem, num );

// 3*4+2=14
}
Exercice

1. The program receives 6 numbers from the keyboard, finds the largest number and counts the
occurrence of the largest number entered from the keyboard.
Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4.

2. A program to display a matrix of order 4x4

37
1. Write a recursion function called “int myprod(int x, int y)”
that take as parameters two integers and return their
product

2. Write a recursion function called “int mydiv (int x, int y)” that
take as parameters two integers and return their integer
division

38
End

39

You might also like