You are on page 1of 38

Problem solving through Programming MODULE-4

USER DEFINED FUNCTIONS AND RECURSION

➢ A function as series of instructions or group of statements with one specific


purpose.
➢ A function is a program segment that carries out some specific, well defined
task.
➢ A function is a self contained block of code that performs a particular task.

4.1 Types of functions


➢ C functions can be classified into two types,

1. Library functions /pre defined functions /standard functions /built in


functions
2. User defined functions

1. Library functions /pre defined functions /standard functions/Built


in Functions

➢ These functions are defined in the library of C compiler which are used
frequently in the C program.
➢ These functions are written by designers of c compiler.
➢ C supports many built in functions like

• Mathematical functions
• String manipulation functions
• Input and output functions
• Memory management functions
• Error handling functions

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 1


Problem solving through Programming MODULE-4

➢ EXAMPLE:
• pow(x,y)-computes xy
• sqrt(x)-computes square root of x
• printf()- used to print the data on the screen
• scanf()-used to read the data from keyboard.

2. User Defined Functions

➢ The functions written by the programmer /user to do the specific tasks are
called user defined function(UDF’s).
➢ The user can construct their own functions to perform some specific task.
This type of functions created by the user is termed as User defined functions.
4.2 Elements of User Defined Function
The Three Elements of User Defined function structure consists of :
1. Function Definition
2. Function Declaration
3. Function call

1. Function Definition:
➢ A program Module written to achieve a specific task is called as function
definition.
➢ Each function definition consists of two parts:
i. Function header
ii. Function body

General syntax of function definition

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 2


Problem solving through Programming MODULE-4

Function Definition Syntax Function Definition Example


Datatype functionname(parameters)
{ void add()
declaration part; {
executable part; int sum,a,b;
return statement; printf(“enter a and b\n”);
} scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“sum is %d”,sum);
}

i. Function header
Syntax
datatype functionname(parameters)
➢ It consists of three parts
a) Datatype:
✓ The data type can be int,float,char,double,void.
✓ This is the data type of the value that the function is expected to return to
calling function.
b) function name:
✓ The name of the function.
✓ It should be a valid identifier.
c) parameters
✓ The parameters are list of variables enclosed within parenthesis.
✓ The list of variables should be separated by comma.
Ex: void add( int a, int b)
➢ In the above example the return type of the function is void
➢ the name of the function is add and
➢ The parameters are 'a' and 'b' of type integer.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 3


Problem solving through Programming MODULE-4

ii. Function body


➢The function body consists of the set of instructions enclosed between { and }
➢ The function body consists of following three elements:
a) declaration part: variables used in function body.
b) executable part: set of Statements or instructions to do specific activity.
c) return : It is a keyword,it is used to return control back to calling
function.
If a function is not returning value then statement is: return;
If a function is returning value then statement is: return value;
2. Function Declaration
➢ The process of declaring the function before they are used is called as
function declaration or function prototype.
➢ function declaration Consists of the data type of function, name of the
function and parameter list ending with semicolon.
Function Declaration Syntax
Datatype functionname(type p1,type p2,………type pn);
Example
int add(int a, int b);
void add(int a, int b);
Note: The function declaration should end with a semicolon ;
3. Function Call:
➢ The method of calling a function to achieve a specific task is called as
function call.
➢ A function call is defined as function name followed by semicolon.
➢ A function call is nothing but invoking a function at the required place in
the program to achieve a specific task.
Ex:
void main()
{
add( ); // function call without parameter
}

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 4


Problem solving through Programming MODULE-4

4.3 Formal Parameters and Actual Parameters


• Formal Parameters:
➢ The variables defined in the function header of function definition are
called formal parameters.
➢ All the variables should be separately declared and each declaration must
be separated by commas.
➢ The formal parameters receive the data from actual parameters.
• Actual Parameters:
➢ The variables that are used when a function is invoked)in function call) are
called actual parameters.
➢ Using actual parameters, the data can be transferred from calling function.
to the called function.
➢ The corresponding formal parameters in the function definition receive
them.
➢ The actual parameters and formal parameters must match in number and
type of data.

Actual parameters Formal parameters

Actual parameters are used in calling fun Formal parameters are used in the function hea
ction when a function is invoked der of a called function

Example : c=sum(a,b) Example : int sum(int m, int n)

