Building A Mad Libs Game
Lesson 14Author : Afrixi
Last Updated : January, 2023
Sure, here’s an example of how to build a Mad Libs game in C:
#include <stdio.h>
int main() {
// Declare variables to store user input
char adjective[20], color[20], animal[20], verb[20];
int number;
// Prompt the user for input
printf("Enter an adjective: ");
scanf("%s", adjective);
printf("Enter a color: ");
scanf("%s", color);
printf("Enter an animal: ");
scanf("%s", animal);
printf("Enter a verb: ");
scanf("%s", verb);
printf("Enter a number: ");
scanf("%d", &number);
// Print out the completed Mad Libs story
printf("\nOnce upon a time, there was a %s %s %s. It loved to %s, but one day it saw %d %s in the distance and decided to chase after them. It ran and ran, but eventually got tired and fell asleep under a tree. When it woke up, it realized that it had become friends with the %s!\n", adjective, color, animal, verb, number, animal, animal);
return 0;
}
In this example, the program prompts the user to enter various types of words (adjective, color, animal, verb, and number) using the scanf()
function. The program stores these inputs in variables declared at the beginning of the program. Then, the program uses these inputs to print out a complete Mad Libs story using printf()
. Finally, the program returns 0 to indicate successful execution.
Note that this is just one example of a Mad Libs game in C. You can customize the prompts and story to your liking. Also, keep in mind that this program assumes that the user enters valid input, so you may want to add some error checking or validation if you’re building a more complex application.