Programming Elements
Chapter 3
Arrays; Arrays (1-D, 2-D), Character arrays and Strings
Why Arrays
• Declaring and Using Multiple variables of same type
• Int a=3, b=4, c=5, d, e, f, g, h….
• Int a=3;
• Int b=4;
• Int c=5;
• Int arr[10] = {3, 4, 5……}
• One Dimensional Array
Multi-Dimensional Array - Concepts
• Character=‘I’, ‘K’, ‘G’/Int/Float
• 1D=> String = “IKGPTU Kapurthala” null Character \0
• 2D=> Page = Multiple String
• 3D=> Book = Multiple Pages
• 4D=> Rack = Collection Books
• 5D=> Library = Collection Rack
• 6D=> Collection of Libraries
Basics of Array for C-Language
• An array is used to store a collection of data of the same data type.
• Declaring Arrays [1-D]
• datetype arrayName [arraySize];
• int numberArray[4] = {5, 3, 7, 1};
• int numberArray[] = {5, 3, 7, 1};
• int numberArray[4] = {5, 3};
Array of Characters
• char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0’};
• char greeting[] = "Hello";
• printf("Greeting message: %s\n", greeting );
• sizeof(greeting)
Passing array to Functions
• Method 1
void myFunction(int *param) {
…
}
• Method 2
void myFunction(int param[10]) {
…
}
• Method 3
void myFunction(int param[]) {
…
}
Practice Programs
Given array is int data type
1. WAP to find average of an array.
2. WAP to find maximum and minimum number is an array.
3. WAP to sort an array in using Bubble Sort method.
4. WAP to sort an array in using Insertion method.
5. WAP to sort an array in using Selection method.
6. WAP to display an array in reverse order.
7. WAP to list unique elements in another array.
2-D Array – An Array of Arrays
• Declaration
• DataType arrayName[Row][Col];
• 2D Array Visualization (For example, int exmArr[2][3]=5)
0 1 2 3 4 5
2 23
3
2D Array Initialization
• Method-1
int arrOne[2][3] = {2, 4, 6, 1, 3, 5};
• Method-2
int arrTwo[2][3] = {
{2, 4, 6},
{1, 3, 5}
};
• Accessing elements => arrTwo[1][2] = 5;
3D Arrays
• Declaration of 3D array
int array3D[Row][Col][Page]; // R C P
• Declaration with initialization
int arrayMethod1[2][2][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int arrayMethod2[2][2][3] = {
{{1, 2, 3}, {4, 5, 6}},
{{7, 8, 9}, {10, 11, 12}}
};
2D Char Array
• Declaration
char fruitBasket[ ][12] = { “3 Orange”,
“2 Banana”,
“4 Apple”,
“2 Pineapple”};
3 O r a n g e \0 \0 \0 \0
2 B a n a n a \0 \0 \0 \0
4 A p p l e \0 \0 \0 \0 \0
2 P i n e a p p l e \0
Array of Pointers
• Declaration
char *fruitBasket[] = { “3 Orange”,
“2 Banana”,
“4 Apple”,
“2 Pineapple”};
fruitBasket[0] 3 O r a n g e \0
fruitBasket[1] 2 B a n a n a \0
fruitBasket[2] 4 A p p l e \0
fruitBasket[3] 2 P i n e a p p l e \0
Array & Pointer
• Pointers
char someArray[5] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}
*somePointer
Memory Locations 2000 2001 2002 2003 2004 2005
someArray a e i o u \0
1-Byte 1-Byte 1-Btye 1-Byte 1-Byte 1-Byte 1-Byte
2D Array Programs
• WAP to calculate determinant of a 3x3 int matrix
• WAP a to add two int square matrices.
• WAP a to multiply two int rectangular matrices.
1 2
•𝐴=
3 4
3 1
•𝐵=
2 4
4 3
• 𝐴𝑛𝑠 =
5 8