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
Related
I'm new to programming and am trying to do this guessing game by a simple C program below. When I input letters from the word "apple", every letter (p,l,e) executes the wrong guess try again statement except for the letter 'a'. I can't seem to understand what I'm doing wrong here. Any insights is highly appreciated.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define size 10
int main() {
// initialize variables
char word[size] = "apple";
char guess;
char arrayofdashes[size] = "_____";
printf("guess a letter \n");
// input loop
for (int i = 0; i < strlen(word); i++)
{
scanf(" %c", &guess);
for (int j = 0; j< strlen(word); j++ )
{
if (guess == word[j])
{
arrayofdashes[j] = guess;
printf("%s \n", arrayofdashes);
}
else
{
printf("wrong guess. Try again \n");
break;
}
}
}
}
Remove the break and add a flag variable to check the correctness of the input letter. And you need a better way to check if the word spelling is complete.
char flag;
int count = 0;
// input loop
while (count < strlen(word))
{
scanf(" %c", &guess);
flag = 0;
for (int j = 0; j< strlen(word); j++ )
{
if (guess == word[j] && guess != arrayofdashes[j])
{
arrayofdashes[j] = guess;
count++;
flag = 1;
}
}
if (flag)
printf("%s \n", arrayofdashes);
else
printf("wrong guess. Try again \n");
}
the problem is that you're using break - this drops out of your inner for-loop after comparing your input against the first character, and prevents it from being compared with subsequent characters.
What strategies have you tried for debugging this yourself? You'll have a few more changes to make aside from removing break, but figuring them out is part of the fun
for (int j = 0; j < strlen(word); j++)//no two loop
{
scanf(" %c", &guess);
if (guess == word[j])
{
arrayofdashes[j] = guess;
printf("%s \n", arrayofdashes);
}
else
{
printf("wrong guess. Try again \n");
j--;
}
}
You don't need the input loop. And if the answer is not correct you should subtract one from j.
First I apologize for any mistype, for I am Brazilian and English is not my native language.
I am a freshman at my college and I got this algorithm to solve, from my teacher:
Make a program that creates a vector of n words, n being a size entered by the user (maximum 100). Your program should remove all duplicate words from the input vector and sort the words. Print the final vector without repeated and ordered words.
E.g. with 7 words to sort:
Input: 7 [enter]
hand ear leg hand hand leg foot
Output: ear foot hand leg
Note: Comment the program prints so that the output of the program is as shown in the example above (the numbers are separated by a spacebar, without space after last digit).
Note2: In case of invalid entry the program should print: "invalid entry" (all lower case).
Ok, I got it working but the I got confused with the notes and I can't find a way to fix the possible bugs, here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[100][100], aux[100];
int i, j, num;
printf("Type how many words you want to order: ");
do
{
scanf("%d", &num);
}while (num>100 || num<=0);
for(i=0; i<num; i++)
scanf("%s",&word[i]);
for (i = 0; i < num; i++) //loop to sort alphabetically
{
for (j = i+1; j < num; j++)
{
if ((strcasecmp(word[i], word[j]) > 0)) //swapping words
{
strcpy(aux, word[j]);
strcpy(word[j], word[i]);
strcpy(word[i], aux);
}
}
}
for (i = 0; i < num; i++) //loop to remove duplicates
{
if ((strcasecmp(word[i], word[i+1]) == 0)) //finding the duplicates
{
for (j = i+1; j < num; j++) //loop to delete it
strcpy(word[j], word[j+1]);
num--;
i--;
}
}
printf("\nWords sorted and without duplicates:\n");
for(i=0; i<num-1; i++)
printf("%s ", word[i]); //output with spacebar
printf("%s", word[num-1]); //last output without spacebar
return 0;
}
When I type a word with more than 100 characters, the Code::Blocks closes with an error, else it works fine. What do you think I should change?
The teacher uses a Online Judge (Sharif Judge) to evaluate if the code is right, and I got error in 3 of the tests (that are not specified), all of them were "Time Limit Exceeded". Maybe it has do to with the size of the matrix, or the problem with words >100.
Thanks in advance, Vinicius.
I guess you input sanity check is causing the issue.
As mentioned in the comment section.
If n is always < 100. Definitely your sorting is not causing any time limit exceeded.
Looks like the n is given something greater than 100 and your scanf is waiting and causing the issue. Also, make sure your input numbers are taken properly. If the input is > 100 print 'invalid entry'.
Something like below should work.
scanf("%d", &num);
if (num > 100)
printf("invalid entry");
for (i = 0; i < num; i++) {
scanf("%s", word[i]);
if (strlen(word[i])>100)
printf("invalid entry");
}
Hope it helps!
of course you will get an error if you use woerds more than 100 length casue you
have this line: char word[100][50], aux[100];
that means that you word length limit is set to 50. use word[100][100];
also you may not delete duplicates, just skip them in output
lol of course if youre using judge , you should not output any symbols except the answer, this means you should delete all lines, like :
printf("Type how many words you want to order: ");
and check the input format, and check limitations, i mean max word length , max amounts of words
try smth like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max_word_length = 101;
#define max_amount_of_words = 101;
int main() {
char word[max_amount_of_words][max_word_length] = {};
char aux[max_word_length];
int i, j, num;
scanf("%d", &num);
if (num < 0 || num > 100) {
printf("invalid entry");
return 0;
}
for (i = 0; i < num; i++) {
scanf("%s", word[i]);
}
for (i = 0; i < num; i++) {//loop to sort alphabetically
for (j = i + 1; j < num; j++) {
if ((strcasecmp(word[i], word[j]) > 0)) { //swapping words
strcpy(aux, word[j]);
strcpy(word[j], word[i]);
strcpy(word[i], aux);
}
}
}
bool is_joint = false;
for (i = 0; i < num; i++) { //loop to skip duplicates
if ((strcasecmp(word[i], word[i + 1]) != 0)) { //if there is a duplicate , we willnot output it
if(is_joint) printf(" ");
printf("%s ", word[i]);
is_joint = true;
}
}
return 0;
}
I got 100% on Judge, I fixed the code and looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char word[101][101],aux[101]; //a number higher than the limit to comparisons
int i,j,num;
scanf("%d",&num);
if(num<=0||num>100){ // if words < 0 or >100
printf("invalid input");
return 0;
}
for(i=0;i<num;i++){
scanf("%s",&word[i]); //read n words
if(strlen(word[i])>100){ //if word >100 caracters
printf("invalid input");
return 0;
}
for(j=0;j<strlen(word[i]);j++){
if (word[i][j]>=65&&word[i][j]<=90){
word[i][j]= word[i][j]+32; // if word is uppercase, make them lowcase
}
else if (word[i][j]>122||word[i][j]<97){// if word is different from alphabet lowercase
printf("invalid input");
return 0;
}
}
}
for(i=0;i<num;i++){
for(j=i+1;j<num;j++){
if((strcmp(word[i],word[j])>0)){ //loop to sort words
strcpy(aux,word[j]);
strcpy(word[j],word[i]);
strcpy(word[i],aux);
}
}
}
for(i=0;i<num-1;i++){
if((strcmp(word[i],word[i+1])!=0)){ // output words with spacebar, without the last one
printf("%s ",word[i]);
}
}
printf("%s",word[num-1]); // last word without spacebar
return 0;
}
Thank you everyone who tried to help, I've learned a lot with your suggestions!
This project is actually pretty tough assignment for a programmer who just
started in C.
Run this program in your computer.
Before running against the Judge, make sure you run many times with your manual inputs. Once you are happy with the tests, try against the Judge.
Like I said, the hardest part is storing the user's inputs according to spec (accepting space or newline characters in multiple lines).
#include <stdio.h>
#include <string.h>
int
main(void)
{
int iNumW, iIndex;
int iWCnt = 0;
int iC;
char caTemp[100];
char caWords[100][100];
char *cpDelimeter = " \n";
char *cpToken;
char *cp;
short sIsWord = 1;
char caGarbage[100];
scanf("%d", &iNumW );
fgets(caGarbage, sizeof caGarbage, stdin); //Remove newline char
//Get word inputs
while( iWCnt < iNumW )
{
fgets(caTemp, sizeof caTemp, stdin );
for( cpToken = strtok( caTemp, cpDelimeter ); cpToken != NULL; cpToken = strtok( NULL, cpDelimeter)){
cp = cpToken;
while( *cp ){
sIsWord = 1;
//Check if alphabet
if( !isalpha(*cp) ){
sIsWord = 0;
break;
}
cp++;
}
if( sIsWord ){
strcpy( caWords[iWCnt], cpToken );
//printf( "%s\n", caWords[iWCnt]);
iWCnt++;
if( iWCnt >= iNumW ) break;
} else {
printf("invalid entry.\n");
}
//printf("%d\n", iWCnt);
}
}
int i,j ;
for (i = 0; i < iWCnt; i++) {//loop to sort alphabetically
for (j = i + 1; j < iWCnt; j++) {
if ((strcasecmp(caWords[i], caWords[j]) > 0)) { //swapping words
strcpy(caTemp, caWords[j]);
strcpy(caWords[j], caWords[i]);
strcpy(caWords[i], caTemp);
}
}
}
for (i = 0; i < iWCnt; i++) { //loop to skip duplicates
if ((strcasecmp(caWords[i], caWords[i + 1]) != 0)) { //if there is a duplicate , we willnot output it
printf("%s ", caWords[i]);
}
}
return 0;
}
I'm having trouble determining if two words entered are anagrams.
#include <stdio.h>
#include <string.h>
int main() {
char ch;
int letter_count[26] = {0};
int i;
int sum = 0;
printf("Enter first word: ");
do
{
scanf("%c", &ch);
letter_count[ch - 'a']++;
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n");
printf("Enter second word: ");
do
{
scanf("%c", &ch);
letter_count[ch - 'a']--;
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
for(i = 0; i < 26; i++)
if(letter_count[ch] != 0)
sum++;
if (sum == 0)
printf("anagrams");
else
printf("not anagrams");
}
I have to use the do while part of the code. I can enter the two words, and it prints out the elements in the array, so that "Mattress" and "Smartest" together would have all the elements be zero. However, I'm having trouble with the last part, which is to use a third loop to check whether all the elements are zero.
I figured I could declare an int before hand and have it increment whenever an element wasn't zero, and I could just have any sum greater than zero not be an anagram. However, it always prints out anagram for me.
In your third loop, using letter_count[ch] will not check the entire array. You should iterate through the array using the loop variable i. That part of the code should be:
for (i=0; i<26; i++)
if (letter_count[i] != 0)
sum++;
To handle both upper case and lower case letters, use topper() or to lower() in <ctype.h> to avoid out-of-bound access.
#include <stdio.h>
#include <string.h>
#include <ctype.h> // <---
int main() {
char ch;
int letter_count[26] = {0};
int i;
_Bool bad = 0;
printf("Enter first word: ");
do
{
scanf("%c", &ch);
if(!isalpha(ch)) // <---
{
puts("Not a letter");
continue;
}
letter_count[tolower(ch) - 'a']++; // <---
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n");
printf("Enter second word: ");
do
{
scanf("%c", &ch);
if(!isalpha(ch)) // <---
{
puts("Not a letter");
continue;
}
letter_count[tolower(ch) - 'a']--; // <---
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n"); // <---
for(i = 0; i < 26; i++)
if(letter_count[i] != 0)
{
bad = 1;
break; // <---
}
if (bad == 0)
printf("anagrams");
else
printf("not anagrams");
}
Take a look at all places marked // <---.
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.
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");
}