I am having trouble with an array exercise from my textbook.
The Assignment is:
Largest/Smallest Array Values
Write a Program that lets the user enter 10 values into an array. The program should then display the largest and smallest values stored in the array.
What I have so far. Seems to have a segmentation fault. Anyone see the problem?
//Paul Thvedt
// CPSC 121
// Professor Worobec
// This program asks the user to enter in integers. It then stores them in an array and outputs the largest number and the smallest number.
int numberA;
int value [numberA];
int count;
int highestValue;
int lowestValue;
// Ask the user how many integers they want to input
cout << "How many integers do you want to enter? \n";
cin >> numberA;
// If loop that catches a value less than 1
if (numberA <1)
{
cout << "Invalid input! Please enter a positive number \n";
cin >> numberA;
}
// Asks the user to input the integers they want
for (int i = 0; i < numberA; i ++)
{
cout << "Enter integer";
cin >> value[numberA];
}
// Allows the program to find the highest value
highestValue = value [0];
for (count = 1; count < numberA; count++)
{
if (value[count] > highestValue)
highestValue = value[count];
}
// Allows the program to find the lowest value
lowestValue = value [0];
for (count = 1; count < numberA; count++)
{
if (value[count] < lowestValue)
lowestValue = value[count];
}
// Output the highest and lowest values
cout << "The largest number you entered was " << highestValue << ". \n";
cout << "The smallest number you entered was " << lowestValue << ".";
First off, you can't use variables to declare a C-style array:
1 2
int numberA;
int value[numberA]; // Nope
You can either use a constant (in this example, the size of the array is provided by the problem itself - ie: 10), or you can use new[] and delete[] if you really want a variable size array. Or you could use std::vector if the problem doesn't forbid it.
Also, this for loop is wrong:
1 2 3 4 5
for (int i = 0; i < numberA; i ++)
{
cout << "Enter integer";
cin >> value[numberA]; // This should be cin >> value[i];
}