-1

[On this Question they are asking assign the numbers to the letters][1]

Question:

Suppose that we assign the score 1 to character A, 2 to B, and 26 to Z by repeating the same rule. With the scores mapped by this rule, the sum of scores for “Luck’ is 47 (12 + 21 + 3 + 11), “Knowledge” is 96, “Hardwork” is 98, and “Attitude” is 100. Complete the following program which computes for an arbitrary string.

#include <stdio.h>
int main() {
char str[1000];
int i, score = 0;
scanf("%s", str);
for (i = 0; ______; ___) 
{ 
int ch = str[i];
if (______________________) {
score += ____________;
}
else if (______________________) {
score += ____________;
}
}
printf("%d\n", score);
return 0;
}

Thanks in advance.

Nicat Muzaffarli
  • 105
  • 4
  • 10

3 Answers3

1

The key insight for this question is that a char is actually an 8-bit number. For instance, 'a' is 97 in decimal, 'z' is 122, 'A' is 65, and 'Z' is 90:

https://en.wikipedia.org/wiki/ASCII#Code_chart

All the alphabet characters are represented sequentially. Because a char is actually a number, you can use it in an arithmetic expression, like so:

 int num = 'd' - 'a'; //num is now (100 - 97), which is 3.

This should be enough information to figure out what they want you to do in that problem.

Gavin Higham
  • 89
  • 1
  • 4
1

You can do this efficiently by using only two conditionals like so:

if (string[i]>='a' && string[i]<='z') {
    Score += (int) string[i] - (int) 'a' + 1;
}

Edit: The int casts are not needed but I put them there so you can tell that the chars are being used as ints

For the second conditional, you can do the same in upper case. This should work.

William Gerecke
  • 371
  • 2
  • 7
1

Please check this table. ASCII values for A-Z ranges from 65-90 and for a-z ranges from 97-122. Hence, to convert a character into a number, you can use:

for UPPER CASE: ch - 64 or ch - 'A' + 1
for lower case: ch - 96 or ch - 'a' + 1

which will map A to 1, B to 2 ... so on
and a to 1, b to 2 ... so on

as shown in the below program:

#include<stdio.h>

int main(){
    char str[1000];
    int i, score = 0;


    printf("Please enter a string: ");
    scanf("%s", str);

    printf("You entered: %s\n", str);


    for( i=0; str[i] != '\0' ; i++ ) {

        int ch = str[i];
        int num;

        if (ch >= 'A' && ch <='Z'){
            num = ch -'A' + 1;
            // num = ch - 64;
        }

        else if (ch >= 'a' && ch <= 'z'){
            num = ch -'a' + 1;
            // num = ch - 96;
        }

        score += num;
    }

    printf("Score: %d\n", score);
}
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87