I know just a little about programming but I'm pretty new to C++. I just started to study it one week ago and I'm posting a question about the code I wrote since I can't solve few small problems.
The program I wrote asks how many elements you'd like to analyze and it returns the sum of the elements, how many even and odd numbers you inserted, the sum of the odd and even numbers only and it should returns the maximum (and minimum) value.
This is the code:
#include <iostream>
using namespace std;
int elements, sum = 0, x, arr[10], even = 0, odd = 0, evenSum = 0, oddSum = 0,
mx; //Variable declaration
int main() {
cout << "Type how many elements you would like to sum and analyze" << endl; //Input of the numbers of elements to analyze
cin >> elements;
if (elements > 10)
cout << "Too many elements" << endl; //If the elements are more than 10, the program quit
else {
for (x = 1; x <= elements; x++) {
cout << "Type the element number " << x << endl; //Input of elements to assign to the array
cin >> arr[x];
}
for (x = 1; x <= elements; x++) { //Sum of the elements of the array
sum += arr[x];
}
mx = arr[0];
for (x = 1; x <= elements; x++) { //Find the maximum value of the array
if (arr[0] >= mx) {
mx = arr[0];
}
}
for (int x = 1; x <= elements; x++) { //Count and sum of the even elements
if (arr[x] % 2 == 0) {
even++;
evenSum += arr[x];
}
if (arr[x] % 2 != 0) { //Count and sum of the odd elements
odd++;
oddSum += arr[x];
}
}
cout << "The sum of the elements of the array is: " << sum << endl; //Outputs
cout << "The max value of the array is: " << mx << endl;
cout << "Even numbers are: " << even << endl;
cout << "Odd numbers are: " << odd << endl;
cout << "The sum of even numbers is: " << evenSum << endl;
cout << "The sum of odd numbers is: " << oddSum << endl;
}
return 0;
}
My questions are:
- Do I have to repeat the "for" loop 4 times or, since the conditions of the loops are the same, I can write it only one time followed by the code to execute?
- To calculate the maximum value, I used as a variable name "max" but the editor doesn't compile. I changed the name from "max" to "mx" and it compiles. Is "max" a reserved word for C++? What is wrong?
- Why the program always gives "0" as the maximum value of the array? I can't understand what is wrong in the algorithm and I can get the maximum value of the listed elements.
Thank you very much for the support. Matteo