0% found this document useful (0 votes)
8 views

Array

The document provides a comprehensive overview of C arrays, detailing their definition, declaration, initialization, indexing, and access methods. It covers various types of arrays, common mistakes, use cases, limitations, and includes sample code for basic array operations. Additionally, it presents a series of problems and examples to illustrate array manipulation techniques.

Uploaded by

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

Array

The document provides a comprehensive overview of C arrays, detailing their definition, declaration, initialization, indexing, and access methods. It covers various types of arrays, common mistakes, use cases, limitations, and includes sample code for basic array operations. Additionally, it presents a series of problems and examples to illustrate array manipulation techniques.

Uploaded by

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

C Arrays

1. What is an Array

An array is a collection of elements, all of the same data type, stored in contiguous
memory locations. Arrays are used to group related data together.

Compared to the basic data type (int, float & char) it is an aggregate or derived
data type.

Example:

int numbers[5]; // Declares an array of 5 integers

This creates a container capable of storing 5 integers.

All the elements of an array occupy a set of contiguous memory locations. This
means that the elements of an array are stored one after another in memory.

2. How to Declare and Initialize an Array

 Declaration: Specify the type and size of the array.

int arr[10]; // Array of 10 integers

 Initialization: You can initialize arrays at the time of declaration or assign


values later. Ensure all elements are initialized before use, as uninitialized
elements may hold garbage values.

int arr[3] = {10, 20, 30}; // Initializes an array with three values

 Automatic Initialization: Uninitialized elements are set to 0 if explicitly


declared but not fully initialized.

int arr[5] = {1, 2}; // Remaining three elements will be 0

3. Indexing

1
Accessing and manipulating array elements requires knowledge of indexing:
 Array indices in C start from 0 and go up to size-1.
 You must ensure indices stay within bounds to avoid accessing unintended
memory locations, which can lead to undefined behavior.

Example:
int arr[5] = {10, 20, 30, 40, 50};
printf("%d\n", arr[2]); // Accesses the 3rd element (30)

Key Points to Remember


a. First Element Index: Always 0.
b. Last Element Index: size - 1.
c. Index as an Integer: The index must be an integer; floating-point values or
strings are not allowed.
d. Random Access: Arrays allow random access to elements using their
indices, which is efficient for accessing specific data quickly.
e. Pointers and Indexing: Array indexing is closely related to pointers in C,
as arr[i] is equivalent to *(arr + i).

2
4. Accessing Array Elements

Array elements are accessed using their index. Note that indexing starts at 0.

Example:

printf("%d", arr[0]); // Prints the first element

 Updating an Element:

arr[2] = 50; // Sets the third element to 50

5. Looping Through Arrays

Arrays are often used with loops to perform operations on all elements.

Example:

for (int i = 0; i < 5; i++) {


printf("%d ", arr[i]);
}

6. Array Size

The size of an array can be determined using the sizeof operator:

int arr[10];
int size = sizeof(arr) / sizeof(arr[0]); // Total size divided by size of one element
printf("%d\n", sizeof(arr));
printf("%d\n", sizeof(arr[0]));
printf("%d", size);

7. Types of Arrays

 1D Arrays: A single row of elements.

int marks[5] = {80, 90, 85, 70, 95};

 2D Arrays: Arrays with rows and columns, used for tabular data.

3
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

8. Common Mistakes

 Accessing Out-of-Bounds Elements: Always ensure that the index is


within valid bounds (0 to size-1). Accessing outside the range leads to
undefined behavior.

int arr[5];
arr[5] = 10; // Incorrect! Index 5 is out of bounds.

 Forgetting Initialization: Uninitialized arrays may contain garbage values.

9. Use Cases of Arrays

Arrays are particularly useful in the following scenarios:

 Storing Collections of Data: Such as exam scores, daily temperatures, or


product prices.
 Implementing Algorithms: Arrays are essential for algorithms like sorting,
searching, and dynamic programming.
 Matrix Representation: Two-dimensional arrays represent matrices, tables, or
grids.
 Buffering: Arrays can act as temporary storage for data in I/O operations.

10. Limitations

While arrays are useful, they come with certain restrictions:

 Fixed Size: Once declared, their size cannot be altered.


 No Built-in Bounds Checking: The programmer must ensure indices are
within bounds.
 Limited Flexibility: Arrays are not suitable for scenarios requiring frequent
insertions or deletions.

4
Write a program that takes an array of integers as input, calculates the sum of all
elements, and prints the result.

Sample Code:

#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int sum = 0;

for (int i = 0; i < 5; i++) {


sum += arr[i];
}

printf("Sum of array elements: %d\n", sum);


return 0;
}

Sessional Problems

Basic Array Problems

1. Input and Output:


o Write a program to take input of n elements in an array and print them.
o Reverse the elements of an array and print the result.

2. Sum and Average:


o Find the sum of all elements in an array.
o Calculate the average of elements in an array.

3. Find Maximum and Minimum:


o Find the largest element in an array.
o Find the smallest element in an array.

