C Program to Accept n Elements in an Array and Find & Replace a Given Number
Arrays are one of the most important concepts in C programming. In this program, we will accept n elements, store them in an array, then find and replace a given number.
📝 Problem Statement
Q1. A) Write a ‘C’ program to accept n elements, store those elements in an array and find and replace a given number.
💡 Logic (Simple Student-Friendly Steps)
- Declare an array.
- Read the number of elements (n).
- Read n elements into the array.
- Ask the user to enter:
- The number to find.
- The number to replace with.
- Use a
forloop:- If element equals the number to find,
- Replace it with the new number.
- Print the updated array.
💻 Source Code (Simple Version)
#include <stdio.h>
int main()
{
int arr[100], n, i;
int find, replace;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter number to find: ");
scanf("%d", &find);
printf("Enter number to replace: ");
scanf("%d", &replace);
for(i = 0; i < n; i++)
{
if(arr[i] == find)
{
arr[i] = replace;
}
}
printf("Updated array is:\n");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
🖥️ Sample Output
Enter number of elements: 5
Enter elements:
10
20
30
20
40
Enter number to find: 20
Enter number to replace: 99
Updated array is:
10 99 30 99 40
🎓 Viva Questions with Answers
1. What is an array?
An array is a collection of elements of the same data type stored in continuous memory locations.
2. Which loop is used to traverse an array?
The for loop is commonly used.
3. How do we replace an element in an array?
By assigning a new value using arr[i] = new_value;.
4. What is the index of the first element?
The first index is 0.
5. What is the time complexity of find and replace?
O(n), because we check each element once.
