C Programming: User-Defined Functions Guide
C Programming: User-Defined Functions Guide
Module – 3
For example:
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("sum = %d",sum);
return 0;
}
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®
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.
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.
[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.
In the above example, int addNumbers(int a, int b); is the function prototype which provides following
information to the compiler:
The function prototype is not needed if the user-defined function is defined before the main() function.
In the above example, function call is made using addNumbers(n1,n2); statement inside the main().
RV Institute of Technology & Management®
⮚ 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
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.
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);
}
*p = *p + 10;
Output:
Value of x is 20
}
Output
4
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.
An automatic or local variable can be declared in any user define function in the starting of the block.
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.
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.
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®
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.
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®
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.
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.
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®
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.
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.
#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.
#include <stdio.h>
{
RV Institute of Technology & Management®
if(i <= 1) {
return 1;
int main()
int i = 12;
return 0;
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
#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:
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')
if (c =='b' || c == 'B')
return 0;
RV Institute of Technology & Management®
rem=n%2;
return binary;
++i;
return decimal;
RV Institute of Technology & Management®
Output:
Instructions:
#include<stdio.h>
int main()
{
char str[100];
int length;
printf("\nEnter the String : ");
gets(str);
length = FindLength(str);
return(0);
}
{
RV Institute of Technology & Management®
int len = 0;
while (str[len] != '\0')
len++;
return (len);
Arrays
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.
▪ Types of Arrays
RV Institute of Technology & Management®
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];
or
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
#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®
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.
int main() {
clrscr();
return 0;
}
#include<stdio.h>
int main() {
int arr1[20], arr2[20], i, num;
return (0);
}
Example :
#include <stdio.h>
int main() {
int n, i, j, a[20], b[20];
scanf("%d", &n);
//Copying reversed
for (i = 0; i < n; i++) {
a[i] = b[i];
}
return 0;
}
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)
#include <stdio.h>
int main() {
int i, j, temp, n, arr[30];
return 0;
}
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);
printf("%d\n", array[i]);
}
return 0;
}
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®
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.
1. Bubble Sort.
2. Selection Sort.
3. Merge Sort.
4. Insertion Sort.
5. Quick Sort.
6. Heap Sort.
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.
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
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.
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.
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.
We compare the value stored at location 5 with our target value. We find that it is a match.
Binary search halves the searchable items and thus reduces the count of comparisons to be made to
very less numbers.
#include <stdio.h>
RV Institute of Technology & Management®
int main()
{
int c, first, last, middle, n, search, array[100];
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;
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®
#include <stdio.h>
int main()
int data[100],i,n,step,temp;
scanf("%d",&n);
for(i=0;i<n;++i)
scanf("%d",&data[i]);
for(step=0;step<n-1;++step)
for(i=0;i<n-step-1;++i)
RV Institute of Technology & Management®
temp=data[i];
data[i]=data[i+1];
data[i+1]=temp;
for(i=0;i<n;++i)
printf("%d ",data[i]);
return 0;
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.
#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])
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.
#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
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;
}
Array having more than one subscript variable is called Multi-dimensional array.
Multi-Dimensional Array is also called as Matrix.
}
}
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.
{
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®
#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®
456
789
scanf("%f", &b[i][j]);
}
if(j==1)
printf("\n");
}
return 0;
}
Output
Sum of Matrix:
2.2 0.5
-0.9 25.0
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.
data_type array_name[size1][size2]....[sizeN];
Examples:
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
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:
Method 2(Better):
int x[2][3][4] =
};
CPP
C
// Array
#include <iostream>
int main()
int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },
{ { 6, 7 }, { 8, 9 }, { 10, 11 } } };
<< 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:
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)
average=sum/n;
printf("Average = %.2f",average);
return 0;
}
Output
5. Enter number: 33
#include <stdio.h>
int main()
{
int i,n;
float arr[100];
RV Institute of Technology & Management®
Output
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.
#include <stdio.h>
int main()
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)
scanf("%d%d",&r2, &c2);
mult[i][j]=0;
mult[i][j]+=a[i][k]*b[k][j];
printf("%d ",mult[i][j]);
if(j==c2-1)
printf("\n\n");
return 0;
Output
RV Institute of Technology & Management®
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®
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.
Matrices use arrays which are used in different fields like image processing, computer graphics, and
many more.
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.