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

Module 8 - Arrays in C

This document provides an overview of arrays in C. It discusses that arrays are fixed size collections of elements of the same data type stored in contiguous memory locations. Arrays are defined with syntax like data_type array_name[size] and elements are accessed using indexes like array_name[0], array_name[1], etc. The document explains how arrays are stored in memory with elements occupying consecutive memory locations. It provides examples of defining, initializing, accessing, and traversing arrays.

Uploaded by

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

Module 8 - Arrays in C

This document provides an overview of arrays in C. It discusses that arrays are fixed size collections of elements of the same data type stored in contiguous memory locations. Arrays are defined with syntax like data_type array_name[size] and elements are accessed using indexes like array_name[0], array_name[1], etc. The document explains how arrays are stored in memory with elements occupying consecutive memory locations. It provides examples of defining, initializing, accessing, and traversing arrays.

Uploaded by

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

Module 8 – Arrays in C

BITS Pilani Dr. Jagat Sesh Challa


Pilani Campus
Department of Computer Science & Information Systems
Module Overview
• Introduction to Arrays in C
• Arrays in Memory
• A few examples
• Passing arrays to functions
• Searching in an Array
• Selection Sort
• Binary Search
• Insert/Delete in an Array
• Character Arrays
• Multi-dimensional Arrays
• Matrix Addition and Multiplication
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Intro to Arrays in C
What are Arrays?
• Array – fixed size sequenced collection of elements of the same data type.
• It is a derived data type.
• Example:
• int arr[10] declares an array of 10 elements each of integer type

arr

10 integer elements

• Single name is used to represent a collection of items.


• arr represents 10 integer elements in the above array
• Arrays are useful in processing multiple data items having a common
characteristic
• E.g.: set of numerical data, list of student names, etc.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Importance of Arrays
• Easier storage, access, and data management
• Easier to search
• Easier to organize data elements
• Useful to perform matrix operations
• Useful in databases
• Useful to implement other data structures

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Defining Arrays
Syntax:
<Storage-class> <data-type> <array_name>[<size>]

Note: Storage-class is optional

Examples:
int count[100];
char name[25];
float cgpa[50];

Good practice:
#define SIZE 100
int count[SIZE];
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Initializing arrays
Few valid ways of initializing arrays in C

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

1 2 3 4 5 6

float floatArray[10] = {1.387, 5.45, 20.01};


1.387 5.45 20.01 0.0 0.0 0.0 0.0 0.0 0.0 0.0

double fractions[] = {3.141592654,1.570796327,0.785398163};

3.141592654 1.570796327 0.785398163

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Accessing elements of an array
int arr[10];
arr

arr[0] arr[2] arr[4] arr[6] arr[8]

arr[1] arr[3] arr[5] arr[7] arr[9]

For an n-element array:


