GESP Level 3 C++ Programming (51C++): Flexible Use of ASCII for Letter Summation

For the GESP Level 3 exam: C++ 202403 Level 3 Letter SummationThis problem is relatively simple, but the main difficulties are:1. Confusing character type conversions can lead to chaotic results, with conversions going back and forth.2. Candidates often struggle to remember ASCII codes; what should they do? How much to subtract or add?Look at the problem:GESP Level 3 C++ Programming (51C++): Flexible Use of ASCII for Letter Summation

Solution Approach:

1. If you don’t know what ASCII is, you can write code to output it and find out. For example:

    cout<<(int)'a'<<" "<<(int)'A';        97 65

Now you know how to add or subtract!

Look at the code:

#include <bits/stdc++.h>using namespace std;int main(){    int n;    string s;    cin >> n >> s;    int result = 0;    for (char c : s)    {        (c > 96) ? result += c - 96 : result -= c;    }    cout << result;}
    for (char c : s) can also be replaced with    for( int i=0;i<s.size();i++)

What does for (char c : s) mean?

1. The loop will automatically iterate through all characters in the string s, 2. Each time, the current character is assigned to the variable c (of type char). 3. The loop body (the code within the braces) can operate on each character c.

Here it is read-only, so you can directly use char c.But what if you want to modify it in reverse? For example, changing c to c+4 and then assigning it back to s. You would need to use the address operator.

#include <bits/stdc++.h>using namespace std;int main(){    string s = "abc";    for (char &c : s)    {        c = (int)c + 4;    }    cout << s;// Output efg

Isn’t this simpler than using s[i]?Have you learned it?GESP Level 3 C++ Programming (51C++): Flexible Use of ASCII for Letter Summation

Leave a Comment