CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Threaded View

  1. #1
    Join Date
    Jun 2009
    Posts
    5

    Need help to avoid using a global array variable

    Hi all, this is my first post :-) I am learning C++ and I would really appreciate your help.

    I wrote a small program that generates random combinations of lottery numbers, and which can be adapted to different types of lotteries.

    The problem I am trying to solve is that, as you can see, I have used an array as a global variable.

    If this wasn't an array, I would know how to use either pointers or references to avoid a global variable. However, I am not sure how to do this with an array.

    Many thanks in advance -- any help or input will be greatly appreciated!



    Code:
    /* Generate combinations of lottery numbers */
    
    #include <algorithm>	// for sort()
    #include <conio.h>	// for getch()
    #include <iostream>
    #include <time.h>	// for time()
    
    using namespace std;
    
    int const HOW_MANY = 5;			// set how many numbers are returned each time
    int const CEILING = 90;			// set the highest number that can be returned
    int numbers[HOW_MANY] = {0};		// array containing the main numbers
    
    int randomize(int max) {		// return a random number between 1 and max
    	return rand() &#37; max + 1;
    }
    
    void doNumbers() {
    	int i;
    	for (i=0; i<HOW_MANY; i++)
    		numbers[i] = randomize(CEILING);	// call randomize() HOW_MANY times to generate the combination
    	sort(numbers, numbers+HOW_MANY);		// sort the combination
    	for (i=0; i<(HOW_MANY-1); i++)
    		if (numbers[i] == numbers[i+1])		// compare each number with the next one
    			doNumbers();			// if there are any duplicates, repeat the function
    }
    
    void printNumbers() {
    	int i;
    	for (i=0; i<HOW_MANY; i++)
    		cout << numbers[i] << "\t";
    }
    
    void giveOptions() {
    	cout << "\n\nWould you like one more combination?\n\n";
    	cout << "- Enter Y for YES\n";
    	cout << "- Enter N to end the program" << "\n\n\n";
    	int _getch();
    	switch (_getch()) {
    		case 'y':
    		case 'Y':
    			doNumbers();
    			printNumbers();
    			giveOptions();
    			break;
    		case 'n':
    		case 'N':
    			return;
    		default:
    			cout << "\n\nPlease enter either Y or N\n\n\n";
    			giveOptions();
    	}
    }
    
    int main() {
    	srand(unsigned(time(NULL)));
    	doNumbers();
    	printNumbers();
    	giveOptions();
    	return 0;
    }
    Attached Files Attached Files
    Last edited by random++; June 23rd, 2009 at 02:59 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured