0% found this document useful (0 votes)
2 views75 pages

C Programming: User-Defined Functions Guide

This document provides an overview of user-defined functions and recursion in C programming. It explains the syntax for defining, declaring, and calling functions, as well as the concepts of passing parameters, function scope, and variable types. Additionally, it covers recursion, including direct and indirect recursion, and the importance of defining base cases to prevent infinite loops.
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)
2 views75 pages

C Programming: User-Defined Functions Guide

This document provides an overview of user-defined functions and recursion in C programming. It explains the syntax for defining, declaring, and calling functions, as well as the concepts of passing parameters, function scope, and variable types. Additionally, it covers recursion, including direct and indirect recursion, and the importance of defining base cases to prevent infinite loops.
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

RV Institute of Technology & Management®

Module – 3

Functions and Arrays

User Defined Functions and Recursion

3.1 Introduction using functions


A function is a block of code that performs a specific task. ‘C’ language allows you to define functions according
to your need. These functions are known as user-defined functions. Fig 4.1 shows the control flow during the
execution of function.

For example:

Fig 3.1: Control Flow during the execution of function

3.1.1 User defined functions

Example: User-defined function

Here is an example to add two integers. To perform this task, an user-defined function addNumbers() is defined.
RV Institute of Technology & Management®

#include <stdio.h>
int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


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

sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;
}

int addNumbers(int a,int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

3.2. Function definition

Function definition contains the block of code to perform a specific task i.e. in this case, adding two numbers
and returning it.
RV Institute of Technology & Management®

Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)


{
//body of the function
}

When a function is called, the control of the program is transferred to the function definition. And, the compiler
starts executing the codes inside the body of a function.

⮚ Passing arguments to a function

In programming, argument refers to the variable passed to the function. In the above example, two
variables n1 and n2 are passed during function call. The parameters a and b accepts the passed arguments in the
function definition. These arguments are called formal parameters of the function. Fig 4.2 shows the illustration
of passing arguments to a function.

Fig 3.2: Passing Arguments to Functions


RV Institute of Technology & Management®

[Link] declaration
Function declaration. ... In computer programming, a function declaration or function interface is a
declaration of a function that specifies the function's name and type signature, but omits the function body.

A function prototype gives information to the compiler that the function may later be used in the program.

Syntax of function declaration

returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides following
information to the compiler:

1. name of the function is addNumbers()


2. return type of the function is int
3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before the main() function.

3.4. Function call

Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

In the above example, function call is made using addNumbers(n1,n2); statement inside the main().
RV Institute of Technology & Management®

⮚ Is Main a user defined function?


main() function is a user defined, body of the function is defined by the programmer or we can
say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence
we can say that main() in c programming is user defined as well as predefined because it's prototype is
predefined.

⮚ Why do we use functions?


This example highlights the two most important reasons that C programmers use functions. The first
reason is reusability. Once a function is defined, it can be used over and over and over again. ... Another
aspect of reusability is that a single function can be used in several different (and separate) programs.

⮚ Types of function

Depending on whether a function is defined by the user or already included in C compilers, there are two
types of functions in C programming

There are two types of function in C programming:


✔ Standard library functions

✔ User defined functions

⮚ Standard library functions


The standard library functions are built-in functions in C programming to handle tasks such as mathematical
computations, I/O processing, string handling etc. These functions are defined in the header file. When you
include the header file, these functions are available for use.

For example:
The printf() is a standard library function to send formatted output to the screen (display output on the screen).
This function is defined in "stdio.h" header file. There are other numerous library functions defined
under "stdio.h", such as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these
functions are available for use
RV Institute of Technology & Management®

⮚ User-defined function
As mentioned earlier, C allow programmers to define functions. Such functions created by the user are
called user-defined functions. You can create as many user-defined functions as you want.

⮚ Advantages of user-defined function


1. The program will be easier to understand, maintain and debug.
2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be divided among
many programmers.

3.5. Return statements


A return statement ends the execution of a function, and returns control to the calling function. Execution
resumes in the calling function at the point immediately following the call. A return statement can return a
value to the calling function.
Syntax
jump-statement:
return expressionopt ;
The value of expression, if present, is returned to the calling function. If expression is omitted, the return value
of the function is undefined. The expression, if present, is evaluated and then converted to the type returned by
the function. When a return statement contains an expression in functions that have a void return type, the
compiler generates a warning, and the expression isn't evaluated.

3.6. Passing parameters to functions

⮚ Types of Function calls in C

Functions are called by their names; we all know that, then what is this tutorial for? Well if the function does not
have any arguments, then to call a function you can directly use its name. But for functions with arguments, we
can call a function in two different ways, based on how we specify the arguments, and these two ways are:
1. Call by Value
RV Institute of Technology & Management®

2. Call by Reference

❖ Call by Value

Calling a function by value means, we pass the values of the arguments which are stored or copied into the formal
parameters of the function. Hence, the original values are unchanged only the parameters inside the function
changes.

#include<stdio.h>
void calc(int x); // Function Prototype

int main()
{
int x = 10;
calc(x);
// this will print the value of 'x'
printf("\nvalue of x in main is %d", x);
return 0;
}

void calc(int x)
{
// changing the value of 'x'
x = x + 10 ;
printf("value of x in calc function is %d ", x);
}
Output
Value of x in calc function is 20
Value of x in main is 10

In this case, the actual variable x is not changed. This is because we are passing the argument by value, hence a
copy of x is passed to the function, which is updated during function execution, and that copied value in the
RV Institute of Technology & Management®

function is destroyed when the function ends(goes out of scope). So the variable x inside the main() function is
never changed and hence, still holds a value of 10.
But we can change this program to let the function modify the original x variable, by making the
function calc() return a value, and storing that value in x.

#include<stdio.h>
int calc(int x);

int main()
{
int x = 10;
x = calc(x);
printf("value of x is %d", x);
return 0;
}

int calc(int x)
{
x = x + 10 ;
return x;
}

Output:

