4 Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Functions

• We have already seen that 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.
• 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.
• This is known as This is known as modular
programming.
Benefits of Modularization
• The use of functions avoids the need for redundant
(repeated) programming of the same instructions.
• Equally important is the logical clarity resulting
from the decomposition of a program into several
concise functions, where each function represents
some well-defined part of the overall program.
— Such programs are easier to write and to debug.
• These functions that are frequently used have been
thoroughly debugged and written to be as efficient
as possible
Benefits of Modularization
• The use of functions also 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.
Function Definition
• 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.
• 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.
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.
Examples 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
//Using the greater_int function in a main
function
main()
{
int greatest, a=10, b=20;
greatest=greater_int(a,b);
printf(“The greater number is
%d”,greatest);
}
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
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 is a main program where you ask the
user to enter a number the your program outputs the
factorial.
Variable Scope
• Refers to the section of the program within which a
variable is accessible.
• Variables can be classified according to their 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.
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.
External variable definition vs External Variable
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.
Example : External and Global Variables
#account.h
extern int account;
void deposit(int amount);
void withdraw(int amount);
#account.c
int account=0;
void deposit(int amount)
{
account+=amount;
}
void withdraw(int amount)
{
account-=amount;
}
Example : External and Global Variables
#bank.c
#include "account.h"
#include <stdio.h>
void main()
{
printf("\nBalance=%d", account);
deposit(5000);
printf("\nBalance=%d", account);
withdraw(2000);
printf("\nBalance=%d", account);
}
#Compile
#cl account.c bank.c -o bank
Static variable
• 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.
• 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.
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
/*Using the times_called function */
main()
{
char choice;
do
{
printf(“To call the function enter y
else enter n”);
choice=getchar();
if (choice==’y’)
{
times_called();
}
}while (choice==’y’);
}
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 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;
}
/*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));
}
Example 2: we write 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 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;
}
/*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));
}
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).
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
//Definition of the factorial function
int factorial(int n)
{
if (n<=1)
{
return 1;
}
else
{
return (n  factorial(n-1));
}
}
Exercise:
Write a recursive function that given a positive integer n,
gets the sum of all integers from 0 to the given number n.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy