132k views
0 votes
Write a C++ Program to find Sum of Odd Numbers from an array.

Follow the instructions:
Declare an array
Take an array input using for loop
Run another for loop on the array
Write IF condition to check the number is odd or not
IF odd then do summation

1 Answer

6 votes

Final answer:

To calculate the sum of odd numbers in a C++ array, declare an array, input its elements, iterate over them, check if each is odd using an IF condition, and add it to a sum variable if it is odd.

Step-by-step explanation:

To find the sum of odd numbers from an array in C++, you can follow these steps:

  1. Declare an array to store the numbers.
  2. Take array input using a for loop.
  3. Run another for loop on the array to process each element.
  4. Inside the loop, write an IF condition to check if the number is odd.
  5. If the number is odd, add it to a sum variable.

Here's a sample C++ program to demonstrate this:

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n]; // Declare the array
int sum = 0; // Initialize sum of odd numbers

// Taking input in the array
for (int i = 0; i < n; i++) {
cout << "Enter element " << i + 1 << ": ";
cin >> arr[i];
}

// Finding sum of odd numbers
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) { // Check if the number is odd
sum += arr[i]; // Sum odd number
}
}

cout << "Sum of odd numbers: " << sum << endl; // Display the sum

return 0;
}

This program will calculate and print the sum of odd numbers from the given array.

User Trendfischer
by
8.6k points

No related questions found