In: Computer Science
Need to write a c program
Program prints a message telling the user to push a key to start the game.
Once in game, output tells the player which key to push. The key to press should be determined randomly.
Game runs continuously until the user reaches a loose condition.
A wrong key is pressed
Code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
// ask user to press any key to start the game
printf("Push any key to start the game: ");
char c;
scanf("%c",&c);
srand(time(NULL));
// use a while loop to randomly print characters
while(1){
int r = rand();
char random = 'a' + (r%26);
printf("%c\n",random);
// accept input char
char input;
scanf(" %c",&input);
// if they are different break
if(input!=random){
printf("You lost. Wrong key pressed !!");
// break out of the loop
break;
}
}
return 0;
}
Code screenshot::
Code output:
==================
Code along with output and screenshot has been attached.
Note: In line 22, you may see the scanf has " %c" i.e. space before %c, this is done to read extra newline character that may be present.
For any query comment.