Value of x is 20
❖ Call by Reference
In call by reference we pass the address (reference) of a variable as argument to any function. When we pass the
address of any variable as argument, then the function will have access to our variable, as it now knows where it
is stored and hence can easily update its value.

In this case the formal parameter can be taken as a reference or a pointer (don't worry about pointers, we will
soon learn about them), in both the cases they will change the values of the original variable.
RV Institute of Technology & Management®

#include<stdio.h>
void calc(int *p); // function taking pointer as argument
int main()
{
int x = 10;
calc(&x); // passing address of 'x' as argument
printf("value of x is %d", x);
return(0);
}

void calc(int *p) //receiving the address in a reference pointer variable

/* Changing the value directly that is stored at the address passed */

*p = *p + 10;

Output:
Value of x is 20
}
Output
4

3.7. Scope of variables

Scope & Lifetime: The scope of a declaration is the part of the program for which the declaration is in
effect. C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which
the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."
RV Institute of Technology & Management®

⮚ Automatic Variables: The variables which are declared inside a block are known
as automatic or local variables; these variables allocates memory automatically upon entry to that block
and free the occupied memory upon exit from that block.

These variables have local scope to that block only that means these can be accessed in which variable
declared.

Keyword 'auto' may be used to declare automatic variable but we can declare these variable without
using 'auto' keywords.

Consider the following declarations


int main()
{
auto int a;
int b;
....
return 0;
}

Here, both variables a and b are automatic variables.

Automatic variables in other user defined functions

An automatic or local variable can be declared in any user define function in the starting of the block.

Consider the following code

void myFunction(void)
RV Institute of Technology & Management®

{
int x;
float y;
char z;
...
}
int main()
{
int a,b;
myFunction();
....
return 0;
}

In this code snippet, variables x, y and z are the local / automatic variable of myFunction() function, while
variables a and b are the local / automatic variables of main() function.

⮚ External Variables: In the C programming language, an external variable is a variable defined outside
any function block. On the other hand, a local (automatic) variable is a variable defined inside a function
block.

For most C implementations, every byte of memory allocated for an external variable is initialized to zero.
The scope of external variables is global, i.e. the entire source code in the file following the declarations.
All functions following the declaration may access the external variable by using its name.

⮚ Static variable: Static variable is one that is not seen outside the function in which it is declared but
which remains until the program terminates. It also means that the value of the variable persists between
successive calls to a function.

static data_type var_name = var_value;


RV Institute of Technology & Management®

For example

#include<stdio.h>
int fun()
{
static int count = 0; // Static Variable
count++;
return count;
}

int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

Output:

12

But the same program when executed using normal auto variables prints the output

#include<stdio.h>
int fun()
{
int count = 0; // Auto Variable
count++;
return count;
}
RV Institute of Technology & Management®

int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

Output:

11

⮚ Register Variables
Registers are faster than memory to access, so the variables which are most frequently used in a C program
can be put in registers using register keyword. The keyword register hints to compiler that a given variable
can be put in a register. It's compiler's choice to put it in a register or not.

What is a Register Variable?

1. Register variables are stored in the CPU registers. Its default value is a garbage value
2. Variable stored in a CPU register can always be accessed faster than the one that is stored in
memory. ...
3. Variables for loop counters can be declared as register.

Example:
register int x=5;
RV Institute of Technology & Management®

3.8. Recursion in ‘C’ Language

Recursion is a programming technique that allows the programmer to express operations in terms of
themselves. In C, this takes the form of a function that calls itself. A useful way to think
of recursive functions is to imagine them as a process being performed where one of the instructions is to
"repeat the process". Flow chart of recursion is shown in Fig 4.3.

Fig 3.3: Flowchart Showing Recursion

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.

The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into
an infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial
of a number, generating Fibonacci series, etc.
RV Institute of Technology & Management®

How recursion works?


A function that calls itself is known as a recursive function. And, this technique is known as recursion.

void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}

The recursion continues until some condition is met to prevent [Link] prevent infinite recursion, if...else
statement (or similar approach) can be used where one branch makes the recursive call and other doesn't.
Base condition in recursion:

In recursive program, the solution to base case is provided and solution of bigger problem is expressed in
terms of smaller problems.

int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
RV Institute of Technology & Management®

In the above example, base case for n < = 1 is defined and larger value of number can be solved by
converting to smaller one till base case is reached.

Different ways of defining recursion

Some of the ways in which recursive functions are characterized. The characterizations are based on:
1. whether the function calls itself or not (direct or indirect recursion).
2. whether there are pending operations at each recursive call (tail-recursive or not).
3. the shape of the calling pattern -- whether pending operations are also recursive (linear or tree-recursive).

⮚ Direct Recursion:
A C function is directly recursive if it contains an explicit call to itself. For example, the function

int foo(int x)
{
if (x <= 0)
return x;
return foo(x - 1);
}

includes a call to itself, so it's directly recursive. The recursive call will occur for positive values of x.

⮚ Indirect Recursion:
A C function foo is indirectly recursive if it contains a call to another function which ultimately calls foo.
The following pair of functions is indirectly recursive. Since they call each other, they are also known as
mutually recursive functions.

int foo(int x)
{
if (x <= 0)
RV Institute of Technology & Management®

return x;
return bar(x);
}

int bar(int y) {
return foo(y - 1);
}

⮚ Tail Recursion:
A recursive function is said to be tail recursive if there are no pending operations to be performed on
return from a recursive call.

Tail recursive functions are often said to "return the value of the last recursive call as the value of the
function." Tail recursion is very desirable because the amount of information which must be stored
during the computation is independent of the number of recursive calls. Some modern computing systems
will actually compute tail-recursive functions using an iterative process.

The "infamous" factorial function fact is usually written in a non-tail-recursive manner:

int fact (int n)


{ /* n >= 0 */
if (n == 0)
return 1;
return n * fact(n - 1);
}

Notice that there is a "pending operation," namely multiplication, to be performed on return from each
recursive call. Whenever there is a pending operation, the function is non-tail-recursive. Information
about each pending operation must be stored, so the amount of information is not independent of the
number of calls.
RV Institute of Technology & Management®

The factorial function can be written in a tail-recursive way:

int fact_aux(int n, int result)


{
if (n == 1)
return result;
return fact_aux(n - 1, n * result)
}

int fact(n)
{
return fact_aux(n, 1);
}

The "auxiliary" function fact_aux is used to keep the syntax of fact(n) the same as before. The recursive
function is really fact_aux, not fact. Note that fact_aux has no pending operations on return from recursive
calls. The value computed by the recursive call is simply returned with no modification. The amount of
information which must be stored is constant (the value of n and the value of result), independent of the
number of recursive calls.

Advantages and Disadvantages of Recursion

Recursion provides a clean and simple way to write code. Some problems are inherently recursive like
tree traversals, Tower of Hanoi, etc.
Recursive program has greater space requirements than iterative program as all functions will remain in
stack until base case is reached. It also has greater time requirements because of function calls and return
overhead.

3.10 Example Programs: Recursion

Sum of Natural Numbers


RV Institute of Technology & Management®

#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of num is 3 initially. During next function call, 2 is passed to the sum() function. This
process continues until num is equal to 0.
When num is equal to 0, the if condition fails and the else part is executed returning the sum of integers to
the main() function.

3.11 Example: Factorial of a positive integer


The following example calculates the factorial of a given number using a recursive function

#include <stdio.h>

unsigned long long int factorial(unsigned int i)

{
RV Institute of Technology & Management®

if(i <= 1) {

return 1;

return i * factorial(i - 1);

int main()

int i = 12;

printf("Factorial of %d is %d\n", i, factorial(i));

return 0;

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

Factorial of 12 is 479001600

3.12 Example: Fibonacci Series


The following example generates the Fibonacci series for a given number using a recursive function

#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{
return 0;
RV Institute of Technology & Management®

}
if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t\n", fibonacci(i));
}
return 0;
}

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

0
1
1
2
3
5
8
13
21
34
RV Institute of Technology & Management®

Example Programs:

1. /* C programming source code to convert either binary to decimal or decimal to binary


according to data entered by user. */

#include <stdio.h> #include <math.h>


int binary_decimal(int n); int decimal_binary(int n); int main()
{

int n; char c;
printf("Instructions:\n");

printf("1. Enter alphabet 'd' to convert binary to decimal.\n"); printf("2. Enter alphabet 'b' to convert decimal
to binary.\n"); scanf("%c",&c);
if (c =='d' || c == 'D')

printf("Enter a binary number: "); scanf("%d", &n);


printf("%d in binary = %d in decimal", n, binary_decimal(n));

if (c =='b' || c == 'B')

printf("Enter a decimal number: "); scanf("%d", &n);


printf("%d in decimal = %d in binary", n, decimal_binary(n));

return 0;
RV Institute of Technology & Management®

int decimal_binary(int n) /* Function to convert decimal to binary.*/

int rem, i=1, binary=0; while (n!=0)


{

rem=n%2;

n/=2; binary+=rem*i; i*=10;


}

return binary;

int binary_decimal(int n) /* Function to convert binary to decimal.*/

int decimal=0, i=0, rem; while (n!=0)


{

rem = n%10; n/=10;


decimal += rem*pow(2,i);

++i;

return decimal;
RV Institute of Technology & Management®

Output:

Instructions:

1. Enter alphabet 'd' to convert binary to decimal.

2. Enter alphabet 'b' to convert decimal to binary.

Enter a binary number: 110111

110111 in binary = 55 in decimal

2. With using user-defined function write a program to find length of string.

#include<stdio.h>

// Prototype Declaration int FindLength(char str[]);

int main()

{
char str[100];
int length;
printf("\nEnter the String : ");
gets(str);
length = FindLength(str);

printf("\nLength of the String is : %d", length);

return(0);
}

int FindLength(char str[])

{
RV Institute of Technology & Management®

int len = 0;
while (str[len] != '\0')
len++;
return (len);

Arrays

3.13 Arrays in C Language

An array is a collection of a fixed number of values of a single data type. For example: if you want
to store 100 integers in sequence, you can create an array for it. int data[100]; The size and type
of arrays cannot be changed after its declaration. An array is a collection of data items, all of the
same type, accessed using a common name. A one-dimensional array is like a list; A two
dimensional array is like a table; The C language places no limits on the number of dimensions in
an array, though specific implementations may.

3.14 Declaration of Arrays: It is used to represent multiple data items of same type by using only
single name. It can be used to implement other data structures like linked lists, stacks, queues, trees,
graphs etc. 2D arrays are used to represent matrices. Representation of array of integers is shown in
Fig 3.1.

Fig 3.5: Array of integers

▪ Types of Arrays
RV Institute of Technology & Management®

There are two type of array in C language:

⮚ One dimensional array:


Single or One Dimensional array is used to represent and store data in a linear form. Array having
only one subscript variable is called One-Dimensional array. It is also called as Single Dimensional
Array or Linear Array. Fig 3.2 shows one dimensional array.

Fig 3.6: One Dimensional Array

Declaration of 1D array:

For example: if you want to store 100 integers in sequence, you can create an array for it.

data_type array_name[array_size];

Ex.: int data[100];

3.15 Accessing and storing the elements of an array

It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};


RV Institute of Technology & Management®

or

int mark[ ] = {19, 10, 8, 17, 9};

Here, the array mark is initialized as shown below.

mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9

Example: C Arrays

// Program to find the average of n (n < 10) numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number %d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
RV Institute of Technology & Management®

printf("Average = %d", average);


return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

3.16 Operations on Array

There are a number of operations that can be performed on an array which are:
1. Traversal
2. Copying
3. Reversing
4. Sorting
5. Insertion
6. Deletion
7. Searching
8. Merging

3.16.1 Traversal:
RV Institute of Technology & Management®

 Traversal means accessing each array element for a specific purpose, either to perform an
operation on them , counting the total number of elements or else using those values to calculate
some other result.
 Since array elements is a linear data structure meaning that all elements are placed in consecutive
blocks of memory it is easy to traverse them.

 Example: Write a program to calculate the average marks of a particular student:


#include <stdio.h>
#include <conio.h>

int main() {
clrscr();

int i, marks[5], n, sum = 0;


float avg;

printf("Enter the [Link] subjects:\n");


scanf("%d", &n);

printf("Enter the marks obtained in your %d subjects\n", n);

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


scanf("%d", &marks[i]);
}

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


sum = sum + marks[i];
}

avg = (sum / n);


RV Institute of Technology & Management®

printf("Average of marks is : %.2f \n", avg);

return 0;
}

3.16.2 Copying elements of an array:


 Copying array elements to another array will yield an array of the same length and elements as
the original one.
 In order to so, we need to know the length of original array in advance.
 The destination array should also be of the same or greater size as that of original array in order
to hold the array contents.
 The copying of elements would be done on index by index basis.
Example :

#include<stdio.h>

int main() {
int arr1[20], arr2[20], i, num;

printf("\nEnter the no of elements in the array :");


scanf("%d", &num);

//Accepting values into Array


printf("\nEnter the array elements :");
for (i = 0; i < num; i++) {
scanf("%d", &arr1[i]);
}

// Copying data from source array A to destination array 'b


RV Institute of Technology & Management®

for (i = 0; i < num; i++) {


arr2[i] = arr1[i];
}

//Printing of all elements of array


printf("The copied array is as follows:");
for (i = 0; i < num; i++) {
printf("\narr2[%d] = %d", i, arr2[i]);
}

return (0);
}

3.16.3 Reversing elements of an array:


 Reversing an array means that the sequence of elements of array will be reversed.
 For instance if your array ‘A’ has two elements : A[0] = 1; A[1] = 2; then after reversal A[0] = 2
and A[1] = 1.
 There are two methods to perform reversal of array.
 For the below two approaches using same logic you can later try incorporating functions and
pointers.
 Let us now see the two basic approaches.

Example :

#include <stdio.h>

int main() {
int n, i, j, a[20], b[20];

printf("Enter the number of elements in array\n");


RV Institute of Technology & Management®

scanf("%d", &n);

printf("Enter array elements\n");

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


scanf("%d", &a[i]);
}

//Copying elements into array b starting from end of array a


for (i = n - 1, j = 0; i >= 0; i--, j++) {
b[j] = a[i];
}

//Copying reversed
for (i = 0; i < n; i++) {
a[i] = b[i];
}

printf("Reversed array is\n");


for (i = 0; i < n; i++) {
printf("%d\n", a[i]);
}

return 0;
}

3.16.4 Sorting elements of an array:


 Sorting elements if array means to order the elements in ascending or descending order – usually
in ascending order.
RV Institute of Technology & Management®

 There are a number of algorithms or techniques available for sorting arrays in C, however we
shall do the basic technique here.
 Sorting techniques in depth will be covered under data structures as complete separate module.
 The basic approach to sorting is Bubble sort method where in nested loop is used to sort elements
of array.
 It is not an efficient approach however is the basic building block to understand sorting of arrays.
We will be sorting the array in ascending order.
Approach using Bubble Sort: (Ascending Order)

Create an array of fixed size.


Take n, a variable which stores the number of elements of the array, less than maximum capacity of
array.
Iterate via for loop to take array elements as input, and print them.
The array elements are in unsorted fashion, to sort them, make a nested loop.
In the nested loop, the each element will be compared to all the elements below it.
In case the element is greater than the element present below it, then they are interchanged.
After executing the nested loop, we will obtain an array in ascending order arranged elements.

#include <stdio.h>

int main() {
int i, j, temp, n, arr[30];

printf("Enter the number of elements in your array: \n");


scanf("%d", &n);

printf("Enter the array elements: \n");


for (i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}
RV Institute of Technology & Management®

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


for (j = i + 1; j < n; ++j) {
if (arr[i] > arr[j]) { //to check if current element greater than i+1th element, if yes; perform swap.
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

printf("\nThe array sorted in ascending order is as given below: \n");


for (i = 0; i < n; ++i) {
printf("%d\n", arr[i]);
}

return 0;
}

3.16.5 Insertion of an element into the array:

 Insertion of an element in the array, could either be at the start , at the end or anywhere in between
as well.
 We take the location at which the user wants to insert the element into the array.
 Next, we check if the position entered is valid or not. For the user the position would start from
number 1. Thus in terms of array index, actual array index position is position – 1
 If the position is invalid same is communicated to the user and program is terminated.
RV Institute of Technology & Management®

 The position is invalid if position is < 1 i.e. less than starting of array and position > n+1 , i.e.
if your array has 4 elements; the user might want to insert element at 4th position which is nth
position, else also insert it as the n+1th element i.e. 5th element or after the current arrays end.
 If position is valid, the element is inserted at required location and resultant array is displayed.

#include <stdio.h>
int main()
{
int array[100], position, i, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);

if(position > n+1 || position < 1)


{
printf("The position entered is invalid\n");
}
else
{
printf("Enter the value to insert\n");
scanf("%d", &value);
for (i = n - 1; i >= position - 1; i--)
array[i+1] = array[i];
array[position-1] = value; //inserting value at the required location
printf("Resultant array is:\n");
for (i = 0; i <= n; i++)
RV Institute of Technology & Management®

printf("%d\n", array[i]);
}
return 0;
}

3.16.6 .Deletion of an element from the array:


 For deletion of an element from the array, we need to accept the location from which user wishes
to delete the element.
 When the location is entered by user, we store it in a variable – position.
 For user location starts from position : 1. However array index starts from 0. Hence, when we
delete the element we need to delete element present at location = position -1.
 What we essentially do is, shift the element next to the element to be deleted to the location
= position -1, i.e. the next element is placed in position of deleted element and so on we keep
shifting the remaining elements by one position to the left.
 If an invalid location is entered, deletion is not possible an the same is conveyed to the user.
#include <stdio.h>
int main()
{
int array[100], position, i, n, num;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter the location from where you wish to delete the element:\n");
scanf("%d", &position);

num = array[position-1];
if (position >= n+1 || position < 0) /*n+1, since user will count element as position 1
onwards. Internally though indexing starts from 0,
RV Institute of Technology & Management®

which user would not know.*/


printf("Deletion not possible as entered location is invalid.\n");
else
{
for (i = position - 1; i < n - 1; i++) //since array index starts from 0; thus position in terms
of array index is position-1
array[i] = array[i+1];
printf("Resultant array after deletion of element %d from location %d:\n", num, position);
for (i = 0; i < n - 1; i++)
printf("%d\n", array[i]);
}
return 0;
}

[Link] element of an array:


⮚ Searching algorithm Definition: A search algorithm is the step-by-step procedure used to
locate specific data among a collection of data. It is considered a fundamental procedure in
computing. In computer science, when searching for data, the difference between a fast application
and a slower one often lies in the use of the proper search algorithm.

These algorithms are generally classified into two categories:

1. Sequential Search: In this, the list or array is traversed sequentially and every element is
checked. For example: Linear Search.
2. Interval Search: These algorithms are specifically designed for searching in sorted data-
structures. This type of searching algorithms are much more efficient than Linear Search as they
repeatedly target the center of the search structure and divide the search space in half. For
Example: Binary Search.

⮚ Sorting Algorithm Definition: A sorting algorithm is an algorithm that puts elements of a list
in a certain order. Efficient sorting is important for optimizing the efficiency of
RV Institute of Technology & Management®

other algorithms (such as search and merge algorithms) which require input data to be in sorted
lists.

These algorithms are generally classified into six categories:

1. Bubble Sort.
2. Selection Sort.
3. Merge Sort.
4. Insertion Sort.
5. Quick Sort.
6. Heap Sort.

3.6 Searching algorithm- 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. Fig 3.4 shows an illustration of Linear Search algorithm.

Fig 3.4: Linear Search Algorithm

Implementing Linear Search

The steps to implement linear search:


RV Institute of Technology & Management®

1. Traverse the array using a for loop.


2. In every iteration, compare the target value with the current value of the array.
▪ If the values match, return the current index of the array.
▪ If the values do not match, move on to the next array element.
3. If no match is found, return -1.

🖳 Write a ‘C’ Program to search an element using Linear search

#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);

printf("Enter %d integer(s)\n", n);


for (c = 0; c < n; c++)
scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

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


{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
RV Institute of Technology & Management®

}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}

