Program to find spreadsheet column number from the column title in C++


Suppose we have a column title of spreadsheet. We know that the spreadsheet column numbers are alphabetic. It starts from A, and after Z, it will AA, AB, to ZZ, then again AAA, AAB, to ZZZ and so on. So column 1 is A, column 27 is Z. Here we will see how to get the column letter if number of column is given. So if the column number is 80, then it will be CB. So we have to find the corresponding column title from the number. If the input is like 30, it will AD.

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
void showColumnLetters(int n) {
   string str = "";
   while (n) {
      int rem = n%26;
      if (rem==0) {
         str += 'Z';
         n = (n/26)−1;
      }
      else{
         str += (rem-1) + 'A';
         n = n/26;
      }
   }
   reverse(str.begin(), str.begin() + str.length());
   cout << str << endl;
}
int main() {
   int n = 700;
   cout << "Cell name of " << n << " is: ";
   showColumnLetters(700);
}

Input

700

Output

Cell name of 700 is: ZX

Updated on: 21-Oct-2020

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements