0% found this document useful (0 votes)
18 views60 pages

Unit-1 Part 3

The document provides an introduction to arrays in C, explaining their definition, declaration, initialization, and memory representation. It discusses the advantages and disadvantages of arrays, their relationship with pointers, and how to pass arrays to functions. Additionally, it covers array operations such as insertion, deletion, searching, and sorting algorithms like binary search and bubble sort.

Uploaded by

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

Unit-1 Part 3

The document provides an introduction to arrays in C, explaining their definition, declaration, initialization, and memory representation. It discusses the advantages and disadvantages of arrays, their relationship with pointers, and how to pass arrays to functions. Additionally, it covers array operations such as insertion, deletion, searching, and sorting algorithms like binary search and bubble sort.

Uploaded by

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

Unit-1 Introduction

Array
Arrays
 In C language, arrays are referred to as structured data types. An array is
defined as finite ordered collection of homogenous data, stored in
contiguous memory locations.
 finite means data range must be defined.
 ordered means data must be stored in continuous memory addresses.
 homogenous means data must be of similar data type.
 Example where arrays are used,
 to store list of Employee or Student names,
 to store marks of a students,
 or to store list of numbers or characters etc.
•Arrays are used as the base of all sorting algorithms.
•Arrays are used to implement other DS like a stack, queue, etc.
•Used for implementing matrices.
•Graphs are also implemented as arrays in the form of an adjacency
matrix.
Declaring an Array
Declaring one dimensional Array
 Arrays must be declared before they are used. General form of array
declaration is,
data-type variable-name[size];

for example : int arr[10];


Initialization of an Array

 After an array is declared it must be initialized. Otherwise, it will


contain garbage value(any random value). An array can be initialized at either compile
time or at runtime.
Compile time Array initialization (1 D array)
1. Array declaration by initializing elements
int arr[] = {10, 20, 30, 40} ;
Note: Compiler creates an array of size 4.
// above is same as int arr[4] = {10, 20, 30, 40};

Compile time Array initialization (2 D array)


When we initialize a 1 D array during declaration, we need not to specify the size of it.
However that’s not the case with 2D array, we must always specify the second dimension
even if we are specifying elements during the declaration. Example
Initialization of an Array
Initialization of an Array
2. Initializing values one after another.

Note: arr[] (It gives compile time error if we do not specify size of array)
Initialization of Array
3. Runtime Array initialization (1D array): store user input data
into 1 D array
An array can also be initialized at runtime using scanf() function. This
approach is usually used for initializing large array, or to initialize array
with user specified values. Example,
Initialization of Array
Runtime Array initialization (2 D array): store user input data into 2 D
array
We can calculate number of elements in 2 dimensional array using this formula:

The array arr[n1][n2] can have n1*n2 elements. The array that we have in the
example below is having the dimensions 5 and 4. These dimensions are known as
subscripts. So this array has first subscript value as 5 and second
subscript value as 4.
So the array
abc[5][4] can have 5*4 = 20 elements.

 To store the elements entered by user we are using two for loops, one of them
is a nested loop. The outer for loop(for row) runs from 0 to the (first subscript -
1) and the inner for loops(for column) runs from 0 to the (second subscript -1).
This way the the order in which user enters the elements would be abc[0][0],
abc[0][1], abc[0][2]…so on.
Example
How arrays are stored in memory:
Conceptual Representation
Actual Representation
Points to remember:
1. No Index Out of bounds Checking:
There is no index out of bound checking in C, for example the following
program compiles fine but may produce unexpected output when run.

2. In C, it is not compiler error to initialize an array with more elements


than specified size. For example the below program compiles fine.
Points to remember:

We will not get compile time error but get a warning (may get error
also- i.e, compiler dependent)
#include<stdio.h>
int main()
{

int arr[3]={1,2,3,9,10};
printf("%p\n%p\n%p\n%p\n%p\n\n\
n",arr,arr+1,arr+2,arr+3,arr+4);
printf("%p\n%p\n%p\n%p\n%p\
n",&arr[0],&arr[1],&arr[2],&arr[3],&arr[4]);
printf("%d\n%d\n%d\n%d\n%d\
n",arr[0],arr[1],arr[2],arr[3],arr[4]);

return 0;
}
Points to remember:
 If 1 array element is initialized, remaining contains 0
 If no array element is initialized, all the elements will contain 0 or
garbage value (compiler dependent)
Advantages & Disadvantages of
Array
 Advantages
 Arrays allow random access to elements. This makes accessing
elements by position faster.
 Arrays represent multiple data items of the same type using a single
name.

 Disadvantages
 You can’t change the size i.e. once you have declared the array you
can’t change its size because of static memory allocation. Here
Insertion(s) and deletion(s) are difficult as the elements are stored in
consecutive memory locations and the shifting operation is costly too.
Arrays and Pointer in C
(important)
Arrays and Pointer in C
(important)
Pointer and []
Example-1

Output
Example-2
Output
Difference between pointer and array in C?

1. Behavior of sizeof operator

sizeof(array) returns the amount of memory used by all elements in


array
sizeof(pointer) only returns the amount of memory used by the pointer
variable itself

Output:
Size of arr[] 24
Size of ptr 4
Difference between pointer and array in C?

2. Assigning any address to an array variable is not allowed.


Similarity between pointer and array in C?

1) Array name gives address of first element of array.


 Array name in C language behaves like a constant pointer and
represents the base address of the array.
 It points to the first element of the array which is located at 0th index.
As array name serves like a constant pointer, it cannot be changed
during the course of program execution.
 Example: int arr[] = {1,23,17,4,-5,100};
 Here we have an array containing 6 integers. Here,
arr = &arr[0];
and
*(arr+0)=a[0];
Similarity between pointer and array in C?

2) Array members are accessed using pointer arithmetic.


Compiler uses pointer arithmetic to access array element. For example,
an expression like “arr[i]” is treated as *(arr + i) by the compiler.
Similarity between pointer and array in C?

3. Array parameters are always passed as pointers, even when we use


square brackets.

Output:
sizeof(ptr) = 4 or 8
(compiler dependent)
*ptr = 10
Computing address in one
Dimensional Arrays
 Below is the pictorial representation of arr, where the array arr points
to first element at location 0. This element has address 1024 that is
the base address of the array and represented by the array name.
Computing address in one
Dimensional Arrays
 Elements stored in an array are accessed by following the syntax
"arrayName[index]" e.g., arr[3] yields 4 in above example.
 This strategy computes the address of the desired element by
combining the base address of the array with the index of desired
element.
 Every array element takes a fixed number of bytes, which is known at
compile time and this is decided by the type of array. In above
example array is of type integer thus consumes 4 bytes (size of
integer) per element.
 nth element address = base address of array + (n * size of
element in bytes)
 Ex: arr[3]= 1024+(3*4)=1036 (Here base address is 1024 and
n is 3)
Computing address in 2D array
 https://www.geeksforgeeks.org/calculation-of-address-of-element-of-1-
d-2-d-and-3-d-using-row-major-and-column-major-order/
Array and Function
 Passing Array to Function
Single element of an array can be passed in similar manner as
passing variable to a function.
Array and Function
Passing an entire one-dimensional array to a function
 While passing arrays as arguments to the function, only the name of the
array is passed (,i.e, starting address of memory area is passed as argument).
 When we pass an array to a function, the reference of the array "decays" into
a pointer to its first element.

Declaring Function with array in parameter list


 We can either have an array in parameter.
int sum (int arr[])
 Or, we can have a pointer in the parameter list, to hold base address of array.
int sum (int* ptr)
 int sum (int arr[]) means exactly the same as int sum (int* ptr)
Example 1
Example: C program to pass an array containing age of person to a
function. This function should find average age and display the
average age in main function.
Example 2
PART A
PART B
Passing 2d array to function
Array Operations:

 Insertion
 Deletion
 Searching
 Sorting
// An iterative binary search function.
int binarySearch(int arr[], int low, int high, int x)
{
while (low <= high) {
int mid = low + (high - low) / 2;

// Check if x is present at mid


if (arr[mid] == x)
return mid;

// If x greater, ignore left half


if (arr[mid] < x)
low = mid + 1;

// If x is smaller, ignore right half


else
high = mid - 1;
}

// If we reach here, then element was not present


return -1;
}
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {

// Assume the current position holds the minimum element


int min_idx = i;

// Iterate through the unsorted portion to find the actual minimum


for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {

// Update min_idx if a smaller element is found


min_idx = j;
}
}

// Move minimum element to its correct position


int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
 void bubbleSort(int arr[], int n){
 int i, j;
 bool swapped;
 for (i = 0; i < n - 1; i++) {
 swapped = false;
 for (j = 0; j < n - i - 1; j++) {
 if (arr[j] > arr[j + 1]) {
 swap(&arr[j], &arr[j + 1]);
 swapped = true;
 }
 }
 // If no two elements were swapped by inner loop,
 // then break
 if (swapped == false)
 break;
 }
 }
Best case time complexity: O (N)
Lab Exercise 1
 Write a menu driven program for the following tasks:
 A) Insertion at desired location
 B) Delete an element from the desired location
 C) Search an element using Linear Search
 D) Search an element using Binary Search
 E) Sort an array using Bubble sort

You might also like