Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit II Arrays

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Arrays in C Programming Language

Arrays in C programming language


When we need to store multiple values of same type like names of 10 students, 50 mobile numbers,
weight of 100 people. In this case, to declare and manage different variables to store separate values
are really tough and unmanageable.

As the number of variables increases, the complexity of the program also increases and so the
programmers get confused with the variable names. There may be situations where we need to work
with a large number of similar data values.

C programming language provides an amazing feature to deal with such kind of situations that is
known as "Arrays".

An "Array" is a group of similar data type to store series of homogeneous pieces of data that all are
same in type.

It is a derived data type which is created with the help of basic data type. An array takes contiguous
memory blocks to store series of values.

There are three types of an array:

1) One Dimensional (One-D) Array,


2) Multi-Dimensional Array.
a. Two Dimensional (2-D) Array,
b. Three Dimensional (3-D) Array and
c. More Dimensional Array

One Dimensional (One-D) Array


In C programming language, when we want to create an array we must know the datatype of values
to be stored in that array and also the number of values to be stored in that array.

We use the following general syntax to create an array...

datatype arrayName [ size ] ;

Syntax for creating an array with size and initial values

datatype arrayName [ size ] = {value1, value2, ...} ;

Syntax for creating an array without size and with initial values

datatype arrayName [ ] = {value1, value2, ...} ;

In the above syntax, the datatype specifies the type of values we store in that array and size specifies
the maximum number of values that can be stored in that array.

int a[3];

Here, the compiler allocates 12 bytes of contiguous memory locations with a single name 'a' and tells
the compiler to store three different integer values (each in 4 bytes of memory) into that 12 bytes of
memory. For the above declaration, the memory is organized as follows...

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
In the above memory allocation, all the three memory locations have a common name 'a'. So accessing
individual memory location is not possible directly. Hence compiler not only allocates the memory but
also assigns a numerical reference value to every individual memory location of an array. This
reference number is called "Index" or "subscript" or "indices". Index values for the above example are
as follows...

Accessing Individual Elements of an Array


The individual elements of an array are identified using the combination of 'arrayName' and
'indexValue'. We use the following general syntax to access individual elements of an array...

arrayName [ indexValue ] ;

For example, if we want to assign a value to the second memory location of above array 'a', we use
the following statement..

a[1]=100

You can access elements of an array by indices.


Suppose you declared an array mark as above. The first element is mark[0], the second
element is mark[1] and so on.

Few keynotes:
 Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
 If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
 Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1]
will be 2124d. Similarly, the address of mark[2] will be 2128d and so on.
 This is because the size of a int & float is 4 bytes.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Array Manipulation

Initialize an array

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

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

You can also initialize an array like this.

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

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.

Here,

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

Change Value of Array elements


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

// make the value of the third element to -1


mark[2] = -1;

// make the value of the fifth element to 0


mark[4] = 0;

Input and Output Array Elements


Here's how you can take input from the user and store it in an array element.
// take input and store it in the 3rd element
scanf("%d", &mark[2]);

// take input and store it in the ith element


scanf("%d", &mark[i-1]);

Here's how you can print an individual element of an array.


// print the first element of the array
printf("%d", mark[0]);
// print the third element of the array

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
printf("%d", mark[2]);

// print ith element of the array


printf("%d", mark[i-1]);

Example 1: Array Input/Output


// Program to take 5 values from the user and store them in an
array
// Print the elements stored in the array
#include <stdio.h>

int main() {
int values[5],i;

printf("Enter 5 integers: ");

// taking input and storing it in an array


for( i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
Output:
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
Here, we have used a for or any loop to take 5 inputs from the user and store them in an
array. Then, using another for or any loop, these elements are displayed on the screen.

Example 2: Calculate Average


// Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;

printf("Enter number of elements: ");

scanf("%d", &n);

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

// adding integers entered by the user to the sum variable


sum += marks[i];
}

average = sum/n;
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

Here, we have computed the average of n numbers entered by the user.

Access elements out of its bound!


Suppose you declared an array of 10 elements. Let's say,
int testArray[10];

You can access the array elements from testArray[0] to testArray[9].

Now let's say if you try to access testArray[12]. The element is not available. This may
cause unexpected output (undefined behaviour). Sometimes you might get an error and some
other time your program may run correctly.
Hence, you should never access elements of an array outside of its bound.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Searching an element/s from an Array
Searching is a process by which we can check whether an element is present within a set of
elements or not. If it present we can also find the position of that element in the list. There
are two algorithm for searching an element from an array.

 Linear Search
 Binary Search

Linear Search Algorithm (Sequential Search Algorithm)


Linear search algorithm finds a given element in a list of elements with O(n) (Big O of n) time
complexity where n is total number of elements in the list. This search process starts
comparing search element with the first element in the list. If both are matched then result
is element found otherwise search element is compared with the next element in the list.
Repeat the same until search element is compared with the last element in the list, if that last
element also doesn't match, then the result is "Element not found in the list". That means,
the search element is compared with element by element in the list.
Linear search is implemented using following steps...
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the first element in the list.
Step 3 - If both are matched, then display "Given element is found!!!" and terminate
the function
Step 4 - If both are not matched, then compare search element with the next element
in the list.
Step 5 - Repeat steps 3 and 4 until search element is compared with last element in
the list.
Step 6 - If last element in the list also doesn't match, then display "Element is not
found!!!" and terminate the function.

Step by step descriptive logic to search element in array using linear search algorithm.

1. Input size and elements in array from user. Store it in some variable say size and arr.
2. Input number to search from user in some variable say toSearch.
3. Define a Count variable as Count = 0. I have initialized count with 0, which means
initially I have assumed that searched element does not exists in array.
4. Run loop from 0 to size. Loop structure should look like
for(i=0; i<size; i++).
5. Inside loop check if current array element is equal to searched number or not. Which
is if(arr[i] == toSearch) then set count = 1 and terminate from loop. Since
element is count no need to continue further.
Outside loop if(count == 1) then element is found otherwise not.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Example: Consider the following list of elements and the element to be searched...

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
/*** C program to search element in array */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size

int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, count;

/* Input size of array */


printf("Enter size of array: ");
scanf("%d", &size);

/* Input elements of array */


printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

printf("\nEnter element to search: ");


scanf("%d", &toSearch);

/* Assume that element does not exists in array */


found = 0;

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


{
/*
* If element is found in array then raise found flag
* and terminate from loop.
*/
if(arr[i] == toSearch)
{
count = 1;
break;
}
}

/*
* If element is not found in array
*/
if(count == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array", toSearch);
}

return 0;
}

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Binary Search Algorithm
Binary search algorithm finds a given element in a list of elements with O(log n) (Bid O of log
n time) time complexity where n is total number of elements in the list. The binary search
algorithm can be used with only a sorted list of elements. That means the binary search is
used only with a list of elements that are already arranged in an order. The binary search
cannot be used for a list of elements arranged in random order. This search process starts
comparing the search element with the middle element in the list. If both are matched, then
the result is "element found". Otherwise, we check whether the search element is smaller or
larger than the middle element in the list. If the search element is smaller, then we repeat the
same process for the left sub list of the middle element. If the search element is larger, then
we repeat the same process for the right sub list of the middle element. We repeat this
process until we find the search element in the list or until we left with a sub list of only one
element. And if that element also doesn't match with the search element, then the result is
"Element not found in the list".
So to implement the binary searching we need to learn sorting.

Sorting of an Array elements

Sorting is a process by which we can arrange the elements in a specific order. The order may
increasing or decreasing. By default it is increasing. There are several algorithm are available
to sort an array. They are
 Bubble sort
 Selection sort
 Insertion sort

Bubble sort
Bubble Sort in C is a sorting algorithm where we repeatedly iterate through the array and
swap adjacent elements that are unordered. We repeat this until the array is sorted.
How Bubble Sort Works?
1) Starting from the first index, compare the first and the second elements. If the first
element is greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if they are not in order.
The above process goes on until the last element.
2) The same process goes on for the remaining iterations. After each iteration, the largest
element among the unsorted elements is placed at the end.
In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct
positions.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language

Step by step descriptive logic to sort array in ascending order.

1. Input size of array and elements in array. Store it in some variable say size and arr.
2. To select each element from array, run an outer loop from 0 to size - 1. The
loop structure must look like for(i=0; i<size; i++).
3. Run another inner loop from i + 1 to size - 1 to place currently selected
element at its correct position. The loop structure should look like
for(j = i + 1; j<size; j++).
4. Inside inner loop to compare currently selected element with subsequent element
and swap two array elements if not placed at its correct position.
Which is if(arr[i] > arr[j]) then swap arr[i] with arr[j].

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
/*** C program to sort elements of array in ascending order */

#include <stdio.h>
int main()
{
int size;
int i, j, temp;

/* Input size of array */


printf("Enter size of array: ");
scanf("%d", &size);
int arr[size];
/* Input elements in array */
printf("Enter elements in array: ");
for(i=0; i<size; i++) {
scanf("%d", &arr[i]);
}
for(i=0; i<size; i++){
/* * Place currently selected element array[i]
* to its correct place.
*/ Sorting
for(j=i+1; j<size; j++){
/** Swap if currently selected array element Logic
* is not at its correct position.
*/
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
/* Print the sorted array */
printf("\nElements of array in ascending order: ");
for(i=0; i<size; i++){
printf("%d\t", arr[i]);
}
return 0;
}
Modified logic for bubble sort
for(i=0; i<size-1; i++)
{
swap=0;
for(j=0; j<size-i-1; j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j+1];
arr[j] = arr[j+1];
arr[j+1] = temp;
swap++;
}
}
if(swap==0)
break;
}

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Selection sort
The basic theory of this sorting technique is first find the smallest element in given list and
then this element will be interchanged with the element of first position. Now first element
is in its proper position and the rest of elements are unsorted. So, consider the rest of
elements agin find the smallest element in rest of elements and then this element will be
interchanged with the element of next position and so on..
This process continues by selecting the smallest element from the rest and placed it into its
proper position by
interchanging with logical
next element.
As in each iteration
corresponding smallest
elements are selected and
placed into their proper
position, this algorithm is
known as SLECTION sort.
As in each pass a single
element willmove to its
required position, there are
n-1 pass will be required to
sort an array.

/*** C program to sort elements of array in ascending order */

#include <stdio.h>
int main()
{
int size;
int i, j, temp,min,p;

/* Input size of array */


printf("Enter size of array: ");
scanf("%d", &size);
int arr[size];
/* Input elements in array */
printf("Enter elements in array: ");
for(i=0; i<size; i++) {
scanf("%d", &arr[i]);
}

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
/* Before sort elements in array */
printf("Before sorting elements in array: ");
for(i=0; i<size; i++) {
printf("%d\t", arr[i]);
}
for(i=0;i<size-1;i++){
min=arr[i];
p=i;
for(j=i+1;j<size;j++)
{
if(arr[j]<min){
min=arr[j];
p=j; Sorting
} Logic
}
if(p!=i){
temp=arr[i];
arr[i]=arr[p];
arr[p]=temp;
}
/* At each iteration elements in array */
printf("At %d iteration elements in array: ",i);
for(k=0; k<size; k++) {
printf("%d\t", arr[k]);

}
/* After successful sort elements in array */
printf("After sorting elements in array: ");
for(i=0; i<size; i++) {
printf("%d\t", arr[i]);
}
Insertion sort
The basic theory of the this sorting tehnique is that each element is inserted into its proper
position in a previously sorted array. The process starts from the 2 nd element of the array.
Before this initially considered a single element only and it can be considered as asorted array
which has only one element. Now considered two elements form an array i.e. upto 2nd
element into array, check the 2nd elements is in proper position or not compare with previous
element. If it not insert into proper position. Consideered three elements, already two
elements are sorted, now check new elements in proper position or not if it not compare with
adjecent and previous elements and set into proper position. Now considered four elements
continue same process. This process will repeted untill all emenets are set into proprer
position. This process is called Insertion sorting, because we inserting an elemnts into proper
position.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language

Example:
#include<stdio.h>
void main()
{
int i,j,k,temp,n;
printf("Enter how many elements you want giving");
scanf("%d",&n);
int array[n];
for(i=0;i<n;i++)
scanf("%d",&array[i]);
printf("The Array Elements are\n");
for(i=0;i<n;i++)
printf("%d\t",array[i]);
for(i=0;i<n-1;i++){
j=i;
if(array[j]>array[j+1])
{ back:
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp; Sorting
} Logic
if(i>0&&array[j-1]>array[j])
{
j=j-1;
goto back;
}

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
printf("\nStep=%d the Array Elements are\n",i);
for(k=0;k<n;k++)
printf("%d\t",array[k]);
}
printf("\nAfter sorting the Array Elements are\n");
for(i=0;i<n;i++)
printf("%d\t",array[i]);
}

Binary searching example code:


#include <stdio.h>
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 the 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 is present at index %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Insertion & Deletion of an Element from an Array
C program to insert an element in an array, for example, consider an array a[10] having three
elements in it initially and a[0] = 1, a[1] = 2 and a[2] = 3 and you want to insert a number 45
at location 1 i.e. a[0] = 45, so we have to move elements one step below so after insertion
a[1] = 1 which was a[0] initially, and a[2] = 2 and a[3] = 3. Array insertion does not mean
increasing its size i.e array will not contain 11 elements.
Example: C program to insert an element in an array
#include <stdio.h>
#define size 100
int main()
{
int p/*position*/, i, n, value;

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


scanf("%d", &n);
int array[size];
printf("Enter %d elements\n", n);

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


printf("Enter %d elements\n", i);
scanf("%d", &array[i]);
}

printf("Enter the location where you wish to insert an


element\n");
scanf("%d", &p);

printf("Enter the value to insert\n");


scanf("%d", &value);
if(p<0)
{
printf("Invalid position! Please enter position between 1 to
%d", size);
}
else
{
for (i = n; i >= p; i--){
array[i] = array[i-1];
}
if(p>0)
{
array[p-1]=value;
n++;
}
else
{
array[p]=value;
n++;
}
}
printf("Resultant array is\n");

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
for (i = 0; i < n; i++)
printf("%d\n", array[i]);

return 0;
}
Output:
Enter number of elements in array
4
Enter 4 elements
Enter 0 elements
9
Enter 1 elements
8
Enter 2 elements
7
Enter 3 elements
6
Enter the location where you wish to insert an element
0
Enter the value to insert
10
Resultant array is
10
9
8
7
6

C program to deletion an element in an array, for example, consider an array a[10] having ten
elements in it initially and a[0] = 10, a[1] = 20 a[2] = 30, a[3] = 40…… and a[9] = 100 and you
want to delete an element at location 1 i.e. a[0] = 10, so we have to remove elements at a[0].
Then we copy the elements a[1] to a[0], a[2] to a[1] and so on.. And finally reduce the no. of
elements in an array. Array deletion does not mean decreasing its size i.e array will contain
09 elements.

Example: C program to insert an element in an array

/* * C program to delete an element from array at specified position*/

#include <stdio.h>
#define SIZE 100

int main()
{
int arr[SIZE];
int i, n, pos,j;

/* Input size and element in array */


printf("Enter size of the array : ");
scanf("%d", &n);

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
/* Input element position to delete */
printf("Enter the element position to delete : ");
scanf("%d", &pos);

/* Invalid delete position */


if(pos < 0 || pos > n)
{
printf("Invalid position! Please enter position between 1 to
%d", n);
}
else
{
/* Copy next element value to current element */
for(i=pos-1; i<n-1; i++)
{
arr[i] = arr[i + 1];
printf("Swap");
for(j=0; j<n; j++)
{
printf("%d\t", arr[j]);
}
printf("\n");
}
/* Decrement array size by 1 */
n--;
}

/* Print array after deletion */


printf("\nElements of array after delete are : ");
for(i=0; i<n; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}
Output:
Enter size of the array : 5
Enter elements in array : 10
20
30
40
50
Enter the element position to delete : 3
Swap 10 20 40 40 50
Swap 10 20 40 50 50

Elements of array after delete are : 10 20 40 50

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Finding the Largest/Smallest Element in An Array
Example: Display Largest Element of an array
#include <stdio.h>

int main()
{
int i, n;
float arr[100];

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


scanf("%d", &n);
printf("\n");

// Stores number entered by the user


for(i = 0; i < n; ++i)
{
printf("Enter Number %d: ", i+1);
scanf("%f", &arr[i]);
}

// Loop to store largest number to arr[0]


for(i = 1; i < n; ++i)
{
// Change < to > if you want to find the smallest element
if(arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);

return 0;
}
Example: C program for Reverse array
#include <stdio.h>

int main()
{
int n, i, j;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
int arr1[n], arr2[n];

printf("Enter array elements\n");


for (i = 0; i < n ; i++)
{
printf("Enter the arr1[%d] element",i);
scanf("%d", &arr1[i]);
}
printf("The array elements are\n");
for (i = 0; i < n ; i++)
{
printf("%d\t", arr1[i]);
}
/* Copying elements into array b starting from end of array a
*/

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
for (i = n - 1, j = 0; i >= 0; i--, j++)
arr2[j] = arr1[i];

/* Copying reversed array into the original.


* Here we are modifying original array, this is optional.
*/

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


arr1[i] = arr2[i];

printf("\nAfter Reverse The array elements are\n");


for (i = 0; i < n; i++)
printf("%d\t", arr1[i]);

return 0;
}

Output:
Enter the number of elements in array
4
Enter array elements
Enter the arr1[0] element 9
Enter the arr1[1] element 8
Enter the arr1[2] element 7
Enter the arr1[3] element 6
The array elements are
9 8 7 6
After Reverse The array elements are
6 7 8 9
Example: C program for second Largest elements in an array

/*** C program to find second largest number in an array */

#include <stdio.h>
#include <limits.h> // For INT_MIN

#define MAX_SIZE 1000 // Maximum array size

int main()
{
int arr[MAX_SIZE], size, i;
int max1, max2;

/* Input size of the array */

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
printf("Enter size of the array (1-1000): ");
scanf("%d", &size);

/* Input array elements */


printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}

max1 = max2 = INT_MIN;

/*
* Check for first largest and second
*/
for(i=0; i<size; i++)
{
if(arr[i] > max1)
{
/*
* If current element of the array is first largest
* then make current max as second max
* and then max as current array element
*/
max2 = max1;
max1 = arr[i];
}
else if(arr[i] > max2 && arr[i] < max1)
{
/*
* If current array element is less than first largest
* but is greater than second largest then make it
* second largest
*/
max2 = arr[i];
}
}

printf("First largest = %d\n", max1);


printf("Second largest = %d", max2);

return 0;
}

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Two-Dimensional Arrays
An array of arrays is called as multi-dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi-dimensional array. Multi-dimensional array
can be of two dimensional array or three dimensional array or four dimensional array or
more...
Syntax: datatype arrayname[size][size];

Example: float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the
array as a table with 3 rows and each row has 4 columns.

Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here, the array y can hold 24 elements.

Initializing a multidimensional array

Here is how you can initialize two-dimensional and three-dimensional arrays

Initialization of a 2d array
// Different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

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

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

Initialization of a 3d array

You can initialize a three-dimensional array in a similar way like a two-dimensional array.
Here's an example,

int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Example 1: Two-dimensional array to store and print values
// C program to store temperature of two cities of a week and
display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main()
{
int temperature[CITY][WEEK];

// Using nested loop to store values in a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");

// Using nested loop to display vlues of a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1,
temperature[i][j]);
}
}
return 0;
}

Output:
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26

Displaying values:

City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26

Additions/Multiplication of two matrices


Example: Sum of two matrices
// 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], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int 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 (int i = 0; i < 2; ++i)

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


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

// Displaying the sum


printf("\nSum Of Matrix:");

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


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[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;
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

Example: Program to Multiply Two Matrices


// 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], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
{
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 (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


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

// Displaying the sum


printf("\nSum Of Matrix:");

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


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

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

Transpose of square Matrix


Example: C program to find transpose of a matrix
#include <stdio.h>

int main()
{
int m, n, i, j, temp;

printf("Enter the number of rows and columns of


matrix\n");
scanf("%d%d", &m, &n);
int matrix[m][n];
printf("Enter elements of the matrix\n");

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


for(j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);

printf("The original matrix:\n");

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
for (i = 0; i < m; i++){
for( j = 0 ; j < n ; j++ )
printf("%d\t", matrix[i][j]);
printf("\n");
}

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


for (j = 0; j < i; j++)
temp= matrix[i][j];
matrix[i][j]= matrix[j][i];
matrix[j][i]= temp;
}
printf("Transpose of the matrix:\n");
for (i = 0; i < m; i++){
for( j = 0 ; j < n ; j++ )
printf("%d\t", matrix[i][j]);
printf("\n");
}

return 0;
}

Example: C program to find transpose of a matrix 3x2


#include <stdio.h>

int main()
{
int m, n, i, j, matrix[10][10], transpose[10][10];

printf("Enter the number of rows and columns of


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

printf("Enter elements of the matrix\n");

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


for(j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);

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


for(j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];

printf("Transpose of the matrix:\n");

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


for(j = 0; j < n; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}

return 0;
}

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Example: C program to check symmetric matrix
C program to check if a matrix is symmetric or not: we find transpose of the matrix and then compare
it with the original matrix. For a symmetric matrix AT = A.

#include<stdio.h>

int main()
{
int m, n, i, j, matrix[10][10], transpose[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");

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


for(j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);

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


for(j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];

if (m == n) /* check if order is same */


{
for (i = 0; i < m; i++)
{
for (j = 0; j < m; j++)
{
if (matrix[i][j] != transpose[i][j])
break;
}
if (j != m)
break;
}
if (i == m)
printf("The matrix is symmetric.\n");
else
printf("The matrix isn't symmetric.\n");
}
else
printf("The matrix isn't symmetric.\n");

return 0;
}
Output:
Enter the number of rows and columns of matrix
3
3
Enter elements of the matrix

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
1
3
8
3
8
-4
8
-4
6
For any square matrix A with real number entries, A + A′ is a symmetric matrix and A – A′ is a skew-
symmetric matrix.

Inverse of Matrix
This is a c program to find the inverse of matrix. If M is the matrix and M-1 is its inverse, M x M-1 gives
I (identity matrix).

Inverse of a matrix M is: adjoint(M) / det(M)


If determinant is zero, the matrix is not invertible. Adjoint of matrix M is transpose of cofactor matrix
of M.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language

Example: C program Matrix A inverse of Matrix A-1


#include<stdio.h>

int main(){

int a[3][3],i,j;
float determinant=0;

printf("Enter the 9 elements of matrix: ");


for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);

printf("\nThe matrix is\n");


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

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
for(i=0;i<3;i++)
determinant = determinant + (a[0][i]*(a[1][(i+1)%3]*
a[2][(i+2)%3] - a[1][(i+2)%3]*a[2][(i+1)%3]));

printf("\nInverse of matrix is: \n\n");


for(i=0;i<3;i++){
for(j=0;j<3;j++)
printf("%.2f\t",((a[(i+1)%3][(j+1)%3] *
a[(i+2)%3][(j+2)%3])-(a[(i+1)%3][(j+2)%3]* a[(i+2)%3][(j+1)%3]))/
determinant);
printf("\n");
}

return 0;
}
Output:

Enter the 9 elements of matrix: 3


5
2
1
5
8
3
9
2

The matrix is

3 5 2
1 5 8
3 9 2
Inverse of matrix is:

0.70 -0.25 0.07


-0.09 -0.00 0.14
-0.34 0.25 -0.11

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Character Arrays
A character arrays is used for where we want store a group of character or sequences of
character into one character variable. It is similar like int arr[10]. It is also called as one-
dimensional array.
In int arr[n] means we are allow to store n number of whole number into an arr int type
variable.
Similarly if we want define a character array in place of int we use character data type char
like;
Syntax: <character data type> <variable name>[size];
Example: char ch[n]
now in ch variable we allow to store n number of character

Initialize an array

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

char ch[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};

You can also initialize an array like this.

char ch[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
ch ch[0] ch[1] ch[2] ch[3] ch[4]
a b c d e

Example: C program for reading no.of character and display the character
#include<stdio.h>
void main()
{
int i,n;
printf("Enter how many character of ");
scanf("%d",&n);
char ch[n];
printf("Enter %d character",n);
ch[0]='\0';
for(i=1;i<n;i++){
getchar();
ch[i]=getchar();
}
printf("Your entered character are");

for(i=0;i<=n;i++)
putchar(ch[i]);
Note:
When we assign a string to character array it store entire string of character into character
array variable and last index of that character array variable it store ‘\0’ character, to maintain
where the string is terminated.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Ex:
char ch[]=”INDIA”;
it store like: ch ch[0] ch[1] ch[2] ch[3] ch[4] ch[5]
I N D I A \0

char ch[]={‘I’,’N’,’D’,’I’,’A};
it store like: ch ch[0] ch[1] ch[2] ch[3] ch[4]
I N D I A
Basically the character array is used for accepting the string from user and store into one
variable.

Multi-Dimensional Arrays
C allows for arrays of two or more dimensions. A two-dimensional (2D) array is an array of
arrays. A three-dimensional (3D) array is an array of arrays of arrays.

In C programming an array can have two, three, or even ten or more dimensions. The maximum
dimensions a C program can have depends on which compiler is being used.

More dimensions in an array means more data be held, but also means greater difficulty in
managing and understanding arrays.
How to Declare a Multidimensional Array in C
A multidimensional array is declared using the following syntax:
type array_name[d1][d2][d3][d4]………[dn];
Where each d is a dimension, and dn is the size of final dimension.

Examples:
int table[5][5][20];
float arr[5][6][5][6][5];

In Example 1:
int designates the array type integer.
table is the name of our 3D array.
Our array can hold 500 integer-type elements. This number is reached by multiplying the
value of each dimension. In this case: 5x5x20=500.

In Example 2:
Array arr is a five-dimensional array.
It can hold 4500 floating-point elements (5x6x5x6x5=4500).

Can you see the power of declaring an array over variables? When it comes to holding multiple
values in C programming, we would need to declare several variables. But a single array can
hold thousands of values.

bathala sudhakar | IIIT RGUKT RK VALLEY


Arrays in C Programming Language
Initializing a 3D Array in C

Like any other variable or array, a 3D array can be initialized at the time of compilation. By
default, in C, an uninitialized 3D array contains “garbage” values, not valid for the intended
use.
Let’s see a complete example on how to initialize a 3D array:
#include<stdio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=
{
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
In the code above we have declared a multidimensional integer array named “arr” which can
hold 3x3x3 (or 27) elements.
We have also initialized the multidimensional array with some integer values.

The Conceptual Syntax of a 3D Array in C


data_type array_name[table][row][column];
If you want to store values in any 3D array point first to table number, then row number, and
lastly to column number.

Some hypothetical examples:


arr[0][1][2] = 32;
arr[1][0][1] = 49;

bathala sudhakar | IIIT RGUKT RK VALLEY

You might also like