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:
- Declare an array to store the numbers.
- Take array input using a for loop.
- Run another for loop on the array to process each element.
- Inside the loop, write an IF condition to check if the number is odd.
- 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.