Unit 3 Part A Study Material
Unit 3 Part A Study Material
2D Array Declaration
Syntax:
data_type array_name[row_size][column_size];
Example:
int matrix[3][4]; // Declares a 2D int array named 'matrix' with 3 rows and 4 columns
4. How can you initialize a 2D array with braces? Can you initialize an array with fewer
elements than its declared size?
Initializing a 2D Array with Braces
In C programming 2D array are initialised using nested braces. Each pair of inner
braces represents a row, and the elements within them represent the columns.
Here's an example:
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
1 2 3
This saves matrix as 4 5 6
7 8 9
Initializing an Array with Fewer Elements
PS & PwC Unit 3
In C programming one can initialize an array with fewer elements than its declared
size. The remaining elements will be automatically initialized to their default values,
which is usually 0 for numeric data types.
Here's an example:
int numbers[5] = {1, 2, 3};
In this case, the first three elements of the array will be initialized to 1, 2, and 3,
respectively. The remaining two elements (index 3 and 4) will be initialized to 0.
5. Write a code snippet to traverse an array and print its elements.
#include <stdio.h>
int main() {
int size = 5;
// Sample array
int array[size] = {10, 20, 30, 40, 50};
// Traversing the array and printing its elements
for (int i = 0; i < size; i++) {
printf("%d\n", array[i]);
}
return 0;
}
6. What is the index of first element in an Array? How to access third element in an
array named items?
In most programming languages, including C, the index of the first element in an array
is 0. This means that if you have an array, the first element can be accessed using the
index 0.
To access the third element in an array named items, you would use the index 2, since
indexing starts at 0.
items[2];
Index 2 corresponds to the third element and items correspond to the name of the array
An array is a homogenous data structure in which elements same data type are stored,
in contiguous memory locations. Each element can be accessed directly using an index
(or subscript), which represents its position relative to the first element. The index of
first element is typically 0, and it incremented by 1 for each subsequent element. This
allows for efficient random access to any element in constant time, using index
Declaration of a One-Dimensional Array
In C, a one-dimensional array is declared by specifying the type of elements it will hold,
followed by the array name and size in square brackets. The syntax for declaring a one-
dimensional array is:
dataType arrayName[size];
Example:
int numbers[5]; // Declares an array of 5 integers
Initialization of a One-Dimensional Array
Initialization involves assigning values to the elements of the array at the time of
declaration. This can be done in several ways:
1. Static Initialization: Assigning values directly during declaration.
int numbers[5] = {1, 2, 3, 4, 5}; // Initializes the array with specific values
2. Partial Initialization: Omitting some values initializes the remaining elements to zero.
int numbers[5] = {1, 2}; // Initializes to {1, 2, 0, 0, 0}
3. Implicit Size: The size of the array can be omitted if the initial values are provided.
int numbers[] = {1, 2, 3, 4, 5}; // Compiler determines the size as 5
In C, memory for an array is allocated on the stack (for static arrays) or the heap (for
dynamic arrays).
When an array is declared, a contiguous block of memory is allocated to store its
elements. The size of this memory block depends on the data type of the elements and
the number of elements in the array.
For example, if you declare an integer array of size 5, the compiler allocates a block of
memory that can hold 5 integers. The memory addresses of these elements are
consecutive, and the array name represents the address of the first element.
Example of Using a One-Dimensional Array:
#include <stdio.h>
int main() {
// Declaration and initialization
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing and displaying elements
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
PS & PwC Unit 3
return 0;
}
If numbers[0] is stored at the memory location 2000, then the corresponding elements
will be stored at 2004,2008,2012 and 2016. As each element being an integer occupies 4
bytes.
2000-2003 2004-2007 2008-2011 2012-2015 2016-2019
1 2 3 4 5
In summary, arrays in C provide a way to manage collections of data efficiently. A one-
dimensional array is declared with a specific type and size, can be initialized with
values. The elements of an array stored together in the order of their indices.
2. Write a short note on operations on arrays.
Operations on Arrays in C
Arrays are fundamental data structures in C, storing multiple elements of the same
type under a single name. Key operations on arrays include:
1. Initialization
Initialization involves assigning values to the elements of the array at the time of
declaration. This can be done in several ways:
a. Static Initialization: Assigning values directly during declaration.
int numbers [5] = {1, 2, 3, 4, 5};// Initializes the array with specific values
b. Partial Initialization: Omitting some values initializes the remaining elements to
zero.
int numbers [5] = {1, 2};// Initializes to {1, 2, 0, 0, 0}
2. Accessing Elements
Array elements are accessed by their index (starting at 0). The elements of arrays can
be accessed randomly
int first = numbers [0]; // Accesses the first element
int fourth = numbers [3]; // Accesses the fourth element
3. Modification
Elements can be modified by assigning new values at specific indices:
numbers [2] = 10; // Changes the third element to 10
4. Traversal
Arrays are typically traversed using a loop to access each element:
for (int i = 0; i < 5; i++) {
printf ("%d ", numbers[i]);
}
5. Searching
Elements can be found using a linear or binary search (if sorted):
for (int i = 0; i < 5; i++) {
if (numbers[i] == 3) {
printf ("Found 3 at index %d\n", i);
}
}
6. Sorting
Arrays can be sorted using algorithms like bubble sort, selection sort, or quicksort:
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
PS & PwC Unit 3
if (numbers[j] > numbers[j+1]) {
// Swap
int temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
}
}
}
7. Copying
Arrays can be copied element-by-element, as C does not support direct array copying:
int copy [5];
for (int i = 0; i < 5; i++) {
copy[i] = numbers[i];
}
8. Multi-dimensional Arrays
C also supports multi-dimensional arrays, such as 2D arrays for matrices or grids:
int matrix [3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Arrays in C provide versatile and efficient data storage, supporting a range of
operations essential for data manipulation and algorithm implementation.
Understanding these operations is key to effective programming in C.
3. Write a C program to reverse the contents of an integer array without using another
array.
1. Analysis
Problem: We need to write a C program that reverses the elements of an integer array
in place, i.e., without using an additional array for storage. The original array should
be modified so that its elements appear in reverse order.
Chosen Technique:
Two-Pointer Approach: The most efficient way to reverse an array in place is to use
two pointers:
a. One pointer starts at the beginning of the array.
b. Another pointer starts at the end of the array.
c. These two pointers swap the elements they point to, and then move toward
the center.
This technique avoids the need for additional memory and minimizes operations to the
length of the array divided by two.
2. Algorithm
1. Start the program.
2. Declare a variable to store the size of array.
3. Ask the user to input the size of the array
4. Declare an array
5. Run a loop to read and elements of the array from user.
6. Display the contents of the array as entered
6. Initialize two pointers:
• One (start) at the beginning of the array (index 0).
• Another (end) at the last index of the array (index size - 1).
7. Use a while loop, while start is less than end:
PS & PwC Unit 3
7.1 Swap the elements at the start and end indices.
7.1.1 initialise a temp to element pointed by start.
7.1.2 update the element pointed by the start to element pointed by end
7.1.3 Change the element pointed by the end to the value in temp.
7.2 Increment the start pointer and
7.3 decrement the end pointer.
(After the loop ends, the array will be reversed.)
8. Display the reversed array.
9. End the program.
3. Program
#include <stdio.h>
int main() {
int size;
// Step 2: Declare a variable to store the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
// Step 4: Declare an array with the given size
int array[size];
// Step 5: Run a loop to read elements of the array from user
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
// Step 6: Display the contents of the array as entered
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
// Step 6: Initialize two pointers
int start = 0; // Pointer at the beginning
int end = size - 1; // Pointer at the end
// Step 7: Use a while loop, while start is less than end
while (start < end) {
// Step 7.1: Swap elements at start and end indices
int temp = array[start]; // Step 7.1.1
array[start] = array[end]; // Step 7.1.2
array[end] = temp; // Step 7.1.3
// Step 7.2 and 7.3: Increment start and decrement end
start++;
end--;
}
// Step 8: Display the reversed array
printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
PS & PwC Unit 3
printf("\n");
// Step 9: End the program
return 0;
}
4. Expected Output
Enter the size of the array: 5
Enter 5 elements:
12345
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
4. Using arrays, write a program to print the position of the smallest of n numbers.
1. Problem Analysis
The task is to find and print the position (index) of the smallest element in an array of
n numbers. We will:
1. Input the size n of the array and then the elements of the array from the user.
2. Find the smallest element by comparing each element of the array.
3. Print the position (index) of this smallest element.
The position of the smallest element in an array is useful in various scenarios, such as
sorting, finding the minimum cost or shortest path, and more. The position is often
more informative than the value itself, as it helps us locate the specific data point within
the array.
2. Algorithm
1. Start the program.
2. Declare a variable size to store the size of the array.
3. Prompt the user to input the size of the array and store it in size.
4. Declare an array of size size to hold the elements.
5. Loop through the array indices to input each element from the user.
6. Initialize two variables:
o minIndex to 0 (assume the first element is the smallest).
o minValue to the first element of the array.
7. Loop through the array starting from the second element:
o If the current element is smaller than minValue, update minValue and
minIndex to this element’s value and index, respectively.
8. Print the position of the smallest element (i.e., minIndex).
9. End the program.
3. Program:
#include <stdio.h>
int main() {
int size;
// Step 2: Prompt the user to enter the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
// Step 4: Declare the array with the given size
int array[size];
// Step 5: Read elements into the array
printf("Enter %d elements:\n", size);
PS & PwC Unit 3
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
// Step 6: Initialize minIndex and minValue
int minIndex = 0;
int minValue = array[0];
// Step 7: Find the position of the smallest element
for (int i = 1; i < size; i++) {
if (array[i] < minValue) {
minValue = array[i];
minIndex = i;
}
}
// Step 8: Print the position of the smallest element
printf("The smallest element is at position (index) %d.\n", minIndex);
// Step 9: End the program
return 0;
}
4. Expected Output:
Enter the size of the array: 5
Enter 5 elements:
31425
The smallest element is at position (index) 1.
5. Develop a C program to add two matrices. Cover all necessary conditions.
1. Problem Analysis:
The task is to add two matrices. However, to ensure correct matrix addition, we must
first verify that the two matrices have the same dimensions (i.e., the same number of
rows and columns).
2. Algorithm:
1. Start
2. Input Dimensions:
o Prompt the user to input the number of rows and columns for the first
matrix, read the dimensions and store them in row1 and column1.
o Prompt the user to input the number of rows and columns for the
second matrix, read the dimensions and store them in row2 and
column2.
3. Dimension Check:
o Compare the dimensions of the two matrices.
• row1 must be equal to row2 and column1 must be equal to
column2.
o If the dimensions are not equal, display an error message and exit the
program.
4. Input Matrix Elements:
o Prompt the user to input the elements of the first matrix.
o Prompt the user to input the elements of the second matrix.
PS & PwC Unit 3
• Read the elements using a nested for loop each for both the
matrices
5. Matrix Addition: Iterate through each corresponding element of the two
matrices and add them Store the result in the corresponding element of the
sum matrix.
5.1: For i in the range of 0 to row1-1
5.1.1: For j in the range of 0 to column1-1
5.1.1.1: add mat1[i][j] and mat2[i][j] store the result in sum[i][j]
6. Print the Sum Matrix:
o Display the elements of the sum matrix in a matrix format.
6.1: For i in the range of 0 to row1-1
6.1.1: For j in the range of 0 to column1-1
6.1.1.1: Print sum[i][j]
6.1.2: Print new line
7. Stop
3. Program
#include <stdio.h>
int main() {
int rows1, cols1, rows2, cols2;
// Input dimensions of the matrices
printf("Enter the number of rows and columns of the first matrix: ");
scanf("%d %d", &rows1, &cols1);
printf("Enter the number of rows and columns of the second matrix: ");
scanf("%d %d", &rows2, &cols2);
// Check if dimensions are compatible
if (rows1 != rows2 || cols1 != cols2) {
printf("Error: Matrices must have the same dimensions.\n");
return 1;
}
// Declare matrices
int matrix1[rows1][cols1], matrix2[rows2][cols2], sum[rows1][cols1];
// Input elements of the first matrix
printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input elements of the second matrix
printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
scanf("%d", &matrix2[i][j]);
}
}
// Add the matrices
for (int i = 0; i < rows1; i++) {
PS & PwC Unit 3
for (int j = 0; j < cols1; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Print the sum matrix
printf("Sum of the matrices:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
4. Expected output
Enter the number of rows and columns of the first matrix: 2 2
Enter the number of rows and columns of the second matrix: 2 2
Enter elements of the first matrix:
1345
Enter elements of the second matrix:
5643
Sum of the matrices:
69
88
2. Algorithm
8.1.1: For each (i) generate column index (j) from 0 to C2-1
3. Program
#include <stdio.h>
int main() {
int r1, c1, r2, c2;
// Input dimensions
printf("Enter dimensions of first matrix (rows columns): ");
scanf("%d %d", &r1, &c1);
printf("Enter dimensions of second matrix (rows columns): ");
scanf("%d %d", &r2, &c2);
// Check if multiplication is possible
if (c1 != r2) {
printf("Error: Matrices cannot be multiplied.\n");
return 1;
}
// Declare matrices
int A[r1][c1], B[r2][c2], C[r1][c2];
// Input elements for matrix A
printf("Enter elements of first matrix:\n");
for (int i = 0; i < r1; i++) {
PS & PwC Unit 3
for (int j = 0; j < c1; j++) {
scanf("%d", &A[i][j]);
}
}
// Input elements for matrix B
printf("Enter elements of second matrix:\n");
for (int i = 0; i < r2; i++) {
for (int j = 0; j < c2; j++) {
scanf("%d", &B[i][j]);
}
}
// Perform matrix multiplication
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
C[i][j] = 0;
for (int e = 0; e < c1; e++) {
C[i][j] += A[i][e] * B[e][j];
}
}
}
// Print the resultant matrix
printf("Resultant matrix:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
4. Expected Output:
Enter dimensions of first matrix (rows columns): 2 3
Enter dimensions of second matrix (rows columns): 3 3
Enter elements of first matrix:
134526
Enter elements of second matrix:
100010001
Resultant matrix:
134
526