Thread: Infinite Loop?

  1. #1
    Registered User
    Join Date
    May 2010

    Infinite Loop?

    Hello, I'm a newbie at programming and this example is taken from the book <<C++ Without Fear>>.

    The problem is that the programs runs continuously, as though the "number of cards to draw" is infinite, even when I entered a finite number.

    #include <iostream>
    #include <stdlib.h>
    #include <time.h>
    #include <math.h>
    using namespace std;
    int rand0ton1(int n);
    void draw_a_card();
    char *suits[4] = {"hearts","diamonds","spades","clubs"};
    char *ranks[13] = {"ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king"};
    int main() {
        int n, i;
        while (1) {
            cout << "Enter number of cards to draw (0 to quit): ";
            cin >> n;
            if (n==0)
            for (i=1;1<=n;i++)
        return 0;
    void draw_a_card() {
        int r;
        int s;
        r = rand0ton1(13);
        s = rand0ton1(4);
        cout << ranks[r] << "of" << suits[s] << endl;
    int rand0ton1(int n) {
        return rand()%n;
    Last edited by Freshjunior; 05-14-2010 at 06:54 AM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    I'm guessing that "1<=n" will always be true. Perhaps you mean "i <= n" instead.

  3. #3
    Registered User
    Join Date
    May 2010
    oops sorry. I also just discovered this careless mistake =x.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using while produces an infinite loop...
    By UCF43 in forum C Programming
    Replies: 4
    Last Post: 04-01-2010, 04:47 PM
  2. Replies: 2
    Last Post: 06-14-2009, 11:24 PM
  3. Cosine fucntion and infinite loop.
    By youareafever in forum C Programming
    Replies: 2
    Last Post: 11-07-2008, 04:45 AM
  4. Infinite Loop with GetAsyncKeyState
    By guitarist809 in forum Windows Programming
    Replies: 1
    Last Post: 04-18-2008, 12:09 PM
  5. Switch statement = infinite loop
    By Lucid003 in forum C++ Programming
    Replies: 10
    Last Post: 10-10-2005, 12:46 AM