3
19/10/2024 3:14 am
Topic starter
Write a program which finds the sum of the ASCII codes of the letters in a given string. Your tasks will be a bit harder, because you will have to find the sum of either the lowercase or the uppercase letters.
On the first line, you will receive the string.
On the second line, you will receive one of two possible inputs:
- If you receive “UPPERCASE” find the sum of all uppercase English letters in the previously received string
- If you receive “LOWERCASE” find the sum of all lowercase English letters in the previously received string
You should not sum the ASCII codes of any characters, which is not letters.
At the end print the sum in the following format:
- The total sum is: {sum}
Examples:
1 Answer
2
19/10/2024 3:15 am
Here is my solution:
<?php $word = readline(); $case = readline(); $sum = 0; for ($i = 0; $i < strlen($word); $i++) { if ($case === "LOWERCASE") { if (ctype_lower($word[$i]) && ctype_alnum($word[$i])) { $sum += ord($word[$i]); } } else if (ctype_upper($word[$i]) && ctype_alnum($word[$i])) { $sum += ord($word[$i]); } } echo "The total sum is: " . $sum;