0% found this document useful (0 votes)
8 views33 pages

POP (BPOPS103) - Module-3

Module 3 of the First Year Engineering course covers User Defined Functions and Recursion in C programming. It explains the importance of functions, modular programming, and the elements of user-defined functions, including function definition, call, and declaration. The module also discusses categories of functions, inter-function communication, nesting of functions, and recursion, along with examples and limitations.

Uploaded by

pallavikkotikall
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views33 pages

POP (BPOPS103) - Module-3

Module 3 of the First Year Engineering course covers User Defined Functions and Recursion in C programming. It explains the importance of functions, modular programming, and the elements of user-defined functions, including function definition, call, and declaration. The module also discusses categories of functions, inter-function communication, nesting of functions, and recursion, along with examples and limitations.

Uploaded by

pallavikkotikall
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

First Year Engineering, Sub Name: POP Code: 22POP13 Module No.

: 3

MODULE 3:

USER DEFINED FUNCTIONS AND RECURSION

1. INTRODUCTION
Every C program should consist of one or more functions. Among these functions
main( ) function is compulsory. All programs start execution from main( ) function.
Functions are independent program modules that are designed to carry out a particulartask. In functions we
have two types:

1. Built-in (Library) functions


2. User defined functions
Built-in functions are C language functions already available with C compliers and canbe used by any
programmers. Example: printf( ),scanf( )
User-defined functions are written by programmers to serve their own purpose and arenot readily available.

Advantages of using Functions:


Functions based modular programming is advantageous in many ways:

1. Managing huge programs and software packages is easier by dividing them into
functions/modules—Maintenance is easier
2. Error detection is easier—Debugging is easier
3. Functions once written can be re-used in any other applications – Reusability is
enhanced
4. We can protect our data from illegal users—Data protection becomes easier

Figure 1: Top-down modular programming using functions


First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Following block diagram explains how functions are useful:Instead of writing entire program (to add and

main( ) Subtract ( )
main( ) calls add( ) completes the work
and returns back to
main( )

add( ) completes the main( ) calls


work and returns
add( ) back to main( ) subtract( ) subtract( )

subtract) within main( ) function we can write independent modules add( ) and subtract( ) as shown:

inputs Function Black-box output

Note: As shown in the above diagram, function can accept any number of inputs butone value as
output.

2. MODULAR PROGRAMMING

➢ Modular programming is defined as organizing a large program into small,


independent program segments called modules that are separately named and individually
callable program units.
➢ It is basically a “divide-and-conquer” approach to problem solving.
➢ The characteristics of modular programming are:
1. Each module should do only one thing.
2. Communication between modules is allowed only by calling module.
3. No communication can take place directly between modules that do not have
calling-called relationship.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

4. All modules are designed as single-entry, single-exit systems using control structures.
5. A module can be called by one and only higher module.

3. ELEMENTS OF USER-DEFINED FUNCTIONS


There are three elements that are related to functions:

i. Function definition
ii. Function call
iii. Function declaration/Function prototype

i. Function definition: It is an independent program module that is specially written to


implement the requirements of the function.
ii. Function call: To function should be invoked at a required place in the program
which is called as Function call. The program that calls the function is referred as calling
program or calling function.
iii. Function declaration: The calling program should declare any function that is to be
used later in the program which is called as function declaration.

DEFINITION OF FUNCTIONS

A function definition, also known as function implementation will include:


i. Function name
ii. Function type/ Return type
iii. List of parameters/ Arguments
iv. Local variable declaration
v. Function statements
vi. A return statement

All the above six elements are grouped into two parts. Namely:
➢ Function header (First three elements)
➢ Function body (Second three elements)

Syntax:
function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

executable statement2;
......
......
return statement;
}
The first line function_type function_name(parameter list) is known as the function
header and the statements within opening and closing braces is known as the function body.

i. Function Header: It consists of three parts: Function type, function name and formal
parameter list. The semicolon is not present at the end of header.

Function type:
➢ The function type specifies the type of value that the function is expected to
return to the program calling the function.
➢ If the return type is not specified, then it is assumed as int.
➢ If function is not returning anything, then it is void.

Function name: The function name is any valid C identifier and must follow same rulesas of other variable.
Formal Parameter List:The parameter list declares the variables that will receive the data sent by the
calling program which serves as input and known as Formal ParameterList.

ii. Function Body: The function body contains the declarations and statements necessary
for performing the required task. The body is enclosed in braces, contains three parts:
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.

FUNCTION DECLARATION

A function declaration consists of four parts:


➢ Function type (return type)
➢ Function name
➢ Parameter List
➢ Terminating semicolon

Syntax:function_type function_name(parameter_list);
Ex: int sum(int, int);
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

4. CATEGORIES OF FUNCTIONS

User defined
functions

Functions return Functions with return


nothing value
(void functions)

void functions Functions with


without parameters and
parameters return values

void functions with Functions without


parameters parameters and
with return values

Figure 2: Categories of Functions

1. Void Functions without parameters – No arguments and no return values

➢ When a function has no arguments, it does not receive any data from the calling
function.
➢ Similarly, when it does not return a value, the calling function does not receive any
data from the called function.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Figure 3: No data communication between functions


void display(void); 1
int main( ) Parts of user defined function marked in the
2
{ example given are:
1. function prototype
2. calling function
display( ); 3 3. called function/function call
4. function definition
a. function header
} i. return type
4a ii. function name
iii. parameters if any
void display(void ) b. function body
{

printf(“Welcome to the C World”);


return;

4b

2. Void Functions with parameters – Arguments but no return values

➢ The calling function accepts the input, checks its validity and pass it on to the
called function.
➢ The called function does not return any values back to calling function.
➢ The actual and formal arguments should match in number, type and order as
shown in Figure 3.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Figure 3: One-way data communication

Figure 4: Arguments matching between the function call and the called function

void show(int);
1 Description of user defined function marked in the
int main( ) example given is:
2
1. function prototype of show( ) has an
{ integer parameter ‘int’
2. calling function main ( )
int num=5; 3. actual parameter ‘num’ is passed to
show(num); 3 function show( )
4. formal parameter ‘no’contains value 5
copied from ‘num’ and displays it on
}/* end of main */
screen

void show(int no)

{ 4
printf(“%d”, no);

}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

In this example a photocopy of value stored in ‘num’ (i.e. 5) is made in ‘no’ and finallydisplayed on screen.
Next let us discuss functions with parameters and return values

3. Functions with parameters and return values – Arguments with return


values

➢ The calling function sends the data to called function and also accepts the return
values from called function.
➢ Actual Parameters: When a function is called, the values that are passed in the call
are called actual parameters.
➢ Formal Parameters:The values which are received by the function, and are
assigned to formal parameters.

Figure 5: Two-way data communication between functions

int SquareMaker (int); 1 Description of user defined function marked in


int main( ) the example given is:
2

{ 1. function prototype of SquareMaker( )


has an integer parameter ‘int’ and
int num, square; return type ‘int’
2. calling function
printf(“Enter the number”);
3. actual parameter ‘num’ is passed to
scanf(“%d”, &num); function SquareMaker( ) and the
square=SquareMaker(num); 3
evaluated value is stored in variable
printf(“Square of number is %d”, square); square
4. formal parameter ‘sq’ contains value
} passed by ‘num’ and square of that
number is calculated and sent back to
main
int SquareMaker(int sq) {

return(sq * sq); 4
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

4. Functions without parameters and with return values – No arguments but


returns values

➢ The calling function does not send any data to called function and but, accepts the
return values from called function.
➢ Global Variables: These are declared outside any function, and they can be
accessed on any function in the program.
➢ Local Variables: These are declared inside a function, and can be used only
inside that function.

int SquareMaker ( ); 1
2
int main( ) Description of user defined function marked in
the example given are:
{
1. function prototype of SquareMaker( )
int square; has an integer no parameter but return
type is ‘int’
square=SquareMaker( ); 2. calling function
3
3. No parameter is passed to function
printf(“Square of number is %d”, square); SquareMaker( ) while calling it
4. SquareMaker( ) calculates square of
} ‘num’ and returns that value back to
main( )
int SquareMaker( )

int num;

printf(“Enter the number”);


scanf(“%d”, &num);
return(num * num); 4

Note: Function call can be an expression like: “square=SquareMaker( )” only in functions with
return values. Void function call cannot be an expression.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

5. Inter-Function Communication
Two functions can communicate with each other by two methods:

1. By Passing parameters as values (Pass by value)


2. By passing parameters as address (Pass by address or reference)

1. By Passing parameters as values (Pass by value):

In pass-by-value the calling function sends the copy of parameters (ActualParameters) to the called
function (Formal Parameters).

➢ The change does not affect the actual value.

void main()
void swap( int x, int y )
{
int a=5, b=10; {
int temp;
swap(a, b);
temp=x;
printf(“%d %d”, a,b);
x=y;
}
y=temp;
}

temp=x /* copies 5 to temp*/


Value in a=5 Copied to x
x=y /*copies 10 to x*/

y=temp /* copies 5 to y */
Value in b=10 Copied to y Thus x and y values got swapped, but problem is a and b
values remain unchanged!
So pass by value method fails here!

Alternative is pass by address/reference

2. By Passing parameters as address (Pass by address)

In pass-by-referencethe calling function sends the address of parameters (ActualParameters) to the


called function (Formal Parameters).
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

➢ The change affects the actual value.

void main() void swap( int *x, int *y )


==0)
{ {

int a=5, b=10; int temp;


swap(&a, &b); temp=*x;

printf(“%d %d”, a,b)


*x=*y;

} *y=temp;

Address of is Copied to temp=*x /* copies 5 to temp */


a=say(1002) x
*x=*y /*copies 10 to *x (i.e. to a) */

*y=temp /* copies 5 to y (i.e. to b) */


Address of is Copied to
b=say 2002 y

6. NESTING OF FUNCTIONS
A function within a function is called as nesting of functions.

float checkno(float ); void


div(float, float); void
main( )
{
float a,b,res;
printf(“enter two numbers\n”);
scanf(“%f%f”,&a,&b);
div(a,b);
}
float div(float a, float b)
{
if(checkno(b))
printf(“the result is %f”, a/b);
else
printf(“division not possible”);

}
float checkno(float b)
{
if(b!=0)
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

return 0;
else
return 1;
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

9. RECURSION

Programmers use two approaches to writing repetitive algorithms:

• One approach is to use loops


• The other uses recursion

➢ Recursion is the repetitive process in which a function calls itself.


➢ All recursive functions have two elements each call either solves one part of the
problem or it reduces the size of the problem.

➢ The statement that solves the problem is known as base case.


➢ The rest of the function is known as general case.

Ex: Recursive definition of factorial


Fact(n)= 1 if n=0 base case
n*fact(n-1) if n>0 general case

Limitations of Recursion
➢ Recursive solutions may involve extensive overhead because they use function
calls.
➢ Each time you make a call, you use up some of your memory allocation. If recursion
is deep, then you may run out of memory.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

PROGRAMS
1. Write a C program to find a factorial of number using recursion.
#include<stdio.h>int
fact(int);
void main( )
{
int n,res;
printf(“enter the number to find its factorial\n”);scanf(“%d”,&n);
res=fact(n);
printf(“factorial of %d=%d”,n,res);

}
int fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}

2. Program to generate Fibonacci series using recursion


#include<stdio.h> int
Fibonacci(int); void
main( )
{
int n, i = 0;
printf(" enter the number of terms\n");scanf("%d",&n);
printf("Fibonacci series\n");
printf("%d\n", i);
for ( i = 1 ; i <= n ; i++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
}
int Fibonacci(int n)
{
if ( n == 0 )return
0;
else if ( n == 1 )return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Storage classes in C

• Storage Classes are used to describe the features of a variable/function.


• These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable
during the runtime of a program.
C language uses 4 storage classes, namely:

auto: This is the default storage class for all the variables declared inside a function or a block.
• Hence, the keyword auto is rarely used while writing programs in C language.
• Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines
their scope).
• Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was
declared.
• They are assigned a garbage value by default whenever they are declared.
extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used.
• Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well.
• So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used
elsewhere.
• It can be accessed within any function/block.
• Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in
any function/block.
• This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only.
• The main purpose of using extern variables is that they can be accessed between two different files which are part of a large
program.
static: This storage class is used to declare static variables which are popularly used while writing programs in C language.
• Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables
preserve the value of their last use in their scope.
• So we can say that they are initialized only once and exist till the termination of the program.
• Thus, no new memory is allocated because they are not re-declared.
• Their scope is local to the function to which they were defined.
• Global static variables can be accessed anywhere in the program.
• By default, they are assigned the value 0 by the compiler.
register: This storage class declares register variables that have the same functionality as that of the auto variables.
• The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free registration
is available.
• This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime
of the program.
• If a free registration is not available, these are then stored in the memory only.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

• Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which
improves the running time of the program.
• An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.

ARRAYS

1. WHY DO WE NEED ARRAYS?


Say we have a problem in our hand to store marks scored by 50 students in C language subject. To store 50
marks we have to declare 50 variables of integer data type as shown below:

int marks_1, marks_2, marks_3, marks_4… ..................... marks_50;

Now suppose we have to store values into these variables then 50 scanf statements or initializing 50 values
has to be done as shown:

scanf(“%d”,
&marks_1);
scanf(“%d”,
&marks_2);
scanf(“%d”,
&marks_3);

………………..scanf(“%d”, &marks_50);
OR

marks_1=
25;
marks_2=23;
marks_3=20;

………….. so on marks_50=21;

marks_1 25 marks_2 23 marks_3 20

marks_4 15 So on………… marks_50 21

This style of programming is fine for a small set of values. But if we have to store 1000 or 10000 values
declaring so many variables is a cumbersome process. Alternative solution is Arrays!
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

2. DEFINITION OF ARRAYS

The array is a fixed-size sequenced collection of elements of same data type.


The array is a collection of homogeneous elements of same data type.
Array groups the data items of similar types sharing the common name.
Arrays are called as subscripted variables because; it is accessed using subscripts/indexes.
Ex: 1. List of employees in an organization.
2. List of products and their cost sold by a store.
3. Test scores of a class of students.

Here marks[0]=10, marks[1]=20, marks[2]=30 and marks[3]=40. This subscript/index


notation is borrowed from Mathematics where we have the practice of writing: marks4,
marks3, marks2 and so on.
In C the array index starts with 0.

3. TYPES OF ARRAYS

I. One dimensional arrays/Single-Subscripted Variable


II. Two dimensional arrays/Double-Subscripted Variable
III. Multidimensional arrays

I. One-Dimensional Arrays: A list of items can be given one variable name using only
one subscript and such a variable is called a single subscripted variable or one dimensional
array.

Ex: int marks[4];

➢ Here marks is the name of the array which is capable of storing 4 integer values. The
first value will be stored in marks[0], the second value will be stored in marks[1] and so on
and the last value will be in marks[3].
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Declaration of One-Dimensional Array: Here is general syntax for array declaration along
with examples.

Syntax: data_type array_name[size];

Examples: int marks[4];

float temperature[5];

Note: Declaration and definition specify the data type of


array, its name and size.

Initialization of One-Dimensional Array: After array is declared, next is storing values in


to an array is called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization

1. Compile time initialization: If we assign values to the array during declaration it is


called compile time initialization. Following are the different methods of compile time
initialization.
a) Initialization with size
b) Initialization without size
c) Partial initialization
d) Initializing all values zero

a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[size]={list of values};

Examples: int marks[4]={ 95,35, 67, 87};


float temperature[5]={29.5, 30.7, 35.6, 45.7, 19.5};

b) Initialization without size: We needn’t have to specify the size of array provided we
are initializing the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};

Examples: int marks[ ]={ 95,35, 67, 87};


float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};

c) Partial initialization: If we not specify the all the elements in the array, the
unspecified elements will be initialized to zero.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Example: int marks[5]={10,12,20};


Here, marks[3] and marks[4] will be initialized to zero.

d) Initializing all the elements zero: If we want to store zero to all the elements in the
array we can do.
Examples: int marks[4]={0};
float temperature[5]={0};

2. Run time initialization: Run time initialization is storing values in an array when
program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:

Example:
printf(“Enter the marks”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
Note: Every iteration of for loop will help us to fill values into marks array (i.e. marks[0]=95, marks[1]=35,
marks[2]=67, marks[3]=87)

Accessing the array elements: Accessing the array element is done using a loop statement in combination
with printf statements or any other processing statements. Example of accessing the array elements and
calculating total marks is given below:

Example: void main( )


{
int total=0, marks[4]={35,44,55,67};for(i=0;
i<4; i++)
total=total+marks[i]; /* calculating total marks*/
printf(“Total marks=%d”,total);
}
Output: Total marks=201
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

USING ARRAYS WITH FUNCTIONS:


In large programs that use functions we can pass Arrays as parameters. Two ways ofpassing arrays to
functions are:

1. Pass individual elements of array as parameter


2. Pass complete array as parameter

Let us take an example program that uses a function square( ) to calculate square ofnumbers stored in an
array. In this program each array element is passed one by one.

Example-1 Example-1 cont’d:


int square(int); void square(int no )
void main( ) {
{ int sq;
int num[5], i; sq=no*no; /*square is calculated*/
num[5] ={3,4, 8, 9, 10}; printf(“square is=%d ”, sq);
for(i=0; i<5; i++) }
{
square(num[i]);
} Output:
} Square is=9 16 64 81 100
}

