This is a basic quiz program in C. It will have a timer which was implemented using multi-threading. It will randomly displays questions on sum, product and subtractions. Finally displays the result showing the count of questions answered, correct answers and wrong answers
#include <stdio.h> #include <stdlib.h> #include <pthread.h> int quiz_time = 2; // change the quiz time in minutes int total_questions = 5; // change total number of questions int i = 0; int answered = 0; int correct = 0; int wrong = 0; int _time = 0; int computed_seconds; void endQuiz(int timeout){ if(timeout==1){ printf("Time out : Quiz ended !"); }else{ printf("Quiz ended !"); } printf(" == Your Result == "); printf("Questions answered : %d", answered); printf("Correct answers : %d", correct); printf("Wrong answers : %d", wrong); exit(0); } void *timerThread(void *vargp){ computed_seconds = quiz_time * 60; for(i = 0; i < computed_seconds; i++){ sleep(1); _time = _time + 1; } endQuiz(1); // Calling quiz end function when the time gets over return NULL; } void *askQuestion(void *args){ int _i,a,b; int minutes,seconds; int operand; int ans; for(_i = 0; _i < total_questions; _i++){ srand(time(NULL)); a = rand() % 10; b = rand() % 5; operand = rand() % 2; switch(operand){ case 0: printf("Sum of %d & %d : ",a,b); scanf("%d",&ans); answered++; if((a+b) == ans){ correct++; }else{ wrong++; } break; case 1: printf("Product of %d & %d : ",a,b); scanf("%d",&ans); answered++; if((a*b) == ans){ correct++; }else{ wrong++; } break; case 2: printf("What is %d - %d : ",a,b); scanf("%d",&ans); answered++; if((a-b) == ans){ correct++; }else{ wrong++; } break; default : break; } computed_seconds = quiz_time * 60; minutes = (int)(computed_seconds-_time)/60; seconds = abs((((minutes - (float)(computed_seconds-_time)/60) * 100 ) /100 ) * 60); printf("Time remaining : %d minutes %d seconds", minutes,seconds ); } endQuiz(0); // Calling quiz end function when the questions gets over } int main(){ pthread_t tid,qid; printf("Quiz started"); pthread_create(&qid, NULL, askQuestion, NULL); pthread_create(&tid, NULL, timerThread, NULL); pthread_join(qid, NULL); pthread_join(tid, NULL); return 0; }
Quiz started Product of 1 & 2 : 2 Time remaining : 1 minutes 54 seconds Product of 2 & 1 : 2 Time remaining : 1 minutes 53 seconds Sum of 2 & 3 : 5 Time remaining : 1 minutes 50 seconds Product of 9 & 2 : 18 Time remaining : 1 minutes 47 seconds Product of 0 & 2 : 2 Time remaining : 1 minutes 42 seconds Quiz ended ! == Your Result == Questions answered : 5 Correct answers : 4 Wrong answers : 1
This program will not work with Turbo C. Compile it on a linux machine using the following steps.
Copy the program and save it in a file named quiz.c
Compile using the command gcc quiz.c -lpthread
Execute and see the result using ./a.out
Comments :