Actual parameters can be constants, varia Formal parameters should be only variables. Ex
bles or expression pressions and constants are not allowed.

Example : c= sum (a+4,b) Example : int sum(int m, int n)

Actual parameters sends values to the for Formal parameters receive values from the actu
mal parameters al parameter

Example : c= sum (4, 5) Example : int sum(int m, int n)

Addresses of actual parameters can be sen If formal parameters contains addresses, they s
d to formal parameters hould be declared as pointers.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 5


Problem solving through Programming MODULE-4

4.4 Categories of the functions


1. Function with no parameters and no return values
2. Function with no parameters and return values.
3. Function with parameters and no return values
4. Function with parameters and return values
1. Function with no parameters and no return values
1. Function with no parameters and no return values
(void function without parameter)
Calling function Called function

/*program to find sum of two void add ( )


numbers {
using function*/ int sum;
#include<stdio.h> printf(“enter a and b values\n”);
void add( ); scanf(“%d%d”,&a,&b);
void main( ) sum=a+b;
{ printf(“\n The sum is %d”, sum);
add( ); return;
} }

✓ In this category no data is transferred from calling function to called


function, hence called function cannot receive any values.
✓ In the above example,no arguments are passed to user defined function
add( ).
✓ Hence no parameter are defined in function header.
✓ When the control is transferred from calling function to called function a
,and b values are read,they are added,the result is printed on monitor.
✓ When return statement is executed ,control is transferred from called
function/add to calling function/main.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 6


Problem solving through Programming MODULE-4

2. Function with parameters and no return values


(void function with parameter)
Calling function Called function
/*program to find sum of two
numbers
using function*/
#include<stdio.h> void add(int a, int b)
void add(int m, int n); {
void main() int sum;
{ sum = a+b;
int m,n; printf(“sum is:%d”,sum);
printf(“enter values for m and n:”); return;
scanf(“%d %d”,&m,&n); }
add(m,n);
}

✓ In this category, there is data transfer from the calling function to the
called function using parameters.
✓ But there is no data transfer from called function to the calling function.
✓ The values of actual parameters m and n are copied into formal parameters
a and b.
✓ The value of a and b are added and result stored in sum is displayed on the
screen in called function itself.

3. Function with no parameters and with return values


Calling function Called function
/*program to find sum of two
numbers
using function*/ int add( ) /* function header */
#include<stdio.h> {
int add(); int a,b,sum;
void main() printf(“enter values for a and b:”);
{ scanf(“%d %d”,&a,&b);
int result; sum= a+b;
result=add( ); return sum;
}
printf(“sum is:%d”,result);
}

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 7


Problem solving through Programming MODULE-4

In this category there is no data transfer from the calling function to the
called function.
✓ But, there is data transfer from called function to the calling function.
✓ No arguments are passed to the function add( ). So, no parameters are
defined in the function header
✓ When the function returns a value, the calling function receives one value
from the called function and assigns to variable result.
✓ The result value is printed in calling function.

4. Function with parameters and with return values


Calling function Called function
/*program to find sum of two
numbers
using function*/
#include<stdio.h>
int add(); int add(int a, int b) /* function header */
{
void main()
int sum;
{
sum= a+b;
int result,m,n;
return sum;
printf(“enter values for m and
}
n:”);
scanf(“%d %d”,&m,&n);
result=add(m,n);
printf(“sum is:%d”,result);
}
✓ In this category, there is data transfer between the calling function and
called function.
✓ When Actual parameters values are passed, the formal parameters in called
function can receive the values from the calling function.
✓ When the add function returns a value, the calling function receives a value
from the called function.
✓ The values of actual parameters m and n are copied into formal parameters
a and b.
✓ Sum is computed and returned back to calling function which is assigned
to variable result.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 8


Problem solving through Programming MODULE-4

4.5 Passing parameters to functions or Types of argument passing

The different ways of passing parameters to the function are:

✓ Pass by value or Call by value

✓ Pass by address or Call by address

1. Call by value:

➢ In call by value, the values of actual parameters are copied into formal
parameters.

➢ The formal parameters contain only a copy of the actual parameters.

➢ So, even if the values of the formal parameters changes in the called
function, the values of the actual parameters are not changed.

➢ The concept of call by value can be explained by considering the following