This diagram clearly illustrates how each individual element of array num[ ] is passed tofunction square
through parameter no.

3 4 8 9 10
0 1 2 num[3]=9→ no
3 4
num[1]=4 copied → no

num[0]=3 copied to no
num[2]=8→ no

Next program illustrates how to pass an entire array to a function average( ) andcalculate average marks.
First sum of all the elements of array marks

(i.e.35+65+75+95+85) is calculated and average is stored in a variable avg. value in avg


variable is returned to main( ) and stored in avg1
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Example-2: Example-2 cont’d:


float average(int score[ ] )
float average(int score[]);
{
void main( )
int i , sum=0;
{
float avg;
int marks[5], i for(i=0; i<5;i++)
float avg1; {
marks[5] ={35,65, 75, 95, 85}; sum=sum+score[i];
avg1=average(marks); }
printf(“average=%f”, avg1) avg=sum/5;
} return (avg);
}

Output:

average=71.000000

In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:

marks[0]=35 copied to scores[0]

marks[1]=65 copied to scores[1]

marks[2]=75 copied to scores[2]

marks[3]=95 copied to scores[3]

marks[4]=85 copied to scores[4]

using these values average is calculated:


(35+65+75+95+85)/5=

71.000000
II. Two-Dimensional Arrays: A list of items can be given one variable name using two
subscripts and such a variable is called a single subscripted variable or one dimensional
array.

➢ It consists of both rows and columns. Ex: Matrix.


First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Declaration of Two-Dimensional Array: Here is general syntax for array declaration along

Syntax: data_type array_name[row_size][column_size];

Examples: int marks[4][4];

float city_temper[3][3];

Note: Declaration and definition specify the data type of


array, its name and size.

with examples.

Initialization of Two-Dimensional Array: After array is declared, next is storing values in


to an array is called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization

1. Compile time initialization: If we assign values to the array during declaration it is


called compile time initialization. Following are the different methods of compile time
initialization.

Syntax: data_type array_name[size]={list of values};


Examples: int marks[3][4]={ {1,2,3,4}, {5, 6, 7,8},{9,10,11,12}};
float city_temp[2][2]={29.5, 30.5, 35.6, 45.7};
int age[ ][3]={{50, 60}, {70, 80}}; // other elements are init to 0
int table[2][3]={{50, 60, 70}, {80}};// other elements are init to 0
int m[ ][3]={50, 60}; // other elements are init to 0
int n[2][3]={{40, 60},{50}}; // other elements are init to 0
int k[2][3]={{0},{0}}; // all elements are init to 0
int p[2][3]={0 ,0}; // all elements are init to 0
marks
1 2 3 4 city_temp
29.5 30.5
5 6 7 8
35.6 45.7
9 10 11 12

