-
Length of an array
Hey everyone!
I need a little help with my code... I have made a simple game where you have to guess the number, which has been created by the RNG, and it helps you to get closer to the number by saying : Choose a bigger number / choose a smaller number... and when you finally enter the right number it says : Congrats , you won. But then i would like to know in the end of the programm, that how many times you had to guess to get the correct number. Here's what i have been trying to do, here is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int x = rand()%10;
int i,n=0,tip=0;
int array[tip];
do {
printf(" Enter a number.\n");
scanf("%d",&array[tip]);
if (array[tip]<x) {
printf("Enter a bigger number.\n");
} else if (array[tip]>x) {
printf("Enter a smaller number.\n");
} else {printf("Congratz, you won!\n");
}
}while(array[tip]!=x);
for(i=0;i<10;i++)
if(tomb[tipp]=x) {
n= sizeof(tomb)/sizeof(tomb[i]);
}
printf("You had to guess %d times to win!\n", n);
return 0;
}
Please help me if you can!
-
See if this works for you. I got rid of the do while loop and made the variable names a bit clearer.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int numToGuess = rand()%10;
int guessCount, isGuessRight, currentGuess;
isGuessRight = 0;
guessCount = 0;
while(!isGuessRight)
{
printf(" Enter a number.\n");
scanf("%d",¤tGuess);
if(currentGuess < numToGuess)
printf("Enter a bigger number.\n");
else if(currentGuess > numToGuess)
printf("Enter a smaller number.\n");
else
{
printf("Congrats you won.\n");
isGuessRight = 1;
}
guessCount++;
}
printf("You had to guess %d times to win!\n", guessCount);
system("pause");
return 0;
}
-
You have a problem right here:
Code:
int i,n=0,tip=0;
int array[tip];
You initialised tip to 0, then you tried to create a variable length array of tip, i.e., 0, number of elements. I don't remember offhand if this is permitted, but if it is, you end up with an array that you cannot index since it has no elements. If it isn't permitted, well, then it isn't permitted so you would get an error (or maybe undefined behaviour).
Anyway, for this problem, you don't need an array, whether of fixed size, a variable length array, or a dynamic array. Rather, you need:
- a variable to store the number to be generated by the RNG
- a variable to store the guess of the user
- a variable to store the count of the number of guesses
All these variables can be of integer type.
Note that you also appear to be using another array or pointer named tomb which was not declared, which makes me wonder if you tried copying code from elsewhere without understanding it.
-
Thank you very much!
I wasn't copying i just tried this in my own language and i rewrote it to english, so it would be better to read it for others, but i was too tired already, and made a little bit of mess of it. But thank you again it helped me to learn!