Jeremy
Jeremy

Reputation: 151

C++ unexpected array output

//Page 215, #2, by Jeremy Mill
//program taken in 7 values, displays them, and then sorts them from highest to     lowest, and displays them in order.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
//Define the variable we will need  
const int arraySize = 6;
double dailySales[arraySize];

//Now let's prompt the user for their input
for (int a=0 ; a <= arraySize; a++ )
    {
    cout << "Please enter sale number " << a+1 << " :";
    cin >> dailySales[a];
    }

//Now we display the output of the array
cout << "\n\nSale Number" << setw( 13 ) << "Value" << endl;
    for ( int i =0; i <= arraySize; i++ )        
        cout << setw( 5 ) << i << setw( 14 ) << dailySales[ i ] << endl;

//Now we sort using a bubble sort
for(int b = 0; b<=arraySize; b++)
        for(int c = arraySize-1; c>=b; c--) {
            if(dailySales[c-1] > dailySales[c]) { // if out of order
            // exchange elements 
            int t = 0;        
            t = dailySales[c-1];
                dailySales[c-1] = dailySales[c];
                dailySales[c] = t;
            cout << "it ran";
            }
        }   

cout << "Now we can display the array again! \n\n\n" << endl << dailySales[6] << endl;

//Now we display the output of the sorted array
cout << "\n\nSale Number" << setw( 13 ) << "Value" << endl;
    for ( int d = 0; d <= arraySize; d++ )        
        cout << setw( 5 ) << d << setw( 14 ) << dailySales[ d ] << endl;

cin.clear(); //clear cin
cin.sync(); //reinitialize it
cout << "\n\nPress Enter to end the program\n\n"; //display this text
cin.get(); //pause and wait for an enter
return 0;  

} // end main

Output:

Please enter sale number 1 :1
Please enter sale number 2 :2
Please enter sale number 3 :3
Please enter sale number 4 :4
Please enter sale number 5 :5
Please enter sale number 6 :6
Please enter sale number 7 :7


Sale Number        Value
    0             1
    1             2
    2             3
    3             4
    4             5
    5             6
    6             7
Now we can display the array again! 



7


Sale Number        Value
    0             1
    1             2
    2             3
    3             4
    4             5
    5             6
    6  2.97079e-313


Press Enter to end the program

Why is it that the last 'value' is not 7, but that number in sci. notation??

Upvotes: 2

Views: 438

Answers (2)

Amokrane Chentir
Amokrane Chentir

Reputation: 30395

Be carreful when looping through your array. The loop has to start from 0 to size-1. So instead of using less-than-or-equal:

for (int a = 0; a <= arraySize; a++)

You should use less-than:

for (int a = 0; a < arraySize; a++)

Upvotes: 7

Keith
Keith

Reputation: 6834

The array size is declared to be 6 elements and then 7 elements [0...6] are placed in it.

Redeclare array size to be 7 and then change all the <= to < in the loops.

Upvotes: 3

Related Questions