Thread: Help with for loop and nested if's

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    159

    Help with for loop and nested if's

    Hi

    I have a problem with this code, acting strange

    I need a for loop to ask 2 questions, if the user gives a wrong answer, the user still another chance to get 1 point, the code is working but if the first answer is wrong and the second is right, the program still give me more questions....

    anyone knows whats wrong here??

    Code:
    void gp1_Ques(struct perg *p, char *usr1)
    {
        FILE *f; //apontador para ficheiro
        f=fopen("gp1.dat", "r"); //abertura do ficheiro
        int reg=0,reg1, i; //Variaveis contadoras de perguntas e random
        int random; // Variável de random
        int op, resposta; //Variáveis opções utilizadores
        int qual, result=0; //Variáveis resultados
        rewind(f); //retorna a posição corrente do ficheiro para o início
        srand(time(NULL)); //função random
        system("cls");
        fseek(f, 0, SEEK_END);
        reg=ftell(f) /sizeof *p;
        fseek(f, 0 , SEEK_SET);
        if (reg<=0) //condição que verifica se existem registos
        {
            printf ("Sem registos \n");
            printf ("\n Necessario ter registos para jogar...\n");
            return;
            }
            else
            {
                printf ("\n*=============================================================================*\n");
                printf ("|                       >>>>Visualizao de perguntas<<<<                        |\n");
                printf ("*=============================================================================*\n");
                printf ("                                                                               \n");
                printf ("\n      TOTAL de perguntas: %d \n",reg); //conta as perguntas
                printf ("\n      O seu score maximo sera: %d\n",reg/10); //pontuação máxima do jogo
                qual = reg-19; //contagem minima para passar de fase
                printf ("\n      Para a qualificacao precisa de: %d\n",qual); //total minimo para passar fase
                //testes para ver se funciona o random
                random=rand()%reg; //função random
                reg1 = random; //atribui a variavel reg o valor de random
                }
                printf("\n\n\n      Quer comecar a jogar ?(Sim=1; Nao=0) \n");
                printf ("*=============================================================================*\n");
                scanf("%d", &op);
                system("cls");
                if(op==1)
                {
                    for(i=0; i<=2;i++)
                    {
                        fseek(f, reg1 * sizeof *p, SEEK_SET);
                        fread(p, sizeof *p, 1, f);
                        printf("Bemvindo ao jogo %s", usr1);
                        printf("\nPergunta : %s", p->ques);
                        printf("\nOpcao 1 : %s",p->op1);
                        printf("\nOpcao 2 : %s",p->op2);
                        printf("\nOpcao 3 : %s",p->op3);
                        printf("\nOpcao 4 : %s",p->op4);
                        printf("\nResposta correta?\n");
                        scanf("%d", &resposta);
                        getchar();
                        if(resposta==p->res)
                        {
                            printf("\nRight answer...\n");
                            result++;
                            random=rand()%reg; //random
                            reg1 = random; //
                            fseek(f, reg1 * sizeof *p, SEEK_SET);
                            fread(p, sizeof *p, 1, f);
                            printf("\nPergunta : %s", p->ques);
                            printf("\nOpcao 1 : %s",p->op1);
                            printf("\nOpcao 2 : %s",p->op2);
                            printf("\nOpcao 3 : %s",p->op3);
                            printf("\nOpcao 4 : %s",p->op4);
                            printf("\nRight answer?\n");
                            scanf("%d", &resposta);
                            getchar();
                            if(resposta==p->res)
                            {
                                printf("\nRight answer\n");
                                result++;
                            }
                            else
                            {
                                printf("Wrong...\n");
                            }
                        }
                        else
                        {
                            printf("One mor chance \n");
                            random=rand()%reg; //random
                            reg1 = random; //
                            fseek(f, reg1 * sizeof *p, SEEK_SET);
                            fread(p, sizeof *p, 1, f);
                            printf("\nPergunta : %s", p->ques);
                            printf("\nOpcao 1 : %s",p->op1);
                            printf("\nOpcao 2 : %s",p->op2);
                            printf("\nOpcao 3 : %s",p->op3);
                            printf("\nOpcao 4 : %s",p->op4);
                            printf("\nRight answer?\n");
                            scanf("%d", &resposta);
                            getchar();
                            if(resposta==p->res)
                            {
                                printf("\nRight answer...\n");
                                result++;
                            }
                            else
                            {
                                printf("Wrong...\n");
    
    
                            }
                        }
                    }
                }
                else if (op==0)
                {
                    jogo();
                }
                else
                {
                    printf("\n Invalid option\n");
                    Sleep(2000);
                    jogo();
                }
            fclose(f);
    }

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    505
    You've got a for loop and an if.

    You need to either get rid of the for loop, or use break if the user types in the right answer.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  3. #3
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Good morning

    Thank's for your help
    Iv'e already changed an get rid of the loop but i still have some problems
    This is how a build my if statement (just the if, not all function)
    Code:
     if(op==1) //The user choose the option 1 and will have 2 question to answer
                {
                    fseek(f, reg1 * sizeof *p, SEEK_SET);
                    fread(p, sizeof *p, 1, f);
                    printf("Bemvindo ao jogo %s", usr1);
                    printf("\nPergunta : %s", p->ques);
                    printf("\nOpcao 1 : %s",p->op1);
                    printf("\nOpcao 2 : %s",p->op2);
                    printf("\nOpcao 3 : %s",p->op3);
                    printf("\nOpcao 4 : %s",p->op4);
                    printf("\nResposta correta?\n");
                    scanf("%d", &resposta);
                    getchar();
                    if(resposta==p->res)
                    {
                        printf("\nAcertou na resposta...\n");
                        result++;
                        random=rand()%reg; //função random
                        reg1 = random; //atribui a variavel reg o valor de random
                        fseek(f, reg1 * sizeof *p, SEEK_SET);
                        fread(p, sizeof *p, 1, f);
                        printf("\nPergunta : %s", p->ques);
                        printf("\nOpcao 1 : %s",p->op1);
                        printf("\nOpcao 2 : %s",p->op2);
                        printf("\nOpcao 3 : %s",p->op3);
                        printf("\nOpcao 4 : %s",p->op4);
                        printf("\nResposta correta?\n");
                        scanf("%d", &resposta);
                        getchar();
                        if(resposta==p->res)
                        {
                            printf("\nAcertou novamente na resposta...\n");
                            result++;
                        }
                        else
                        {
                            printf("Errou nesta questao...\n");
                        }
                    }
                    else //if the user fails the fisrt question
                    {
                        printf("Tem mais uma tentativa para atingir o minimo \n");
                        random=rand()%reg; //função random
                        reg1 = random; //atribui a variavel reg o valor de random
                        fseek(f, reg1 * sizeof *p, SEEK_SET);
                        fread(p, sizeof *p, 1, f);
                        printf("\nPergunta : %s", p->ques);
                        printf("\nOpcao 1 : %s",p->op1);
                        printf("\nOpcao 2 : %s",p->op2);
                        printf("\nOpcao 3 : %s",p->op3);
                        printf("\nOpcao 4 : %s",p->op4);
                        printf("\nResposta correta?\n");
                        scanf("%d", &resposta);
                        getchar();
                        if(resposta==p->res)
                        {
                            printf("\nAcertou na resposta...\n");
                            result++;
                        }
                        else
                        {
                            printf("Errou novamente...ai esta cultura geral!!! \n");
                        }
                    }
                    if (result>=1) //Last if statement to count the result (0, if the two answer are wrong) (1 if one is right) (2 if both are right)
                    {
                        printf("Teve pontuacao de %d\n", result);
                        printf("Vai passar para a fase 2...aguarde \n");
                        //Sleep(2000);
                        gp2_Ques(&p, usr1, result); //call the next function
                    }
                    else
                    {
                        printf("Nao atingiu o minimo para seguir....vai voltar ao menu anterior");
                        Sleep(2000);
                        jogo();
                    }
                }
                else if(op==0)
                {
                    jogo();
                }
                else
                {
                    printf("\n     Opcao invalida...vai regressar ao menu anterior\n");
                    Sleep(2000);
                    jogo();
                }
    }

    What do you think??

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,664
    It might be clearer if you created another function, instead of copy/pasting.

    Eg.
    Code:
    int askAQuestion ( FILE *f, int res1 ) {
      struct perg p;
      fseek(f, reg1 * sizeof p, SEEK_SET);
      fread(p, sizeof p, 1, f);
      printf("Bemvindo ao jogo %s", usr1);
      printf("\nPergunta : %s", p.ques);
      printf("\nOpcao 1 : %s",p.op1);
      printf("\nOpcao 2 : %s",p.op2);
      printf("\nOpcao 3 : %s",p.op3);
      printf("\nOpcao 4 : %s",p.op4);
      printf("\nResposta correta?\n");
      scanf("%d", &resposta);
      getchar();
      if(resposta==p.res)
        return 1;
      else
        return 0;
    }
    Then your code might be clearer as
    Code:
      if ( askAQuestion(f,reg1) ) {
        printf("\nAcertou na resposta...\n");
        result++;
        random=rand()%reg; //função random
        if ( askAQuestion(f,random) ) {
          printf("\nAcertou novamente na resposta...\n");
          result++;
        } else {
          printf("Errou nesta questao...\n");
        }
      }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Hi Salem

    Interesting approach, didn't think about that like this.
    Let me try implement this way.

    Thanks

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,664
    There's a basic rule of thumb
    Code:
    void someFunction ( ) { //!! this
      // some code
    } //!! this
    that states if you can't see the open and closing brace of a function on screen at the same time, then the function is too long.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Can you explain me this please

    Code:
    if(result1==3)
                {
                    printf("\nYou have  %d points", result1);
                    printf("You have %d from last stage", result);
                    result+=result1;
                    printf("\nThe total earned is  %d\n", result);
                }
    result = 2
    result1 = 3
    The print is 14????

    It should be 5, right?

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,664
    I'm sure if you try it in an isolated program, like
    Code:
    int main ( ) {
        int result = 2, result1 = 3;
        printf("\nYou have  %d points", result1);
        printf("You have %d from last stage", result);
        result+=result1;
        printf("\nThe total earned is  %d\n", result);
        return 0;
    }
    you'll get 5 printed.

    Which means in your large program, something has almost certainly trashed memory and your erroneous printf() is just where it shows up.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Hi Salem

    Can it be because of this warning in this line ?

    warning: format '%d' expects argument of type 'int', but argument 3 has type 'int *' [-Wformat]|

    void gp2_Ques(struct gp2 *p, char *usr1, int *result)

    printf("%s transporta %d pontos da anterior fase \n",usr1, result);

    I'm prety sure it must be, that result comes from another function but the strange is that i have the correct value...

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,664
    Wait, result is a pointer!?

    Yes, you need to fix the printf.

    You also need to fix the code as well.
    Code:
    printf("\nYou have  %d points", result1);
    printf("You have %d from last stage", *result);
    *result+=result1;
    printf("\nThe total earned is  %d\n", *result);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Hi

    With *result the program gives segmentation fault.

    So my problem is, how to get the value of result from the main funtion

    Code:
    void gp1_Ques(struct perg *p, char *usr1)
    {
        FILE *f; //apontador para ficheiro
        f=fopen("gp1.dat", "r"); //abertura do ficheiro
        int reg=0,reg1; //Variaveis contadoras de perguntas e random
        int random; // Variável de random
        int result=0; //Variáveis resultados
    }
    Then is the new function

    Code:
    void gp2_Ques(struct gp2 *p, char *usr1, int *res)
    {
        FILE *f; //apontador para ficheiro
        f=fopen("gp2.dat", "rb"); //abertura do ficheiro
        int reg=0,reg1; //Variaveis contadoras de perguntas e random
        int random; // Variável de random
        int result1=0; //Variáveis resultados
    }
    Should the prototype be like this?
    then
    gp1_Ques(*result)


    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with nested loop
    By khoavo123 in forum C Programming
    Replies: 0
    Last Post: 01-23-2012, 01:29 PM
  2. Nested while loop inside for loop
    By Sonny in forum C Programming
    Replies: 71
    Last Post: 07-31-2011, 08:38 PM
  3. nested for loop
    By altf4thc in forum C++ Programming
    Replies: 3
    Last Post: 02-18-2010, 12:43 PM
  4. Help with Nested For Loop
    By snugy in forum C Programming
    Replies: 3
    Last Post: 02-17-2009, 10:17 AM
  5. Nested Loop
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 05-07-2002, 12:40 AM