Search code examples
cvisual-studio-2010coin-flipping

Coin Toss program not working Visual Studio 2010


A book exercise prompts me to create a program that simulates coin tossing. My friend says he ran my code in a native GNU compiler, and it worked, but I'm receiving the following errors when I try to run it in Visual Studio 2010:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int result;

int flip();

int main(void)
{
    srand(time(NULL));

    int heads = 0;
    int tails = 0;
    unsigned counter;

    for(counter = 1; counter <= 100; counter++)
    {
        result = flip();

        if(result == 1)
        {
            printf("Heads\n");
            heads++;
        }

        else
        {
            printf("Tails\n");
            tails++;
        }
    }

        printf("Heads: %d\tTails: %d\n", heads, tails);
}

int flip()
{
    result = 1 + rand() % 2;

    if (result == 1)
        return 1;

    if (result == 2)
        return 0;

    return NULL;
}

syntax error: ')' (line 10)

'counter': undeclared identifier (15, 23)

'heads': undeclared identifier (19, 23)

't': undeclared identifier (10, 10)

syntax error: missing ')' before 'type' (line 10)

syntax error: missing ';' before '{' (line 11)

syntax error: missing ';' before 'type' (9, 10, 10, 10)

Thanks for any response.


Solution

  • #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int result;
    
    int flip();
    
    int main(void){
        int heads = 0;
        int tails = 0;
        unsigned counter;
    
        srand(time(NULL));//Executable statement after the declaration
    
        for(counter = 1; counter <= 100; counter++){
            result = flip();
    
            if(result == 1){
                printf("Heads\n");
                heads++;
            } else {
                printf("Tails\n");
                tails++;
            }
        }
    
        printf("Heads: %d\tTails: %d\n", heads, tails);
        return 0;
    }
    
    int flip() {
        result = 1 + rand() % 2;
    
        return result == 1;
    }