3.7 Searching algorithm- Binary Search


Binary search is a fast search algorithm and works on the principle of divide and conquer. For this
algorithm to work properly, the data collection should be in the sorted form.

Binary search looks for a particular item by comparing the middle most item of the collection. If a
match occurs, then the index of item is returned. If the middle item is greater than the item, then the
item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in
the sub-array to the right of the middle item. This process continues on the sub-array as well until the
size of the subarray reduces to zero. Fig 3.5 shows the illustration of Binary Search Algorithm.

Fig 3.7: Binary Search Algorithm

How Binary Search Works?


RV Institute of Technology & Management®

For a binary search to work, it is mandatory for the target array to be sorted. We shall learn the process
of binary search with a pictorial example. The following is our sorted array and let us assume that we
need to search the location of value 31 using binary search.

First, we shall determine half of the array by using this formula −

mid = low + (high - low) / 2

Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that
the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a sorted
array, so we also know that the target value must be in the upper portion of the array.

We change our low to mid + 1 and find the new mid value again.

low = mid + 1
mid = low + (high - low) / 2

Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
RV Institute of Technology & Management®

The value stored at location 7 is not a match, rather it is more than what we are looking for. So, the
value must be in the lower part from this location.

Hence, we calculate the mid again. This time it is 5.

We compare the value stored at location 5 with our target value. We find that it is a match.

We conclude that the target value 31 is stored at location 5.

Binary search halves the searchable items and thus reduces the count of comparisons to be made to
very less numbers.

Write a ‘C’ Program to search an element using Binary search

#include <stdio.h>
RV Institute of Technology & Management®

int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d",&n);

printf("Enter %d integers\n", n);

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


scanf("%d",&array[c]);

printf("Enter value to find\n");


scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
RV Institute of Technology & Management®

if (first > last)


printf("Not found! %d isn't present in the list.\n", search);
return 0;
}

3.16.8 Merging of two arrays:


 Two arrays are taken as input from the user in order to merge them into a resultant array ‘res‘.
 The arrays can be sorted or unsorted.
 You can either after taking the input from the user, sort the array else after merging sort the array.
 In our case, we first merge the array and then sort them.
 For sorting, we use the basic bubble sort technique to sort the array in ascending order as
previously seen in sorting an array program.
 Since in our case, we sort the array post merging, initially you can simply save elements of arr1
and arr2 into result in the entered order itself.
 However, we have written the code for merge considering that if the array input by user is
already sorted then the merge function alone would suffice the need.
 The function, compares the elements of the two arrays and inserts the elements in the ascending
order into res array.
 Since, we do not know if user will always enter a sorted array, we sort the resultant array res post
merging as well.
Code:
#include<stdio.h>
void merge(int arr1[20], int arr2[20], int n1, int n2) //merging arrays
{
int i, j, k;
int res[40];

i = 0;
j = 0;
k = 0;
RV Institute of Technology & Management®

// Merging starts
while (i < n1 && j < n2)
{
if (arr1[i] <= arr2[j])
{
res[k] = arr1[i];
i++;
k++;
}
else
{
res[k] = arr2[j];
k++;
j++;
}
}
/* Some elements in array 'arr1' are still remaining where as array 'arr2' is exhausted */
while (i < n1)
{
res[k] = arr1[i];
i++;
k++;
}
/* Some elements in array 'arr2' are still remaining where as array 'arr1' is exhausted */
while (j < n2)
{
res[k] = arr2[j];
k++;
j++;
}
RV Institute of Technology & Management®

sort(res, (n1+n2));
//Displaying elements of array 'res'
printf("\nMerged array is :");
for (i = 0; i < n1 + n2; i++)
printf("\n%d", res[i]);
}
void sort(int arr[20], int n) //to sort the resultant array
{
int i, j, swap;

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


{
for (j= 0 ; j < n - i - 1; j++)
{
if (arr[j] > arr[j+1]) /* For decreasing order use < */
{
swap = arr[j];
arr[j] = arr[j+1];
arr[j+1] = swap;
}
}
}
}
int main()
{
int arr1[20], arr2[20];
int i, n1, n2;
printf("Enter no of elements in 1st array :\n");
scanf("%d", &n1);
printf("Enter elements of 1st array : \n");
RV Institute of Technology & Management®

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


{
scanf("%d", &arr1[i]);
}
printf("\nEnter no of elements in 2nd array :\n");
scanf("%d", &n2);
printf("Enter elements of 2nd array : \n");
for (i = 0; i < n2; i++)
{
scanf("%d", &arr2[i]);
}
merge(arr1, arr2, n1, n2);
return 0;
}

Sorting algorithms - Bubble Sort

Bubble sort algorithm starts by comparing the first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first element is
greater than second then, you need to swap the elements but, if the first element is smaller than second,
you mustn't swap the element. Then, again second and third elements are compared and swapped if
it is necessary and this process go on until last and second last element is compared and swapped.
This completes the first step of bubble sort.

If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times
to get required result. But, for better performance, in second step, last and second last elements are
not compared because; the proper element is automatically placed at last after first step. Similarly, in
third step, last and second last and second last and third last elements are not compared and so on.
Fig 3.6 shows the working of bubble sort algorithm.
RV Institute of Technology & Management®

Fig 3.6: Working of Bubble Sort Algorithm

🖳 Write a ‘C’ Program to sort the elements using Bubble sort

/*C Program To Sort data in ascending order using bubble sort.*/

#include <stdio.h>

int main()

int data[100],i,n,step,temp;

printf("Enter the number of elements to be sorted: ");

scanf("%d",&n);

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

printf("%d. Enter element: ",i+1);

scanf("%d",&data[i]);

for(step=0;step<n-1;++step)

for(i=0;i<n-step-1;++i)
RV Institute of Technology & Management®

if(data[i]>data[i+1]) /* To sort in descending order, change > to < in this line. */

temp=data[i];

data[i]=data[i+1];

data[i+1]=temp;

printf("In ascending order: ");

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

printf("%d ",data[i]);

return 0;

Enter the number of elements to be sorted: 6


1. Enter element: 12
2. Enter element: 3
3. Enter element: 0
4. Enter element: -3
5. Enter element: 1
6. Enter element: -9
In ascending order: -9 -3 0 1 3 13

✔ Sorting algorithms - Selection Sort


RV Institute of Technology & Management®

Selection sort algorithm starts by comparing first two elements of an array and swapping if necessary,
i.e., if you want to sort the elements of array in ascending order and if the first element is greater than
second then, you need to swap the elements but, if the first element is smaller than second, leave the
elements as it is. Then, again first element and third element are compared and swapped if necessary.
This process goes on until first and last element of an array is compared. This completes the first step
of selection sort.

If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times
to get required result. But, for better performance, in second step, comparison starts from second
element because after first step, the required number is automatically placed at the first (i.e, In case
of sorting in ascending order, smallest element will be at first and in case of sorting in descending
order, largest element will be at first.). Similarly, in third step, comparison starts from third element
and so on. Fig 3.7 shows the working of selection sort algorithm and Fig 3.8 shows the flowchart of
selection sort algorithm.

Fig 3.8: Working of Selection Sort Algorithm


RV Institute of Technology & Management®

Write a ‘C’ Program to sort the elements using Selection Sort

#include <stdio.h>
RV Institute of Technology & Management®

int main()
{
int data[100],i,n,steps,temp;
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("%d. Enter element: ",i+1);
scanf("%d",&data[i]);
}
for(steps=0;steps<n;++steps)
for(i=steps+1;i<n;++i)
{
if(data[steps]>data[i])

/* To sort in descending order, change > to <. */


{
temp=data[steps];
data[steps]=data[i];
data[i]=temp;
}
}
printf("In ascending order: ");
for(i=0;i<n;++i)
printf("%d ",data[i]);
return 0;
}
RV Institute of Technology & Management®

3.17. Passing Arrays to a Function

Whenever we need to pass a list of elements as argument to any function in C language, it is prefered to do so
using an array. But how can we pass an array as argument to a function? Let's see how it is done.

⮚ Declaring Function with array as a parameter


There are two possible ways to do so, one by using call by value and other by using call by reference.
1. We can either have an array as a parameter.
int sum (int arr[]);
2. Or, we can have a pointer in the parameter list, to hold the base address of our array.
int sum (int* ptr);
We will study the second way in details later when we will study pointers.

⮚ Passing arrays as parameter to function


Now let's see a few examples where we will pass a single array element as argument to a function, a one
dimensional array to a function and a multidimensional array to a function.

✔ Passing a single array element to a function


Let's write a very simple program, where we will declare and define an array of integers in our main()function
and pass one of the array element to a function, which will just print the value of the element.

#include<stdio.h>
void giveMeArray(int a);

int main()
{
int myArray[] = { 2, 3, 4 };
giveMeArray(myArray[2]); //Passing array element myArray[2] only.
return 0;
}
RV Institute of Technology & Management®

void giveMeArray(int a)
{
printf("%d", a);
}
Output
4

✔ Passing a complete One-dimensional array to a function

To understand how this is done, let's write a function to find out average of all the elements of the array and print
it. We will only send in the name of the array as argument, which is nothing but the address of the starting element
of the array, or we can say the starting memory address.

#include<stdio.h>
float findAverage(int marks[]);

int main()
{
float avg;
int marks[] = {99, 90, 96, 93, 95};
avg = findAverage(marks); // name of the array is passed as argument.
printf("Average marks = %.1f", avg);
return 0;
}

float findAverage(int marks[])


{
int i, sum = 0;
float avg;
RV Institute of Technology & Management®

for (i = 0; i <= 4; i++) {


sum += marks[i];
}
avg = (sum / 5);
return avg;
}
Output:
94.6

3.18 Two dimensional arrays:

Array having more than one subscript variable is called Multi-dimensional array.
Multi-Dimensional Array is also called as Matrix.

Ex. An 2D array int a[3][3], is shown in the Fig.3.3

Fig 3.3: 2D array of integers

How to initialize 2D-arrays?

There is more than one way to initialize a multidimensional array.

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};


RV Institute of Technology & Management®

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

3.19. Operations on two-dimensional arrays

Update Elements in 2-D Arrays


The updating of elements in an array can be done by either specifying a particular element to be
replaced or by identifying a position where the replacement has to be done. For updating, we generally
require the following details.
1. Elements of an array
2. Position/element, where it has to be inserted
3. The value to be inserted.
For updating the data in an array through element details, first, we need to search for that element in
the array, understand it’s the position, and then replace the old element with the new element.
Here, we have given below two examples of updating the element of a 2-D array.
Firstly, let us go through an example where the position of the element to be updated is already known.
#include <stdio.h>
int main()
{
int b[2][3];
int i,j,num;
printf("Enter elements into 2-D array: ");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d" , &b[i][j]);
RV Institute of Technology & Management®

}
}
b[0][2]=10;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\t%d" , b[i][j]);
}
printf("\n");
}
return 0;
}
In the above program, the element on the 1st row and 3rd column are selected and the value of the data
in that position has been updated.

In the second example, we are going to show how the position of the element can be dynamically
taken as a user inputted value and update the value of the element at that particular position.
#include <stdio.h>
int main()
{
int b[2][3];
int i,j,num;
printf("Enter elements into 2-D array: ");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d" , &b[i][j]);
}
RV Institute of Technology & Management®

}
printf("Enter the value of row and coulmn number :");
scanf("%d %d", &i,&j);
printf("Enter the number you want to update with: ");
scanf("%d" , &num);
b[i][j]=num;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\t%d" , b[i][j]);
}
printf("\n");
}
return 0;
}
Here, we used the scanf function to read the value given by the user as per their choice for the position
of an element based on row and column numbers.

Deleting Elements in 2-D Arrays


After the concepts of insertion and updating of the data inside the array, let’s now see how we can
delete an entire row from the array.
We have written a program in a simple format so that the concept of different operations in a 2-d
array can be understood easily.
#include <stdio.h>
int main()
{
int b[2][3],i,j,num,x;
printf("Enter elements into 2-D array: ");
for(i=0;i<2;i++)
RV Institute of Technology & Management®

{
for(j=0;j<3;j++)
{
scanf("%d" , &b[i][j]);
}
}
printf("Enter the value of row number :");
scanf("%d", &x);
for(i=0;i<2;i++)
{
if(i==x)
{
for(j=0;j<3;j++)
{
if((i+1)<2)
{
printf("\t%d" , b[i+1][j]);
}
}
i++;}
else
{
for(j=0;j<3;j++)
{
printf("\t%d" , b[i][j]);
}
}
printf("\n");
}
}
RV Institute of Technology & Management®

The steps followed are:


1. Took the values of an array dynamically
2. Asked the user to input the number (index) of the row that has to be deleted.
3. Using for loop iteration, we are comparing if the row number and the user input number are
matching or not.
4. If they are matching and if the row number is less than the size of an array, we are printing the
next row. Else, we are printing the row as it is.

3.20 Two-dimensional arrays to functions

✔ Passing a two-dimensional array to a function


Here again, we will only pass the name of the array as argument.

#include<stdio.h>
void displayArray(int arr[3][3]);

int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing the array as argument
displayArray(arr);
return 0;
RV Institute of Technology & Management®

void displayArray(int arr[3][3])


{
int i, j;
printf("The complete array is: \n");
for (i = 0; i < 3; ++i)
{
// getting cursor to new line
printf("\n");
for (j = 0; j < 3; ++j)
{
// \t is used to provide tab space
printf("%d\t", arr[i][j]);
}
}
}
Output:
Please enter 9 numbers for the array:
1
2
3
4
5
6
7
8
9
The complete array is:
123
RV Institute of Technology & Management®

456
789

3.21 Arrays Contd.. and Example programs

// C program to find the sum of two matrices of order 2*2


#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter a%d%d: ", i+1, j+1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter b%d%d: ", i+1, j+1);
RV Institute of Technology & Management®

scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

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


for(j=0; j<2; ++j)
{
printf("%.1f\t", c[i][j]);

if(j==1)
printf("\n");
}
return 0;
}

Output

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
RV Institute of Technology & Management®

Enter elements of 2nd matrix


Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum of Matrix:
2.2 0.5
-0.9 25.0

3.22 Multi-dimensional Arrays

Multidimensional Arrays in C / C++

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form.
Data in multidimensional arrays are stored in row-major order.

The general form of declaring N-dimensional arrays is:

data_type array_name[size1][size2]....[sizeN];

 data_type: Type of data to be stored in the array.

 array_name: Name of the array

 size1, size2,… ,sizeN: Sizes of the dimension

Examples:

Two dimensional array: int two_d[10][20];

Three dimensional array: int three_d[10][20][30];

Size of Multidimensional Arrays:


RV Institute of Technology & Management®

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying
the size of all the dimensions.
For example:

 The array int x[10][20] can store total (10*20) = 200 elements.

 Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

Three-Dimensional Array

Initializing Three-Dimensional Array:

Initialization in a Three-Dimensional array is the same as that of Two-dimensional arrays. The difference is as
the number of dimensions increases so the number of nested braces will also increase.

Method 1:

int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

11, 12, 13, 14, 15, 16, 17, 18, 19,

20, 21, 22, 23};


RV Institute of Technology & Management®

Method 2(Better):

int x[2][3][4] =

{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },

{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }

};

Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional Arrays is also


similar to that of Two-Dimensional Arrays. The difference is we have to use three loops instead of two loops
for one additional dimension in Three-dimensional Arrays.

 CPP

 C

// C++ program to print elements of Three-Dimensional

// Array

#include <iostream>

using namespace std;

int main()

// initializing the 3-dimensional array

int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },

{ { 6, 7 }, { 8, 9 }, { 10, 11 } } };

// output each element's value


RV Institute of Technology & Management®

for (int i = 0; i < 2; ++i) {

for (int j = 0; j < 3; ++j) {

for (int k = 0; k < 2; ++k) {

cout << "Element at x[" << i << "][" << j

<< "][" << k << "] = " << x[i][j][k]

<< endl;

return 0;

Output:

Element at x[0][0][0] = 0

Element at x[0][0][1] = 1

Element at x[0][1][0] = 2

Element at x[0][1][1] = 3

Element at x[0][2][0] = 4

Element at x[0][2][1] = 5

Element at x[1][0][0] = 6

Element at x[1][0][1] = 7

Element at x[1][1][0] = 8

Element at x[1][1][1] = 9

Element at x[1][2][0] = 10

Element at x[1][2][1] = 11
RV Institute of Technology & Management®

In similar ways, we can create arrays with any number of dimensions. However, the complexity also increases
as the number of dimensions increases. The most used multidimensional array is the Two-Dimensional Array.

Practice Programs:

1. Write a C program to calculate Average Using Arrays.


Solution:
#include <stdio.h>

int main()

int n, i;
float num[100], sum=0.0, average;
printf("Enter the numbers of data: ");
scanf("%d",&n);
while (n>100 || n<=0)

printf("Error! number should in range of (1 to 100).\n");


printf("Enter the number again: ");
scanf("%d",&n);

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

printf("%d. Enter number: ",i+1);


scanf("%f",&num[i]);
sum+=num[i];
}
RV Institute of Technology & Management®

average=sum/n;

printf("Average = %.2f",average);
return 0;
}

Output

Enter the numbers of data: 6

1. Enter number: 45.3

2. Enter number: 67.5

3. Enter number: -45.6

4. Enter number: 20.34

5. Enter number: 33

6. Enter number: 45.6


Average = 27.69
This program calculates the average if the number of data is from 1 to 100. If user enters value of
n above 100 or below 100 then, while loop is executed which asks user to enter value of n until it
is between 1 and 100.

2. Write a C program to Display Largest Element of an array

#include <stdio.h>
int main()
{
int i,n;
float arr[100];
RV Institute of Technology & Management®

printf("Enter total number of elements(1 to 100): ");


scanf("%d",&n);
printf("\n");
for(i=0;i<n;++i) /* Stores number entered by user. */
{
printf("Enter Number %d: ",i+1);
scanf("%f",&arr[i]);
}
for(i=1;i<n;++i) /* Loop to store largest number to arr[0] */
{
if(arr[0]<arr[i]) /* Change < to > if you want to find smallest element*/
arr[0]=arr[i];
}
printf("Largest element = %.2f",arr[0]);
return 0;
}

Output

Enter total number of elements(1 to 100): 8


Enter Number 1: 23.4
Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5
RV Institute of Technology & Management®

This program takes n number of elements from user and stores it in array arr[]. To find the largest element,
the first two elements of array are checked and largest of these two element is placed in arr[0]. Then, the first
and third elements are checked and largest of these two element is placed in arr[0]. This process continues
until and first and last elements are checked. After this process, the largest element of an array will be in
arr[0] position.

3. Write a C program to multiply to matrix in C programming

#include <stdio.h>

int main()

int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;

printf("Enter rows and column for first matrix: ");

scanf("%d%d", &r1, &c1);

printf("Enter rows and column for second matrix: ");

scanf("%d%d",&r2, &c2);

/* If column of first matrix in not equal to row of second matrix, asking user to enter the size of matrix
again. */

while (c1!=r2)

printf("Error! column of first matrix not equal to row of second.\n\n");

printf("Enter rows and column for first matrix: ");

scanf("%d%d", &r1, &c1);


RV Institute of Technology & Management®

printf("Enter rows and column for second matrix: ");

scanf("%d%d",&r2, &c2);

/* Storing elements of first matrix. */

printf("\nEnter elements of matrix 1:\n");

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

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

printf("Enter elements a%d%d: ",i+1,j+1); scanf("%d",&a[i][j]);

/* Storing elements of second matrix. */

printf("\nEnter elements of matrix 2:\n");

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

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

printf("Enter elements b%d%d: ",i+1,j+1); scanf("%d",&b[i][j]);

/* Initializing elements of matrix mult to 0.*/

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

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


RV Institute of Technology & Management®

mult[i][j]=0;

/* Multiplying matrix a and b and storing in array mult. */

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

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

for(k=0; k<c1; ++k)

mult[i][j]+=a[i][k]*b[k][j];

/* Displaying the multiplication of two matrix. */ printf("\nOutput Matrix:\n");

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

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

printf("%d ",mult[i][j]);

if(j==c2-1)

printf("\n\n");

return 0;

Output
RV Institute of Technology & Management®

Enter rows and column for first matrix: 3 2


Enter rows and column for second matrix: 3 2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2 3


Enter rows and column for second matrix: 3 2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29
6 25

In this program, user is asked to enter the size of two matrix at first. The column of first matrix should be
equal to row of second matrix for multiplication. If this condition is not satisfied then, the size of matrix is
again asked using while loop. Then, user is asked to enter two matrix and finally the output of two matrix is
calculated and displayed.
This program is little bit larger and it is better to solve this program by passing it to a function.
RV Institute of Technology & Management®

3.22 Applications of Arrays

 Arrays are used to implement data structures like a stack, queue, etc.
 Arrays are used for matrices and other mathematical implementations.
 Arrays are used in lookup tables in computers.
 Arrays can be used for CPU scheduling.

Real-time applications of arrays.

 Contact lists on mobile phones.

 Matrices use arrays which are used in different fields like image processing, computer graphics, and
many more.

 Arrays are used in online ticket booking portals.

 Pages of book.

 IoT applications use arrays as we know that the number of values in an array will remain constant, and
also that the accessing will be faster.

 It is also utilised in speech processing, where each speech signal is represented by an array.

 The viewing screen of any desktop/laptop is also a multidimensional array of pixels.

You might also like