Thread: Need help with "if" function

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    39

    Need help with "if" function

    I just started coding in C today, and I haven't been able to figure out what is wrong with this. I am trying to make a "guess the number" game, but I keep getting a syntax error on the "if" line. Could someone please tell me what is wrong with this?

    Code:
    #include <stdio.h>
    
    
    int main()
    {
        int correct;
        correct=13;
    {
      int number;
      printf ( "Guess a number: ");
      scanf( "%d", &number );
      return 0;
    }
    }
    if(correct==number)
    {
                       printf("You Win!"
                       }
    else
    {
        printf("You Lose")
    }
    Last edited by wipeout4wh; 03-17-2009 at 09:43 PM. Reason: typo

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    You don't need your second, third or forth curly braces, but you should have one after the else statement.

    return 0; should only be at the end of your program - execution will end when it gets to this point.

    There's nothing wrong with the if statement itself.

    You need closing parentheses and semi colon after "You Win!"

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    39
    After the else statement?

    Code:
    else
    {
        printf("You Lose")
    }
    Why would I need another one? It already has a beginning and end bracket...

    Edit: oh, I see what you mean.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    39
    Ok, I got it working, but could you tell me how to make the number random every time instead of a constant?

  5. #5
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    http://www.cprogramming.com/tutorial/random.html

    The code in that tutorial is C++, so it's a slightly different syntax in some parts, but the random number part should be the same for C.

    i.e. You "seed" it by passing srand some value based on the time, then subsequent calls to rand() return random numbers. Include stdlib.h to use those functions and the RAND_MAX constant.

  6. #6
    Resu Deretsiger Nightowl's Avatar
    Join Date
    Nov 2008
    Location
    /dev/null
    Posts
    186
    By using the srand() and rand() functions contained in stdlib.h.

    srand() seeds the random number generator with a value. If given the same seed, then rand() will return the same numbers in sequence. Usually, the time is used to seed the random number generator. So, for example:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main(int argc, char *argv[]) {
        srand(time(NULL));
        printf("A random number: %i\n", rand());
        printf("A random number between 0 and 99: %i\n", rand()%100);
        return 0;
    }
    Stepping through that, well.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    I think you probably know what these are. In this case, stdio.h is used for printf(), stdlib.h for srand() and rand(), time.h for time().

    Code:
    int main(int argc, char *argv[]) {
    Standard main() function.
    Code:
        srand(time(NULL));
    This calls srand() with the current time, as returned by the time() function. If you pass a pointer to time(), it will store the time in that variable. But because it additionally returns the time, you can seed the random number generator directly without using an additional variable.
    Code:
        printf("A random number: %i\n", rand());
        printf("A random number between 0 and 99: %i\n", rand()%100);
    The first simply prints out a randomly-generated number from the rand() function. This will be between 0 and (2^31)-1, probably not what you want. So, the second applies a modulus of 100 to the randomly-generated value. Modulus = remainder. Think of it as converting 1234 into 34, removing all but the tens and ones columns of a number. (If you use number%2, it will be 1 if number is odd, 0 if it's even.)
    Code:
        return 0;
    }
    Terminate with a return code of 0, or success.

    EDIT: dang, sean beat me to it :P
    Do as I say, not as I do . . .

    Experimentation is the essence of programming. Just remember to make a backup first.

    "I'm a firm believer that <SomeGod> gave us two ears and one mouth for a reason - we are supposed to listen, twice as much as we talk." - LEAF

    Questions posted by these guidelines are more likely to be answered.

    Debian GNU/Linux user, with the awesome window manager, the git version control system, and the cmake buildsystem generator.

  7. #7
    Registered User
    Join Date
    Mar 2009
    Posts
    39
    Edit: nvm, I got it. Thanks for your help.
    Last edited by wipeout4wh; 03-17-2009 at 11:14 PM. Reason: nvm

  8. #8
    Registered User
    Join Date
    Mar 2009
    Posts
    39
    Ok, I need help again

    Now I am trying to make it so you can choose to try again after you win or lose. I looked in the other thread that was similar, but I can't figure it out. What is wrong with this?:

    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <ctype.h>
    #include <process.h>
    
    
    int main(int argc, char *argv[])
    {
        int guess;
        char choice, y, n, Y, N;
        Y=y;
        N=n;
        
    while (choice == y)
    {
        printf("Guess a number: ");
        scanf("%i" , &guess);
        srand(time(NULL));
        if(guess==rand()%21)
        printf("\nYou Win!");
        else
        printf("You Lose! My number was: %i" , rand()%21);
                     char choice;
             printf("\nWould you like to try again? [Y/N]: \n");
             scanf( "%c" , &choice );
    }
    }

  9. #9
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    have you already searched the forum?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  10. #10
    Registered User
    Join Date
    Mar 2009
    Posts
    39
    I found a thread about it, but I still can't figure it out.

  11. #11
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Code:
    char choice = 'n';
    do
    {
       ...
       scanf("%c ",&choice);
    } while(tolower(choice) == 'y');
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  12. #12
    Resu Deretsiger Nightowl's Avatar
    Join Date
    Nov 2008
    Location
    /dev/null
    Posts
    186
    Quote Originally Posted by wipeout4wh View Post
    Code:
        
    while (choice == y)
    Should that not be (choice == 'y')?
    Do as I say, not as I do . . .

    Experimentation is the essence of programming. Just remember to make a backup first.

    "I'm a firm believer that <SomeGod> gave us two ears and one mouth for a reason - we are supposed to listen, twice as much as we talk." - LEAF

    Questions posted by these guidelines are more likely to be answered.

    Debian GNU/Linux user, with the awesome window manager, the git version control system, and the cmake buildsystem generator.

  13. #13
    Resu Deretsiger Nightowl's Avatar
    Join Date
    Nov 2008
    Location
    /dev/null
    Posts
    186
    An example program, much like what I think you're trying to do . . .

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <string.h>
    
    int main(int argc, char *argv[]) {
        int i, num, tries;
        char cont;
        srand(time(NULL));
        
        do {
            num = (rand()%100)+1;
            i = -1;
            tries = 0;
            while(num != i) {
                if(i != -1) {
                    if(i > num) {
                        printf("Too high!\n");
                    }
                    else printf("Too low!\n");
                }
                printf("Enter a number between 1 and 100: ");
                scanf("%i", &i);
                tries ++;
            }
            printf("Got it in %i %s. Again? [yY/nN] ", tries, tries == 1?"try":"tries");
            while((cont = tolower(getchar())) && cont != 'y' && cont != 'n') ;
        } while(cont == 'y');
        
        return 0;
    }
    Example output:

    Code:
    Enter a number between 1 and 100: 1
    Too low!
    Enter a number between 1 and 100: 50
    Too low!
    Enter a number between 1 and 100: 75
    Too high!
    Enter a number between 1 and 100: 66
    Too high!
    Enter a number between 1 and 100: 59
    Too high!
    Enter a number between 1 and 100: 55
    Too low!
    Enter a number between 1 and 100: 57
    Too high!
    Enter a number between 1 and 100: 56
    Got it in 8 tries. Again? [yY/nN]y
    Enter a number between 1 and 100: 50
    Too low!
    Enter a number between 1 and 100: 75
    Too low!
    Enter a number between 1 and 100: 88
    Too high!
    Enter a number between 1 and 100: 81
    Too low!
    Enter a number between 1 and 100: 84
    Too low!
    Enter a number between 1 and 100: 86
    Too low!
    Enter a number between 1 and 100: 87
    Got it in 7 tries. Again? [yY/nN]n
    Do as I say, not as I do . . .

    Experimentation is the essence of programming. Just remember to make a backup first.

    "I'm a firm believer that <SomeGod> gave us two ears and one mouth for a reason - we are supposed to listen, twice as much as we talk." - LEAF

    Questions posted by these guidelines are more likely to be answered.

    Debian GNU/Linux user, with the awesome window manager, the git version control system, and the cmake buildsystem generator.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by wipeout4wh View Post
    Ok, I need help again

    Now I am trying to make it so you can choose to try again after you win or lose. I looked in the other thread that was similar, but I can't figure it out. What is wrong with this?:
    Any characters, such as y needs to be enclosed in single quotes, thus: 'y'.
    If you do NOT do this, the compiler thinks it's a variable and it's not, is it?

    Furthermore, srand should only be called once during your program.
    And you'll want to cast the return of time to avoid compiler warnings:

    srand( (unsigned int)time(NULL) );

    And lastly, you need to look into what indentation is: http://cpwiki.sourceforge.net/Indentation
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User
    Join Date
    Mar 2009
    Posts
    39
    Quote Originally Posted by Nightowl View Post
    An example program, much like what I think you're trying to do . . .

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <string.h>
    
    int main(int argc, char *argv[]) {
        int i, num, tries;
        char cont;
        srand(time(NULL));
        
        do {
            num = (rand()%100)+1;
            i = -1;
            tries = 0;
            while(num != i) {
                if(i != -1) {
                    if(i > num) {
                        printf("Too high!\n");
                    }
                    else printf("Too low!\n");
                }
                printf("Enter a number between 1 and 100: ");
                scanf("%i", &i);
                tries ++;
            }
            printf("Got it in %i %s. Again? [yY/nN] ", tries, tries == 1?"try":"tries");
            while((cont = tolower(getchar())) && cont != 'y' && cont != 'n') ;
        } while(cont == 'y');
        
        return 0;
    }
    Ok, thank you. Could you explain this code to me though? Also how would I make it so you don't need to press enter after pressing y or n? If that is too complicated, don't worry about it, since I'm not very good at this yet and probably wouldn't understand.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM