Number to Letter

Hello,

How do you write a program that prints out the alphabet out to the "nth" letter? For example, if the user inputs a 1, it will print out "a". If the user inputs a 5, it will print out "abcde", and if the user inputs 10, it will print out "abcdefghij" and so on?




1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include <iostream>
#include <string>
#include <vector>
#include <cctype>  
using namespace std;  

int main()  {
  int number;
  string letter;
  cout<<"Enter a number 1-26";
  cin>>number;
  //letter=     // i want to convert the number into the alphabet up until the nth letter
  cout<<"The alphabet to the "<<number<<"th letter is "<<letter;
}
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;  

int main()
{
   int n;
   string alphabet = "abcdefghijklmnopqrstuvwxyz";
   cout << "Enter a number (1-26): ";   cin >> n;
   cout << alphabet.substr( 0, n );
}
If you wish to do it with a classic for loop, then note that you can do something like:
1
2
3
4
for (int i = 0; i < n; i++)
{
    cout << (char)('a' + i);
}

because in ASCII, the numeric values of the alphabet (for a particular case) are continuous.
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;  
int main()
{
   int n;
   cout << "Enter a number (1-26): ";   cin >> n;
   for ( char c = 'a'; c < 'a' + n; c++ ) cout << c;
}
Topic archived. No new replies allowed.