Print Characters between a given range in C++

In this c++ programming practical post, we will write a program to print characters between a given range of input. We will take 2 character inputs from user and print all the characters in between them.

For e.g.

  • if user enters char1 = a & char2 = d, output will be – a b c d.
  • if user enters char1 = A & char2 = D, output will be – A B C D.
Program to print characters in given range in C++
/*
	Q) Take input of 2 characters and print the alphabets between them
*/
#include<iostream>
using namespace std;
int main()
{
	char char1,char2;
	cout<<"Enter 2 characters"<<endl;
	cin>>char1;
	cin>>char2;

	// these 2 variables num1 & num2 are not mandatory
	int num1 = char1;
	int num2 = char2;
	
	for(int i = num1;i<=num2; i++)
	{
		cout<<(char)i<<" ";
	}
	
	return 0;
}
Output
Enter 2 characters
a
z
a b c d e f g h i j k l m n o p q r s t u v w x y z
Program Explanation –

As char and int data types are compatible with each other(since they are both integral types). The typecasting between the 2 happens by default. Also the ASCII values of characters are stored in the respective int variables and then they are used in the for loop to iterate through the entire range as given. Also the 2 variables num1, num2 are not mandatory and we can use the for loop directly by using the char variables itself as follows –

for(int i = char1;i<=char2; i++)
{
   cout<<(char)i<<" ";
}

2 thoughts on “Print Characters between a given range in C++

  • May 29, 2018 at 2:49 pm
    Permalink

    Thank you very much it is very simple code

    Reply
    • May 29, 2018 at 4:40 pm
      Permalink

      Thank you so much for the positive response 🙂
      Do share the article and website with your friends too 🙂

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *