1 2
|
int x = 0;
int people[x];
|
That is a coding error awaiting a crash. You are creating an array of ZERO elements. Any indexed access is going outside the bounds of the array.
The program may compile under TDM-GCC 4.9.2, but it is crashes.
Visual C++ 2015 has compile errors. You have to create an array with a constant value, and x is not a constant.
You already know the number of elements your array needs (10), so either "hard-code" the array instantiation
int people[10];
or create a constant variable:
1 2
|
const int num_people = 10;
int people[num_people];
|
You are also initializing your greatest variable to the second element, not the first.
A recap of the changes needed to make this work the way you expect:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
int main()
{
char response;
int x = 0;
const int num_people = 10;
int people[num_people];
bool answer = true;
while (answer == true)
{
int greatest = people[0];
std::cout << "Enter in the amount of years 10 people have ";
std::cin >> people[x];
x++;
if (x == 10)
{
for (int i = 0; i < x; i++)
{
std::cout << people[i] << std::endl;
if (greatest < people[i])
{
greatest = people[i];
}
else
{
continue;
}
}
}
else
{
continue;
}
std::cout << "The oldest person is " << greatest << " years old" << std::endl;
std::cout << "Do you want to continue?" << std::endl << "Y for yes other wise anything. ";
std::cin >> response;
if (response == 'Y')
{
x = 0;
continue;
}
else
{
answer = false;
}
}
}
|
You could do a simple loop to get the array contents, since you already know the number of elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
int main()
{
char response;
const int num_people = 10;
int people[num_people];
bool answer = true;
while (answer == true)
{
int greatest = people[0];
for (int x = 0; x < num_people; x++)
{
std::cout << "Enter age #" << x + 1 << " ";
std::cin >> people[x];
}
for (int i = 0; i < num_people; i++)
{
std::cout << people[i] << std::endl;
if (greatest < people[i])
{
greatest = people[i];
}
else
{
continue;
}
}
std::cout << "The oldest person is " << greatest << " years old" << std::endl;
std::cout << "Do you want to continue?" << std::endl << "Y for yes other wise anything. ";
std::cin >> response;
if (response == 'Y')
{
continue;
}
else
{
answer = false;
}
}
}
|