SYBCom(CA) DS Practical Slip 2 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;
    
    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]);
    }

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

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

    int found = 0;

    // 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 not found in the array.\n");

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

    return 0;
}
Spread the love

Leave a Comment

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

Scroll to Top