Hi I am getting a Runtime error when I debug this code. Could someone lend a helping hand?
It will be very much appreciated.

#include "stdafx.h"
#include<iostream>
using namespace std;

void main(int argc, char* argv[])
{
	const int SIZE = 9;
	int numbers[SIZE];
	int counter;
	int temp_swap=0;
	counter=0;
	

	cout << "This program sorts 10 integers in descending order" << endl << endl;
	cout << "Please enter 10 integers to be sorted:" << endl << endl;
	// This while loop accepts 10 numbers from the user
	// and it terminates when the loop counter 'counter' becomes 10
	while(counter<=SIZE)
	{
		cout << counter+1 << "). Enter a number: ";
		cin >> numbers[counter++];
	}

	/*
	These two for loops implement the Bubble Sort algorithm
	The inner loop goes through the elements
	The outer loop & and the condition of the inner loop decide
	which elements will be checked in the inner loop
	As described in PROCESSING above, with each pass of the inner loop
	the bigger elements will start accumulating at the right end
	of the array
	*/
	for(int outerpass = 1; outerpass<SIZE; outerpass++)
	{
		for(int innerpass=0; innerpass<=SIZE-outerpass; innerpass++)
		{
			/*
			If the number at i'th location is bigger than the one
			coming after it, then the two need to be swapped
			*/
			if( numbers[innerpass] > numbers[innerpass+1] )
			{
				temp_swap = numbers[innerpass];
				numbers[innerpass] = numbers[innerpass+1];
				numbers[innerpass+1] = temp_swap;
			}
		}
	}

	cout << "\n\n  The sorted numbers are. . .\n\n";

	/*
	Simple for loop that displays
	the sorted array in a single column
	*/
	for(counter=0; counter<=SIZE; counter++)
	{
		cout << numbers[counter]<<endl;
	}

	system("pause");

}

Your comments explain it all. Your array is only defined to be 9 elements long (see Lines 7 and 8), but you are processing it as if it were 10 elements long.

example:
Lines 18-22. Your while loop is overshooting the limits of your array. It runs from 0-9 (10 elements) instead of from 0-8 (9 elements).

I haven't fully traced the rest of your code, but I'm guessing you are doing it elsewhere as well...

Edited 6 Years Ago by Fbody: n/a

Your comments explain it all. Your array is only defined to be 9 elements long (see Lines 7 and 8), but you are processing it as if it were 10 elements long.

Would it fix the problem if I changed line 7 to const int SIZE = 10;

Edited 6 Years Ago by oneml: n/a

No, it would not correct the issue, but it may get you closer to what you want. That change would give you an array with 10 elements, instead of 9 (which it sounds like you want).

The problem is, the way the loop is written you would then be inputting 11 values instead of 10. You would still be overruning the boundaries of your array.

You need to change your loop's conditional statement.

Edited 6 Years Ago by Fbody: n/a

This article has been dead for over six months. Start a new discussion instead.