4. Search in an Array:

5
o Write a program to search for a specific element in an array using linear
search.

Input:
Enter the number of elements in the array: 5
Enter 5 elements of the array: 10 20 30 40 50
Enter the element to search: 30

Output: Element 30 found at index 2 (position 3).

5. Frequency of Elements:
o Count the occurrences of a given number in an array.
o Find the element that occurs the most times in an array.

Input:
Enter the number of elements in the array: 7
Enter 7 elements of the array: 1 2 3 2 4 2 3

Output:
The most frequent element is 2, which occurs 3 times.

#include <stdio.h>
void main()
{
int n, maxCount = 0, mostFrequent;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];

printf("Enter %d elements of the array:\n", n);


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Find the most frequent element


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

6
}
}
if (count > maxCount) {
maxCount = count;
mostFrequent = arr[i];
}
}
// Output the result
printf("The most frequent element is %d, which occurs %d times.\n",
mostFrequent, maxCount);
}

6. Array Index Operations:


o Print the indices of all occurrences of a given element in an array.

Input:
Enter the number of elements in the array: 7
Enter 7 elements of the array: 1 3 5 3 7 9 3
Enter the element to search for: 3

Output:
The element 3 is found at indices: 1 3 6

Solution:

#include <stdio.h>

int main() {
int n, key, found = 0;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Input the element to search for


printf("Enter the element to search for: ");
scanf("%d", &key);
// Print indices of all occurrences

7
printf("The element %d is found at indices: ", key);
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
printf("%d ", i);
found = 1;
}
}
// If the element is not found
if (!found) {
printf("None");
}
}

o Swap the first and last elements of an array.

7. Array Manipulation:
o Delete an element from a specific position in an array.

Input:
Enter the number of elements in the array: 6
Enter 6 elements of the array: 10 20 30 40 50 60
Enter the position of the element to delete (1 to 6): 3

Output: Updated array: 10 20 40 50 60


#include <stdio.h>
int main() {
int n, pos;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
// Input elements of the array
printf("Enter %d elements of the array:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input the position to delete from
printf("Enter the position of the element to delete (1 to %d): ", n);
scanf("%d", &pos);
// Validate position

8
if (pos < 1 || pos > n) {
printf("Invalid position!\n");
return 1;
}
// Delete the element by shifting elements to the left
for (int i = pos - 1; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
// Decrease the size of the array
n--;
// Print the updated array
printf("Updated array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}

o Remove duplicate elements from an array.

Intermediate Array Problems

9. Matrix Representation (2D Arrays):


o Write a program to read a 3x3 matrix and print it.
o Find the sum of each row and column of a 2D array.

10. Rearranging Elements:


o Move all negative elements to one side of an array.
o Rotate an array by k positions to the left or right.

11. Reversals:
o Reverse the contents of a one-dimensional array.
o Reverse the rows of a 2D array.

12. Prefix and Suffix Operations:


o Compute the prefix sum of an array.
o Find the maximum difference between two elements where the larger
element comes after the smaller one.

9
13. Specialized Searching:
o Find the second largest and second smallest elements in an array.
o Check if an array is a palindrome (reads the same forward and backward).

Advanced Array Problems


14. Cyclic Operations:
o Rotate an array cyclically by one position.
o Implement the "circular buffer" mechanism for fixed-size input.
15. Set Operations:
o Find the union of two arrays.
o Find the intersection of two arrays.
16. Subarray Problems:
o Find the sum of a given subarray.
o Find the subarray with the maximum sum (Kadane’s Algorithm).
17. Pattern Problems:
o Check if an array contains a given pattern as a subarray.
o Count the number of subarrays with a given sum.
18. Multidimensional Arrays:
o Multiply two matrices.
o Transpose a matrix.
19. Special Tasks:
o Find the majority element in an array (appears more than n/2 times).
o Check if two arrays are permutations of each other.
20. Custom Logic:
o Rearrange an array such that the elements are in the form arr[i] = i wherever
possible.
o Implement a sparse matrix representation using arrays.

Example 1: Find Maximum Element


#include <stdio.h>

int main() {
int arr[5] = {10, 20, 5, 7, 50};
int max = arr[0];

for (int i = 1; i < 5; i++) {


if (arr[i] > max) {
max = arr[i];

10
}
}

printf("Maximum element: %d\n", max);


return 0;
}

Example 2: Reverse an Array


#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("Original array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

printf("\nReversed array: ");


for (int i = 4; i >= 0; i--) {
printf("%d ", arr[i]);
}
return 0;
}

Example 3: Rotate Array by One Position


#include <stdio.h>

int main()
{
int arr[5] = {1, 2, 3, 4, 5};
int temp = arr[0];

for (int i = 0; i < 4; i++) {


arr[i] = arr[i + 1];
}
arr[4] = temp;

printf("Rotated array: ");


for (int i = 0; i < 5; i++) {

11
printf("%d ", arr[i]);
}
return 0;
}

12

You might also like