program. Example:

#include<stdio.h>

void swap(int a,int b);

void main()

int m,n;

printf("enter values for a and b:");

scanf("%d %d",&m,&n);

printf("the values before swapping are m=%d n=%d \n",m,n);

swap(m,n);

printf("the values after swapping are m=%d n=%d \n",m,n);

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 9


Problem solving through Programming MODULE-4

void swap(int a, int b)

int temp;

temp=a;

a=b;

b=temp;

➢ Execution starts from function main( ) and we will read the values for
variables

m and n, assume we are reading 10 and 20 respectively.

➢ We will print the values before swapping it will print 10 and 20.

➢ The function swap( ) is called with actual parameters m=10 and n=20.

➢ In the function header of function swap( ), the formal parameters a and b

receive the values 10 and 20.

➢ In the function swap( ), the values of a and b are exchanged.

➢ But, the values of actual parameters m and n in function main( ) have not
been exchanged.

➢ The change is not reflected back to calling function.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 10


Problem solving through Programming MODULE-4

2. Call by Address

➢ In Call by Address, when a function is called, the addresses of actual

parameters are sent.

➢ In the called function, the formal parameters should be declared as


pointers with the same type as the actual parameters.

➢ The addresses of actual parameters are copied into formal parameters.

➢ Using these addresses the values of the actual parameters can be changed.

➢ This way of changing the actual parameters indirectly using the addresses
of actual parameters is known as pass by address.

Example:

#include<stdio.h>

void swap(int a,int b);

void main()

int m,n;

printf("enter values for a and b:");

scanf("%d %d",&m,&n);

printf("the values before swapping are m=%d n=%d \n",m,n);

swap(&m,&n);

printf("the values after swapping are m=%d n=%d \n",m,n);

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 11


Problem solving through Programming MODULE-4

void swap(int*a, int*b)

int temp;

temp=*a;

*a=*b;

*b=temp;

NOTE:

Pointer: A pointer is a variable that is used to store the address of another variable.

Syntax: datatype *variablename;

Example: int *p;

#include<stdio.h>

void main()

inta ,*p;

p=&a;

In the above program p is a pointer variable, which is storing the address of variable a.

Differences between Call by Value and Call by reference

Call by Value Call by Address

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 12


Problem solving through Programming MODULE-4

When a function is called the values When a function is called the


addresses of
of variables are passed
variables are passed

The type of formal parameters should The type of formal parameters should
be
be same as type of actual parameters
same as type of actual parameters,
but

they have to be declared as pointers.

Formal parameters contains the Formal parameters contain the


addresses
values of actual parameters
of actual parameters.

Example:

Implement using functions to check whether the given number


is prime and display appropriate messages. (No built-in math
function).

#include<stdio.h>

void checkprime( int n )

int i;

if( n== 0 || n==1)

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 13


Problem solving through Programming MODULE-4

printf("Number is neither prime nor composite\n");

exit(0);

for(i=2; i<=n/2; i++)

if( n % i = = 0 )

printf("Number is not prime\n");

exit(0);

printf("Number is prime\n");

main( )

int n;

printf("Enter the value of n\n");

scanf("%d", &n);

checkprime( n );

return 0;

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 14


Problem solving through Programming MODULE-4

OUTPUT

Enter the value of n

Number is neither prime nor composite

Enter the value of n

Number is not prime

Enter the value of n

13

Number is prime

4.6 Nesting of functions

C permits nesting of functions freely. main can call function1, which calls
function2, which calls function3,….and so on.

There is in principle no limit as to how deeply functions can be nested

Example

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 15


Problem solving through Programming MODULE-4

float ratio(int x, int y, int z);

main()

int a,b,c;

scanf(“%d %d %d”, &a, &b, &c);

printf(“%f \n “,ratio(a,b,c));

float ratio(int x, int y, int z)

if(difference(y, z))

return(x/(y-z));

else

return(0.0);

int difference(int p, int q)

if (p!=q)

return (1)

else

return(0);

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 16


Problem solving through Programming MODULE-4

4.7 Recursion

➢ Recursion is a method of solving the problem where the solution to a


problem depends on solutions to smaller instances of the same problem.

➢ Recursive function is a function that calls itself during the execution.

➢ The two types of recursion are

1.Direct Recursion

2. Indirect Recursion

1.Direct recursion

➢ A recursive function that invokes itself is said to have direct recursion.

➢ For example factorial function calls itself hence it is called direct recursion.

2. Indirect recursion

➢ A function which contains call to another function which in turn contains


calls another function, and so on.

Design of recursive function

➢ Any recursive function has two elements:

i. Base case

ii. General case

i. Base case

➢ The statement that solves the problem is called base case.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 17


Problem solving through Programming MODULE-4

➢ Every recursive function must have at least one base case.

➢ It is a special case whose solution can be obtained without using recursion.

A base case serves two purposes:

i). It act as a terminating condition.

ii). the recursive function obtains the solution from the base case it

reaches.

ii. General case:

➢ The statement that reduces the size of the problem is called general case.

➢ This is done by calling the same function with reduced size.

➢ In general recursive function of factorial problem can be written as

Example 1.

/******* Factorial of a given number using Recursion ******/

#include<stdio.h>

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 18


Problem solving through Programming MODULE-4

int fact(int n);

void main( )

int num,result;

printf("enter number:");

scanf("%d",&num);

result=fact(num);

printf("The factorial of a number is: %d",result);

int fact(int n)

if(n==0)

return 1;

else

return (n*fact(n-1));

Example 2:FIBONACCI SERIES


The Fibonacci sequence is the sequence of integers, where each number in this sequence is the
sum of two preceding elements.
A formal definition is
a.If n=0 or 1,then F(n)=n

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 19


Problem solving through Programming MODULE-4

b.If n>1,then F(n)=F(n-1)+F(n-2)

#include <stdio.h>

int fib(int i)

if(i == 0)

return 0;

if(i == 1)

return 1;

return fib(i-1) + fib(i-2);

void main()

int i;

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 20


Problem solving through Programming MODULE-4

for (i = 0; i < 10; i++)

printf("%d\t", fib(i));

When the above code is compiled and executed, it produces the following result

0 1 1 2 3 5 8 13 21 34

3. Implement Recursive functions for Binary to Decimal Conversion.

The general procedure:

(11)₂ = (1 × 2¹) + (1 × 2⁰) = (3)₁₀

#include<stdio.h>

int binarytodecimal(int n)

if(n = = 0)

return 0;

else

return( n%10 + binarytodecimal (n/10) * 2 );

void main( )

int decnum, binnum;

printf(“Enter the binary number : only 0s and 1s”);

scanf(“%d”,&binnum);

decnum= binarytodecimal (binnum);

printf(“The decimal equivalent =%d”, decnum);

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 21


Problem solving through Programming MODULE-4

OUTPUT

Enter the binary number : only 0s and 1s

111

The decimal equivalent =7

Trace:

11%10+ 2* binarytodecimal(11/10)

1+2*1%10+2*binarytodecimal(1/10)

1+2*1+2*0

1+2+0

4.8 Passing arrays to functions

One-Dimensional Arrays

Like the values of simple variables, it is also possible to pass the values of an
array to a function.

To pass a one-dimensional an array to a called function, it is sufficient to list


the name of the array, without any subscripts, and the size of the array as
arguments.

Example, the call

largest(a,n)

The largest function header looks like below:

float largest(float array[], int size)//the function largest is defined to take two
argument array In an array of numbers.

The declaration of the formal argument array is made as:

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 22


Problem solving through Programming MODULE-4

float array[ ];

main() float largest(float a[], int n)

{ {

float largest(float a[],int n); int i;

float value[4]={2.5,-4.75,1.2,3.67}; float max;

printf(“%f\n”,largest(value,4)); max=a[0];

} for(i=1;i<n; i++)

if(max<a[i])

max = a[i] ;

return(max);

When a fun call largest(value, 4) is made the values of all elements of array
value become the corresponding elements of array a in the calling function. The
largest function finds the largest value in the array and returns the result to
the main.

Two Dimensional Arrays

Like simple arrays, we can also pass multi-dimensional arrays to functions.

The function must be called by passing only the array name.

In the function definition, we must indicate that the array has two-dimensions
by including two sets of brackets.

The size of the second dimension must be specified.

The prototype declaration should be similar to the

function header.

Example :

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 23


Problem solving through Programming MODULE-4

double average(

int x[ ][N],int M, int N)

int i,j;

double sum=0.0;

for(i=0;i<M; i++)

for(j=1;i<N; j++)

sum+=x[i][j]

return(sum/(M*N));

This function can be written


in main as below.

main()

int M=3, N=2;

double average(int [ ][n],int,int);

double mean;

int matrix[m][n]=

{1,2},

{3,4},

{5,6}

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 24


Problem solving through Programming MODULE-4

};

