Find Column Name from Column Number in Excel using C++
Today, we are gonna write a simple C++ program to find Column Name from Column Number in Excel sheets.
Also read: Find Column Number from Column Name in Excel using C++
The rows in an excel sheet are numbered with values starting from 1, 2, 3,….., and so on.
The columns, however, are identified with their character names. These start from A, B,………, Y, Z, AA, AB,……., AY, AZ, BA, BB,………, and so on.
For example,
Column Number | Column Name |
26 | Z |
51 | AY |
80 | CB |
702 | ZZ |
705 | AAC |
Algorithm to get Column Name from Column Number
- Let us suppose that the user has entered a number num, which is 28, for which we have to find the corresponding column name.
- We need to take the remainder of num, 28 here, with 26.
- If the remainder comes out to be 0 (for numbers like 26, 52, 78,…etc.), then we insert ‘Z’ in the char array that we made for storing the output string.
- Simultaneously, the new num now is updated to num/26 -1, because here assuming that 26 is ‘Z’ while in reality ‘Z’ is 25th with respect to the letter ‘A’.
- Otherwise, if the remainder is non-zero. (like 1, 2, ……, 24, 25), then we just insert the letter accordingly in the char array.
- And simultaneously, update num = num/26.
- To print the finally answer, we reverse the string and display it.
C++ code to get Column Name from Column Number in Excel
#include <bits/stdc++.h> #include<iostream> using namespace std; //function to display the column name form column number void Convert_to_Column_Name(int num) { //variables used //array to store column name after conversion char name[100]; int i = 0; //iterating loop while(num > 0) { //remainder after dividing number by 26 is stored int remainder = num%26; //if else condition to store appropriate alphabets if(remainder == 0) { name[i++] = 'Z'; num = (num/26) - 1; } else { name[i++] = (remainder-1) + 'A'; num = num/26; } } //storing '\0' at the end of the string name[i] = '\0'; //we use the library function to reverse the string reverse(name, name + strlen(name)); //display the result cout<<name; return; } //int main/Driver program int main() { //variable to store the column number int num; //taking the input from the user cout<<"Enter column number for which you want the column name: "; cin>>num; //checking for valid input if(num > 0) { //calling the function for conversion and displaying result cout<<"\nThe column name for column number "<<num<<" is: "; Convert_to_Column_Name(num); } else { cout<<"\nInvalid input!"; } return 0; }
Output
- 1 – Character Input
Enter column number for which you want the column name: cghf Invalid input!
- 2 – Negative Input
Enter column number for which you want the column name: -85 Invalid input!
- 3 – Zero Input
Enter column number for which you want the column name: 0 Invalid input!
- 4 – Positive/Valid Input
Enter column number for which you want the column name: 702 The column name for column number 702 is: ZZ
Leave a Reply