write a hangman program in c language that guess random words with letter
Assistant
Here's a simple Hangman program in C that guesses random words with letters. This program uses a predefined list of words, but you can easily modify it to use a different word list or even load words from a file.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_WORDS 100
#define MAX_WORD_LENGTH 20
char words[MAX_WORDS][MAX_WORD_LENGTH] = {
"hello", "world", "c", "programming", "language", "hangman", "game", "computer", "science", "algorithm"
};
int random_word(char words[][MAX_WORD_LENGTH], int size) {
int index = rand() % size;
return index;
}
void print_word(char word[], char guessed[]) {
for (int i = 0; word[i] != '\0'; i++) {
if (guessed[i] == word[i]) {
printf("%c ", word[i]);
} else {
printf("_ ");
}
}
printf("\n");
}
int main() {
srand(time(NULL));
int word_count = sizeof(words) / sizeof(words[0]);
int word_index = random_word(words, word_count);
char word[MAX_WORD_LENGTH] = {0};
strcpy(word, words[word_index]);
int word_length = strlen(word);
char guessed[word_length];
memset(guessed, '_', word_length - 1);
guessed[word_length - 1] = '\0';
int attempts = 0;
int max_attempts = 7;
printf("Welcome to Hangman!\n");
printf("The word has %d letters.\n", word_length);
while (attempts < max_attempts && strcmp(guessed, word) != 0) {
printf("\nAttempt %d: ", attempts + 1);
char guess;
scanf(" %c", &guess);
if (strchr(word, guess) != NULL) {
for (int i = 0; word[i] != '\0'; i++) {
if (word[i] == guess) {
guessed[i] = guess;
}
}
} else {
attempts++;
}
print_word(word, guessed);
}
if (strcmp(guessed, word) == 0) {
printf("\nCongratulations! You've guessed the word correctly.\n");
} else {
printf("\nSorry, you've run out of attempts. The word was %s.\n", word);
}
return 0;
}
This program generates a random word from the predefined list and allows the user to guess the letters. The user has a maximum of 7 attempts to guess the word correctly. If the user guesses the word within the attempts, they win; otherwise, they lose.
To run this program, save it as hangman.c and compile it using a C compiler like gcc:
sh
gcc hangman.c -o hangman
./hangman
You can also modify the program to load words from a file or use a different word list.