Here’s a beginner-friendly blog post explaining the provided C program that uses arrays. How to Modify Array Elements in C – A Beginner’s Guide
Introduction
In this tutorial, we’ll look at a simple program that initializes an array, prints its elements, modifies them, and then prints the modified array. This is a great way to understand how arrays work in C and how we can change array elements.
Understanding the Program
In C, an array is a way to store multiple values of the same data type. Here, we’ll declare an array called marks
and then explore how to initialize, access, and modify each element of the array.
Let’s dive into the code step-by-step.
Code
#include<stdio.h>
void main() {
int marks[3] = {10, 20, 30}; // Initializing the array with values
// Printing original array elements
for(int i = 0; i < 3; i++) {
printf("%d ", marks[i]);
}
printf("\n");
// Modifying array elements
marks[0] = 1;
marks[1] = 1;
marks[2] = 1;
// Printing modified array elements
for(int i = 0; i < 3; i++) {
printf("%d ", marks[i]);
}
}
Explanation
- Declaring and Initializing the Array
int marks[3] = {10, 20, 30};
Here, we declare an integer array called marks
with a size of 3. This array is initialized with three values: 10, 20, and 30.
- Printing the Original Array Elements
for(int i = 0; i < 3; i++) {
printf("%d ", marks[i]);
}
- This loop goes through each element in the
marks
array and prints its value. - When
i
is 0, it printsmarks[0]
, which is 10. - When
i
is 1, it printsmarks[1]
, which is 20. - When
i
is 2, it printsmarks[2]
, which is 30.
- Modifying the Array Elements
marks[0] = 1;
marks[1] = 1;
marks[2] = 1;
- Here, we change the values of each element in the array.
marks[0]
,marks[1]
, andmarks[2]
are all set to 1.
- Printing the Modified Array Elements
for(int i = 0; i < 3; i++) {
printf("%d ", marks[i]);
}
- After modifying the elements, we again use a loop to print the new values.
- This time, since each element is set to 1, the output will show
1 1 1
.
Complete Output
When you run this code, you’ll see:
10 20 30
1 1 1
- The first line displays the initial values of the array (
10 20 30
). - The second line displays the modified values of the array after setting each element to 1 (
1 1 1
).
Conclusion
In this program, we learned how to:
- Declare and initialize an array.
- Access and print each element in an array.
- Modify the elements in an array.
Arrays in C allow us to store and manipulate multiple values easily. By practicing modifying array elements as shown here, you can develop a strong foundation for using arrays in larger programs.
Happy Coding!