kk i fixed it but there is still one statement i have to put i think which is if (hit == length) then outside the while loop printf you won. but my question now where should i put the if (hit == length)
#include <stdio.h>
#include <conio.h>
#include <string.h>
//function prototypes
void game(char [], char [], int);
int main()
{
char word[20] = {'d', 'u','c','k'};
char guessed[20] ={'*s', '*s','*s','*s' };
int length = strlen(word);
game(word,guessed, length);
getch();
return 0;
}
void game(char answer[], char guess[], int length)
{
int life = 5;
int x = 0;
int y = 0;
char letter;
while (x < length && life > 0){
int hit = 0;
printf("enter letter\n");
scanf(" %c",&letter);
for (y = 0; y < length; ++y) {
if (answer[y] == letter && guess[y] != letter)
{
++hit;
guess[y] = letter;
}
}
if (!hit)
{
x += hit;
printf("try again\n");
life = life - 1;
printf("%d tries remaining \n", life);
}
else {
printf("keep going\n");
}
}
}
Your condition if (!hit) checks out if hit is 0 or not.
However, you initialize it to 0 only once, at the beginning of the procedure - and not for every iteration of your while(..) loop.
Therefore - once hit was set to be not 0 (in some iteration) it will always remain that way (not 0).
You should set hit = 0; inside the while loop (probably at its start).
You should set hit to 0 at the start of your while loop so it'll check hit seperately for every iteration of the for loop :P
try this
char guessed[20] ={ '*', '*','*','*' };
....
if (!hit) {
printf("try again\n");
life = life - 1;
printf("%d tries remaining \n", life);
}
else {
x = hit;
printf("keep going\n");
}
Related
I am trying to write a program in C that will read max of 50 rows of 5 integers and print them after reaching end of stdin.
#include <stdio.h>
#include <stdlib.h>
int readInput(int numbers[][5], int row) {
int x, i = 0;
while (1) {
if (scanf("%d", &x) !=1 ) exit (1);
if (x == 0) {
return 1;
}
if (feof(stdin)) {
return 0;
}
numbers[row][i] = x;
i++;
}
}
int main ( void ) {
int numbers[50][5];
int row = 0; int val;
int i,j;
while (1) {
val = readInput(numbers, row);
if ( val == 1){
row++;
continue;
} else if (val == 0) {
break;
}
}
for (i = 0; i < row+1; i++) {
for ( j = 0; j < 5; j++) {
printf("%d ", numbers[i][j]);
}printf("\n");
}
}
Problem is that no matter how I try to tell the program that the endless loop in main needs to end, it never does. I really need to understand the concept of reaching end of input, that is why I dont want to simply write a loopthat finishes after a certain amount of iterations, I want to learn how to break the loop after reaching end of stdin.
Your current code doesn't capture the EOF that scanf may return.
You can try something like:
int readInput(int numbers[][5], int row) {
int x, i = 0;
while (1) {
int t = scanf("%d", &x); // Save return value
if (t == EOF) return 0; // Check for EOF
if (t !=1 ) exit (1);
if (x == 0) {
return 1;
}
numbers[row][i] = x;
i++;
}
}
CTRL+D (or CTRL+Z for windows) can be used to indicate EOF
I would like to know if the number the user enters is number in the array.
Here is my code:
#define ARR_SIZE 10
int main()
{
int my_arr[10];
int secnum = 0;
int i = 0;
for (i = 0; i < ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
if(my_arr[i] == secnum)
{
printf("an ex");
}
}
But it doesn't work.
How can I compare a number with another number in array?
Note: I don't know pointers so I need to do it without pointers.
Why it doesn't work and what is wrong with the code?
You are comparing against just one value rather than all the array elements.
The value of i after the scanf loop is 10 so arr[i] would exceed the
array and could cause Illegal memory access.
Check the comments in the program.
#define ARR_SIZE 10
int main()
{
int my_arr[ARR_SIZE]; //Use ARR_SIZE because if ARR_SIZE changes, 10 won't causing unforseen errors.
int secnum = 0;
int i = 0;
for (i = 0; i < ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
for (i = 0; i < ARR_SIZE ; i++) // Ensures you are comparing secnum with each array element.
{
if(my_arr[i] == secnum)
{
printf("an ex"); //Do you wish to break here because one you find a match, the goal is attained :)
}
}
}
After the loop, i is equal to ARR_SIZE (10). So you compare my_arr[10] with secnum (0). But my_arr[10], while syntactically correct, points to an undefined value because the size of the array is 10.
#define ARR_SIZE 10
int main()
{
int my_arr[10];
int secnum = 0;
int i = 0;
for (i=0;i<ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
for (i=0;i<ARR_SIZE ; i++)
{
if(my_arr[i]==secnum)
{
printf("Given number is in array\n");
break;
}
}
}
As pointed by OP in comments to one of the answers, OP apparently need a routine to check for the key in an array.
So once we have stored an array and have accepted a key to search, we need to pass this array and key to a search function which will return true or false depending upon whether the key is present in the array or not.
#include <stdbool.h> // We need this for `true` and `false` bool values
bool search(int [], int); // Function declaration
/**** Function Definition *****/
bool search(int numbers[], int key)
{
int i;
for(i = 0; i < ARR_SIZE; i++)
if(numbers[i] == key)
return true;
return false;
}
/** Calling search function from main **/
...
if(search(my_arr, secnum))
printf("Number found in array!\n");
else
printf("Number could NOT be found in array!\n");
To find a value in an array you should iterate through it and compare each value with the wanted number. You should also check the return value of scanf() to control how many item did it actually read. See if this reviewed code is helpfull:
#include <stdio.h>
#define ARR_SIZE 10
int read_numbers(int a[], int size) {
int i = 0;
int r = 0;
while ( i < size ) {
printf("Please, enter a number (%d of %d): ",i+1,size);
r = scanf(" %d",&a[i]); // the space before will ignore any trailing newline
if ( r == EOF ) break; // if scanf fails return
if ( r != 1 ) { // if user don't enter a number, repeat
printf("Wrong input!\n");
scanf("%[^\n]*"); // will read and ignore everything lweft on stdin till newline
continue;
}
++i;
}
return i; // return size, unless scanf fails
}
int find_number(int a[], int size, int x) {
int i = 0;
while ( i < size && a[i] != x ) ++i;
return i; // if x isn't in the array returns size
}
int main()
{
int my_arr[ARR_SIZE];
int secnum = 0;
int i = 0;
int n = 0;
n = read_numbers(my_arr, ARR_SIZE);
if ( n < ARR_SIZE ) {
printf("Warning, only %d numebers read out of %d!\n",n,ARR_SIZE);
} // if happens you have uninitialized elements in array
printf("Now, enter the value you want to find.\n");
if ( read_numbers(&secnum, 1) != 1 ) { // reuse the function
printf("Sorry, an error has occurred.\n");
return -1;
}
i = find_number(my_arr, n, secnum); // If all went right n==ARR_SIZE
if ( i < n ) { // a match has been found
printf("Found!\n");
} else {
printf("Not found.\n");
}
return 0;
}
What in the world, is the matter here:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int array[20];
int *pArray = array;
int count;
int i = 0;
while(1)
{
scanf("%d", array+i );
if(*(pArray+i) == -1) break;
i++;
}
printf("Contents: ");
while(1){
if (*(pArray + i) != -1)
{
printf("%d ", *(pArray + i) );
i++;
}
}
return 0;
}
Thank you. I am trying to take input from the user and then display the contents of the array. I was going to arrange them in order too using pointers, but I'll wait till someone replies.
Here is my rewrite attempt:
#include <stdio.h>
int main(void)
{
int array[20];
int i = 0;
while(1)
{
scanf("%d", &array[i] );
if(array[i] == -1) break;
i++;
}
printf("Contents: ");
i = 0; // RESET the counter back to ZERO.
while(1)
{
if (array[i] != -1)
{
printf("%d ", array[i] );
i++;
}
}
return 0;
}
You may be facing the error of stack around the variable array is corrupted. The reason is that you are first taking an input and then terminating the loop if the given input was -1.
scanf("%d", array+i );
if(*(pArray+i) == -1) break;
Now assume that i=20 what will happen???
Of course your code will crash on the scanf statement because it will try to access array+20 (the 20th index) which will not be allowed.
You also need to initialize the array first because when you declare an array, it contains junk values perhaps initializing the last index with zero will do the job. You can use the following code:
#include <stdio.h>
int main(void)
{
int array[20];
/*INITIALIZE THE LAST INDEX WITH -1 TO APPLY THE TERMINATING CONDITION*/
array[19] = -1;
int i = 0;
while(1)
{
scanf("%d", array+i );
i++; //INCREMENT HERE TO CHECK THE NEXT INDEX INSTEAD OF CHECKING THIS ONE
if(array+i == -1)
{
scanf("%d", array+i ); //TAKE THE INPUT FOR THE LAST INDEX
break; //TERMINATE THE LOOP
}
}
printf("Contents: ");
i = 0; // RESET the counter back to ZERO.
while(i != 20)
{
printf("%d ", array[i] );
i++;
}
return 0;
}
It seems like you are using pArray without any reason. array can also do exactly what you are trying to do with pArray. For arranging the order, you have to apply any sorting algorithm. Hope this helps.
I am trying to run a program that will repeatedly read a letter from the user, with the most being entered as 12. If the user enters a sentinel value that they input, the loop should terminate. However, as soon as the first character is read in the loop, it terminates.
Also, the program will place the same word in the reverse order in another array, then check them to see if the first array (read forward), is the same as the other array (read backward). If it is, it displays that the word is a palindrome.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int charCount, counter, i, temp, check,check2;
char letter[12], letter2[12];
charCount = 0;
counter = 10;
check = 0;
i = 1;
check2 = 0;
printf("Enter your sentinel value.:");
scanf_s(" %c", &letter[check2]);
while ((i<13) && (letter[i] != letter[check2]))
{
printf("Enter individual letters in word (in order).:");
scanf_s(" %c", &letter[i]);
charCount++;
if (letter[i] == letter[check2])
{
break;
}
i++;
}
printf("Letters entered:%i\n", charCount);
for (i = 0; i < charCount; i++)
{
letter2[i] = letter[i];
}
for (i = 0; i <= (charCount / 2); i++)
{
temp = letter2[counter];
letter2[counter] = letter2[i];
letter2[i] = temp;
counter--;
}
for (i = 0; i <= charCount; i++)
{
if (letter[i] = letter2[i])
{
check++;
}
}
if (check = charCount)
{
printf("Word is a palindrome.\n");
}
system("PAUSE");
return 0;
}
the letter[1] value will be unassigned when the while loop enters for the first time right ? I think you can take that condition out of the while loop since you are considering it in the if statement inside the while loop
The following code needs to check for palindromes and write the user input backwards using recursion, and then find the Greatest Common Denominator using the same method. The code section that finds the gcd and tells whether or not it is a palindrome works, but it crashes every time it gets the the part where it reverses the code. Why is it crashing every time.
#include <stdio.h>
#include <stdlib.h>
/*Delare the prototypes*/
char palindromes(char[], int);
char backwards(char[], int, int);
int gcdfunc(int, int);
int findgcd(int, int);
int main ()
{
char userinput[10];/*Declares the character array for the input*/
int index= 0;/*Index for the counting loop*/
int counter= 0;/*Counts number of elements entered in the array*/
int printindex= 0;/*Index to print the values on the screen*/
int gcd= 0;/*Sets a value for the GCD*/
int palcheck = 0;
int value1= 0;/*User value 1*/
int value2= 0;/*User value 2*/
int flipindex=0;/*Sets an index for the gcd function*/
printf("Please enter a series of nine or less characters to test for a palindrome.\n");
scanf(" %9s%n", &userinput, &counter);
printf("\n");
palcheck = palindromes(userinput, counter-1);
if(palcheck == 0)
{
printf("Your input was not a palindrome \n");
}/*End of if statement*/
else
{
printf("Your input was a palindrome \n");
}/*End of else statement*/
backwards(userinput, counter-1, flipindex);
printf("Your input backwards is: ");
for(printindex; printindex <= counter; printindex++)
{
printf("%c", userinput[printindex]);
}/*End of printing backwards loop*/
printf("\n");
printf("\nEnter two numbers: ");
scanf("%d %d",&value1,&value2);
gcd=gcdfunc(value1, value2);
printf("The GCD of %d and %d is: %d",value1,value2,gcd);
system("pause");
}/*End of main function*/
char palindromes(char userinput[], int counter)
{
int palindex= 0;/*Declares the index to check for a palindrome*/
int palendinx= counter;
int modulus = counter%2;
if(modulus = 0)
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
else
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
}/*End of palidrome function*/
char backwards(char userinput[], int counter, int flipindex)
{
while(flipindex<(counter/2))
{
char temp;/*Sets a temporary value to swap the two values*/
temp = userinput[flipindex];
userinput[flipindex] = userinput[counter-flipindex];
userinput[counter-flipindex] = temp;
backwards(userinput, counter, flipindex++);
}
}/*End of reverse function*/
int gcdfunc(int value1, int value2)
{
int gcd;
gcd=findgcd(value1,value2);
return gcd;
}
int findgcd(int value1,int value2)
{
while(value1!=value2)
{
if(value1>value2)
return findgcd(value1-value2,value2);
else
return findgcd(value1,value2-value1);
}
return value1;
}
in your function there is no pass for the variables and it stays in the same cycle over and over and in recursion the same function does not share the same variables it create new one and if you modify one it does not affect the others variables.
char palindromes(char userinput[], int counter)
{
int palindex= 0;/*Declares the index to check for a palindrome*/
int palendinx= counter;
int modulus = counter%2;
if(modulus = 0)
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
else
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
}/*End of palidrome function*/
So here is the code i did
int palindromes(char userinput[], int counter,int index , int palendex)
{
if(userinput[palendex] == userinput[index])
{
if(counter%2 == 0 && ( index - palendex) == 1)
return 0;
if( index == palendex )
return 0;
else
return palindromes(userinput, counter , index-1 ,palendex+1 );
}
else
return 1;
return 1;
}
In your backward function is that it never leaves the cycle while and do a lot of instances that the memory available runs out. so I changed it to an if statement and it looks like this (and a few changes)
int backwards(char userinput[], int counter, int flipindex)
{
if(flipindex<(counter/2))
{
char temp;/*Sets a temporary value to swap the two values*/
temp = userinput[flipindex];
userinput[flipindex] = userinput[counter-flipindex-1];
userinput[counter-flipindex-1] = temp;
backwards(userinput, counter, flipindex+1);
}
return 1;
}
It looks like you go past the end of the buffer with this code:
for(printindex; printindex <= counter; printindex++)
{
printf("%c", userinput[printindex]);
}/*End of printing backwards loop*/
because printindex == counter and userinput[counter] is out of bounds. Try this for-statement instead:
for(printindex; printindex < counter; printindex++)
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
It call recursively condition in the if statement is not satisfied. but It will stack overflow repeated calls indefinitely because there is no change in the situation.