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.
- 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.
Q) Take input of 2 characters and print the alphabets between them
using namespace std;
cout<<"Enter 2 characters"<<endl;
// these 2 variables num1 & num2 are not mandatory
int num1 = char1;
int num2 = char2;
for(int i = num1;i<=num2; i++)
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++)