• The first element is accessed by arr[0]
• The second element is accessed by arr[1]
• The last element is accessed by arr[n-1]
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Initializing Arrays During
Program Execution
#include <stdio.h>
int main()
{
int nums[10]; int i;
for(i=0; i<10; i++)
{
/* Reading an array of elements */
scanf(“%d”,&nums[i]);
}
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example
A program that takes 10 elements from the user and stores them in
an array and then computes their sum.
#include <stdio.h>
int main(){
int nums[10]; int sum=0; int i;
for(i=0; i<10; i++){
scanf(“%d”,&nums[i]);
}
for(i=0;i<10;i++){
sum = sum + nums[i];
}
printf(“The sum is: %d”, sum);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Arrays in Memory
Arrays in memory

Frame allocated to • Elements of arr are stored in


1 2 3 4 contiguous memory locations
Stack

main() in the stack


• arr references the first element
in the array.
• In other words, the variable arr
Array arr residing in
contains the address of the first
the frame allocated to
location/element of the 4
main()
Heap

elements array that we have just


defined.
• What is this address?
Data

Consider this program: • We will see


int main(){
int arr[4] = {1, 2, 3, 4};
Text


return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Addresses in Main Memory

low address • Remember how our memory is


actually organized
• It is like a table of contiguous
memory locations, each having an
address
• Each address is represented
by a string of bits
• typically 32 or 64 bits in
modern computers
high address

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Addresses in Main Memory
Addresses • Note: our memory is byte
10010000 addressable.
10010001 o every byte in the memory has an
10010010
10010011
address,
10010100 o In other words, size of each
10010101 memory location is 1 byte.
• For Simplicity let us consider each
address in the main memory to be
represented by 8 bits.
• The addresses of the memory
locations are depicted in the figure
10011101
10011110
• Note:The addresses of two contiguous
locations differ by 1 (in binary)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
Consider this program:
Addresses
int main(){
10010000
int arr[4] = {1, 2, 3, 4};
10010001
10010010 …
10010011 return 0;
10010100 }
10010101

• Say each integer variable takes 2


bytes of memory
• To store an integer array of size 4,
we need 4*2 = 8 bytes of memory
10011101
or 8 contiguous locations in memory
10011110 (given each location is of size 1 byte)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
Consider this program:
Addresses
int main(){
10010000
int arr[4] = {1, 2, 3, 4};
10010001
10010010 …
10010011 return 0;
10010100 }
10010101

• Say each integer variable takes 2


bytes of memory
• To store an integer array of size 4,
we need 4*2 = 8 bytes of memory
10011101
or 8 contiguous locations in memory
10011110 (given each location is of size 1 byte)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
int arr[4] = {1, 2, 3, 4}; Addresses
10010000
10010001
Stores first element of arr, accessed by arr[0] 10010010
10010011
Stores second element of arr, accessed by arr[1] 10010100
10010101
Stores third element of arr, accessed by arr[2]

Stores fourth element of arr, accessed by arr[3]

10011101
10011110

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
Addresses
10010000
10010001
10010010 arr points here and contains this address
arr[0] = 1
10010011
10010100 arr+1 refers to this address
arr[1] = 2
10010101
arr+2 refers to this address
arr[2] = 3
arr+3 refers to this address
arr[3] = 4
• We are storing 2 bytes of memory at address arr
• We are storing 2 bytes of memory at address
arr+1, and so on.
• arr and arr+1 differ by one unit of space required
10011101
to store an integer, which is of 2 bytes or 2
10011110
addressable memory locations.
• If our array is storing float values, arr and arr+1
would differ by 4 bytes or 4 addressable memory
locations.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

A few examples
Example 1
int main(){
int arr[6] = {1, 2, 3, 4, 5, 6};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]); i++)
printf("%d\t",arr[i]);
return 0;
}

Output?
1 2 3 4 5 6

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 2
int main(){
int arr[6] = {1, 2, 3};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
printf("%d\t",arr[i]);
return 0;
}

Output?
1 2 3 0 0 0

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 3
int main(){
int arr[] = {1, 2, 3};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
printf("%d\t",arr[i]);
return 0;
}

Output?
1 2 3

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 4
int main(){
int arr[6];
arr[6] = {1, 2, 3, 4, 5, 6};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
printf("%d\t",arr[i]);
return 0;
}

Output?
Compile-time error

What is the right way in such a scenario (declaration and initialization are separated) ?
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 5
int main(){
int arr[6];
for (int i=0;i<6;i++)
arr[i] = i;
for (int i=0;i<6;i++)
printf("%d\t",arr[i]);
return 0;
}

