I. Basic Array Concepts
1. Define array. Why do we use arrays in computer programs?
Array Definition: An array is a collection of elements of the same data type stored in contiguous memory locations. Each element can be accessed using an index.
Why we use arrays:
- To store multiple values of the same type under a single name
- To efficiently manage and process large amounts of data
- To enable easy access to elements using indices
- To reduce code complexity when working with multiple similar variables
- To facilitate operations on collections of data (sorting, searching, etc.)
- To implement data structures like stacks, queues, and matrices
2. Can we store both integer and float types of data in a single array? Demonstrate this by writing a simple C program.
No, we cannot store different data types in the same array in C. All elements in an array must be of the same data type.
However, we can use unions or structures to store different data types, but this is not a standard array. Here's a demonstration:
#include <stdio.h>
int main() {
// This will cause compilation error
// int float mixedArray[5] = {1, 2.5, 3, 4.7, 5}; // INVALID
// Correct approach - separate arrays for different types
int integers[3] = {1, 2, 3};
float floats[3] = {1.5, 2.5, 3.5};
printf("Integer array: ");
for(int i = 0; i < 3; i++) {
printf("%d ", integers[i]);
}
printf("\nFloat array: ");
for(int i = 0; i < 3; i++) {
printf("%.1f ", floats[i]);
}
return 0;
}
Note: In C, all elements of an array must be of the same data type. If you need to store different data types, consider using structures or unions.
3. Write the indices of the first and last element of the following array declaration.
char city[7] = {'S', 'I', 'L', 'C', 'H', 'A', 'R'};
First element index: 0 (city[0] = 'S')
Last element index: 6 (city[6] = 'R')
Note: In C, array indices always start from 0. For an array of size N, the valid indices are from 0 to N-1.
4. Write a C program and declare an integer type array with capacity 7. Take input to the array from the keyboard. Display the 8th element of the array. Hint: display num[7] if num is the name of the array. Analyze the output.
#include <stdio.h>
int main() {
int num[7]; // Array with capacity 7 (indices 0 to 6)
int i;
// Taking input
printf("Enter 7 integers:\n");
for(i = 0; i < 7; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &num[i]);
}
// Displaying all elements
printf("\nArray elements: ");
for(i = 0; i < 7; i++) {
printf("%d ", num[i]);
}
// Trying to access 8th element (index 7)
printf("\n\nTrying to access 8th element (num[7]): %d\n", num[7]);
return 0;
}
Analysis: Accessing num[7] is accessing memory beyond the array bounds. This will:
- Compile successfully (no syntax error)
- Cause undefined behavior at runtime
- May display garbage value or cause program crash
- Is a common source of bugs in C programs
5. Write a C program and declare an integer type array with 7 elements in it. Display the address of the individual elements in the array.
#include <stdio.h>
int main() {
int arr[7] = {10, 20, 30, 40, 50, 60, 70};
int i;
printf("Array elements and their addresses:\n");
for(i = 0; i < 7; i++) {
printf("arr[%d] = %d, Address = %p\n", i, arr[i], &arr[i]);
}
// Demonstrating contiguous memory allocation
printf("\nDifference between consecutive addresses: %ld bytes\n",
(long)(&arr[1]) - (long)(&arr[0]));
return 0;
}
Output Analysis: The program will show that array elements are stored in contiguous memory locations, with each integer typically taking 4 bytes (depending on the system).
II. Array Operations
6. Write a C program and declare two integer type arrays, each with capacity 7. Take input only to the first array. Write a loop to copy the elements of the first array to the second one. Display the elements of the second array.
#include <stdio.h>
int main() {
int arr1[7], arr2[7];
int i;
// Taking input for first array
printf("Enter 7 integers for first array:\n");
for(i = 0; i < 7; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &arr1[i]);
}
// Copying elements from arr1 to arr2
for(i = 0; i < 7; i++) {
arr2[i] = arr1[i];
}
// Displaying second array
printf("\nElements of second array (copied from first): ");
for(i = 0; i < 7; i++) {
printf("%d ", arr2[i]);
}
return 0;
}
7. Write a strategy to find the summation of all the even numbers stored in an array. Write a C program for the same. If the array elements are {1, 2, 4, 3, 5, 6, 7, 7, 8}, the output of the program will be 20.
Strategy:
- Initialize a sum variable to 0
- Iterate through each element of the array
- For each element, check if it's even (element % 2 == 0)
- If even, add it to the sum
- After processing all elements, display the sum
#include <stdio.h>
int main() {
int arr[] = {1, 2, 4, 3, 5, 6, 7, 7, 8};
int size = sizeof(arr) / sizeof(arr[0]);
int sum = 0, i;
for(i = 0; i < size; i++) {
if(arr[i] % 2 == 0) { // Check if number is even
sum += arr[i];
}
}
printf("Sum of even numbers: %d\n", sum);
return 0;
}
8. Write a strategy to find the summation of all the even positioned numbers stored in an array. Write a C program for the same. If the array elements are {1, 2, 4, 3, 5, 6, 7, 7, 8}, the output of the program will be 18.
Strategy:
- Initialize a sum variable to 0
- Iterate through the array with index i starting from 0
- Check if the position is even (i % 2 == 0)
- If position is even, add the element to sum
- Display the final sum
#include <stdio.h>
int main() {
int arr[] = {1, 2, 4, 3, 5, 6, 7, 7, 8};
int size = sizeof(arr) / sizeof(arr[0]);
int sum = 0, i;
for(i = 0; i < size; i++) {
if(i % 2 == 0) { // Check if position is even (0, 2, 4, ...)
sum += arr[i];
}
}
printf("Sum of even positioned numbers: %d\n", sum);
return 0;
}
Note: In programming, positions typically start from 0, so even positions are indices 0, 2, 4, etc.
11. Write a C program to replace all the even positioned elements in an integer array by 0. For example, if the array elements are {1, 2, 3, 9, 5, 5, 7, 1, 9}, it becomes {1, 0, 3, 0, 5, 0, 7, 0, 9}.
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 9, 5, 5, 7, 1, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array: ");
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
// Replace even positioned elements with 0
for(i = 0; i < size; i++) {
if(i % 2 == 1) { // Even positions (1, 3, 5, ...) since we start from 0
arr[i] = 0;
}
}
printf("\nModified array: ");
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
12. Write a strategy to replace all the odd numbers in an integer array by 0. For example, if the array elements are {1, 2, 3, 9, 5, 5, 7, 1, 9}, it becomes {0, 2, 0, 0, 0, 0, 0, 0, 0}. Write a C program for the same.
Strategy:
- Iterate through each element of the array
- For each element, check if it's odd (element % 2 != 0)
- If odd, replace it with 0
- Display the modified array
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 9, 5, 5, 7, 1, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array: ");
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
// Replace odd numbers with 0
for(i = 0; i < size; i++) {
if(arr[i] % 2 != 0) { // Check if number is odd
arr[i] = 0;
}
}
printf("\nModified array: ");
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
III. Advanced Array Problems
9. Write the logic to replace only the first occurrence of an element in an array. For example, if the array elements are {1, 2, 3, 4, 5, 1, 2, 3} and we want to replace element 3 by 0, the array content becomes {1, 2, 0, 4, 5, 1, 2, 3}. Write a complete C program incorporating the logic.
Logic:
- Iterate through the array from start to end
- Check if current element matches the target element
- If match found, replace it with new value and break the loop
- If no match found, continue until the end
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5, 1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3, replace_with = 0;
int i, found = 0;
printf("Original array: ");
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
// Replace first occurrence
for(i = 0; i < size; i++) {
if(arr[i] == target) {
arr[i] = replace_with;
found = 1;
break; // Exit after first replacement
}
}
if(found) {
printf("\nAfter replacing first %d with %d: ", target, replace_with);
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
} else {
printf("\nElement %d not found in array.", target);
}
return 0;
}
10. Write the logic to replace only the last occurrence of an element in an array. For example, if the array elements are {1, 2, 3, 4, 5, 1, 2, 3} and we want to replace element 3 by 0, the array content becomes {1, 2, 3, 4, 5, 1, 2, 0}. Write a complete C program incorporating the logic.
Logic:
- Iterate through the array from end to start
- Check if current element matches the target element
- If match found, replace it with new value and break the loop
- If no match found, continue until the beginning
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5, 1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3, replace_with = 0;
int i, found = 0;
printf("Original array: ");
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
// Replace last occurrence (iterate from end)
for(i = size - 1; i >= 0; i--) {
if(arr[i] == target) {
arr[i] = replace_with;
found = 1;
break; // Exit after last replacement
}
}
if(found) {
printf("\nAfter replacing last %d with %d: ", target, replace_with);
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
} else {
printf("\nElement %d not found in array.", target);
}
return 0;
}
13. Write a C program to store your name and your mother's name in two different strings. Display them one after another.
#include <stdio.h>
int main() {
char myName[50] = "John";
char motherName[50] = "Mary";
printf("My name: %s\n", myName);
printf("Mother's name: %s\n", motherName);
return 0;
}
Alternative version with user input:
#include <stdio.h>
int main() {
char myName[50], motherName[50];
printf("Enter your name: ");
scanf("%s", myName);
printf("Enter your mother's name: ");
scanf("%s", motherName);
printf("\nMy name: %s\n", myName);
printf("Mother's name: %s\n", motherName);
return 0;
}
14. Write a C program to declare 3 integer type arrays to store the marks of 10 students scored in 3 different subjects. Take another integer to store the average marks of the students. The average mark of a student is the average of the marks scored by the student in 3 subjects. This should be calculated and inserted by the program. Then you should display the average marks of the students. The program should also display "PASS" or "FAIL" along with the average as per the rule: PASS if average >= 45, FAIL otherwise.
#include <stdio.h>
int main() {
int subject1[10], subject2[10], subject3[10];
float average[10];
int i;
// Input marks for 10 students
printf("Enter marks for 10 students:\n");
for(i = 0; i < 10; i++) {
printf("\nStudent %d:\n", i+1);
printf("Subject 1: ");
scanf("%d", &subject1[i]);
printf("Subject 2: ");
scanf("%d", &subject2[i]);
printf("Subject 3: ");
scanf("%d", &subject3[i]);
// Calculate average
average[i] = (subject1[i] + subject2[i] + subject3[i]) / 3.0;
}
// Display results
printf("\n\nStudent Results:\n");
printf("Student\tSubject1\tSubject2\tSubject3\tAverage\tStatus\n");
for(i = 0; i < 10; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%.2f\t",
i+1, subject1[i], subject2[i], subject3[i], average[i]);
if(average[i] >= 45) {
printf("PASS\n");
} else {
printf("FAIL\n");
}
}
return 0;
}
15. Write any two limitations of arrays. Can you store your name and roll number in the same array?
Two limitations of arrays:
- Fixed Size: Once declared, the size of an array cannot be changed. This can lead to either wasted memory (if array is too large) or insufficient space (if array is too small).
- Homogeneous Elements: All elements in an array must be of the same data type. You cannot store different data types in the same array.
Can you store your name and roll number in the same array?
No, you cannot store both name (string/char array) and roll number (integer) in the same standard array because:
- Arrays in C are homogeneous - all elements must be of the same type
- Name is typically stored as character array (string)
- Roll number is typically stored as integer
Alternative solutions:
- Use separate arrays for names and roll numbers
- Use structures to combine different data types
- Use arrays of structures