Addition of Even and Odd of Array Elements


Explanation

An array can store multiple values of the same data type. In this program, the user enters 5 numbers into an integer array. Each array element is checked using the if-else statement. If the number is even, it is added to the even total. Otherwise, it is added to the odd total. Finally, the program displays the sum of even and odd numbers separately.

How It Works?

  • Step 1: Declare an integer array r[5] and variables k, e, and d.
  • Step 2: Initialize e and d with 0.
  • Step 3: Use a for loop to accept 5 numbers from the user and store them in the array.
  • Step 4: Use another for loop to access each array element.
  • Step 5: Check whether the array element is even using r[k] % 2 == 0.
  • Step 6: If the number is even, add it to e; otherwise add it to d.
  • Step 7: Display the total of even and odd numbers separately.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    int r[5], k, e = 0, d = 0;

    clrscr();

    for(k = 0; k <= 4; k = k + 1)
    {

        printf("\nEnter no : ");

        scanf("%d", &r[k]);

    }

    for(k = 0; k <= 4; k = k + 1)
    {

        printf("\n%d", r[k]);

        if(r[k] % 2 == 0)
        {

            e = e + r[k];

        }

        else
        {

            d = d + r[k];

        }

    }

    printf("\nEven total %d", e);

    printf("\nOdd total %d", d);

    getch();

}

Output

Enter no : 10
Enter no : 15
Enter no : 20
Enter no : 25
Enter no : 30

10
15
20
25
30

Even total 60
Odd total 40

Practice Exercises

Task 1: Write a C program to accept 6 numbers into an array and calculate the sum of even numbers and odd numbers separately using a for loop.

Goal: Learn how to use arrays, for loops, and the if-else statement to separate and add even and odd array elements.

💡 Hint: Declare an array of size 6. Initialize two variables even and odd with 0. Check each array element using % 2. If the remainder is 0, add it to the even total; otherwise add it to the odd total.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    int r[6], k, even = 0, odd = 0;

    clrscr();

    for(k = 0; k <= 5; k++)
    {

        printf("Enter no : ");

        scanf("%d", &r[k]);

    }

    for(k = 0; k <= 5; k++)
    {

        if(r[k] % 2 == 0)
        {

            even = even + r[k];

        }

        else
        {

            odd = odd + r[k];

        }

    }

    printf("\nEven total = %d", even);

    printf("\nOdd total = %d", odd);

    getch();

}

Output
Enter no : 12
Enter no : 7
Enter no : 20
Enter no : 15
Enter no : 30
Enter no : 9

Even total = 62
Odd total = 31
Explanation: The program accepts 6 numbers and stores them in an array. A for loop checks each element using the modulus operator %. Numbers divisible by 2 are added to the even variable, while remaining numbers are added to the odd variable. Finally, both totals are displayed separately.