Reputation: 3
When you run this, the line with the error comment causes the program to stop working, at least for me. It's such simple code, I am sort of baffled as to why this would cause things to break?
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
using namespace std;
static const int ARRAY_SIZE = 100;
bool runAgain ( ) {
char runChar;
cout << "\n\nRun again? (Y/N)";
cin >> runChar;
runChar = toupper(runChar);
if(runChar != 'Y')
return false;
system("cls");
return true;
}
int main ( ) {
int nums[ARRAY_SIZE];
int length;
int num, highIndex, lowIndex;
length = sizeof(nums)/sizeof(int);
srand((unsigned)time(NULL)); //make numbers more random
do {
cout << "Array contains: \n";
for(int i = 0; i < length; i++) {
num = rand() % 1000 + 1;
if(i == 0)
highIndex, lowIndex = i;
else if(num > nums[highIndex]) //@@ ERROR occurs on this line
highIndex = i;
else if(num < nums[lowIndex])
lowIndex = i;
nums[i] = num;
cout << num << "\n";
}
cout << "\nHighest Value: " << nums[highIndex] << " at index " << highIndex;
cout << "\nLowest Value: " << nums[lowIndex] << " at index " << lowIndex;
}while(runAgain());
return 0;
}
The error is specifically that windows says that .cpp has stopped working and ends the run superficially. From running a debugger, I know it happens after the first iteration of the loop during the first else if in the for loop.
edit: ahh, yes the issue was the 'highIndex, lowIndex = i'. Thanks for the help
Upvotes: 0
Views: 112
Reputation: 37122
The problem is highIndex, lowIndex = i;
.
This does not, as you think, assign highIndex
and lowIndex
the value of i
. Only lowIndex
is assigned, highIndex
remains uninitialised. Therefore the program crashes when you try to dereference the array using highIndex
as the value could be anything.
Change your code line to:
highIndex = lowIndex = i;
Upvotes: 2