Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Functions

C functions
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Functions

C functions
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

UNIT-IV COMPUTER PROGRAMMING

4.1 Function definition


A Function is a self-contained block of statement that performs a specific task
when called. A function is also called as sub program or procedure or subroutine.
Every C Program can be thought of as a collection of these functions. Function is
a set of instructions to carry out a particular task. Function after its execution returns a
single value. Generally, the functions are classified into two types:
1. Standard functions
2. User-defined functions.
The Standard functions are also called library functions or built-in functions. All standard
functions, such as sqrt(), abs(), log(), sin() etc. are provided in the library of function. But,
most of the applications need other functions than those available in the software, those are
known as user-defined functions.

Advantages of functions
Several advantages of dividing the program into functions include:
1. Modularity
2. Reduction in code redundancy
3. Enabling code reuse
4. Better readability

Parts of a function
A function has the following parts:
1. Function prototype declaration.
2. Function definition.
3. Function call.
4. Actual arguments and Formal arguments.
5. The return statement.

Function Declaration
Function prototype declaration consist function return type, function name, and argument
list. A function must be declared before it is used
Syntax
return_type function_name(parameter_list);
parameter_list: type param1,type param2,type param3, etc
Examples
double sqrt(double);
int func1();
void func2(char c);

Function Definition also known as function implementation, means composing a function.


Every Function definition consists of two Parts:
1. Header of the function,
2. Body of the function.
Syntax

return_type function_name(parameter_list)
{
// Function body
}

The body of a function consists of a set of statements enclosed within braces.


The return statement is used to return the result of the computations done in the called

Ch.Vijayanand@Dept. of CSE 1
UNIT-IV COMPUTER PROGRAMMING
function and/or to return the program control back to the calling function. A function can
be defined in any part of the program text or within a library

Example: Function header


void welcome( )
{
printf(“hello world\n”; function body
}

Function Call
A function call has the following syntax:

<function name>(<argument list>);


Example:
sum(a,b);

4.2 Types of functions


Functions can be divided into 4 categories:
1. A function with no arguments and no return value
2. A function with no arguments and a return value
3. A function with an argument or arguments and returning no value
4. A function with arguments and returning a values

A function with no arguments and no return value


 Called function does not have any arguments
 Not able to get any value from the calling function
 Not returning any value
 There is no data transfer between the calling function and called function.
Example
#include<stdio.h>
void welcome(); //function prototype declaration
int main() // calling function
{
welcome(); //function call
return 0;
}
void welcome() //called function
{
printf("Hi students..!"); function body
}
OUTPUT
Hi students..!

A function with no arguments and a return value


 Does not get any value from the calling function
 Can give a return value to calling program

Example
#include <stdio.h>
int send();
int main()
{

Ch.Vijayanand@Dept. of CSE 2
UNIT-IV COMPUTER PROGRAMMING
int x;
x=send()
printf("\nYou entered : %d",x);
return 0;
}
int send()
{
int n;
printf("\nEnter a number: ");
scanf("%d",&n);
return n;
}
OUTPUT
Enter a number: 5
You entered: 5

A function with an argument(s) and returning no value


 A function has argument(s).
 A calling function can pass values to function called , but calling function not receive
any value.
 Data is transferred from calling function to the called function but no data is
transferred from the called function to the calling function.
 Generally Output is printed in the Called function.
Example
#include<stdio.h>
void add(int x, int y);
int main()
{
add(30,15);
add(63,49);
add(952,321);
return 0;;
}
void add(int a, int b)
{
int result;
result = a+b;
printf("Sum of %d and %d is %d\n",a,b,result);
}
OUTPUT
Sum of 30 and 15 is 45
Sum of 63 and 49 is 112
Sum of 952 and 321 is 1273

A function with arguments and returning a values


 Argument are passed by calling function to the called function
 Called function return value to the calling function
 Data returned by the function can be used later in our program for further
calculation
 Mostly used in programming because it can two way communication
Example
#include <stdio.h>

Ch.Vijayanand@Dept. of CSE 3
UNIT-IV COMPUTER PROGRAMMING
int add(int x, int y);
int main()
{
int z;
z=add(952,321);
printf("Result %d\n", add(30,55));
printf("Result %d\n", z);
return 0;
}
int add(int a, int b)
{
int result;
result = a + b;
return (result);
}
OUTPUT
Result = 85
Result = 1273

4.3 Recursion
A function that calls itself repetitively is known as a recursive function. And, this
technique is known as recursion. The function calls itself repetitively until certain
condition is satisfied.
The recursive function has following types of statements:
1. A statement or condition to determine if the function is calling itself again.
2. A function call which should have argument.
3. Conditional statement(if-else)
4. A return statement.

Example: C Program that calculates factorial of a given number using recursion


#include <stdio.h>
long int factorial(int);
int main()
{
int x;
long int f;
prinf(“Enter a number:”);
scanf(“%d”,&x);
f=factorial(x);
printf("Factorial of %d is %ld\n",x,f);
return 0;
}
long int factorial(int n)
{
if(n==0 ) //base condtion
return 1;
else
return n*factorial(n-1);
}
OUTPUT
Factorial of 5 is 120

Ch.Vijayanand@Dept. of CSE 4
UNIT-IV COMPUTER PROGRAMMING
4.4 Storage classes
From C compiler’s point of view, a variable name identifies some physical
location within the computer where the value of the variable is stored. There are basically
two kinds of locations in a computer where such a value may be kept—
1. Memory
2. CPU registers.

A storage class defines the scope (visibility) and life time of variables and/or functions
within a C Program.

A variable’s storage class tells us:


1. Where the variable would be stored.
2. What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e. the default value).
3. What is the scope of the variable; i.e. in which functions the value of the variable
would be available.
4. What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C:


