Write a menu driven C program to perform the following operation on an integer array: a) Display the sum of elements at even subscript position of array b) Display the sum of elements at odd subscript position of array

c programs


 Write a menu driven C program to perform the following operation on an integer array:

a) Display the sum of elements at even subscript position of array b) Display the sum of elements at odd subscript position of array


  #include <stdio.h>
int main() {
    int array[100];
    int n, i, sum_even = 0, sum_odd = 0;
    
    printf("Enter the size of the array: ");
    scanf("%d", &n);

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

    int choice;
    do {
        printf("\nMenu:\n");
        printf("1. Display the sum of elements at even subscript position\n");
        printf("2. Display the sum of elements at odd subscript position\n");
        printf("3. Exit\n");
        printf("Enter your choice (1/2/3): ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                sum_even = 0;
                for (i = 0; i < n; i += 2) {
                    sum_even += array[i];
                }
                printf("Sum of elements at even subscript position: %d\n", sum_even);
                break;

            case 2:
                sum_odd = 0;
                for (i = 1; i < n; i += 2) {
                    sum_odd += array[i];
                }
                printf("Sum of elements at odd subscript position: %d\n", sum_odd);
                break;

            case 3:
                printf("Exiting the program.\n");
                break;

            default:
                printf("Invalid choice! Please enter a valid option (1/2/3).\n");
        }

    } while (choice != 3);

    return 0;
}
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.