w3resource

C++ Exercises: Get the column number that corresponds to a column title as appear in an Excel sheet

C++ Math: Exercise-8 with Solution

Write a C++ program to get the column number (integer value) that corresponds to a column title as it appears on an Excel sheet.

For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

// Function to convert Excel column title to a corresponding number
int excel_title_to_Number(string s) {
    int number = 0; // Initialize the resulting number to 0
    for (const auto& c : s) { // Loop through each character in the input string
        number *= 26; // Multiply the number by 26 (Excel's base)
        number += c - 'A' + 1; // Convert the character to its corresponding numeric value and add to the result
    }
    return number; // Return the calculated number
}

int main(void) {
    // Test cases to convert Excel column titles to numbers
    string col_title1 = "C";
    cout << "\nExcel column title = " << col_title1 << ", Corresponding number = " << excel_title_to_Number(col_title1) << endl;

    col_title1 = "AD";
    cout << "\nExcel column title = " << col_title1 << ", Corresponding number = " << excel_title_to_Number(col_title1) << endl;

    col_title1 = "WX";
    cout << "\nExcel column title = " << col_title1 << ", Corresponding number = " << excel_title_to_Number(col_title1) << endl;

    return 0; // Return 0 to indicate successful completion
}

Sample Output:

Excel column title = C, Corresponding number = 3

Excel column title = AD, Corresponding number = 30

Excel column title = WX, Corresponding number = 622

Flowchart:

Flowchart: Get the column number that corresponds to a column title as appear in an Excel sheet.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to get the Excel column title that corresponds to a given column number (integer value).
Next: Write a C++ program to find the number of trailing zeroes in a given factorial.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/math/cpp-math-exercise-8.php