I need a function that will have the randomly generate 4 digits for the user to
ID: 3547771 • Letter: I
Question
I need a function that will have the randomly generate 4 digits for the user to guess. The digits can nly be from 1-4, so 1234, 4233, and so on.
.The user will have 20 tries to guess the 4 digits.
.The guesses need to be saved in an array.
.Also, a switch needs to be applied to allow the user to decide if he will guess the digits or provide the digits.
.Here is the code for the user to provide the digits.
.#include"stdafx.h"
.
.#include"stdio.h"
.
.#include<stdlib.h>
.
.int valid(char);
.
.int main(void)
.
.{char c;
.
.int test, i, guess=0, j=0, k=0;
.
.char numbers[4];
.
.char computerNumber[4];
.
.for(i=0; i<4; i++)
.
.{
.
.do{
.
.printf(" Enter a number between 1 and 4: ");
.
.numbers[i]=getchar();
.
.test=valid(numbers[i]);}
.
.while(test);}
.
.for(j=1;j<=20;j++)
.
.{printf("The computer guess is: ");
.
.for(i=0; i<4; i++){computerNumber[i] = rand()%4+49;
.
.printf("%c", computerNumber[i]);}
.
.printf(" ");
.
.guess = 0;
.
.for(k = 1; k<5; k++)
.
.if(computerNumber[k] == numbers[k])
.
.guess++;
.
.if(guess==4)
.
.{
.
.printf("The computer guessed correctly! ");
.
.j = 21;
.
.}
.
.else
.
.printf("The computer did not guess correctly ");
.
.}
.}
.
.int
.
.valid(char c)
.
.{if ((c>='1') && (c<='4'))
.
.{return 0;
.
.}
.
.else
.
.{
.
.return 1;
.
.
.
.}
.
.
.
.}
Explanation / Answer
You can use an 4 dimensional array and can generate elements of it using rand function
or you can make a structure with 4 elemnets and generate them using rand function...include<time.h> and stdlib.h
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.