Thread: help with this code- loops

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    11

    help with this code- loops

    I'm writing a program to create 2 random numbers and ask the user what's the product of these 2 eg (5*4=?). I have written the code for this but the program needs to test the user 10 times. And on top of that I need to say the percentage of all the answers they have answered correctly to display at the end. eg you have answered correctly 60%.

    Please help. Im new to C. As you can see I've tried putting in the integers but wherever I put loop++; and while(loop<10) it never comes out right

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <time.h>
    #include <conio.h>
    
    
    
    
    void print_rand_msg(const int msg_type);
    
    
    int main(void) 
    {
    int n1;
    int n2;
    int prd, guess;
    int loop;
    loop=0;
    
    
    
    
    srand((unsigned int)time(NULL));
    
    
    n1 = rand()%12+1;
    n2 = rand()%12+1;
    prd = n1 * n2;
    
    
    printf("What is %d x %d\?\n",n1,n2);
                           
    
    
    if(scanf("%d", &guess) != 1) 
    printf("Incorrect input.");
    
    
    else if(guess == prd) 
         {
         printf("CORRECT");
         }
    else 
         {
         printf("INCORRECT");
         }
         
    getch();
    return 0;
    
    
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Try something like
    Code:
    for ( numTests = 0 ; numTests < 10 ; numTests++ ) {
        n1 = rand()%12+1;
        n2 = rand()%12+1;
        // more of your code
    }
    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.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    In addition to Salem's advice, I'd recommend the following:

    - #define the maximum number of loop iterations you want
    - Create a new variable that tracks the number of correct answers within the loop
    - You can use this variable with the #define constant to determine the percentage of correct answers at the end of the program

  4. #4
    Registered User
    Join Date
    Nov 2012
    Posts
    11
    Quote Originally Posted by Matticus View Post
    In addition to Salem's advice, I'd recommend the following:

    - #define the maximum number of loop iterations you want
    - Create a new variable that tracks the number of correct answers within the loop
    - You can use this variable with the #define constant to determine the percentage of correct answers at the end of the program
    Ok I didn't 100% understand what you meant. I haven't really touched define stuff yet. Here's what I've tried to do to get the final message of "you answered ...% of the questions correctly".

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <time.h>
    #include <conio.h>
    
    
    
    
    void print_rand_msg(const int msg_type);
    
    
    int main(void) 
    {
    int n1;
    int n2;
    int prd, guess;
    int numTests;
    numTests=0;
    
    
    int correct;
    correct=0;
    int percentage;
    
    
    
    
    
    
    
    
    srand((unsigned int)time(NULL));
    
    
    for ( numTests = 0 ; numTests < 10 ; numTests++ )
        {
    n1 = rand()%12+1;
    n2 = rand()%12+1;
    prd = n1 * n2;
    
    
    printf("What is %d x %d\?\n",n1,n2);
                           
    
    
    if(scanf("%d", &guess) != 1) 
    printf("Incorrect input.\n");
    
    
    else if(guess == prd) 
         {
         printf("CORRECT\n");
         correct++;
         }
    else 
         {
         printf("INCORRECT\n");
         }
         
    percentage=correct/percentage
    printf("You answered %d of the Questions Correctly.", percentage);
         
         }
    getch();
    return 0;
    
    
    }

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Not a bad start. But please make sure your indentation is carries over to the forum so it's easier to read your code.

    Right now, you're trying to print out the percentage after each question is answered, because it's in your "for()" loop. If you only want it to print once, at the end of the program, move it out of (after) the "for()" loop.

    Your percentage calculation is also not quite right.

    - You don't want to use integers for percentages; floating point would be better.
    - Percentage should be: (correct answers / total questions) * 100

    If your percentage is a floating point number, but you're using integers to calculate that value, then you need to cast one of the integers to floating point to get a non-truncated result. If you're confused about casting a variable from one type to another, let us know.

  6. #6
    Registered User
    Join Date
    Nov 2012
    Posts
    11
    Quote Originally Posted by Matticus View Post
    If your percentage is a floating point number, but you're using integers to calculate that value, then you need to cast one of the integers to floating point to get a non-truncated result. If you're confused about casting a variable from one type to another, let us know.
    Did not get this at all. I did implement what you said above and that makes sense. Here's what I have now....

    int n1;int n2;
    int prd, guess;
    int numTests;
    numTests=0;


    int correct;
    correct=0;
    float percentage;
    percentage=(correct/numTests)*100;
    printf("You have answered %f of the Questions Correctly.", percentage);

  7. #7
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    "Casting" is when you tell the compiler to convert a variable of a certain type to the equivalent value of a different type. If you divide integers, any remainder is lost, so you need to tell the compiler that when you say "correct/numTests" (and both variables are declared as ints), what you really mean is to convert them to floats before doing the computation. So something like "(float)correct/numTests" should preserve the remainder.

  8. #8
    Registered User
    Join Date
    Nov 2012
    Posts
    11
    I have tried
    percentage=float(correct/numTests)*100;
    printf("You have answered %f % of the Questions Correctly.", percentage);
    but I get this issue
    help with this code- loops-issue-png

    How do I resolve this?
    Attached Images Attached Images help with this code- loops-issue-png 
    Last edited by Gareth Morgan; 11-28-2012 at 11:53 AM.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Um, are you compiling as C? This looks like a compile error, though it is valid C++: float(correct/numTests). It should have been: (float)(correct/numTests), but that looks like it may result in integer division, hence the previously suggested (float)correct/numTests would be better.

    Also, within the format string of printf, a literal '%' should be escaped, i.e., "%f %" should be "%f %%".
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Nov 2012
    Posts
    11
    yes the (float) worked plus the %%. So random.

    One last question. I need to add the Q prefix to each question. So it should say Q1 5*4, Q2 8*6 so on until Q10. Any ideas? I haven't got a clue!

  11. #11
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    numTests go from 0 to 9. You could tweak your for loop to go from 1 to 10 and then just display numTests' current value as part of your prompt.

  12. #12
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    So random.
    Quite the opposite, in fact.

  13. #13
    Registered User
    Join Date
    Nov 2012
    Posts
    11
    Quote Originally Posted by sean View Post
    numTests go from 0 to 9. You could tweak your for loop to go from 1 to 10 and then just display numTests' current value as part of your prompt.
    Thanks. That was actually kinda obvious if I had thought about it! lol It worked after a few failed attempts! Finally finished my project. Thanks for all your help everyone!

  14. #14
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    yes the (float) worked plus the %%. So random.
    The (float) worked because it applies to a different expression whether it's inside or outside the parentheses. If it's outside, it will do integer division, lose the remainder, and THEN convert to a float. You wanted to convert before losing the remainder.

    The %% worked for the same reason escape sequences always work. Just think of "%" as being used in the same way as "\" is used for newlines, etc.

  15. #15
    Registered User
    Join Date
    Nov 2012
    Posts
    11
    One last question. how do I get the last bit of my code to repeat the application once its finished assuming the user clicks Y?

    Code:
    //
    
    
    #include <stdio.h>          //commands that essentially pastes previously written code into your program eg printf
    #include <stdlib.h>         //Defines numeric conversion functions, pseudo-random numbers generation functions and memory allocation                
    #include <time.h>           //Allows the user to use srand and define time and date values
    #include <conio.h>          //Allows the program to use getch();
    #include <ctype.h>          //
    
    int main(void)              //where the program start the execution
    {
        int a;                      //This is where we will temporarily store a value for the first random operand
        int b;                      //This is where we will temporarily store a value for the second random operand
        int sum, guess;             //An array to store the users inputed answer(guess) and where to compare it to the sum(correct answer) 
        int numTests;               //A counter for 2 parts of the application. One for Question Number and for the loop            
        int correct;                //A counter to add the correct answers
        correct=0;                  //This is so the application knows to start the score at 0 answers correct  
        float percentage;           //Part of the formula to calulate the final percentage of correct answers
    
        srand((unsigned char)time(NULL));   //Seeds the random number generator
    
        for ( numTests = 1 ; numTests < 11 ; numTests++ )     //This is to start the loop and to stop at Q10 by adding one each time the loop has been executed 
            {
              a = rand()%12+1;              //Generates a random number between 1-12 for operand 1
              b = rand()%12+1;              //Generates a random number between 1-12 for operand 2
              sum = a * b;                  //Calculates the sum by multiplying the 2 random numbers above
    
              printf("Q%d What is %d x %d\?\n",numTests,a,b);    //Will ask the user the maths question using random numbers
                           
              if(scanf("%d", &guess) != 1)                       //This will ask the computer to see if a number has been been inputed and not a character
              printf("Incorrect input.\n");                      //Error message if a character has been entered for the maths question
    
              else if(guess == sum)                              //Compares users guess with the correct sum
                   {
                    printf("CORRECT\n");                          //Prints CORRECT promt if answer by user is correct
                    correct++;                                    //Adds 1 to the loop
                   }
                    else                                               //If the user has not entered a character or a correct answer then this command is executed          
                       {
                          printf("INCORRECT\n");                        //Incorrect prompt for user
                       }     
         
            }
                {
                   percentage=(float)correct/(numTests-1)*100;   //Formula to work out final percentage at end of test
                   printf("You have answered %f %% of the Questions Correctly.", percentage);           //Promt telling user percentage mark
                }
                   {
                                char ch;                                      //Assigns the Y or N to the computers memory
    
                                printf("\n\n\n Another Go? (Y/N)");           //Promt asking user if they want another go
                                do
                                  {
                                    ch=getch();                           //Promts the user to press a character which is not entered on screen
                                    ch=toupper(ch);                       //Changes an inputted characted into upper case
                                  }
    
                                while (ch!='Y' && ch!='N');                   //If the user inputs y or n then the compiler will execute the above comand and convert to uppercase
                    }
    }
    Last edited by Gareth Morgan; 11-29-2012 at 07:48 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 06-01-2011, 04:19 PM
  2. can i ask what is wrong with this code? [LOOPS only]
    By Huskar in forum C Programming
    Replies: 6
    Last Post: 03-18-2009, 02:05 PM
  3. Help with a code using File I/O and Loops
    By bns1201 in forum C Programming
    Replies: 27
    Last Post: 10-17-2008, 09:19 PM
  4. while loops...a problem with my simple code?
    By niceguy in forum C Programming
    Replies: 13
    Last Post: 02-20-2008, 02:59 PM
  5. Loops OR Functions!! HELP WITH THIS CODE!!!!!!!!!!
    By WIshIwasGooD in forum C++ Programming
    Replies: 4
    Last Post: 10-24-2001, 12:49 PM