mean = average(matrix, M,N);

printf(“%lf\n”,mean);

4.9 Passing strings to functions

The strings are treated as character arrays in c and therefore the rules for
passing strings to function are very similar to those for passing arrays to
functions.

Basic rules are:The strings to be passed must be declared as a formal


argument of the function when it defined.

Example:void display(char item_name[])

----

----

2. The function prototype must shown that the arguments is a string.

void display(char str[]);

3. A call to the function must have a string array name without subscripts as
its actual argument.

Example: display(names);

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 25


Problem solving through Programming MODULE-4

where name is a properly declared string array is the calling function.

Example:Write functions to implement string operations such as compare,


concatenate, string length. Convince the parameter passing techniques.

#include<stdio.h>

int my_strcmp(char str1[ ], char str2[ ])

int i = 0;

while( str1[i] != '\0' && str2[i] != '\0')

if(str1[i] > str2[i])

return 1;

else if(str1[i] < str2[i])

return -1;

else

i++;

if(str1[i]!='\0' && str2[i]=='\0')

return 1;

if(str1[i]=='\0' && str2[i]!='\0')

return -1;

return 0;

void my_strcat(char str1[ ], char str2[ ])

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 26


Problem solving through Programming MODULE-4

int i, j;

i = 0;

while( str1[i] != '\0')

i++;

j=0;

while( str2[j] != '\0')

str1[i] = str2[j];

i++;

j++;

str1[i] = '\0';

int my_strlen(char str[ ])

int i = 0;

while( str[i] != '\0')

i++;

return i;

main( )

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 27


Problem solving through Programming MODULE-4

int choice, difference, len;

char str1[20], str2[20], str[20];

for( ; ;)

printf("1.Compare 2.Concatenate 3.Length 4.Exit\n");

printf("Enter your choice\n");

scanf("%d", &choice);

switch(choice)

case 1: printf("Enter the string1\n");

scanf("%s", str1); // gets(str1);

printf("Enter the string2\n");

scanf("%s", str2); // gets(str2);

difference = my_strcmp(str1, str2);

if(difference==0)

printf("%s = %s\n", str1, str2);

else if (difference==1)

printf("%s > %s\n", str1, str2);

else if (difference==-1)

printf("%s < %s\n", str1, str2);

break;

case 2: printf("Enter the string1\n");

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 28


Problem solving through Programming MODULE-4

scanf("%s", str1); // gets(str1);

printf("Enter the string2\n");

scanf("%s", str2); // gets(str2);

my_strcat(str1, str2);

printf("Concatenated string = %s\n", str1);

break;

case 3: printf("Enter the string\n");

scanf("%s", str); // gets(str);

len = my_strlen(str);

printf("Length of the string = %d\n",len);

break;

case 4: exit(0);

return 0;

Output

1.Compare 2.Concatenate 3.Length 4.Exit

Enter your choice

Enter the string1

ksit

Enter the string2

pavithra

ksit < pavithra

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 29


Problem solving through Programming MODULE-4

1.Compare 2.Concatenate 3.Length 4.Exit

Enter your choice

Enter the string1

friday

Enter the string2

monday

Concatenated string = fridaymonday

1.Compare 2.Concatenate 3.Length 4.Exit

Enter your choice

Enter the string

sfyrh

Length of the string = 5

1.Compare 2.Concatenate 3.Length 4.Exit

Enter your choice

GCD of Two Numbers using Recursion

#include <stdio.h>

int gcd(int n1, int n2);

