Introduction to Computing
and Programming
Arrays and Function
Following are the basic Array operations:
1. Traverse − Print each element in the array one by one.
2. Insertion − At the specified index, adds an element.
Basic Array
3. Deletion − The element at the specified index is deleted.
Operations
4. Search − Uses the provided index or the value to search
for an element.
5. Update − The element at the specified index is updated.
Array Traversal
• Traversal is the process in which we visit every
element of the data structure.
• Loops to iterate through each element of the
array.
• Array Traversal using for Loop
for (int i = 0; i < N; i++) {
array_name[i];
}
Array Operation: Insert
an element at the end of
the array
#include <stdio.h> if (n >= capacity)
int main() {printf("\nElement cannot be inserted");}
{ else{
int arr[10] = { 12, 16, 20, 40, 50, 70 }; arr[n] = key;
int capacity = sizeof(arr) / sizeof(arr[0]); n = n+1;}
int n = 6; printf("\n After Insertion: ");
int i, key = 26; for (i = 0; i < n; i++)
printf("\n Before Insertion: "); printf("%d ", arr[i]);
for (i = 0; i < n; i++) return 0;
printf("%d ", arr[i]); }
Array Operation: Insert
an element at a position
pos in the array
int main()
{
int arr[15] = { 2, 4, 1, 8, 5 }; arr[pos] = x;
int n = 5; n++;
printf("Before insertion : ");
for (int i = 0; i < n; i++){ printf("After insertion : ");
printf("%d ", arr[i]);} for (int i = 0; i < n; i++) { printf("%d ", arr[i]);}
printf("\n"); return 0;
int x = 50, pos = 5; }
for (int i = n - 1; i >= pos; i--){ arr[i + 1] = arr[i];}
Array Operation:
Delete an element
int main()
{ if (pos == -1) {
int i; printf("\nElement not found");
int arr[] = { 10, 50, 30, 40, 20 }; }
int n = sizeof(arr) / sizeof(arr[0]); else{
int key = 60; for (int i = pos; i < n - 1; i++){
printf("Array before deletion\n"); arr[i] = arr[i + 1];}
for (i = 0; i < n; i++){ n = n-1;}
printf("%d ", arr[i]);} printf("\nArray after deletion\n");
int pos = -1; for (i = 0; i < n; i++){
for (int i = 0; i < n; i++) printf("%d ", arr[i]);}
{ if (arr[i] == key){ return 0;
pos = i;}} }
Array Operation:
Search an element
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main() found = 0; If element does not exist in array */
{ for(i=0; i<size; i++)
int arr[MAX_SIZE]; { if(arr[i] == toSearch)
int size, i, toSearch, found; { found = 1;
printf("Enter size of array: "); break;}}
scanf("%d", &size); if(found == 1)
printf("Enter elements in array: "); { printf("\n%d is found at position %d",
for(i=0; i<size; i++) toSearch, i + 1);
{ }
scanf("%d", &arr[i]); else { printf("\n%d is not found in the array",
} toSearch); }
printf("\nEnter element to search: "); return 0;}
scanf("%d", &toSearch);
Update Array Element
• We can update the value of an element at the given index i in
a similar way to accessing an element by using the array
subscript operator [ ] and assignment operator =.
array_name[i] = new_value;
Update Array Element // Ensure valid index
if (i >= 0 && i < 5) {
printf("Enter the new value: ");
• We can update the value of an element at scanf("%d", &new_value);
the given index i in a similar way to
accessing an element by using the array // Update the value at the given index
subscript operator [ ] and assignment arr[i] = new_value;
operator =
array_name[i] = new_value; // Print the updated array
#include <stdio.h> printf("Updated array: ");
int main() { for (int j = 0; j < 5; j++) {
int arr[5] = {10, 20, 30, 40, 50}; // Initialize an printf("%d ", arr[j]);
array of 5 elements }
int i, new_value; } else {
printf("Invalid index!\n");
// Ask for the index and new value }
printf("Enter the index to update (0-4): "); return 0;
scanf("%d", &i); }
Example: Write a C program that calculates the average of
different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70}; // An array storing different ages
float avg, sum = 0;
int i;
int length = sizeof(ages) / sizeof(ages[0]); // Get the length of the array
for (i = 0; i < length; i++) { // Loop through the elements of the array
sum += ages[i];
}
avg = sum / length; // Calculate the average by dividing the sum by the length
printf("The average age is: %.2f", avg); // Print the average
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
int i;
// Get the length of the array
Write a program int length = sizeof(ages) / sizeof(ages[0]);
that finds the // Create a variable and assign the first array element
of ages to it
lowest age int lowestAge = ages[0];
among different // Loop through the elements of the ages array to find
the lowest age
ages for (i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}}
• A multi-dimensional array can be defined as an array
that has more than one dimension.
• It can grow in multiple directions.
• Syntax:
Multidimensiona • The general form of declaring N-dimensional arrays
is shown below:
l Arrays – 2D
and 3D • type arr_name[size1][size2]….[sizeN];
• Ex.
• Two-dimensional array: int two_d[10][20];
• Three-dimensional array: int
three_d[10][20][30];
Size of Multidimensional Arrays
• The total number of elements that can be stored in a multidimensional array
can be calculated by multiplying the size of both dimensions.
• Example:
• The array arr[10][20] can store total of (10*20) = 200 elements.
• To get the size in bytes, we multiply the size of a single element (in bytes)
by the total number of elements in the array.
• Example:
• The size of array int arr[10][20] = 10 * 20 * 4 = 800 bytes, where the
size of int is 4 bytes.
Two-Dimensional • 2D array is also known as a matrix (a table of rows
Array and columns).
• Example:
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
Access the Elements of a 2D Array
• To access an element of a two-dimensional array, you must specify the
index number of both the row and column.
• This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.
• Example
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
printf("%d", matrix[0][2]); // Outputs 2
Change Elements in a 2D Array
• To change the value of an element, refer to the index number of the element
in each of the dimensions:
• The following example will change the value of the element in the first row
(0) and first column (0):
• Example
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
printf("%d", matrix[0][0]); // Now outputs 9 instead of 1
#include <stdio.h>
int main() {
// Initialize an array with 3 rows and 2 columns
int arr[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
Traversal in // Print each array element's value
for (int i = 0; i < 3; i++) {
2D Array for (int j = 0; j < 2; j++) {
printf("arr[%d][%d]: %d ", i, j, arr[i][j]);
}
printf("\n"); }
return 0;}
#include <stdio.h>
void main ()
{ int arr[3][3],i,j;
Storing and for (i=0;i<3;i++)
printing
{ for (j=0;j<3;j++) {
printf("Enter a[%d][%d]: ",i,j);
elements at } }
scanf("%d",&arr[i][j]);
runtime printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{ printf("\n");
for (j=0;j<3;j++)
{ printf("%d\t",arr[i][j]); } } }
Three-Dimensional (3D) Array in C
• A Three-Dimensional Array or 3D array
is a collection of two-dimensional arrays.
• It can be visualized as multiple 2D arrays
stacked on top of each other.
Declaration and Initialization
Declaration: Initialization:
• type arr_name[x][m][n]; • int arr[2][3][2] = {0, 1, 2, 3,
4, 5, 6, 7 , 8, 9, 10, 11}
Or
• int arr[2][3][2] = { { { 0, 1 }, {
2, 3 }, { 4, 5 } },
• { { 6, 7 }, { 8, 9 }, { 10, 11 } } };
#include <stdio.h> Traversal in
3D array
int main() {
// Create and Initialize the 3-dimensional array
int arr[2][3][2] = { { { 1, 1 }, { 2, 3 }, { 4, 5 } }, { { 6, 7 }, { 8, 9 }, { 10, 11 } } };
for (int i = 0; i < 2; ++i) {// Loop through the depth
for (int j = 0; j < 3; ++j) {// Loop through the rows of each depth
for (int k = 0; k < 2; ++k) // Loop through the columns of each row
printf("arr[%i][%i][%i] = %d ", i, j, k, arr[i][j][k]);
printf("\n");}
printf("\n\n"); }
return 0;}
Advantages:
• Fast access to elements.
• Efficient memory usage.
Advantages
and
Disadvantages Disadvantages:
• Fixed size (in static arrays).
• Insertion and deletion can
be costly.
Use Cases of Arrays
Matrix Buffers and
Data Storage:
Representation: Tables:
Storing Use in graphics,
2D arrays for
collections of tables, and
matrices.
data. buffers.
Array with pointer will be discussed
later
Announcement
• We will post the Assignment on Saturday or Sunday that would be fair with Monday
batch as well.
• Next week, Thursday (26th Sept) class would be of revision class; Attendance will be
given to all the students.
• Till Function would be given to Mid-sem; I will upload the question bank of Array &
Function early next week.
• Will discuss the Mid-sem pattern on Tuesday, 24th Sept.
• We will be taking graded lab 2 from 7th to 11th Oct.
• Office hour for doubt clearing before mid term exam
• 23-09-2024 – 1:30 PM – 3:00 PM
• 24-09-2024 – 9:00 AM – 12:00 PM
• 25-09-2024 – 2:00 PM – 5:00 PM
• 26-09-2024 – 12:30 PM – 2:00 PM
Upcoming Slides
• Functions