This program is supposed to shuffle a Deck of cards and display them so I know it is working correctly. But one of the values displayed is -858993460 which is not possible when it should only be between 1 and 52. Obviously there is some sort of data loss going on but I cannot figure out what exactly it is. Please help me solve this, thank you.

#include "stdafx.h"
#include <algorithm>//swap
#include <iostream>  
#include <ctime> //system clock
#include <cstdlib>   //random
using namespace std;//Swap lives in std namespace

const int nLow=0;   //lists of constants
const int nHigh=52;
const int nSize=52;


int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));  //sets the seed to system time

    //Intializes Array to size of Deck of cards
    int anDeck[nSize]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52};

    //loop variables
    int rNumber=0;
    int aaa=0;

    //Gets Random number for each element and switches element with random element
    for(; aaa<=nSize; aaa++)
    {
        //Gets the Random number to use to find the element that will be switched
        rNumber=(rand()%(nHigh-nLow+1))+nLow;
        //Switches value of element aaa with the value of random element
        swap(anDeck[aaa],anDeck[rNumber]);
    }

    //displys each element of Array
    for( int iii=0; iii<nSize; iii++)
        cout<<anDeck[iii]<<endl;


    //stops program and allows user to respond
    int stop;
    cin>>stop;

    return 0;
}

The deck has 52 elements, so the elements will be indexed from 0-51, but in the loop it indexes 52. replacing aaa<=nSize with aaa<nSize will solve it.

Also in the random index generating statement (line 28), (nHigh-nLow+1)is 53, so when using mod (%) with it has the possibility of generating the index 52 which obviously exceeds the deck index (0-51). It should be ( (nHigh-1) - nLow + 1). Hope this helps you. :)

Edited 3 Years Ago by ken_taiken

Thanks man. I would never have figured out the problem with the generating statement.

Comments
Glad I could help you. :)
This question has already been answered. Start a new discussion instead.