Excel Sheet Column Number in C++


We know that the excel 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 a number of columns is given. So if the column number is 80, then it will be CB.

Suppose we have a number n, and its value is 28, then we need to take a reminder with 26. If the remainder is 0, then the number is 26, 52 and so on. Then we put Z in the output string. The value of n becomes n/26 – 1. And if the remainders are non-zero then we need to just insert the character accordingly into the string and do n = n/26. Finally, the reverse of the string will be printed.

Example (C++)

 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

Cell number: 700

Output

Enter cell number:700
Cell name of 700 is: ZX

Updated on: 28-Apr-2020

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements