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

Unit III - Arrays and Functions (1)

This document covers the concepts of arrays and functions, focusing on one-dimensional and two-dimensional arrays in programming. It includes definitions, properties, initialization methods, and example programs for both types of arrays. Additionally, it outlines learning objectives and provides a structured approach to understanding array operations.

Uploaded by

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

Unit III - Arrays and Functions (1)

This document covers the concepts of arrays and functions, focusing on one-dimensional and two-dimensional arrays in programming. It includes definitions, properties, initialization methods, and example programs for both types of arrays. Additionally, it outlines learning objectives and provides a structured approach to understanding array operations.

Uploaded by

stallionnexus
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT - 3 ARRAYS AND FUNCTIONS

STRUCTURE

3.2 Learning Objectives

3.3 Introduction

3.4 Arrays

3.5 String Processing

3.6 Functions

3.6.1 Categories Of Functions

3.6.2 Recursion

3.7 Summary

3.8 Keywords

3.9 Learning Activity

3.10 Unit End Questions

3.11 References

3.0 LEARNING OBJECTIVES

After studying this unit, you will be able to:

 Define and Describe One Dimensional Arrays


 Example Programs using One Dimensional Arrays
 Define and Describe Two Dimensional Arrays
 Example Programs using Two Dimensional Arrays

3.1 INTRODUCTION

An array is a group of elements (data items) that have common characteristics (Ex: Numeric
data, Character data etc.,) and share a common name. The elements of an array are
differentiated from one another by their positions within an array.

88
Each array element (i.e., each individual data item) is referred as specifying the array name
followed by its subscript enclosed in square brackets. The subscript indicates the position of
the particular element with respect to the rest of the element. The subscript must be a non-
negative number.

For example, in the n element array, x, the array elements are x [1], x [2], x [3], x [4] ….x[n]
and 1,2,3…n are the subscripts x[i] refers to the ith element in a list of n elements.

Depending on the number of subscripts used, arrays are classified into one-dimensional
arrays, two-dimensional arrays and so on.

3.2 ARRAY

Definition of Array

An array is defined to be a group of logically related data items of similar type stored in
contiguous memory location is called array.

One dimensional arrays

Arrays whose elements are specified by a single subscript are called one-dimensional or
single dimensional array. It is used to store a list of values, all of which share a common
name and disguisable by subscripts values.

Declaration of one-dimensional arrays

A single dimensional array is declared as follows:

SYNTAX

type array-name[n];

Where,

array name->is the name of an array of n elements of the type specified. The size of an array
must be an integer constant.

89
Example

int i[100]; char text[80]; float n[12];

The integer array declaration int x[100] creates an array that is 100 elements long with the
first element being 0 and the last being 99.

The subscript used to declare an array is sometimes called a dimension and the declaration
for the array is often referred to as dimensioning. The dimension used to declare an array
must always be a positive integer constant, or an expression that can be evaluated to be
constant when the program is compiled. It is sometimes convenient to define an array size in
terms of the symbolic constant. For example i[20]=124.

An individual element in an array can be referred to by means of the subscript, the number

In brackets following the array name. A subscript is the number that specifies the elements
position in an array. In the C language, subscript begins with zero. Thus, the valid subscript
value can from 0 to n-1, if n is the dimension of array. The subscript value used to access an
array element could a binary expression etc. Thus, i[2] is not the second element of the array
I but the third.

Properties of an array

1. The type of an array is the data type of its elements.

2. The location of an array is the location of its first element.

3. The length of an array is the number of data elements in an array.

4. The size of the array is the length of the array times the size of the elements, but the
size of the array is usually referred as the product of subscript used.

Accessing Array Elements

Once the array is declared, how individual elements in the array are accessed. This is done
with the help of subscripts (i.e., number specified in the square brackets following the array

90
name). The subscript specifies the elements position in the array. The array elements are
numbered, starting from zero. The first item stored at the address pointed by the array name
itself. This can also be referred as position 0. Thus, the first element of the array age is
referred as age. The fourth element of the array is reoffered as age.

Initialization Of One-Dimensional Arrays

An array can be initialized when declared by specifying the values of some or all of its
elements. Array can be initialized at the time of declaration when their initial values are
known in advance. The values to initialize an array must be constants never variables or
function calls. The array can be initialized as follows:

int array[5]={4,6,5,7,2};
float x[6]={0,0.25,-0.50,0,0};

when an integer array is declared as int array [5] = {4,6,5,7,2}; the compiler will reserve ten
contiguous bytes in hold the five integer elements as shown in the diagram.

4 6 5 7 2

array [0] array [1] array [2] array [3] array [4]

The array size need not be specified explicitly. When initial values are included as a part of
an array declaration. With a numerical array, the array size will automatically be set equal to
the number initial values included within the declaration.

int digits [] = {1,2,3,4,5,6}

float x [] = {0,0.25,0, -0.5}

91
Thus, digits will be a six-element integer array, and x will be a four-element floating-point
array. The individual elements will be assigned the following values. The example given
below,

digits [0] =1; digits [1] =2; digits [2] =3; digits [3] =4; digits [4] =5; digits [5] =6;

An array may also be initialized as follows:

int xyz [10] = {78,23,67,56,87,76}

in the above array initialization, although the array size is 10, values were defined only for
the first six elements. If fewer then all numbers have values specified, then the rest will have
undefined values.

Example Program Using One Dimensional Array

Example 1

Write a program to get five person ages to calculate average of person age.

#include<stdio.h> void main ()

int age [5]; int in;

printf(“Number of Persons:”); scanf(“%d”,&n); if(n<=0||n>5)

printf(“Invalid number of persons entered \n”);

else

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

92
printf(“Age:”);

scanf(“%d”,&age[i]); sum=sum+age[i];

printf(“The average of age are: \n”) for(i=0;i<n;i++)

printf(“%d \n”,age[i]); printf(“The average is %f,sum);

EXAMPLE 2

Write a program to get 10 elements, to display any one of the element in the given list.

#include<stdio.h> void main()

int array[10]={10,20,30,40,50,60,70,80,90,100};

printf(“which element do you want display? \n”);

print(“The element value is:%d \n”,array[getchar()]-„\‟);

printf(“\n Do you wish to display another element! (y/n));

if(getchar()=‟Y‟);

printf(“\n Enter element number(1 to 10):”);

printf(“The element value is:%d”,array[getchar()-]„\‟);

}}

TWO DIMENSIONAL ARRAYS

93
Arrays whose elements are specified by two subscripts are referred as two-dimensional arrays
or double dimensional arrays. A two-dimensional arrays of size m rows by n columns are
declared as follows:

type array-name[m][n];

A two-dimensional array two dimension of type int, 3 rows and 4 columns are declared as
follows:

int two dim[3][4];

EXAMPLE

Arrays can be stored in the memory in two orders. Row major order and column major order.
Multi-dimensional arrays are stored in memory using the row major order. Organization of
the array named two dims with 3 rows and 4 columns in the row major order is shown here:

Column 1 Column2 Column 3 Column 4

Row 1 [0][0] [0][1] [0][2] [0][3]

Row 2 [1][0] [1][1] [1][2] [1][3]

Row 3 [2][0] [2][1] [2][2] [2][3]

Table 3.1 Row Major Order

Elements in a two-dimensional array can be accessed by means of a row and a column. The
row subscript generally is specified before the column subscript.

For example, two dim [1][3] will access the elements in two number 1(the second row) and in
a column number (fourth) of the array. In array notation, two dim [1] represents a row and
two dim [1][3] represents a column within that row. When initializing a two-dimensional

94
array at the time of array declaration, the elements will be assigned by rows, that are the
elements of the first row will be assigned, then the elements of the second and so on.

Consider the following array declaration:

int values[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}

The result of this initial assignment is as follows:

values [0][0] =1 values [0][1] =2 values [0][2] =3 values [0][3] =4

values [1][0] =5 values [1][1] =6 values [1][2] =7 values [1][3] =8

values [2][0] =9 values [2][1] =10 values [2][2] =11 values [2][3] =12

Table 3.2 Array Declaration

The values can also be initialized by forming groups of initial values enclosed within braces.
The value within an integer pair of braces will be assigned to the elements of a row.

For Example,

int values [3][4]={

};{1,2,3,4}

{5,6,7,8}

{9,10,11,12}

NOTE

1. If there are too few values within a pair of braces the reaming elements of that row will be
assigned zero.

2. If the number of values in each inner pair of braces exceeds the defined row size, it will
result a compilation error.

Initializing two dimensional arrays

95
Like single-dimensional array, a double dimensional array can also be initialized. Arrays can
be initialized by the following ways,

Initializing an array during declaration


Initializing an array using loops

Initializing an array during declaration

Similar to single dimensional arrays, a double dimensional array can also be initialized with
one or more values during its declaration.

Storage-type data type array-name[row size][col size]={list of values};

Where the storage type, may be either auto or register or static or extern. The storage type
while declaring an array is optional. The datatype specifies the type of elements that will be
stored in the array. The array name is the name used to identify the array. The rules for
naming array names are same as identifiers. Note that an array should not have the same
name as an ordinary variable in the same block or a function.

For Example

int marks[4][2];

marks[4][2]={82,44},

{92,65},

{73,64},

{65,100}.

The first subscript ranges from 0 to 3 and the second subscript ranges from 0 to 1. In the first
case, the first inner pair of braces are assigned to the array elements in the first row, the value
of second inner pair of braces are assigned to the array elements in the row and so on.

The array of mark can also be declared as, int marks{82,44,92,65,73,64,65,100};

marks[0][0]=82 marks[0][1]=44

96
marks[1][0]=92 marks[1][1]=65

marks[2][0]=73 marks[2][1]=64

marks[3][1]=65 marks[3][2]=100

Table 3.3 Int Marks

Examples for initializing an array using declaration

float amount[2][3]={70.50,90.74,50.75,75.10}

In the example, the size of the array is 6(3*2) and the values 1,2,3,4,5,6 are assigned to the
variable amount [0][0], amount [0][1] …. amount [2][1], amount [3][1] respectively. In the
second example’s row size is missing. While initializing an array, the second dimension (i.e.,
Col size) is missing, but the first dimension (i.e., row size) is optional.

Initializing an array using loops

An array can be initialized by using for loop, a while loop or do-while loop. The given
example illustrates the use of initializing an array using for loops.

Examples for initializing an array using a for loop, int i, j, mark [5][5]

for (i=0; i<0; i++) scanf(“%d”, &mark[i][j]);

In the example, the for loop initializes all the program elements of the array to zero.
Similarly, array elements of the index to zero. Similarly, array can also be initialized while
loop and do- while loops.

Declaration of two-dimensional arrays

The syntax of declaring a two-dimensional array is as follows:

data-type variable-name[row-size][col-size];

where,

97
data-type->refers to any valid c data-type.

variable-name-> (A valid C identifier), refers to the name of the array

row-size->indicates the number of rows and column size indicates the number of elements in
each row

Row size and column size should be integer consists or convertible into integer values. Total
number of locations allocated will be equal to row size* column size. Each element in a 2D
array is identified by the array name followed by a pair of square brackets enclosing its row-
number, followed by a pair of square brackets enclosing its column-number. Row number
ranges from 0 to row-size-1 and column number ranges from 0 to column size-1.

Example

int a[3][3];

Where, a declared to be an array of two dimensions and of data type int. Row size and
column size of a 3 and e respectively. Memory gets allocated to accommodate the array are
as follows. It is important to note that a is the column name shared by all the elements of the
array.

column numbers

0 1 2

0 a [0][0] a [0][1] a [0][2]

1 a [1][0] a [1][1] a [1][2]

2 a [2][0] a [2][1] a [2][2]

Table 3.4 Array of Two Dimensions

Each data item in the array a is identifiable by specifying the array name a followed by a pair
of square brackets enclosing row number, followed by a pair of square brackets enclosing

98
row number followed by a pair of square brackets enclosing column number. Row-number
ranges from 0 to 2 that are first row is identified by row-number 0, second row is identified
by row- number 1 and so on. Similarly, column-number ranges from 0 to 2. First column is
identified by column-number 0, second column is identified by column-number 1 and so on.

