Finding points of a scrabble word [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So i recently started c language with no prior knowledge of coding or computer science. Wrote this piece of code to find value of a word using scrabble points as below:
1:AEILNORSTU 2:DG 3:BCMP 4:FHVWY 5:K 8:JX 10:QZ.
# include <stdio.h>
# include <ctype.h>
# include <conio.h>
int main (void)
{
int n=0;
char ch;
clrscr();
printf("Enter the SCRABBLE word\n");
ch = getchar();
while(ch!='\n')
{
toupper(ch);
if(ch =='A'||'E'||'I'||'L'||'N'||'O'||'R'||'S'||'T'||'U')
n=n+1;
else if (ch =='D'||'G')
n=n+2;
else if (ch =='B'||'C'||'M'||'P')
n=n+3;
else if (ch =='F'||'H'||'V'||'W'||'Y')
n=n+4;
else if (ch =='K')
n=n+5;
else if (ch =='J'||'X')
n=n+8;
else if (ch =='Q'||'Z')
n=n+10;
ch = getchar();
}
printf("The value is %d",n);
return 0;
}
So what happens when i run this code is that :
Enter the SCRABBLE word
eg: barrier
The value is 7
though it should be 9 as b carries 3 points as noted above the code,a carries 1,r carriers 1,again r 1 point,i carries 1 point and the last two alphabet are one point each so thats 3+1+1+1+1+1+1=9

An expression like ch =='D'||'G' is equal to (ch == 'D')||'G'.
In other words you first perform the sub-expression ch == 'D'. Then you do a logical or using 'G'. The result will always be true since 'G' is non-zero, and everything non-zero is true in C.
You want ch == 'D' || ch == 'G' instead, to check if ch is equal to 'D' or if ch is equal to 'G'.
This is very basic and every good beginners book would have told you so.
In the specific case of the code you show, the very first check will always be true because of this, and you will not check any other cases.

you forgot to get the return value of toupper. Also you don't check it
(according to man 3 toupper, the function will return the same char in case of failure)
Then your conditions aren't good:
if (ch == 'Q' || 'Z') is different from if (ch == 'Q' || ch == 'Z')
The || means if the right or the left condition is true and in the first case (ch == 'Q') is not always true, but 'Z' is always true.
This means your first condition :
if(ch =='A'||'E'||'I'||'L'||'N'||'O'||'R'||'S'||'T'||'U')
is always true
Here are littles corrections you can apply, this might work
char tmp;
ch = getchar();
while(ch!='\n')
{
//Stocking in a tmp char to check return value
tmp = ch;
//Here
ch = toupper(ch);
if (ch == tmp)
{
//Error
break;
}
{...}
else if (ch =='Q'|| ch =='Z')
n += 10;
ch = getchar();
}
Edit : Correction of return value of toupper();

Related

what is wrong with this execution of OR operand in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When I separate the str[i] with all the vowels it works, what is wrong with the current execution?
#include <stdio.h>
#include<string.h>
int main() {
int k = 0;
char str[100];
scanf("%[^\n]s", str);
for(int i = 0; i < strlen(str); i++){
if(str[i] == ('a' || 'e' || 'i' || 'o' || 'u')){
k++;
}
}
printf("%d",k);
}
It compares str[i] with the expression 'a' || 'e' || 'i' || 'o' || 'u', which gets evaluated to true, which value is equal to 1. Think about characters as integers, which char correspond to (in ASCII), then your expression would be 97 || 101 || ..., which is certainly true.
To make this work as intended, you need to split all comparisons:
str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u'
When I separate the str[i] with all the vowels it works...
This is due to the fact that you are comparing a character with a boolean expression, which will be either 1 or 0, this comparison will never be true, str will not have any characters with 0 or 1 codes, these are non-printable control characters.
In practical terms ('a'||'e'||'i'||'o'||'u') is equivalent to (97 || 101 || 105 || 111 || 117) these are each character's ASCII codes as an example, other encodings will have different codes, this is how your program really sees them.
Anyway, this sequence of OR's will evaluate to 1, so let's say str[i] is 'a', the comparison will be 97 == 1, this is of course false, the same for the other vowels, so k will never be incremented.
Of course separating the characters one by one will work because each individual comparison will now work as expected.
If you don't like the long if you can use :
#include <stdio.h>
#include <string.h>
int main() {
int k = 0;
char str[100];
scanf("%[^\n]", str);
for (int i = 0; i < strlen(str); i++) {
switch(str[i]){
case 'a': case 'e': case 'i': case 'o': case 'u':
k++;
}
}
printf("%d", k);
}
Or you can use strchr as posted by Vlad.
On a side note, scanf("%[^\n]s", str); should be scanf("%[^\n]", str);, the %[^\n] specifier doesn't need an s at the end, if you include it it means that scanf will be expecting a string ending in s.
According to the C Standard (6.5.14 Logical OR operator)
3 The || operator shall yield 1 if either of its operands compare
unequal to 0; otherwise, it yields 0. The result has type int.
So this primary expression within the condition of the if statement
('a'||'e'||'i'||'o'||'u')
is always evaluates to integer 1 because at least the first operand 'a' is unequal to 0.
So in fact this if statement
if(str[i]==('a'||'e'||'i'||'o'||'u')){
is equivalent to
if( str[i] == 1 ){
and it evaluates to logical true only in one case when str[i] is equal to 1.
You need to write
if( str[i] == 'a' || str[i] == 'e'|| str[i] == 'i'|| str[i] == 'o'|| str[i] == 'u' ){
Another approach is to use the standard function strchr. For example
if ( strchr( "aeiou", str[i] ) ) {
//...
}
You probably forgot that you should use operators with two operands, so the compiler could recognize each operation and label them as True or False. use this code instead:
int main() {
int k=0;
char str[100];
scanf("%[^\n]s",str);
for(int i=0;i<strlen(str);i++){
if((str[i]== 'a')||(str[i] == 'e')||(str[i] == 'i')||(str[i] == 'o')||(str[i] == 'u')){
k++;
}
}
printf("%d",k);
}```

scanning an integer ONLY into an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
As a part of an assignment I've got, I need to get from a user a digit only using the <stdio.h> library.
do {
scanf("%d",&num);
} while (num>9 || num<0);
But the program will get from the user also chars and other things.
Any advice?
One way of solving this is getting the ASCII value of the scanned "digit" and making sure it lies between ASCII values 0X30 and 0X39 (or 48 and 57).
Seeing your logic, you seem to be interested in numbers greater than 9 (multiple digit numbers) and numbers less than 0 (signed numbers/integers).
I suggest instead of using scanf better use something like getchar which will return one character at a time.
A simple way to scan multiple digit numbers using getchar can be:
int getNumber()
{
int sign = 1;
int i = 0;
int ch;
ch = getchar();
if((ch == '-') || (ch == '+')) //check sign
{
if(ch == '-') sign = -1;
}
else
{
if (ch > '9' || ch < '0')
return NULL; // Your requirement - it's a non number
i *= 10;
i += ch - '0';
}
while ((ch = getchar()) != '\n') //get remaining chars
{
if (ch > '9' || ch < '0')
return NULL; // Your requirement - it's a non number
i *= 10;
i += ch - '0';
}
i *= sign; //change sign
return i;
}
You can call this function in place of scanf.
You can use getchar() to read a single character from stdin and then compare it to the ASCII values for 0 and 9 (your upper and lower bounds for a single character). The digit as an integer is equal to the character code minus the character code for 0.
#include <stdio.h>
int main(void) {
char c;
while((c = getchar()) >= '0' && c <= '9')
printf("Digit is: %d\n", c - '0');
return 0;
}

For loop and getchar/putchar usage in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm quite new to C and I'm trying to write a loop that takes input with getchar, then print only the U's and K's from the input using putchar.
I tried this:
printf("Enter a bunch of letters: ");
char ch;
while (ch != 'x') {
ch = getchar();
if ( ch >= 'a' && ch <= 'z') {
putchar(ch - 32);
ch;
}
}
Looks to me like you're trying to read input until 'x' is entered, then print the U's and K's from said input. Try this.
Per your comment, seems like you want to print them as upper whether or not they're read as upper. You can use tolower() for that.
char ch;
while ((ch = getchar()) != 'x')
if (toupper(ch) == 'U' || toupper(ch) == 'K')
putchar(toupper(ch));
#include <stdio.h>
int main()
{
puts("(I will print U and K only): ");
int c;
while(EOF != (c=getchar())){
if(c=='U'||c=='K')
putchar(c);
}
}

Exceptions in c programming language

I'm learning c language and I hit a wall, if you would like to help me I appreciate (here is the ex: "Write a program that reads characters from the standard input to end-of-file. For each character, have the program report whether it is a letter. If it is a letter, also report its numerical location in the alphabet and -1 otherwise." btw is not homework).The problem is with the \n i don't know how to make it an exception. I'm new around here please let me know if I omitted something. Thank you for your help.
int main(void)
{
char ch;
int order;
printf("Enter letters and it will tell you the location in the alphabet.\n");
while ((ch = getchar()) != EOF)
{
printf("%c", ch);
if (ch >= 'A' && ch <= 'Z')
{
order = ch - 'A' + 1;
printf(" %d \n", order);
}
if (ch >= 'a' && ch <= 'z')
{
order = ch - 'a' + 1;
printf(" %d \n", order);
}
if (order != (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
{
if (ch == '\n');
else if (order != (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
printf(" -1 \n");
}
}
system("pause");
}
You are talking about an "exception" which can be interpreted in other ways in programming.
I understand that you want that '\n' be "excepted" in the set of nonalphabetical characters, that is, that it doesn't generate the error value -1.
Since you are using console to run the program, a sequence of character is going to be read till ENTER key is pressed, which generates the character \n. So, I'm not pretty sure that the while() condition you used, that compares against EOF, it's a good decision of yours.
I would put there directly the comparisson against '\n'.
while ((ch = getchar()) != '\n')
To inform if ch is a letter or not, we could use string literals. The following use of string assignment would deserve more explanation, but I will omit it. It's valid with string literals:
char *info;
if (order != -1)
info = "is a letter";
else
info = "is not a letter";
You are assuming an encoding where the letters are in contiguous increasing order (as in ASCII).
By assuming that, it's enough to work with uppercase or lowercase letters, since you are only interested in the position that the letter occupy in the alphabet. So, you can choose to work with uppercase, for example, in this way:
if (ch >= 'a' && ch <= 'z')
ch = (ch - 'a' + 'A');
The effect of that line of code is that ch is converted to uppercase, only if ch is a lowercase letter. Another kind of character is not affected.
As a consequence, from now on, you only have uppercase letters, or nonalphabetical characters.
Then it's easy to code the remaining part:
if (ch >= 'A' && ch <= 'Z')
order = ch - 'A' + 1; // It brings no. position of letter in alphabet
else
order = -1; // This is the erroneous case
A printf() at the end of the loop could bring all the information about the character:
printf(" %16s: %4d \n", info, order);
The resulting code is shorter in more clear:
#include <stdio.h>
int main(void) {
char ch;
int order;
char *info;
while ((ch = getchar()) != '\n') {
printf("%c",ch);
if (ch >= 'a' && ch <= 'z') /* Converting all to uppercase */
ch = (ch - 'a' + 'A');
if (ch >= 'A' && ch <= 'Z')
order = ch - 'A' + 1; /* Position of letter in alphabet */
else
order = -1; /* Not in alphabet */
if (order != -1)
info = "is a letter";
else
info = "is not a letter";
printf(" %16s: %4d \n", info, order);
}
}
If you need to end the input by comparing against EOF, then the type of ch has to be changed to int instead of char, so you can be sure that the EOF value (that is an int) is properly held in ch.
Finally, this means that ch needs initialization now, for example to a neutral value in the program, as '\n'.
Finally, just for fun, I add my super-short version:
#include <stdio.h>
int main(void) {
int ch, order;
while ((ch = getchar()) != '\n') {
order = (ch>='a' && ch<='z')? ch-'a'+1:((ch>='A' && ch<='Z')? ch-'A'+1: -1);
printf("%c %8s a letter: %4d \n", ch, (order != -1)? "is":"is not", order);
}
}
The C language does not have exceptions. Exceptions were first introduced into programming in C++. You can do it manually in C using setjmp() and longjmp(), but it really isn't worth it.
The two most popular of doing error handling in C are:
Invalid return value. If you can return -1 or some other invalid value from a function to indicate 'there was an error', do it. This of course doesn't work for all situations. If all possible return values are valid, such as in a function which multiplies two numbers, you cannot use this method. This is what you want to do here - simply return -1.
Set some global error flag, and remember to check it later. Avoid this when possible. This method ends up resulting in code that looks similar to exception code, but has some serious problems. With exceptions, you must explicitly ignore them if you don't want to handle the error (by swallowing the exception). Otherwise, your program will crash and you can figure out what is wrong. With a global error flag, however, you must remember to check for them; and if you don't, your program will do the wrong thing and you will have no idea why.
First of all, you need to define what you mean by "exception"; do you want your program to actually throw an exception when it sees a newline, or do you simply want to handle a newline as a special case? C does not provide structured exception handling (you can kind-of sort-of fake it with with setjmp/longjmp and signal/raise, but it's messy and a pain in the ass).
Secondly, you will want to read up on the following library functions:
isalpha
tolower
as they will make this a lot simpler; your code basically becomes:
if ( isalpha( ch ) )
{
// this is an alphabetic character
int lc = tolower( ch ); // convert to lower case (no-op if ch is already lower case)
order = lc - 'a' + 1;
}
else
{
// this is a non-alphabetic character
order = -1;
}
As for handling the newline, do you want to just not count it at all, or treat it like any other non-alphabetic character? If the former, just skip past it:
// non-alphabetic character
if ( ch == '\n' )
continue; // immediately goes back to beginning of loop
order = -1;
If the latter, then you don't really have to do anything special.
If you really want to raise an honest-to-God exception when you see a newline, you can do something like the following (I honestly do not recommend it, though):
#include <setjmp.h>
...
jmp_buf try;
if ( setjmp( try ) == 0 ) // "try" block
{
while ( (ch = getchar() ) != EOF )
{
...
if ( ch == '\n' )
longjmp( try, 1 ); // "throw"
}
}
else
{
// "catch" block
}
I'm having hard time trying to understand why you even try to handle '\n' specifically.
You might be trying to implement something like this:
int main(void)
{
char ch;
int order;
printf("Enter letters and it will tell you the location in the alphabet.\n");
while ((ch = getchar()) != EOF)
{
printf("%c", ch);
if (ch >= 'A' && ch <= 'Z') {
order = ch - 'A' + 1;
printf(" %d \n", order);
} else if (ch >= 'a' && ch <= 'z') {
order = ch - 'a' + 1;
printf(" %d \n", order);
} else if (ch == '\n') { } else {
printf(" -1 \n");
}
}
system("pause");
}
While this is a good solution, I would recommend rewriting it in a more optimal way:
int main(void)
{
char ch;
printf("Enter letters and it will tell you the location in the alphabet.\n");
while ((ch = getchar()) != EOF)
{
int order;
if (ch != '\n'){
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') {
order = ch & 11111B;
printf("Letter %d\n", order);
} else {
order = -1;
printf("Not letter: %d\n", order);
}
}
}
system("pause");
}
This way the program relies on specific way letters coded in ASCII

C Programming question - Branching

Write a program that reads input up to # and reports the number of times that the sequence ei occurs.
I have little confusion with sequence such as 'ieei' where compiler does enter 3rd 'e' but never fetches 'i' with getchar(), why and if someone can improve this before myself it'd be good?
char ch;
int sq=0;
while ((ch = getchar()) != '#')
{
if (ch == 'e')
{
ch = getchar();
if (ch == 'e')
ch = getchar();
if (ch == 'i')
sq++;
}
}
printf("Sequence occurs %d %s\n", sq, sq == 1 ? "time" : "times");
In my opinion it's simplest to keep the result of the last getchar() in a variable rather than have an extra getchar() inside your loop.
char ch;
int sq=0;
char lastCh = ' ';
while((ch=getChar())!='#') {
if(lastCh=='e' && ch=='i')
sq++;
lastCh=ch;
}
This gives the correct result no matter how many e's in a row or whatever, and breaks at the first # character.
I'm tempted to implement it as:
char ch=0;
int sq=0;
do{
if( (ch=( ch=='e'? ch:getchar() )) == 'e' && (ch=getchar()) == 'i' )
++sq;
}while(ch!='#');
But it uses ?: and && for control flow, which might be confusing especially to beginners.
On second thought it's not that hard to unroll it:
char ch=0;
int sq=0;
do{
if( ch!='e' ) ch = getchar();
if( ch == 'e' ){
ch = getchar();
if( ch == 'i' ) ++sq;
}
}while(ch!='#');

Resources