Search code examples
c++algorithmprintingstdstringalphabet

How to print next letters until Z and continue to A?


This code prints the next letters of what I input. For example, I input "v", it will show vwxyz, but I want it to print the others too, like vwxyzabc.....

int main()
{
   char a;
   int flag = 0;
   scanf("%c", &a);

   while (a <= 'z') 
   {
      printf("%c", a);
      a++;
   }

   printf("\n");
   return 0;
}

I am new to c++, can someone help me?


Solution

  • If the incremented character is not an alphabet, deduct 26 to go back to the starting and do the loop until you see the entered character.

    #include <cctype> // std::isalpha
    
    char curr = a;
    do
    {
       printf("%c", curr);
       ++curr;
       if (!std::isalpha(static_cast<unsigned char>(curr)))
          curr -= 26;
    
    } while (curr != a);
    

    (See live demo)