Output?
0 1 2 3 4 5
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 6
int main(){
int arr[6];
for (int i=0;i<6;i++)
arr[i] = i;
for (int i=0;i<9;i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
0 1 2 3 4 5 3965 -8905 4872
(junk values)
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 7
int main(){ Problems with arrays – No
int arr[6]; bounds checking!!
for (int i=0;i<8;i++) • There is no check in C compiler to
see if the subscript used for an
arr[i] = i;
array exceeds the size of the array.
for (int i=0;i<6;i++) • Data entered with a subscript
printf("%d\t",arr[i]); exceeding the array size will simply
return 0; be placed in memory outside the
} array limit and lead to
unpredictable results.
• It’s the programmer’s responsibility
to take care.
Output?
*** stack smashing detected ***: ./a.out terminated
0 1 2 3 4 5 Aborted (core dumped)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 8
int main(){
int arr[6]={0};
arr[6]= 1;
for (int i=0;i<7;i++)
printf("%d\t",arr[i]);
return 0;
}

Output?
*** stack smashing detected ***: ./a.out terminated
0 0 0 0 0 0 1
Aborted (core dumped)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 9
Write a C code #include<stdio.h>
which takes an int #include<stdlib.h>
array of size SIZE
#define SIZE 9
and calculates int main()
(and displays) the {
average of all int arr[SIZE], sum=0;
numbers for (int i=0;i<SIZE;i++)
arr[i] =i;
for (int i=0;i<SIZE;i++)
sum = sum + arr[i];
printf("AVG=%d\n",sum/SIZE);
return 0;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Copying Arrays
int old_value[5]={10,20,30,40,50};
int new_value[5];
How to copy the elements of old_value into new_value?
new_value = old_value;
It will not work. Why?

Question:
What is the correct way of copying arrays?
Sol:
Copy each individual element one by one
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Home Exercise

Write a C program to find out the largest element in an array of


integers. Assume N numbers are entered by the user (N is
#defined)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Passing Arrays to functions


Passing arrays to functions

USING FUNCTIONS:
Write a C function that takes an int array of size SIZE and
calculates (and displays) the average of all numbers

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Solution
#define SIZE 9 When avg() is called, the address of
int avg(int n, int list[]){ the first element of the array intArr
int sum = 0; is copied into the array list.
for (int i=0;i<n;i++)
sum = sum + list[i];
return sum/n; intArray 0
}
list 1
int main(){
int intArray[SIZE], 2
int average; 3
for (int i=0;i<SIZE;i++) 4
intArray[i] = i;
5
average=avg(SIZE, intArray);
printf("Average=%d\n", average); 6
return 0; 7
} 8
Output:
Average=4 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Slight change…
int main(){ int avg(int n, int list[])
int intArray[SIZE], average; {
for (int i=0;i<SIZE;i++){ int sum = 0;
intArray[i] = i; for (int i=0;i<n;i++){
printf(“%d\t”,intArray[i]); list[i] = list[i]*2
} sum = sum + list[i];
}
average=avg(SIZE,intArray); return sum/n;
printf("Average=%d\n", average); }
printf(“After calling avg…\n”);
Output:
for (int i=0;i<SIZE;i++) 0 1 2 3 4 5 6 7 8
printf(“%d\t”,intArray[i]); Average = 8
return 0; After calling avg…
} 0 2 4 6 8 10 12 14 16
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Arguments to functions
Ordinary variables are passed by value
– Values of the variables passed are copied into local variables of the
function
However… when an array is passed to a function
– Values of the array are NOT passed
– Array name interpreted as the address of the first element of the array
is passed [Pass by reference]
– This value is captured by the corresponding function parameter, which
becomes a Pointer to the first element of the array that was passed to it.

Therefore, altering list[i] within avg() altered the original


values of intArray[i].

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Can we ‘return’ an array from a
function?
If the array is defined inside the function, returning the array would
give run-time error.
• Why?
• Try this! Next Slide.

We can return dynamically allocated arrays.


• We will study about them when we study pointers.

We can also use global arrays in place of arrays defined inside


functions.
• We don’t have to pass arrays into functions. Global arrays are
accessible to all the functions in the program.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Let us try to explain with our
memory diagram
Stack frame allocated to When f1() returns, the memory
main_arr
main() in stack allocated to it is destroyed.
Stack

Stack Frame allocated to So arr declared inside f1() does


arr 1 2 3 4 not exist anymore. Accessing arr in
f1() in the stack
main function now gives an error.

Consider this program:


int f1(){
Heap

int arr[4] = {1, 2, 3, 4};


return arr;
}
Data

int main(){
int main_arr[] = f1();
printf(”First ele is: %d”, main_arr[0]);
Text

return 0;
}
Memory allocated Output:
to our program Error!
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example with global arrays
#define SIZE 4
int globArray[SIZE];
// int globalArray[SIZE] = {1,2,3,4} is also allowed
int avg(){
int sum = 0;
for (int i=0;i<n;i++)
sum = sum + globArray[i];
return sum/n;
int main(){
}
int average;
for (int i=0;i<SIZE;i++)
globArray[i] = i;
average=avg();
printf("Average=%d\n", average);
return 0;
} Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example (Worked on the Board)

Write a C function which accepts an array as the input and returns


the index of the largest element in the array. Assume N numbers are
entered by the user (N is #defined)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Searching in an Array
Linear search
Task: Search for an element key in the Array.
Each item in the array is examined until the desired item is found
or the end of the list is reached
Algorithm:
1. Read an array of N elements named arr[0…N-1] and search element key
2. Repeat for i=0 to i=N-1
If key equals to arr[i]
Display element found and stop
3. Display element not found
4. Stop

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Linear Search – Implementation
#include <stdio.h>

int linearSearch(int arr[], int size, int key)


{
// Function implementing linear search of key in array
arr of size size

int i = 0;

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


if(key == arr[i])
return i; // element found at index i in the array
}

return -1; // element not found in the array


}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Linear Search – Implementation
(contd.)
int main() {
int arr[10],pos,key;
printf("Enter Array elements:");
for(index = 0; index<10; index++)
scanf("%d",&arr[index]);
printf("Enter search element");
scanf("%d", &key);

pos = linearSearch(arr,10,key);

if (pos == -1) printf("Element not found");


else printf(“Element found at index %d\n”,pos);

return 0;
} Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Sorting – Selection Sort


Sorting
• Sorting refers to ordering data in an increasing or decreasing order
• Sorting can be done by
– Names
– Numbers
– Records
– etc.
• Sorting reduces the time for lookup (or search for an element)
• Example: Telephone directory
– Time to search for someone’s phone number
• Directory sorted alphabetically vs. no ordering
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Various Algorithms for Sorting
We would be studying
• Selection sort
in this course!
• Bubble sort
• Insertion sort
• Merge sort
• Quick sort
• Shell sort
• Bucket sort
• Radix sort
• and more . . .

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Sorting (Selection Sort)
• Selection sort is a simple sorting algorithm.
• In this algorithm, the list (or an array) is divided into two parts:
• The sorted part at the left
• The unsorted part at the right
• Initially, the sorted part at the left is empty, and the unsorted part at
the right is the full list.
• In each iteration, the smallest element from the unsorted part of the
array is added to the sorted part.
• The process continues until the unsorted part of the array is empty.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Selection Sort

14 33 27 10 35 19 42 44

Find the minimum element in the array and bring to the 0th index of the array

14 33 27 10 35 19 42 44

Element 10 is the minimum element in the array. To bring it the 0th index, we need to
swap it with the element present at the 0th index

10 33 27 14 35 19 42 44

We can now see that the sorted portion of the array is from index 0 to 0, and the
unsorted portion of the array is from index 1 to 7.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Selection Sort (Cont.)

10 33 27 14 35 19 42 44

Now, we have to look at the array excluding the first element (element at 0th index). In
the remaining (unsorted) portion of the array, again we will find the minimum element.

10 33 27 14 35 19 42 44

The minimum element in the unsorted portion of the array is 14 at index 3. We should
swap it with the element at index 1.

10 14 27 33 35 19 42 44

We can now see that the sorted portion of the array is from index 0 to 1, and unsorted
portion of the array is from index 2 to 7.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Selection Sort (Cont.)
In the same way, we can continue this process. In the end, the sorted portion will be the
entire array, and the unsorted portion will be empty.

10 14 27 33 35 19 42 44

10 14 19 33 35 27 42 44

10 14 19 27 35 33 42 44

10 14 19 27 33 35 42 44

10 14 19 27 33 35 42 44

10 14 19 27 33 35 42 44

10 14 19 27 33 35 42 44

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Selection Sort: Implementation
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, min;

// One by one move the boundary of the unsorted subarray


for (i = 0; i < n-1; i++){
min = i; //minimum element in unsorted array

for (j = i+1; j < n; j++){


if (arr[j] < arr[min]) min = j;
}

// Swap the min element with the first element in the unsorted subarray
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
} Does this function need to return
} anything?
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Selection Sort: Implementation
(contd.)
int main()
{
int a[] = {24, 36, 20, 7, 42, 19};
int size = sizeof(a) / sizeof(a[0]);
selectionSort(a, size);
return 0;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Binary Search in an array


Binary Search
• Useful when the array is already sorted
• More efficient than linear search
• It performs lesser number of comparisons with the elements in
the array, when compared to linear search
• Hence, very fast!

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Binary Search Algorithm
Algorithm // Pre-condition: List must be sorted

• The desired item is first compared to the element in the middle of the list

• If the desired item is equal to the middle element:


– No further searches are required

• If the desired item is greater than the middle element:


– The left part of the list is discarded from any further search

• If the desired item is less than the middle element:


– The right part of the list is discarded from any further search

• This process continues either until element is found or list reaches to


singleton element
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Binary Search
1. The array in which searching is to be performed is:

Initial Array(sorted)
Let x = 4 be the element to be searched.
2. Set two pointers low and high at the lowest and the highest
positions respectively.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Binary Search
3. Find the position of the middle element mid = (low+high)/2. The middle
element is arr[mid] = 6.

4. If x==arr[mid], then return mid.


5. Else If x > arr[mid], compare x with the middle element of the elements on
the right side of mid. This is done by setting low to low = mid + 1.
6. Else If x < arr[mid], compare x with the middle element of the elements on
the left side of mid. This is done by setting high to high = mid - 1.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Binary Search
7. Repeat steps 3 to 6 until low meets high.

8. x = 4 is found.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Binary Search - Code
#define Size 10
main(){ // Binary search implementation
int arr[Size], index, upper, lower, key, mid;
printf("Enter Array elements:");
for(index = 0; index<Size; index++)
scanf("%d", &arr[index]);
printf("Enter search element");
scanf("%d",&key);
upper=Size-1; lower=0;
while(lower<=upper){
mid=(lower+upper)/2;
if(key>arr[mid]) lower=mid+1;
else if(key<arr[mid]) upper=mid-1;
else{
printf("Element found at location %d", mid);
return;
}
}
printf("Element no found"); Exercise: Re-write this program to do
} the searching part with a function call.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Insert/Delete in an Array
Handling changing number of
elements in the array
Insert/Delete in an Array
• Arrays once declared they are of fixed size.
• Example:
int arr1[10]; declares an array of size 10.
We can’t store 11 elements to this array.

• To enable insertion and deletion in an array


• Choose MAX_SIZE and declare the array with it.
• Insertions can be done as long as the number of elements of the array does
not exceed MAX_SIZE.
• Keep a count of actual number of elements present in the array
• count <= MAX_SIZE
• Some positions will remain vacant. We shall need to store a
DEFAULT_VALUE in those positions.
• Keep all occupied positions contiguous (Unoccupied positions as well)
• If MAX_SIZE is 10, count is 6, then first 6 positions of the array should be
occupied with some values and remaining 4 positions should have
DEFAULT_VALUE.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Insert/Delete in an Array
• Choose MAX_SIZE and declare #define MAX_SIZE 10
the array with it. #define DEFAULT_VALUE -1
• Insertions can be done as long as int main() {
the number of elements of the
array does not exceed // declare array with MAX_SIZE
MAX_SIZE. int arr[MAX_SIZE];
• Keep a count of actual number
of elements present in the array // declare a variable to keep count of
– count <= MAX_SIZE number of elements in the array
• Some positions will remain vacant. int count = 0;
We shall need to store a
DEFAULT_VALUE in those // fill all the positions with the
positions. DEFAULT_VALUE
• Keep all occupied positions for(int i=0;i<MAX_SIZE;i++){
contiguous (Unoccupied positions as
well) arr[i] = DEFAULT_VALUE;
– If MAX_SIZE is 10, count is 6, } arr at this stage
then first 6 positions of the array
should be occupied with some values … … …
and remaining 4 positions should } -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
have DEFAULT_VALUE.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Insert in an Array
#define MAX_SIZE 10
#define DEFAULT_VALUE -1
int main() {
int arr[MAX_SIZE];
int count = 0;

for(int i=0;i<MAX_SIZE;i++){ 0 1 4 9 16 25 -1 -1 -1 -1
arr[i] = DEFAULT_VALUE;
}

// Insert 6 elements into the array.


Insert squares of their respective
index.
for (int i=0;i<6;i++){
arr[i] = i*i;
count+=1;
}

// Append an element at the end of


the array and increment count Element inserted here
arr[count]=12;
count+=1;
0 1 4 9 16 25 12 -1 -1 -1
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Insertion in a sorted array
#define MAX_SIZE 10
#define DEFAULT_VALUE -1
int main() {
int arr[MAX_SIZE];
0 1 4 9 16 25 -1 -1 -1 -1
int count = 0;

for(int i=0;i<MAX_SIZE;i++){
arr[i] = DEFAULT_VALUE;
}

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


arr[i] = i*i;
count+=1;
}

// Insert 10 into arr, while keeping arr sorted Insert 10 here after shifting
// It should get inserted between 9 and 16. elements to the right
// What should be done ?
// Shift 25, 16, by one place towards right and
// insert 10 in the place of 16.

}
0 1 4 9 16 25 -1 -1 -1 -1

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Insertion in a sorted array
#define MAX_SIZE 10 // Now shift elements from last
#define DEFAULT_VALUE -1 occupied position until i, one
int main() { position to right
… for (int j=count-1; j>i;j--){
… arr[j+1] = arr[j];
}
int x=10; //element to be inserted // loop exits when j=i, the
position to insert x.
int i=0;

arr[j] = x; count++;
// Find the position to insert x
// x inserted at its position
for (i=0; i<count; i++){
}
if (arr[i]>=x)
break; 0 1 4 9 16 25 -1 -1 -1 -1
}
// i is the position in arr where Insert 10
x should be inserted
0 1 4 9 10 16 25 -1 -1 -1

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Delete in Array (Sorted or
unsorted)
Delete is similar to insert.

Example: Delete 9 from arr

0 1 4 9 10 16 25 -1 -1 -1

Delete 9 from arr:


• shift 10,16,25 to one position towards left
• arr[count-1] = DEFAULT_VAL
• count = count -1

0 1 4 10 16 25 -1 -1 -1 -1

Exercise: Implement this operation


Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Character Arrays
Character Arrays
char color[3] = “RED”; R E D

char color[ ] = “RED”;


R E D \0

Are they the same?

Character arrays are the way to represent strings in C.


Each string typically ends with a NULL character “\0”.

More about strings in Module 13.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Char Arrays

Write a C program which reads a 1D char array, converts all


elements to uppercase, and then displays the converted array.

Hint: use toupper(ch) of <ctype.h>

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Lower Case to Upper Case
using char array
#include <stdio.h> name[i]='\0'; ????
#include <ctype.h> size = i;
int main(){ printf("\nName is %s", name);
int size,i=0; for(i=0;i<size;i++)
char name[50]; putchar(toupper(name[i]));
name[0]=getchar(); return 0;
while(name[i]!='\n') }
{
i++;
name[i]=getchar();
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Char Arrays

Modify the previous code to use scanf()/printf() in place of


getchar()/putchar()

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Lower Case to Upper Case
using char array
#include <stdio.h> name[i]='\0';
#include <ctype.h> size = i;
int main(){ printf("\nName is %s",name);
int size,i=0; for(i=0;i<size;i++)
char name[50]; printf(toupper(name[i]));
scanf(“%c ”,&name[0]); return 0;
while(name[i]!='\n') }
{
i++;
scanf(“%c ”,&name[i]);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Char arrays – using gets/puts
int main() Note:
{ • It is not required to
explicitly insert “\0”
char c[20]; character at the end of
int i=0; each character array
while using gets().
printf("Enter the Name"); • It automatically adds so.
gets(c);
printf("The name is %s",c);
puts(c);
return 0;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Multi-dimensional Arrays in C
Multi-dimensional Arrays
• C supports arrays of multiple dimensions
• A basic multi-dimensional array is a 2-D array
• Also known as a matrix

Declaring 2-D Arrays - Syntax:

type variable_name[row_size][column_size];

row_size → Number of rows in the matrix


column_size → Number of columns in the matrix

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Examples of 2-D Arrays
column_size=4

row_size=3
Examples:
int number[3][4]; /* 12 elements */
float number[3][2]; /* 6 elements */
char name[10][20]; /* 200 chars */

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Initializing a 2-D Array

All are equivalent


int a[2][3]={1,2,3,4,5,6}; are produce the
int a[2][3]={{1,2,3}, {4,5,6}}; following array:
int a[][3]={{1,2,3}, {4,5,6}} 1 2 3
4 5 6

How will the values will be assigned in each case?

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Incorrect Ways of Initializing 2-
D Arrays
Following initializations are not allowed
int a[3][]={2,4,6,8,10,12};
int a[][]={2,4,6,8,10,12};

Note:
• If the first bracket pair is empty, then the compiler takes the size
from the number of inner brace pairs
• If the second bracket pair is empty, the compiler throws a
compilation error!

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Accessing a 2-D Array
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}

Run time initialization of an array can be done in a similar way by


changing printf() to scanf() inside the j loop.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Memory Maps of 2-D Arrays


Storing 2-D Arrays in Memory
• 2-D arrays are stored in the memory as a linear sequence of
variables
• Two methods for storing:
– Row major
– Column major

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Row Major vs. Column Major
Example:
int a[3][3];

Row major storage will have this sequence in main memory:


a a+1 a+2 a+3 a+4
a[0][0], a[0][1], a[0][2], a[1][0], a[1][1],
a+5 a+6 a+7 a+8
a[1][2], a[2][0], a[2][1], a[2][2] Indicates
addresses
Column major storage will have this sequence in main memory:
a a+1 a+2 a+3 a+4
a[0][0], a[1][0], a[2][0], a[0][1], a[1][1],
a+5 a+6 a+7 a+8
a[2][1], a[0][2], a[1][2], a[2][2]

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Matrix Addition
Matrix Addition and
Subtraction
Matrix Addition:

1 3 0 0 1 + 0 3 + 0 1 3
1 0 + 7 5 = 1 + 7 0 + 5 = 8 5
1 2 2 1 1 + 2 2 + 1 3 3

Matrix Subtraction:

1 3 0 0 1 - 0 3 - 0 1 3
1 0 _ 7 5 = 1 - 7 0 - 5 = -6 -5
1 2 2 1 1 - 2 2 - 1 -1 1

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Working with two dimensional Arrays
(Matrix Addition & Subtraction)
Let A[m][n] and B[p][q] be two matrices.

Precondition: m equals to p and n equals to q.

Algorithm Steps:
1. Read two matrices A and B, and initialize C matrix to zero
2. Repeat (3) for i=0 to m-1
3. Repeat (3.a) for j=0 to n-1
3.a) C[i][j] = A[i][j] + B[i][j]
4. Display C matrix

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code
#define ROW 10
#define COL 10
int main(){
int M1[ROW][COL],M2[ROW][COL],M3[ROW][COL],i,j;
int row1,col1,row2,col2;
printf(“Enter row value for M1\n”);
scanf(“%d”,&row1);
printf(“Enter column value for M1\n”);
scanf(“%d”,&col1);
printf(“Enter row value for M2\n”);
scanf(“%d”,&row2)
printf(“Enter column value for M2\n”);
scanf(“%d”,&col2)

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code (Contd.)
if(row1!=row2 || col1!=col2)
{
printf(“Invalid Input: Addition is not possible”);
return;
}
printf(“Enter data for Matrix M1\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&M1[i][j]);
}
printf(“\n”);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code (contd.)
printf(“Enter data for Matrix M2\n”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&M2[i][j]);
}
printf(“\n”);
}
printf(“Addition of Matrices is as follows\n”);
for(i=0;i<row2;i++)
for(j=0;j<col2;j++)
M3[i][j]= M1[i][j] + M2[i][j]);

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code (contd.)
// display the new matrix after addition
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
printf(“%d”,M3[i][j]);
}
printf(“\n”);
}
}

Matrix Subtraction can be done in a similar way

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Matrix Multiplication
Matrix Multiplication

10 11
1 2 3
X 20 21
4 5 6
30 31

1x10 + 2x20 + 3x30 1x11 + 2x21 + 3x31


=
4x10 + 5x20 + 6x30 4x11 + 5x21 + 6x31

10+40+90 11+42+93 140 146


= =
40+100+180 44+105+186 320 335

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication M1xM2
Pre-condition: Number of columns in M1 should be equal to
number of rows in M2
Algorithm Steps:
1. Read two matrices M1[m][n] and M2[n][r] and initialize
another matrix M3[m][r] for storing result
2. Repeat for i=0 to m-1
Repeat for j=0 to r-1
M3[i][j] = 0
Repeat for k=0 to n-1
M3[i][j] += M1[i][k] * M2[k][j]
3. Print matrix M3

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
#include <stdio.h>
#define row1 4
#define col1 3
#define row2 3
#define col2 4
#define row3 4
#define col3 4

void main()
{
int M1[row1][col1],M2[row2][col2],M3[row3][col3];
int i,j,k;

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
printf(“Enter data for Matrix M1\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&M1[i][j]);
}
printf(“\n”);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
printf(“Enter data for Matrix M2\n”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&M2[i][j]);
}
printf(“\n”);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
if (col1!= row2){
printf(“Multiplication is not possible”);
return;
}
for(i=0;i<row1;i++){
for(j=0;j<col2;j++){
M3[i][j] = 0;
for(k=0;k<col1;k++){
M3[i][j] += M1[i][k] * M2[k][j];
}
}
10 11
} 1 2 3
X 20 21
4 5 6
30 31
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
printf(“RESULT MATRIX IS\n ”);
for(i=0;i<row3;i++){
for(j=0;j<col3;j++){
printf(“%d”,M3[i][j]);
}
printf(“\n”);
}
return;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

n-dimensional arrays: A glimpse


N-dimensional arrays
3D array: int arr[2][2][3];
4D array: int arr[2][2][2][2];
5D array: int arr[2][2][2][2][2];

Note:
• Elements are stored and accessed in a similar way as that of
2D arrays.
• They are also stored in Row Major format.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Exercises
Q. 1 Generate Fibonacci series using Array.

Q. 2 Write a program to find a binary equivalent of a decimal


number using an array.

Q. 3 Write a program to find the transpose of a matrix.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

You might also like