I am trying to create a program that assigns the user one of three questions at random. I figured out that part however I want to make it so that after they correctly answer their assigned question that they are asked if they want to take another one.
int main(void) {
srand(time(0));
int luckyNumber;
int quizNumber;
int score;
int totalScore;
int averageScore;
int attempts;
char answer1;
char answer2;
char answer3;
char opt1;
char loop = 'y';
printf("Welcome to the quiz program!\n");
while(loop == 'y') {
printf("Please enter a lucky number between 1 and 9: ");
scanf("%d", &luckyNumber);
quizNumber = rand() % 3 + 1;
printf("Your quiz number is %d\n", quizNumber);
if (quizNumber == quizNumber) {
while (score != 5) {
printf("Quiz 1\n");
printf("A. True\n");
printf("B. False\n");
printf("Enter your answer: ");
scanf(" %c", &answer1);
if (answer1 == 'B' || answer1 == 'b') {
printf("Correct!\n");
score = score + 5;
break;
}
else {
printf("Incorrect!, Try again.\n");
printf("\n");
}
break;
}
break;
}
printf("Would you like to go again y/n?");
scanf("%c", &loop);
if (loop != 'y')
loop = 'n';
}
return 0;
}
The problem I am having is after I compile the code, it stops when the correct answer is input rather than going on to ask if the user would like to do another quiz.
Related
I have managed to create a game that tries to guess what the user is thinking about, but the problem is that the number guessed is stored into l_guess or h_guess depending on the condition met, how can I store it into a third variable that would be the new guess used on the next guess?
My question might not be clear, but I hope looking at the code will help.
// Assignment #7
// This program guesses the number that you have picked.
#include <stdio.h>
#define UPPER 100
#define first_Guess 50
char answer;
int h_Guess;
int l_Guess;
int new_Guess;
void game_Start();
void game_Play();
int main(void)
{
h_Guess = (first_Guess + UPPER) / 2;
l_Guess = first_Guess;
game_Start();
game_Play();
return 0;
}
void game_Start()
{
printf("Hello, and welcome to the guessing game\n Think of a number between 0 and 100 and I will try to guess it.\n");
printf("... Is it %d ?", first_Guess);
printf("If the answer is correct, press (c) \n If your number is higher, press (h)\n if your number is lower, press (l)\n");
scanf("%c", &answer);
}
void game_Play()
{
while (answer != 'c')
{
if (answer == 'h')
{
printf("Then ... is it %d?\n", h_Guess);
h_Guess = (h_Guess + UPPER) / 2;
}
else if (answer == 'l')
{
l_Guess = l_Guess / 2;
printf("Then ... is it %d?\n", l_Guess);
}
scanf("%c", &answer);
}
printf(" I knew it, I am a genius\n");
}
You're not properly re-setting the boundaries of your guesses.
void game_Play()
{
int upper = MAX;
int lower = MIN;
int guess = FIRST_GUESS;
while (answer != 'c')
{
if (answer == 'h')
{
lower = guess;
}
else if (answer == 'l')
{
upper = guess;
}
guess = (upper + lower) / 2;
printf("Then is it %d?\n", guess);
scanf(" %c", &answer);
}
printf(" I knew it. I am a genius.\n");
}
Note: with your constants defined as they are, there is an edge-case error in my solution. Can you find it, and fix it?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am making a tic tac toe game in C language but it won't run
I don't know where is the error at. The compiler just freeze without any error messages this is my code below if anyone could point out the errors and the way of writing clean code i am a new programmer who is still learning and this is my first project.
#include <stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
void BuildGround;
void first_player_choice;
void second_player_choice;
void ai_choice;
char result;
void AiVsP;
void PVP;
int count_ground;
int main()
{
char ground[9] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
int mode;
printf("choose game mode (1 or 2): ");
printf("1. PVP ");
printf("2. AI vs P: ");
scanf("%d",&mode);
switch(mode){
case 1 :
PVP();
break;
case 2:
AiVsP();
break;
default:
printf("Invalid input: ");
break;
}
}
int count_ground(char symbole){
int total=0;
for(int i =0 ; i<9 ; i++){
if(ground[i]== symbole)
total=+ 1;
}
}
void AiVsP(void){
char name[100];
printf("Enter your name : ");
gets(name);
while(1==1){
system("cls");
BuildGround();
if (count_ground('X') == count_ground('O')){
puts("Turn: ");
puts(name);
fisrt_player_choice();
}
else{
ai_choice;
}
char winner == result();
if (winner == 'X'){
system("cls");
BuildGround();
puts("The winner is: ");
puts(name);
break;
}
else if
(winner == 'O'){
system("cls");
BuildGround();
printf("AI wins ")
break;
}
else winner == 'D'
printf("The Game is Draw ")
break;
}
}
void PVP(void){
char name1[100];
char name2[100];
printf("Enter the name of the first player : ");
gets(name1);
printf("Enter the name of the second player : ");
gets(name2);
while(1==1){
system("cls");
BuildGround;
if (count_ground('X') == count_ground('O')){
puts("Turn: ");
puts(name1);
first_player_choice();
}
else{
puts("Turn: ");
puts(name2);
second_player_choice();
}
char winner == result();
if (winner == 'X'){
system("cls");
BuildGround();
puts("The winner is: ");
puts(name1);
break;
}
else if
(winner == 'O'){
system("cls");
BuildGround();
puts("The winner is: ");
puts(name2);
break;
}
else winner == 'D'
printf("The Game is Draw ")
break;
}
}
char result(char ground[9]){
int i;
for(i = 0;i<=6; i+=3)//it's for row
if(ground[i] == ground[i+1]== && ground[i+1]== ground[i+2]&& ground[i] != ' ' ){
return ground[0];
}
for(i = 0;i<3; i++)//it's for column
if(ground[i]== ground[i+3]== && ground[i+3]== ground[i+6] && ground[i]!=' ' ){
return ground[1];
}
if(ground[0] == && ground[4] == && ground[4]== ground[8] && ground[0]!=' '){
return ground[4];
}
else if(ground[2] == && ground[4] == && ground[4]== ground[6] && ground[2]!=' '){
return ground[6];
}
else if(count_ground('X')+ count_ground('O') < 9){
return 'C';
}else return 'D';
}
void ai_choice(void){
srand(time(0));
do{
int c;
c = rand()%10;
}
while(ground[c]!= ' ');
ground(c)='O';
}
void first_player_choice(char ground[9]){
while(1==1){
int position;
printf("Choose your position from 0-8 (column wise): ");
scanf("%d", &position);
if(position < 0 || position > 8 ){
printf("Invalid number please try again: ");
}
else if(ground[position]!=' '){
printf("Position is already taken please try again: ");
}
else
ground[c]='X';
break;
}
}
void second_player_choice(char ground[9]){
while(1==1){
int position;
printf("Choose your position from 0-8 (column wise): ");
scanf("%d", &position);
if(position < 0 || position > 8 ){
printf("Invalid number please try again: ");
}
else if(ground[position]!=' '){
printf("Position is already taken please try again: ");
}
else
ground[c]='O';
break;
}
}
void BuildGround(char ground[9]){
printf("\t\t\t\tT i c t a c t o e");
printf("\nPlayers 1 Symbol: X");
printf("\nPlayers 2 Symbol: O");
printf("\n\t\t\t | | ");
printf("\n\t\t\t %c | %c | %c ",ground[0],ground[1],ground[2]);
printf("\n\t\t\t_______|_______|_______");
printf("\n\t\t\t %c | %c | %c ",ground[3],ground[4],ground[5]);
printf("\n\t\t\t_______|_______|_______");
printf("\n\t\t\t %c | %c | %c ",ground[6],ground[7],ground[8]);
printf("\n\t\t\t | | ");
}
You have multiple issues, like
case 1 :
PVP; //this is not a function call.
break;
should use the call like
PVP();
or rather, pvp(); , as uppercase letters usually carry special meaning, not a good idea to use them for user-defined code.
That said, function definitions like
void ai_choice{
srand(time(0));
and
void PVP{
char name1[100];
char name2[100];
are wrong syntax, you have to use the parenthesis, like
void PVP (void){
char name1[100];
char name2[100];
That said, scanf("%d",& mode); is usually written as scanf("%d",&mode); (no space between operand and operator, but that's just a choice).
I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
Hi I'm new to C and I wrote a simple program. I want to restart the program if the user picked the wrong choice, here is the code:
#include <stdio.h>
#include <cs50.h>
int main(void){
char choices;
float math, pc, svt, eng, philo;
do {
do {
printf("Enter your math score: ");
math = GetFloat();
}
while( math>20 || math<0);
do {
printf("Enter your pc score: ");
pc = GetFloat();
}
while(pc>20 || pc<0);
do {
printf("Enter your svt score: ");
svt = GetFloat();
}
while(svt>20 || svt<0);
do {
printf("Enter your eng score: ");
eng = GetFloat();
}
while(eng>20 || eng<0);
do {
printf("Enter your philo score: ");
philo = GetFloat();
}
while(philo>20 || philo<0);
printf("Are you pc or sm?\n");
printf("Write 1 for pc. 2 for sm\n");
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
}
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
} while (choices == 'Y' || choices == 'y');
}
So what I mean here, I want to insert the code in the else block to restart the program and give the user another time. It would be very nice if I can just make him choose again between 1 or 2.
If you have any suggestions or improvement please don't hesitate to comment.
Thanks :)
What you need is do while loop surrounding choice code:
int choice;
do {
choice = GetInt();
if (choice == 1) {
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if (choice == 2) {
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else {
printf("You've picked the wrong choice, try again.\n");
}
} while(choice < 1 || choice > 2)
You already have a loop to try again, you can reuse that loop to get the user input again for choice. So, if the user enters choice other than 1 or 2, you can set choices = Y and redo the loop. without asking for user input.
Code is below.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
char choices;
float math, pc, svt, eng, philo;
do
{
// Other code here
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");
choices = 'Y';
}
if ((choice == 1) || (choice == 2))
{
printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
}
} while (choices == 'Y' || choices == 'y');
}
Well, if somebody reading this has to actually restart their program for a more nontrivial reason (e.g. an exception handler, like me a couple of minutes ago), there is a portable way to to so in C, like so:
#include <setjmp.h> //from C standard library
jmp_buf restart_env;
int main() {
//some initialization you don't want to repeat
if(setjmp(restart_env)) {
//restarted, do whatever
}
//the code
}
void evenFromAnotherFunction() {
//...
if(something_that_justifies_this_approach) {
longjmp(restart_env, 1); //this restarts the program
//unreachable
}
//...
}
Note that you had better not use this if there's a better way. Using setjmp is bound to produce extremely annoying bugs. If you have no choice, remember that some data may preserve the value it had before calling setjmp for the first time, and some may not, so don't assume anything.
I am a beginner in C...
I have made a made a calculator type program which uses four basic functions in C using if-else loop.
I want when the program comes to end(after the user has added, subtracted etc. etc. then there is a option "Y/N" so that the program can be restarted???"
Here is the sample of the code
#include<stdio.h>
int main()
{
int choi;
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
end:
getch();
return 0;
}
The best way would be to do some sort of a while loop.
int goAgain=1;
while (goAgain==1) {
... //Normal code here
printf("Again?")
scanf("%c",&again)
if (again=='N') {
goAgain=0;
}
}
Or you could use a do-while loop as well
do {
... //Normal code here
printf("Again?")
scanf("%c",&again)
} while (again=='Y')
Basically, this will keep looping over the bit of code over and over until the person types N to end it.
A do-while loop would be most suitable for this purpose.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
scanf("%c", &choice);
} while (choice == 'Y');
}
Edit: As it turns out, there is another problem with the program above, which is that scanf() reads a character but leaves a Newline character in the buffer. Therefore, if the user types YEnter, the program will repeat once (choice == 'Y' the first time), then exit (choice == '\n' the second time).
It is therefore necessary to keep reading until the Newline has been consumed.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
choice = getchar();
while (choice != '\n' && getchar() != '\n') {};
} while (choice == 'Y' || choice == 'y');
}
char continue = 'Y'
while (continue == 'Y') {
... //Normal code here
printf("Again?")
scanf("%c",&continue)
}
you can try like this, avoid go to
#include<stdio.h>
int main()
{
int choi;
while(true)
{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\n5. Exit");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==1)
{
}
else if(choi==2)
{
}
else if(choi==3)
{
}
else if(choi==4)
{
}
else if(choi==5)
{
return 0; //exit(0);
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2,3,4 or 5 !\n\n");
}
}
return 0;
}
By using do-while loop, which is generally used for menu-driven programs.
#include<stdio.h>
int main()
{
int choi;
char choice;
do{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
printf("Want to continue (y/n)?");
scanf("%d", &choice); // Enter the character
}while (choice == 'y' || choice == 'Y');
end:
getch();
return 0;
P.S.: I would suggest you to use switch case, instead of if-else statements to do the job.
You can also use a goto:
int main() {
...
if (c=='y') {
main();
} else {
goto end;
}
end:
...
}