After initialization the arrays appear as follows:


First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

2. Run time initialization: Run time initialization is storing values in an array when
program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:

Example: printf(“Enter the marks”);


for(i=0; i<3; i++)
for(j=0;j<4;j++)
{
scanf(“ %d”, &marks[i][j]);
}

More Examples: Other way of initialization:


int a[ ][3]= { 0, 1, 2, 3,4,5,6,7,8};
int b[ ][4] ={1,2,3,4,5,6,7,8,9,10,11,12};

012 1234
a b
345 5678
67 8 9 10 11 12

Example for Invalid initialization


int A[3][ ]={1,2,3};
Note: Never have column size undeclared in two dimension array.

III. Multi Dimensional Arrays: Multidimensional arrays can have three, four or more
dimensions.
➢ A three-dimension array is an array of two dimensional arrays. It has row, column and
depth associated with it.
➢ Declaring multidimensional arrays
int table[3][5][4];
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

Here are two examples illustrating three-dimensional array declaration and


initialization

A[3][4][2]={
{ {{{1,2},{3,4}},{{5,6},{7,8}}}
{ 1,2},
{3,4}, 4 rows &

{5,6}, 2 columns
{7,8}

},

{ 3 depth
{ 8,9},
{10,11},
{12,13},
{14,15}
},

{
{ 8,9},
{10,11},
{12,13},
{14,15}
}
}

3. OPERATIONS PERFORMED ON ONE_DIMENSIONAL ARRAY


SORTING: It is the process of arranging elements in the list according to their values in ascending or
descending order. A sorted list is called an ordered list.
Ex: Bubble Sort, Selection Sort, Insertion Sort, Shell Sort, Merge Sort, Quick Sort.

Bubble Sort
Bubble sort will start by comparing the first element of the array with the second element, if the first element
is greater than the second element, it will swap both the elements, and then move on to compare the second
and the third element, and so on.

#include<stdio.h>
void main( )
{
int i,j,n,temp,a[100]; printf("Enter the
value of n\n");scanf("%d",&n);
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

printf("Enter the numbers in unsorted order:\n");


for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
for(j=0;j<(n-i)-1;j++)
{
if( a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
}

Selection Sort
Selection sort will start by comparing the first element with other elements and finds minimum element and
swaps, then it starts comparing by taking second element with other elements and so on.

#include<stdio.h>
void main( )
{
int a[100],i,j,n,temp,pos; printf("Enter
the value of n\n");scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
pos=j;
}
if(pos !=i )
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}

SEARCHING: It is the process of finding the location of the specified element in a list.

➢ The specified element is often called the search key.


➢ If it is found search is successful, otherwise it is unsuccessful.
Ex: Binary Search, Linear Search, Sequential Search.

Linear Search

Linear search is a very basic and simple search algorithm. In Linear search, we search an element or value in
a given array by traversing the array from the starting, till the desired element or value is found.

#include<stdio.h>
#include<stdlib.h> void )
main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i]
{
loc=i+1;
break;
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

}
if(loc>=0)
printf("The element %d is found at %d \n",key,loc);else
printf("The search is unsuccessful\n");
}
Binary Search
Binary search works only on a sorted set of elements. To use binary search on acollection, the collection
must first be sorted. The array is divided into two parts,

compared with middle element if it is not successful, then it is compared whether it is lesser or greater than
middle element. If it is lesser, search is done towards left part else right part.

#include<stdio.h>
#include<stdlib.h> void
main( )
{
int n, a[100], i, key, loc, high, low, mid;loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low +high)/2;
if(key==a[mid])
{
loc = mid+1;
break;
}
else
{
if(key<a[mid])
high=mid-1;
else
low=mid+1;

}
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

if(loc>=0)
printf("The element %d is found at %d \n",key,loc);else
printf("The search is unsuccessful\n");
}