int main() {

int n1, n2;

printf("Enter two positive integers: ");

scanf("%d %d", &n1, &n2);

printf("G.C.D of %d and %d is %d.", n1, n2, gcd(n1, n2));

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 30


Problem solving through Programming MODULE-4

return 0;

int gcd(int n1, int n2) {

if (n2 != 0)

return gcd(n2, n1 % n2);

else

return n1;

output

Enter two positive integers: 366

60

G.C.D of 366 and 60 is 6.

4.10 Scope and Life time of a variable

Scope of a variable is defined as the region or boundary of the program in


which

the variable is visible. There are two types

(i) Global Scope

(ii) Local Scope

i. Global Scope:

➢ The variables that are defined outside a block have global scope.

➢ That is any variable defined in global area of a program is visible from its

definition until the end of the program.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 31


Problem solving through Programming MODULE-4

➢ For Example, the variables declared before all the functions are visible

everywhere in the program and they have global scope.

ii. Local Scope

a. The variables that are defined inside a block have local scope.

b. They exist only from thepoint of their declaration until the end of the block.

c. They are not visible outside the block.

❖ Life Span of a variable

➢ The life span of a variable is defined as the period during which a variable
is active during execution of a program.

For Example

❖ The life span of a global variable is the life span of the program.

❖ The life span of local variables is the life span of the function, they are

created.

❖ Storage Classes

➢ There are following storage classes which can be used in a C Program:

i. Global variables

ii. Local variables

iii. Static variables

iv. Register variables

i. Global variables:

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 32


Problem solving through Programming MODULE-4

➢ These are the variables which are defined before all functions in global area

of the program.

➢ Memory is allocated only once to these variables and initialized to zero.

➢ These variables can be accessed by any function and are alive and active

throughout the program.

➢ Memory is deallocated when program execution is over.

#include<stdio.h> void main()

int a=10,b=20; {

int c; add ();

void add() printf(“a= %d\tb=%d\n”,a,b);

{ printf(“a+b=%d\n”,c);

c=a+b; a+b=30;

} subtract();

void subtract() printf(“a-b=%d\n”,c);

{ }

c=a-b;

}
Output:

a= 10 b=20

a+b=30

a-b=-10

ii. Local variables (automatic variables)

➢ These are the variables which are defined within a functions.

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 33


Problem solving through Programming MODULE-4

➢ These variables are also called as automatic variables.

➢ The scope of these variables are limited only to the function in which they

are declared and cannot be accessed outside the function.

#include<stdio.h>

void add(int a,int b) void main()

{ {

int c; int a=10, b=20;

c=a+b; add(a,b);

printf(“Result = %d\n”,c); }

iii. Static variables

➢ The variables that are declared using the keyword static are called static

variables.

➢ The static variables can be declared outside the function and inside the

function. They have the characteristics of both local and global variables.

➢ Static can also be defined within a function.

Ex:

static int a,b;

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 34


Problem solving through Programming MODULE-4

#include<stdio.h> void main()

void display() {

{ int j;

static int i=0; for(j=0;j<5;j++)

i++; display();

printf(“ %d\n”,i); 1 2 3 45 }

iv. Register variables

➢ Any variables declared with the qualifier register is called a register variable.

➢ This declaration instructs the compiler that the variable under use is to be

stored in one of the registers but not in main memory.

➢ Register access is much faster compared to memory access.

Ex:

register int a;

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 35


Problem solving through Programming MODULE-4

/*program which shows the scope level "visibility level" for auto variables
in each block code which are independently to each other*/

#include <stdio.h>

int main( )

auto int j = 1;

auto int j= 2;

auto int j = 3;

printf ( " %d ", j);

printf ( "\t %d ",j);

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 36


Problem solving through Programming MODULE-4

printf( "%d\n", j);

OUTPUT: 3 2 1

/*Program to explains the behaviour of a static variable.*/

void stat(void)

main()

int i;

for(i=1;i<=3;i++)

stat();

void stat(void)

static int x=0;

x=x+1;

printf( “x= %d\n”,x);

OUTPUT

x=1 x=2 x=3

/*Write a multifunction program to illustrate the properties of global


variables*/

int fun1(void);

int fun2(void);

int fun3(void);

int x ; /global */

main()

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 37


Problem solving through Programming MODULE-4

x=10;

printf(“x=%d\n”,x);

printf(“x=%d\n”,fun1());

printf(“x=%d\n”, fun2());

printf(“x=%d\n”, fun3());

fun1(void)

x = x+10;

int fun2(void)

int x;

x=1;

return (x);

fun3(void)

x=x+10;

OUTPUT: x=10

x=20

x=1

x=30

Pavithra.J Assistant Prof, Dept of CSE,KSIT Page 38

You might also like