How to get sum of char values produced in a loop?

后端 未结 5 1121
迷失自我
迷失自我 2021-01-22 09:45

Sorry if the title is misleading or is confusing, but here is my dilemma. I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, ..

5条回答
  •  执念已碎
    2021-01-22 10:15

    It would look something like this (in C programming language) which you can easily modify for other programming languages:

    #include 
    #include 
    #include 
    
    int main() {
      int i;
      char word[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      unsigned int sum = 0;
      unsigned int charVal;
    
      for (i=0; i < strlen(word); ++i) {
        charVal = word[i] - 'A' + 1;
        printf("Value of %c is %d\n", word[i], charVal);
        sum += charVal;
      }
      printf("Sum of %s = %d\n", word, sum);
      return(0);
    }
    

    The trick is to take the character value, subtract the baseline 'A' value and add 1 to arrive at your calculation range:

    charVal = word[i] - 'A' + 1;
    

提交回复
热议问题