I'm having a bit of trouble with an assignment.
I need to use while loop to obtain 10 numbers. Then I need to output whether each number is even or odd, and output the sum/avg/min/max of the 10 numbers. I've looked at similar questions, but they seem to use array which we did not learn yet.
Below is what I have so far, which makes me stuck in an infinite loop of entering numbers but even/odd does work.
#include <iostream>
usingnamespace std;
int main()
{
int n;
int minimum;
int maximum;
double average;
int x=1;
int sum = 0;
while(x <= 10)
{
cout << " Please enter a number." << endl;
cin >> n;
minimum = n;
maximum = n;
if (n%2==0) {
cout << n << " is even.";
}
else {
cout << n << " is odd.";
}
}
while(x <= n)
{
sum = sum + x;
x = x + 1;
}
average = sum / 10.0;
while(x<=n)
{
cin >> n;
if (n < minimum)
{
minimum = n;
}
x = x + 1;
}
while(x<=n)
{
cin >> n;
if (n > maximum)
{
maximum = n;
}
x = x + 1;
}
cout << "The average is " << average << endl;
cout << "The minimum is " << minimum << endl;
cout << "The maximum is " << minimum << endl;
cout << "The sum is " << sum << "." << endl;
return 0;
}
He still has a point. Always make sure you know what you want your program to do and you can do that by the use of pseudocode. I am not sure if writing it on pencil and paper is necessary.
while loops, do-while loops and for loops are interchangeable just make sure when you use a while loop or do-while loop you have the integer that you are looking for declared outside the loop.
Like this:
1 2 3 4 5 6 7 8 9 10 11
#include <array>;
#include <iostream>;
int main () {
std::array<int, 5>person = {1, 2, 3, 4, 5}
int i = 0
while (0 < 5) {
std::cout << person[i]
i++
}
return 0;
}
or like so:
1 2 3 4 5 6 7 8 9 10 11 12
#include <array>;
#include <iostream>;
int main() {
std::array<int, 5>person = {1, 2, 3, 4, 5}
int i = 0
do {
std::cout << person[i]
i++
}while (0 < 5)
return 0;
}
or finally like:
1 2 3 4 5 6 7 8 9
#include <array>;
#include <iostream>;
int main() {
std::array<int, 5>person = {1, 2, 3, 4, 5}
for (int i = 0; i < 5; i++) {
std::cout << person[i]
}
return 0;
}
Yes I saw examples using array. However, we did not learn them in class, and the assignment has to be done only using the material learned so far.
The link seems helpful, I'll try to fix the code using that
You only need an array if you need/want to store the 10 numbers. Otherwise you can do the calculations progressively as you enter and count the numbers as they are input.
#include <iostream>
usingnamespace std;
int main()
{
int n = 0;
int count = 0;
int sum = 0;
int minimum = 10000;
while(count < 5)
{
cout << " Please enter a number " ;
cin >> n;
if (n % 2 == 0)
cout << n << " is even" << endl;
else
cout << n << " is odd" << endl;
if (n < minimum)
minimum = n;
sum += n;
count++;
}
cout << "The minimum is " << minimum << endl;
cout << " The sum is " << sum << endl;
return 0;
}