a [0][0] refers to data item in the first row and first column a [0[1] refers to data item in the
first row and second column

a [3][3] refers to data item in the fourth row and fourth column a [3][4] refers to data item in
the fourth row and fifth column

Example programs using two-dimensional arrays

Example 1

Write a program to accept and display a matrix.

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

int a[3][4],i ,j; clrscr();

printf(“Enter the elements of matrix a of order 3*4 \n”); for(i=0;i<3;i++)

for(j=4;j<4;j++)

scanf(“%d”,&a[i][j]);

printf(“Matrix a \n”);

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

for(j=0;j<4;j++)

printf(“%4d”,a[i][j]); printf(“\n”);

99
getch();

Example 2

Write a program to calculate the sum of all elements in a matrix.

#include<stdio.h>

void main()

int num[5][5],i,j,m,n,sum=0;

printf(“Enter the order of matrix:”);

scanf(“%d %d”,&m,&n);

printf(“Enter the elements of matrix:”);

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

for(j=0;j<n;j++)

scanf(“%d”,&num[i][j]);

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

for(j=0;j<n;j++)

sum=sum+num[i][j];

printf(“Sum of elements of the matrix is %d:”,sum);

Example 3

Write a to add two matrices

#include<stdio.h>

100
#include<conio.h>

void main()

int a[3][3],b[3][3],c[3][3],I,j,m,n,p,q;

printf(“Input Row and Column of n Matrix \n”);

scanf(“%d %d”, &m,&n);

printf(“Input Row and Column of B Matrix \n”);

scanf(“%d %d”,&p,&q);

if(n==p) && (m==q)

printf(“Matrices can be added \n”);

printf(“Input A-matrix \n”);

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

for(j=0;j<m;++j)

scanf(“%d”,&a[i][j]);

printf(“Input B-matrix \n”);

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

for(j=0;j<m;++j)

scanf(“%d”,&b[i][j]);

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

for(j=0;j<m;++j)

c[i][j]=a[i][j]+b[i][j];

printf(“Sum of A and B matrices:\n”);

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

101
}

elsefor(j=0;j<m;++j)

printf(“%5d”,c[i][j]);

printf(“\n”);

printf(“Matrices Cannot be an Added \n”);

3.3 STRING PROCESSING

String is a sequence of characters that is treated as a single data item and terminated by null
character'\0'. Remember that C language does not support strings as a data type. A string is
actually one-dimensional array of characters in C language. These are often used to create
meaningful and readable programs.

For example : The string "hello world" contains 12 characters including '\0' character which
is automatically added by the compiler at the end of the string.

Declaring and initializing a string variable

There are different ways to initialize a character array variable.

char name[12]="Tutink"; //valid character array initialization

char name[12]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'i', 'n', 'k', '\0' }; //valid initialization

Remember that when you initialize a character array by listings all its characters separately
then you must supply the '\0' character explicitly.

3.4 FUNCTIONS

In this unit, you study about user has chosen the function name, return data type and
arguments (numbers and type), are called user-defined functions.

102
In C functions can be classified into two categories,

1. Library functions

2. User-defined functions

main() is the example of user-defined functions.

printf() and scanf() are called the library functions.

We already user other library functions such as sqrt(),cos(),sin(),tan(),strcmp(),strcat() etc.

This is greatest features in C is that there is no conceptual difference between the user-
defined functions and library functions. For example, we can write a series of function to
process matrices (such as square of given number, finding cos value, finding sine value, etc.).

These are user-defined functions they are written by user. After user, they can be compiled
into libraries and distributed. To the users of the library, these functions will act as library
functions. That is these functions are predefined and precompiled; the users need not worry
about the functions work internally

3.4.1 Categories of functions

A function depending upon the arguments present or not and whether a value is returned or
not, may be classified as

 Function with no arguments and no return values

 Function with return values and no arguments

 Function with arguments and no return values

 Function with arguments and return values

A User-Defined Function, or UDF, is a function provided by the user of a program. C


functions can be classified into two categories, namely, library functions and user-defined
functions. Main is an example of user defined function. printf and scanf belongs to the
category of library functions.

103
The use of functions in C has many advantages:

1. It facilitates top-down modular programming.

2. The length of a source program can be reduced by using functions at an appropriate Places.

3. It is easy to locate and isolate a faulty function for further investigations.

4. A function may be used by many other programs.

They are three elements that are related to user defined functions are:

1. Function definition

2. Function call

3. Function declaration

The function definition is an independent program module that is specially written to


implement the requirements of the function. In order to use this function, we need to invoke it
at a required place in the program. This is known as the function call. The program (or a
function) that calls the function is referred to as the calling program or calling function.
The calling program should declare any function (like declaration of a variable).This is
known as function declaration or function prototype.

Function Definition

A function definition, also known as function implementation it includes the following


elements.

1. Function name

2. Function type

3. List of parameters

4. Local variable declaration

5. Function statements

6. A return statements

104
All the six elements are grouped into two parts, namely,

 Function header

 Function body

SYNTAX

return-type function-name(parameters)
{
Declarations;
Statements;
return value;
}

where,

return-type ->type of value returned by function or void if none function-name-> unique


name identifying function

parameters comma->separated list of types and names of parameters value-> value returned
upon termination (not needed if return-type void)

The list of parameters is a declaration on the form

type1 par1, ..., typen par n

And represents external values needed by the function. The list of parameters can be empty.
All declarations and statements that are valid in the main program can be used in the Function
definition, where they make up the function body.

Function Header

The function header consists of three parts: The function type (also known as return type, the
function name and the formal parameters list. Note that a semicolon is not used at the end of
the function header.

105
Function Body

The function body contains the declarations and statements necessary for performing the
required task. The body enclosed in braces, contains three parts, and is given below:

1. Local declarations that specify the variables needed by the function

2. Function statements that perform the task of the function

3. A return statement that returns the value evaluated by the function

Example, computing averages

double average(double x, double y)

return (x+y)/2;

The return statement forces the function to return immediately, possibly before reaching the
end of the function body.

Function Call

A function can be called by simply using the function name followed by a list of actual
parameters (or arguments), if any, enclosed in parentheses.

SYNTAX

Variable=function-name (arguments);

Variable is assigned the return-value of the function.

The arguments are values with types corresponding to the function parameters.

EXAMPLE

106
int main(int argc, char **argv)

double a=1; double avg;

avg = average(a, 3.0); return 0;

Implicit type conversion is used when the types of the arguments and parameters do not
agree.

When a function is called the value of the argument is copied to the corresponding parameter.
Changes made to the parameter inside the function will not affect the argument (call by
value).

EXAMPLE

#include <stdio.h> void decrease(int i)

i--;

printf("%d ", i);

void main()

int i=1; printf("%d ", i); decrease(i); printf("%d\n", i);

gives the output 1 0 1.

107
Function Declaration

Like variables all function in a C program must be declared, before they are invoked. A
function declaration (also known as function prototype) consists of four parts.

SYNTAX

Function type (return type)

1. Function name

2. Parameter list

3. Terminating semicolon

return-type function-name(parameter types);

The function body is replaced by a semi-colon.

Parameters need not be named; it is sufficient to specify their types.

Example declaring average

double average(double, double);

Declaration is not necessary if the function definition precedes the first call.

Definition of functions

A function is defined as a self-contained program which is written for the purpose of


accomplishing some task.

A function definition consists of two parts. They are,

1. Argument declaration

108
2. Body of the function

The first part of the function specification consists of type specification of the value returned
by the function followed by the function name, a set of arguments (may or may not be
present) separated by commas and enclosed in parenthesis. If the function definition does not
include any arguments, an empty pair of parentheses must follow the function name.

SYNTAX

returntype functionname(argument list)


{
declaration(s);
statement(s);
return(expression);
}

where

return type->specifies the data type value to be returned by the function. The return type is
assumed to be of type int by default if it is not specified.

function name-> used to identify the function. The rules for naming a function are Same as
identifiers.

argument list->specified inside the parenthesis after the function name is optional.

Most functions have list of parameters and a return value that provides means for
communication between functions. The arguments in the function reference, which defines
the data items that are actually transferred, are referred as actual arguments or actual
parameters. All variables declared in function definitions are local variables. Their scope is
visible known only in the function in which they are defined. Functions arguments are als0
local variables.

109
EXAMPLE

Write a program for sum of two numbers and return the sum to the main function.

#include<stdio.h> void main()

int addnum(int,int);

int sum,a,b;

printf(“\n Enter two number to be summed:”);

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

sum=addnum(a,b);

printf(“\n The sum of %d and %d is %d”,a,b,sum);

int addnum(num1,num2)

int tot; tot=num1+num2; return(tot);}

