Homework Assignment Error

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.

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>

using namespace std;

int main()
{

// Declare variables and array

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 << ".";

return 0;
}
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];
  }
std::minmax_element (C++11) fetches the minimum and maximum values together:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <algorithm>

int main()
{
    int v[] = { 3, 9, 1, 4, 2, 5, 9 };

    auto result = std::minmax_element(v, v + sizeof(v)/sizeof(v[0]));
   //http://en.cppreference.com/w/cpp/algorithm/minmax_element

    std::cout << "Minimum: " << *result.first << "; Maximum: " << *result.second << "\n";
}

Last edited on
Topic archived. No new replies allowed.