Applications of an array:
Apart from being widely used in programming, arrays have additional applications as well:
• Used in mathematical problems like matrices etc.
• They are used in the implementation of other data structures like linked lists etc.
• Database records are usually implemented as arrays.
• Used in lookup tables by computer.
• It effectively executes memory addressing logic wherein indices act as addresses to the one-dimensional
array of memory.

PROGRAMS
1. WACP to read N integers into an array A and to
i. Find the sum of odd numbers.
ii. Find the sum of even numbers.
iii. Find the average of all numbers.
Output the results compared with appropriate headings.

#include<stdio.h>
void main( )
{
int oddsum=0, evensum=0, i ,N, A[20];float
avg;
printf(“enter the size of an array\n”);
scanf(“%d”,&N);
printf(“Enter the array elements\n”);
for(i=0;i<N;i++)
{
scanf(“%d”, &A[i]); /* reading array values*/
}
for(i=0;i<N;i++)
{
if(A[i]%2==0)
{
{
}
else }
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

} evensum=evensum+A[i]; /* compute even sum */

oddsum=oddsum+A[i]; /* compute odd sum */


First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

avg=(evensum+oddsum)/N; printf(“even sum is


= %d\n”, evensum);printf(“odd sum is = %d\n”,
oddsum); printf(“Average of all is = %f\n”, avg);
}

2. Program to read and write the elements of one-dimensional array


void main( )
{
int a[10],i,n;
printf(“enter the number of elements in an array\n”);
scanf(“%d”,&n);
printf(“enter the elements of an array\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“the elements of an array are\n”);for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
}

3. Program to read and write the elements of two-dimensional arrays

void main()
{
int a[10][10],i,j,m,n;
printf(“enter the size1 and size2 of 2 dimensional array\n”);scanf(“%d”,&m,&n);
printf(“enter the elements of an array\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“the elements of 2 dimensional array are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“%d”,a[i][j]);
printf(“\n”);
}
}

30
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

4. Program to count number of odd numbers and even numbers in an array:


void main( )
{
int odd_count=0, even_count=0, i , num[10];
printf(“Enter the array elements\n”); for(i=0;i<10;i++)
{
scanf(“%d”, &num[i]); /* reading array values*/
}
for(i=0;i<10;i++)
{
rem=num[i]%2;
if(rem==0)
{
even_count++; /* increase even counter by1 */
}
else
{

odd_count++; /* increase odd counter by1 */


}
}
printf(“odd count is = %d\n”, odd_count); printf(“even
count is = %d\n”, even_count);
}

5. C program to find largest element in the two dimensional array.


#include<stdio.h>void
main()
{
int m,n,a[5][5],i,j,large;
printf("enter the size1 and size2 of 2D array\n");
scanf("%d%d",&m,&n);
printf("enter the elements of 2d array\n");for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d"&a[i][j]);
large=a[0][0];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(a[i][j]>large)
large=a[i][j];
printf("large=%d",large);

31
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

6. Write a C program to concatenate two strings without using built in


function strcat.
void main()
{
char str1[50],str2[25];int
i=0,j=0;
printf("enter the string1\n");

gets(str1); //Shri\0
printf("enter the string2
\n"); gets(str2); //kant\0
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
str1[i]='\0' ;
printf("concatanation of string is %s",str1);
}

7. Implement string copy operation STRCOPY(str1,str2) that copies a string


str1 to another string str2 without using library function.

#include<stdio.h>
#include<conio.h>void
main()
{
char s1[100],s2[100];int i;
printf("\nEnter the string1 :");
gets(s1);
i=0;
while(s1[i]!='\0')
{
s2[i]=s1[i];

32
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3

i++;
}
s2[i]='\0';
printf("\nString2 value is %s ",s2);
}

33

You might also like