# Thread: help with this code- loops

1. ## 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. Try something like
Code:
```for ( numTests = 0 ; numTests < 10 ; numTests++ ) {
n1 = rand()%12+1;
n2 = rand()%12+1;
// more of your code
}```

3. 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. Originally Posted by Matticus
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. 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. Originally Posted by Matticus
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. "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. I have tried
percentage=float(correct/numTests)*100;
printf("You have answered %f % of the Questions Correctly.", percentage);
but I get this issue

How do I resolve this?

9. 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 %%".

10. 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. 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. So random.
Quite the opposite, in fact.

13. Originally Posted by sean
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. 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. 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
}
}```

Popular pages Recent additions