Sample program output:

Enter two numbers to be summed: 15, 17 The of 15 and 17 is 32

The above program consists of two functions, The required main function

The programmer defined function addnum, which sums the two values.

The function main reads in two integer values, and assigns them to a and b. Then, main calls
addnum, transferring the integer values a and b receiving their sum. The sum is then
displayed and the program terminates.

The integer values are transferred via the arguments num1 and num2,and their sum tot is
returned to the calling portion of the program via the return statement.

110
Return values and their types

The return () Statement versus exit()

The return statement is used to return the control from the calling function to the next
statement of the called portion of the program. The return statement also causes program
logically to return to the point from where the function is accessed (called).The return
statement returns one value per call.

The return statement can be any one of the types as shown below, return;

return(); return(constant); return(variable); return(expression);

return(conditional expression); return(function);

The first and second return() statements, does not return any value, and are just equal to the
closing brace of the function. If the function reaches the end without using a return statement,
the control is simply transferred back to the calling portion of the program without returning
any value. The return() statement returns a value 1 to the calling function. The third return()
statements return a value 1 to the calling function.

The exit() is build-in function available as part of C library. The common thing shared by
both the return statement and the exit() is that both are used to exit the function in which they
are used.

EXAMPLE 1

if(fact<=1) return(1);

This return() statement returns a constant q when the condition specified inside the if
statement evaluates to true.

EXAMPLE 2

return(num1+num2+num3);

111
This return() statement returns a value depending upon the result of the conditional
expression specified inside the parenthesis.

EXAMPLE 3

return(power(5,2));

This return() statement calls the function specified inside the parenthesis and collects the
result obtained from that function, and returns it to the calling function.

NOTE

1 The limitation of a return statement is that it can return only one value from the
called function to the calling function.
2 The return statement can be present anywhere in the function, not necessarily at the
end of the function.
3 Number of return statements used in a function is not restricted, since the return
statement which executes first will return the value from the called function to the
calling function and the other return statements are left unexpected.
4 If the called function does not return any value, then the keyword void must be used
as the return specifier.
5 Parenthesis used around the expression in a return statement is optional.

Function Prototypes

A C function returns an integer value by default. Whenever a call is made to a function the
compiler assumes that this function would return a value of type int.If you decide that a
function should return a value other that int, then it is necessary to mention the first line of
the function in the program, before it is used, which is called the function prototype also
referred as the function declaration.

112
Function prototypes are usually written at the beginning of the program explicitly before all
user-defined functions including the main() function.

SYNTAX

return type function name(dt1 arg1,dt2 arg2…dtn argn)

where,

return type->represents the data type of the value that is returned by the function dt 1,dt 2…dt
n->represents the data types of the arguments

arg1,arg2…argn->The data types of the arguments should be specified compulsorily in the


Function definition

EXAMPLE

int sum(int num)

where sum is the name of the function, int before the function name sum() indicates that the
function returns a value of type int. The variable num inside the parenthesis is the parameter
passed to the called function. The data type int before the parameter num indicates that is
type integer.

3.4.2 Recursion

The process of calling a function by itself is called recursion and the function which calls
itself is called recursive function. Recursion is used to solve various mathematical problems
by dividing it into smaller problems. This method of solving a problem is called Divide and
Conquer.

113
In programming, it is used to divide complex problem into simpler ones and solving them
individually.

Syntax of Recursive Function

returntype recursive_func ([argument list])

statements;

... ... ...

recursive_func ([actual argument]);

... ... ...

Flowchart of Recursion

Fig 3.1 Flowchart of Recursion

114
Note: In order to prevent infinite recursive call, we need to define proper exit condition in a
recursive function.

For example, consider the program below:

Example #1: C Program to show infinite recursive function

#include<stdio.h>

int main()

printf("Hello world");

main();

return 0;

In this program, we are calling main() from main() which is recursion. But we haven’t
defined any condition for the program to exit. Hence this code will print “Hello world”
infinitely in the output screen.

Types of recursions

 Direct Recursion

 Indirect Recursion

Direct Recursion

A function is said to be direct recursive if it calls itself directly.

Example #2: C Program Function to show direct recursion

int fibo (int n)

if (n==1 || n==2)

return 1;

else

return (fibo(n-1)+fibo(n-2));

115
}

In this program, fibo() is a direct recursive function. This is because, inside fibo() function,
there is a statement which calls fibo() function again directly.

Indirect Recursion

A function is said to be indirect recursive if it calls another function and this new function
calls the first calling function again.

Example #3: C Program Function to show indirect recursion

int func1(int n)

if (n<=1)

return 1;

else

return func2(n);

int func2(int n)

return func1(n);

In this program, func1() calls func2(), which is a new function. But this new
function func2() calls the first calling function, func1(), again. This makes the above function
an indirect recursive function.

3.5 SUMMARY

 A function is a self-contained program segment that performs some specific well-


defined tasks.

116
 Three steps in using a function are declaring a function, defining a function and
calling the function.
 A function is called by specifying its name, followed by a pair of parentheses, which
contains parameters if needed.
 The argument that represents the names of data items that are transformed into the
function from the calling portion of the program are called as formal arguments or
formal parameters.
 The corresponding arguments in the function reference which define the data items
that are actually transferred are called as actual arguments or actual parameters.
 The return statement is used to return the information from the function to the calling
function of the program
 A function may be declared anywhere as long as its declaration is above all reference
to the function. So, a function should be declared before it is called.
 The execution of a function is terminated when it executes the return statement or
when the last statement of the function is executed or when it encounters the closing
brace of the function.

3.6 KEYWORDS

 Main (): main () is a specifically recognized function in C. Every Program must have
a main () function to indicate where the program has to begin its execution.
 Function Definition: function definition is an independent program module that is
specially written to implement the requirements of the function.
 Function Call: The program or a function that calls the function is referred to as the
calling program or calling function.
 Function Definition or Function Prototype: The calling program should declare any
function (like declaration of variable) that is to be used later in the program. This is
known as the function declaration or function prototype.
 Function Body: The function body contains the declarations and statements
necessary for performing the required task. The body enclosed in braces, contains
three parts.
 Return (): A return () statement that returns the value evaluated by the function.

117
 Function parameters: Function parameters are the means of communication between
the calling and the called functions.
 Formal parameters: The formal parameters (commonly called parameters) are the
parameters given the function declaration and function definition.

3.7 LEARNING ACTIVITY

1. What is the return () statement mandatory in a function?

___________________________________________________________________________
___________________________________________________________________________

2. State several advantages to the use of functions.

___________________________________________________________________________
___________________________________________________________________________

3.8 UNIT END QUESTIONS

A. Descriptive Questions

Short Questions

1. What is the need for functions?

2. What is a function?

3. Explain the general form of defining a function.

4. What are formal arguments?

5. What are actual arguments?

Long Questions

1. What do you mean by function call?

2. Difference between build-in functions and user-defined functions. Give examples.

3. Define function prototype.

118
4. What is calling function?

5. What is called function?

6. Write a program to swap two numbers using functions.

B. Multiple Choice Questions

1. Choose correct statement about Functions in C Language.


a. A Function is a group of c statements which can be reused any number of times
b. Every Function has a return type
c. Every Function may know may not return a value
d. All of these

2. Choose a correct statement about C Function?


void main() {
printf("Hello");
}
a. "main" is the name of default must and should Function
b. main() is same as int main()
c. By default, return 0 is added as the last statement of a function without specific
return type
d. All of these

3. A function which calls itself is called a ___ function.


a. Self Function
b. Auto Function
c. Recursive Function
d. Static Function

4. The keyword used to transfer control from a function back to the calling function is
int **a;
a. switch
b. goto
c. go back
d. return

119
5. How many times the program will print "Algbly"?
int main() {
printf("Algbly");
main();
return 0;
}
a. Infinite times
b. 32767 times
c. 65535 times
d. Till stack overflows

Answer

1-d, 2-d, 3-c, 4-d, 5-d

3.9 REFERENCES

References Book

 Programming in ANSI C - Agarwal


 Let us C - Kanitkar
 Programming in ANSI C - Bal Guruswamy
 How to solve it by Computer: Dromey, PHI
 Schaums outline of Theory and Problems of programming with C : Gottfried

120

You might also like