DS Practical Slip 9 Q A

C Program to Accept n Elements in an Array and Find & Replace a Given Number

This program demonstrates how to accept elements from the user, store them in an array, and replace a specific value with a new value. It is simple, student-friendly, and commonly asked in practical exams.


📝 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 Steps)

  1. Declare an array.
  2. Accept the number of elements n from the user.
  3. Input n elements into the array.
  4. Accept the number to find and the number to replace.
  5. Traverse the array using a for loop:
    • If an element matches the number to find, replace it.
  6. 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 contiguous memory locations.

2. How do you replace an element in an array?

By assigning a new value: arr[i] = new_value;.

3. What is the index of the first element?

0 (zero).

4. What happens if the number to find is not present?

No changes will be made; the array remains the same.

5. What is the time complexity of find and replace?

O(n), because each element is checked once.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top