1. auto
2. register
3. static
4. external

Automatic Variables
These are declared inside a function in which they are to be utilized. These are declared
using a keyword auto.
Example:
auto int number;

 These are created when the function is called and destroyed automatically when the
function is exited.
 These variables are private (local) to the function in which they are declared.
 Variables declared inside a function without storage class specification is, by default,
an automatic variable.

Properties of automatic variable are as under:

Storage Memory.
Initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the variable is defined.

Example
#include<stdio.h>
int main( )
{
auto int i=1;
{
auto int i=2;
{
auto int i=3;

Ch.Vijayanand@Dept. of CSE 5
UNIT-IV COMPUTER PROGRAMMING
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
return 0;
}
OUTPUT
321

Register variables
These variables are stored in one of the machine’s register and are declared using keyowd
register.
Example
register int count;
 Since register access are much faster than a memory access keeping frequently
accessed variables in the register lead to faster execution of program.
 Use register storage class for only those variables that are being used very often in a
program (loop counters).

Properties of external variable are as under:

Storage CPU registers


Initial value Garbage value
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is defined

Example
#include<stdio.h>
int main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( “%d ", i ) ;
}

OUTPUT
1 2 3 4 5 6 7 8 9 10

Static variables
The value of static variables persists until the end of the program. It is declared using the
static keyword.
Example
static int x;
 Static variables are initialized only once, when the program is compiled.
 Use static storage class only if you want the value of a variable to persist between
different function calls.
Properties of static variable are as under:

Storage Memory
Initial value Zero
Scope Local to the block in which the variable is defined

Ch.Vijayanand@Dept. of CSE 6
UNIT-IV COMPUTER PROGRAMMING
Life Value of the variable persists between different function calls

Example
#include<stdio.h>
void increment();
int main( )
{
increment();
increment();
increment();
return 0;
}
void increment()
{
static int i ;
printf ( "%d\n", i ) ;
i=i+1;
}
OUTPUT
0 1 2

External or Global Variables


 These variables are declared outside any function.
 These variables are active and alive throughout the entire program.
 Sometimes the keyword extern used to declare these variables.
 Unlike local variables they are accessed by any function in the program.
 In case local and global variable have the same name, the local variable will have
precedence over the global one.
Properties of external variable are as under:

Storage Memory
Initial value Zero
Scope Global
Life As long as the program’s execution doesn’t come to an end

Example
#include<stdio.h>
void inc();
void dec();
int i; //i is a global variable
int main( )
{
printf(“Intial value is %d ", i);
inc();
inc();
dec();
dec();
return 0;
}
void inc()
{
i++;

Ch.Vijayanand@Dept. of CSE 7
UNIT-IV COMPUTER PROGRAMMING
printf("\nOn incrementing:%d ",i);
}
void dec()
{
i--;
printf("\nOn decrementing:%d ",i);
}

OUTPUT
Initial value is 0
On incrementing: 1
On incrementing: 2
On decrementing: 1
On decrementing: 0

4.5 Parameter passing mechanism


There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference

Call by Value
In call by value method, the value of the variable is passed to the function as
parameter. The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of
actual parameter is copied to formal parameter.
Example
#include<stdio.h>
void swap(int , int );
int main()
{
int a = 22, b = 44;
printf("\nValues before swap \n a = %d and b = %d", a, b);
swap(a,b);
printf(" \nValues after swap \n a = %d and b = %d", a, b);
return 0;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}

OUTPUT
Values before swap
a =22 and b = 44
Values after swap
a =22 and b = 44

Call by reference

Ch.Vijayanand@Dept. of CSE 8
UNIT-IV COMPUTER PROGRAMMING
In call by reference method, the address of the variable is passed to the function
as parameter. The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by
both parameters.
Example

#include<stdio.h>
void swap(int *, int *);
int main()
{
int a = 22, b = 44;
printf("\nValues before swap \n a = %d and b = %d", a, b);
swap(&a,&b);
printf(" \nValues after swap \n a = %d and b = %d", a, b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
OUTPUT
Values before swap
a =22 and b = 44
Values after swap
a =44 and b = 22

Ch.Vijayanand@Dept. of CSE 9

You might also like