Back to C Programming
2026-07-145 min read

Change Value of Array Elements

Learn Change Value of Array Elements step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on manipulating array elements in C programming! In this tutorial, we will delve into why it is crucial for exams, interviews, and real-world coding scenarios. We will also walk you through a practical example with detailed explanations. Let's get started!

Why This Matters

Understanding how to change the value of array elements is essential for several reasons:

  1. Exams: Many programming exams will test your ability to handle arrays effectively.
  2. Interviews: During job interviews, you may be asked to solve problems involving arrays and their elements.
  3. Real-world scenarios: Arrays are frequently used in various applications, games, and data structures, making it essential to know how to modify array elements as needed.
  4. Enhancing code readability and maintainability by allowing developers to easily update or change values within an array.
  5. Facilitating efficient data manipulation and processing through dynamic memory allocation when dealing with large datasets.

Prerequisites

To follow this guide, you should have a basic understanding of the following concepts:

  1. C programming basics, including variables, data types, operators, pointers, and functions.
  2. Array declarations and initializations in C.
  3. Basic input/output (I/O) operations using scanf(), printf(), and other standard library functions.
  4. Understanding of pointers and dynamic memory allocation to handle arrays of varying sizes.

Core Concept

Declaring and Initializing Arrays

In C, an array is a collection of elements of the same data type, stored in contiguous memory locations. To declare an array, you specify its data type followed by the array name and square brackets containing the array size:

int arr[5]; // Declare an array named 'arr' with 5 integer elements

To initialize an array, you can assign values to each element during declaration or use assignment statements afterward.

int arr[5] = {1, 2, 3, 4, 5}; // Initialize the array 'arr' with given values

Changing Array Elements

To change the value of an array element, you simply assign a new value to its index. Remember that array indices start from 0:

arr[0] = 10; // Change the first element's value to 10

Accessing Array Elements

To access an array element, you use its index within the square brackets:

printf("%d", arr[2]); // Print the third element's value (since indices start from 0)

Dynamic Memory Allocation for Arrays

To declare a dynamic-sized array, use malloc() to allocate memory dynamically:

int *arr = (int *) malloc(size * sizeof(int));
// ...
free(arr); // Don't forget to free the memory when done!

Worked Example

Let's consider a simple example where we read numbers from the user, store them in an array, and then find the sum of all even numbers.

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, *arr; // Declare a pointer to an integer array
printf("Enter the number of integers: ");
scanf("%d", &n);

arr = (int *) malloc(n * sizeof(int)); // Dynamically allocate memory for the array

printf("Enter %d integers: ", n);
// Read numbers from the user and store them in the array
for (i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}

int sum = 0; // Initialize the sum variable
// Check if the current number is even and add it to the sum variable
for (i = 0; i < n; ++i) {
if (arr[i] % 2 == 0) {
sum += arr[i];
}
}

// Print the sum of all even numbers found in the input
printf("The sum of even numbers is: %d\n", sum);

free(arr); // Free the dynamically allocated memory when done!
return 0;
}

Common Mistakes

  1. Forgetting to initialize an array: Always initialize arrays when they are declared, or assign default values using loops if the size isn't known at compile time.
  2. Accessing out-of-bounds array elements: Be mindful of the array bounds, as accessing invalid indices can lead to unexpected behavior and segmentation faults.
  3. Not accounting for negative indices: In C, negative indices are valid but count from the end of the array instead of the beginning.
  4. Failing to handle empty arrays: Check if an array is empty before trying to access or manipulate its elements.
  5. Using scanf() without a specific format specifier for the data type: Always use the correct format specifier for the data type you're reading, such as %d for integers and %f for floating-point numbers.
  6. Forgetting to free dynamically allocated memory when it is no longer needed.
  7. Using pointers incorrectly or not understanding their role in handling arrays.
  8. Overlooking the difference between statically allocated arrays and dynamically allocated arrays.

Practice Questions

  1. Write a program that reads an array of 10 integers from the user and finds the maximum value using both static and dynamic memory allocation methods.
  2. Create a program that sorts an array of 10 integers in ascending order using bubble sort, quicksort, or mergesort.
  3. Write a function to reverse the elements of an array without using any additional arrays or temporary variables (in-place reversal).
  4. Implement a program that checks if an array contains a specific target number using linear search and binary search.
  5. Develop a program that finds the second-highest number in an array of 10 integers using both static and dynamic memory allocation methods.
  6. Write a function to find the kth smallest element in an unsorted array of size n using quickselect algorithm.
  7. Implement a program that calculates the average (mean) of elements in an array using both static and dynamic memory allocation methods.
  8. Create a program that finds the median of an odd-sized sorted array and the average of two middle elements for even-sized sorted arrays.
  9. Write a function to find the first occurrence of a specific target number in an array using linear search, binary search, or jump search depending on the size of the array.
  10. Develop a program that finds all pairs of integers (i, j) such that arr[i] + arr[j] equals a given sum S, where 0 <= i < j < n.

FAQ

How can I find the average (mean) of elements in an array?

To calculate the average (mean) of elements in an array, sum all the elements and divide by the array size:

float avg = 0;
for (int i = 0; i < size; ++i) {
avg += arr[i];
}
avg /= size;

How can I find the sum of all elements in an array?

To calculate the sum of all elements in an array, simply iterate through the array and add each element to a variable:

int sum = 0;
for (int i = 0; i < size; ++i) {
sum += arr[i];
}

How can I find the maximum value in an array?

To find the maximum value in an array, compare each element to a variable that keeps track of the current maximum value:

int max = arr[0];
for (int i = 1; i < size; ++i) {
if (arr[i] > max) {
max = arr[i];
}
}

How can I find the minimum value in an array?

To find the minimum value in an array, compare each element to a variable that keeps track of the current minimum value:

int min = arr[0];
for (int i = 1; i < size; ++i) {
if (arr[i] < min) {
min = arr[i];
}
}