You are on page 1of 30

ICS 2175: Programming

Functions in C
Functions

• C supports a number of library functions which are used to carry


out a number of commonly used operations or calculations.
Examples include the scanf and printf functions.

• C also allows programmers to define their own functions. This is


known as modular programming.

The use of programmer defined functions allows a large program


to be broken down into a number of smaller, self-contained
components, each of which has a unique identifiable purpose.
Functions
• Modular programming leads to Top-down design or stepwise
refinement

• If we look at a problem as a whole, it may seem impossible to


solve because it is so complex. Examples:

-        Writing a tax computation program


-        Writing a word processor
 These kinds of problems can be solved by applying the
stepwise refinement approach.
Functions

 Definitions of Stepwise Refinement


1.It is a divide and conquer approach to programming, in which a
complex problem is recursively divided into smaller, more
manageable, sub-problems.

2.The development of a program by breaking the original problem


into smaller sub-problems and then applying the same process to
each sub-problem.

3.The process of repeatedly subdividing a problem into smaller


sub-problems until a detailed algorithm for solving the problem
emerges.
Functions

Stepwise Refinement process


1. Start with what you want
2. Cut it up in parts
3. If the parts are trivial to solve, then solve them
4. If the parts are non trivial, apply top-down again

 You will cut up the problem in smaller and smaller sub-


problems until they can be solved trivially.
Functions

Stepwise Refinement : Advantages


1. There is a separation of what is supposed to happen and what
is next
2. The maintenance of your program is made easy
3. Modular program production where each module is developed
independently
4. Incremental progress
5. The design is easy to modify and change
The use of modularization offers several advantages to
program development:
• The use of functions avoids the need for redundant (repeated)
programming of the same instructions.
• Provides logical clarity resulting from the decomposition of a
program into several concise functions, Such programs are
easier to write and to debug.

• Enables the programmer to build a customized library of


frequently used routines. The routines are then stored in
special library files. If a program requires a particular routine,
the corresponding library function can be accessed and
attached to the program during the compilation process.
Hence a single function can be used in many programs. This
avoids repetitive programming.
Functions: Definitions

• A function is a self contained program segment that carries


out some specific, well-defined task.
• Every C program consists of one or more functions.
• One of these functions must be called main().
• Execution of the program will always begin by carrying out
the instructions in the main function.

• A function will carryout its intended function whenever it is


accessed i.e. whenever it is “called” from some other portion
of the program.
Functions : Definitions

• Generally, a function will process information that is passed


to it from the calling portion of the program and return a
single value.

• Information is passed to a function via special identifiers


called arguments or parameters and returned via the return
statement.

• Some functions do not return anything.


Functions : Defining a function
data-type name(type1 arg1, type2 arg2,…, typen argn)
{
body
}

• data-type represents the data type of the value that will be


returned by the function
• name is the name(identifier) of the function
• type1 is the data type of the first argument (arg1), type2 is the
data type of the second argument (arg2) and so on. You can
have 0 or more arguments enclosed in brackets.
• body – Enclosed in curly braces and used to specify the
actions the function will take.
Functions : Defining functions; example 1
A function to return the greater of two
numbers:
#include <stdio.h>
int greater_int(int first, int second)
{
if (first>= second)
{
return first;
}
else
{
return second;
}
}//end function
Functions : Defining functions; example 1

//Using the greater_int function in a


main function
main()
{
int greatest, a=10, b=20;
greatest=greater_int(a,b);
printf(“The greater integer is
%d”,greatest);
}
Functions : Defining functions; example 2
To get the square of a number

#include <stdio.h>

int square(int num)

{ return num * num ;

}//end function

main()

{ int num;

printf(“Please enter an integer::”);

scanf(“%d”,&num);

printf(“The square of %d is
%d”,num,square(num));

} //end main
Functions : Exercise

Try out the following problem. Use the


function you define within a main program.

1.      Define a function that returns the factorial of a


number (you have to use a loop). The argument to the
function is an integer whose factorial is to be found. Use
the function in a main program where you ask the user to
enter a number then your program outputs the factorial.
Functions : Assignment 1

Write a function that converts an input string to uppercase. The argument to the
function is a string. The function then returns the string in uppercase. Use your
function in a main program where you ask the user to enter a string and then
you output the string in uppercase. Do not use the strupr or toupper functions.
You have to use a loop.

Hint: Characters in C are stored as integers using the American Standard Code
for information interchange (ASCII). The lowercase characters are given the
integers 97 to 122 where ‘a’=97, ‘b’=96, … The upercase characters are
represented by the integers 65 to 90 where ‘A’=65, ‘B’=66 …

If you have the statement putchar(97) in your program, then the character ‘a’ is
output on the screen. Since characters are integers, then it is possible to do
some basic mathematics with them e.g. ‘a’+2=99 which is equal to c.
Functions : Variable Scope
• Refers to the section of the program within which a variable is
accessible/visible.
• Variables can be classified according to their scope.
Functions : Variable Scope: local variables (Automatic variables)
• These are declared within a function and are local to that
function i.e. their scope is confined to that function.
• Local variables defined in different functions will be
independent of each other even though they may have the same
name.
• Any variable declared within a function is interpreted as a local
variable unless otherwise specified.
• Arguments to a function are also considered as local variables.
A local variable does not retain its value once control is
transferred out of the defining function. Therefore any value
assigned to a local variable within a function will be lost once
the function is exited.
Functions : Variable Scope: Global variables (External variables)
• Not confined to single functions.
• Their scope extends from the point of definition to through the
remainder of the program.
• Since they are recognized globally, they can be accessed by any
function that falls within their scope.
• They retain their values within this scope. Therefore a global
variable can be assigned a value within one function and this
value can be used within another function.
• Use of external variables provides an efficient mechanism for
transferring information back and forth between functions.
• Moreover we now have multiple ways to transfer multiple data
items out of a function, since the return statement can return
only one data item.
Functions : Variable Scope: External variables definition vs
declaration

• When you define an external variable, you give its type and
optionally, its value just like any other variable. This is done
outside any function and usually, before any function that
accesses it.
• If a function precedes any external variable definition and needs
to use the variable, then it needs to declare the variable using the
extern statement.
• The declaration is similar to the definition except for the use of
the extern keyword.
• An external variable declaration cannot include assignment of
an initial value to the external variable.
Functions : Static Variables

• Declared in the same way as local variables but they are


preceded by the static keyword.
• Declared within a function and only accessible within that
function.
• Do not lose their values when the function is exited. They
retain their values to the end of the program.

NB: Local and Static variables may have the same name within
a function as a global variable. In such a situation the local
variable takes precedence i.e. the common name, when
used, is assumed to refer to the local variable.
Functions : Variables: Example 1
To calculate the area of a circle given the
diameter
 #include <stdio.h>
float pi=3.14; /*pi is an external/global variable –
accessible in all functions that come after it is
defined.*/
float function circle_area(float diameter)
{ float area,radius; /*area and radius are
local variables accessible only within the
circle_area function*/
radius=diameter/2;
area=pi*(radius*radius);
return area;
}
Functions : Variables: Example 1

/*Using the circle_area function and the pi


global variable*/
main()
{
float diameter=0;
printf(“Enter the diameter of the
circle:”);
scanf(“%f”,&diameter);
printf(“The area of the circle is
%f”,circle_area(diameter));
}
Functions : Variables: Example 2
A program to get the circumference of a circle.
This time the function will come before the
definition of the global variable so we will
need to use the extern keyword.

 #include <stdio.h>
float function circumference(float diameter)
{ extern float pi; /*we declare pi as an
external variable.*/
float perimeter; /*perimeter is a local
variable within circumference function*/
perimeter=pi*diameter;
return perimeter;
}
Functions : Variables: Example 2

/*Using the circumference function and the pi


global variable*/

float pi=3.14; /*pi is an external/global


variable – accessible in all functions that come
after it is defined.*/
main()
{ float diameter=0;
printf(“Enter the diameter of the circle:”);
scanf(“%f”,&diameter);

printf(“The circumference of the circle is %f”, circumference(diameter));

}
Functions : Variables: Example 3
To demonstrate the use of static variables, we
write a function that counts the number of times
it has been called.
#include<stdio.h>
void times_called()
{ static int count=0;
count+=1;
if (count ==1)
{
printf(“ I have been called %d.
time”,count);
}
else
{ printf(“ I have been called %d.
times”,count);
}
} //end times_called function
Functions : Variables: Example 3
/*Using the times_called function and the pi
global variable*/
main()
{ char choice;
do
{
printf(“To call the function enter y
else enter n”);
choice=getchar();
if (choice==’y’)
{
times_called();
}
}while (choice==’y’);
}
Recursion

• It is the process by which some function calls itself repeatedly


until some specified condition has been satisfied.
• The process is used in repetitive computations in which each
action is stated in terms of a previous result.
• In order to solve a problem recursively, two conditions must
be satisfied.
First, it should be possible to define the problem in recursive
form,
Second, the problem statement must include a stopping
condition (base case).
Recursion:Example

The following example shows how to calculate the factorial of an


integer using a recursive function. Note that the header of the
function (prototype) is defined first, then we have the main
function. The function definition is after the main function.

#include<stdio.h>
int factorial(int n); /* function prototype */
main()
{
int n;
printf(“n=”);
scanf(“%d”,&n);
printf(“\n n!=%d\n”,factorial(n));
} //end main
Recursion:Example

//Definition of the factorial function


int factorial(int n)
{
if (n<=1)
{
return 1;
}
else
{
return (n  factorial(n-1));
}
}
Recursion:Exercise;Assignment

Write a program that uses a recursive function power to calculate


the result of raising a number n to the power of another number p.
Assignment 2
The fibonacci series has the following form: 0, 1, 1, 2, 3, 5, 8...
It can be solved recursively
fib( n ) = fib( n - 1 ) + fib( n – 2 )
i.e. the nth fibonacci number is defined as shown by the above expression
Write a function using recursion that calculates the nth recursive number
For instance fib(3) = 1 i.e 1+0 and fib(4)=2 i.e. 1+1
Tip: The base case: fib(0)=0 and fib(1)=1

Use your function in a main program where you ask the user to a number n and
then you output the nth fibonacci number

You might also like