The Program in C++ to Calculate sum of all even and odd numbers in an array is given below:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int oddSum=0,evenSum=0;
int i,size;
cout<<"Hello Codeauri Family,, please enter the size of the array here: ";
cin>>size;
int arr[size];
cout<<"similarly, enter the Array elements here: ";
for(i=0; i<size; i++){
cin>>arr[i];
}
for(i=0; i<size; i++){
if(arr[i]%2==0){
evenSum=evenSum+arr[i];
}
else{
oddSum=oddSum+arr[i];
}
}
cout<<"Then, the sum of odd numbers are calculated as :"<<oddSum;
cout<<"\nThen, the sum of even numbers are calculated as:"<<evenSum;
getch();
return 0;
}
Output:
Hello Codeauri Family,, please enter the size of the array here: 4
similarly, enter the Array elements here: 5
3
10
20
Then, the sum of odd numbers are calculated as :8
Then, the sum of even numbers are calculated as:30
Pro-Tips💡
The program first declares two variables, one for the sum of odd numbers (oddSum) and another for the sum of even numbers (evenSum) and initializes them to 0.
It then prompts the user to enter the size of the array and stores the value in the variable “size”.
It then creates an array of “size” elements called “arr” and prompts the user to enter the elements of the array and stores them in the array using a for loop.
The program then uses another for loop to iterate through each element in the array and checks whether the element is even or odd using the if statement.
If the element is even, it adds the element to the evenSum, otherwise, it adds the element to the oddSum.
Finally, the program outputs the sum of odd numbers and the sum of even numbers and the program is ended with return 0; which indicates the successful execution of the program.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.