SYBCom(CA) DS Practical Slip 9 Q.A

Write a ‘C’ program to accept n elements store those elements in array and find
and replace a given number.

#include <stdio.h>

int main() {
    int n, i, found = 0;
    int search, replace;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];

    // Input elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Input number to search and replace
    printf("Enter number to find: ");
    scanf("%d", &search);

    printf("Enter number to replace with: ");
    scanf("%d", &replace);

    // Find and replace
    for(i = 0; i < n; i++) {
        if(arr[i] == search) {
            arr[i] = replace;
            found = 1;
        }
    }

    if(found)
        printf("Number replaced successfully.\n");
    else
        printf("Number %d not found in the array.\n", search);

    // Display updated array
    printf("Updated array:\n");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
Spread the love

Leave a Comment

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

Scroll to Top