Print till Z with loop count calculation – Computer Sir Ki Class

Code Learning #CPP#2034

## Print till Z with loop count calculation

As user enters a lower case or upper case alphabet the program prints from that alphabet till z.

## Learning Objectives

• Use of for loop with a pre-generated loop count condition.
• Handling of implicit and explicit conversion between char to int and int to char.

## Source Code

 #include using namespace std; int main() { char ch; int lc; cout<<"Enter an alphabet :"; cin>>ch; int n=ch; if(n>=65 && n<=90) lc=90-n+1; else if (n>=97 && n<=122) lc=122-n+1; else {cout<<"Entry was not an alphabet"; return 0;} for(int i=0;i

## Run Output

``````Enter an alphabet :R
RSTUVWXYZ

-OR-
Enter an alphabet :e
efghijklmnopqrstuvwxyz

-OR-
Enter an alphabet :4
Entry was not an alphabet``````

## Code Understanding

int n=ch;
Here user given character type stored in ch is implicitly converted to integer type in variable n. This conversion we are doing to allow easy checking using the ascii code of uppercase and lowercase range.

if(n>=65 && n<=90) lc=90-n+1;
This is check for upper case range of alphabets which is from ascii code 65 to ascii code 90. Here if the upper case alphabet is give we are trying to generate a loop count value for how many alphabets shall be printed in the alphabet. For e.g. if it is 65 means alphabet is a the 90-65+1, 26 alphabets have to be printed.

else if (n>=97 && n<=122) lc=122-n+1;
Here the loop count for lowercase characters which are in the range of 97 to 122 ascii code is being generated.

else {cout<<“Entry was not an alphabet”; return 0;}
Here we are returning to operating system if the given character is not being found in the alphabet range of upper or lower characters.

for(int i=0;i<lc;i++)  cout<< ((char) n++);
Here the loop count generated above is being used run the loop condition. The character code given as ascii is being typecasted explicitly back to a (char) type data so that it properly prints the alphabet symbol and not the ascii code. with n++ we are able to print the next symbol in the next iteration.

## Notes

• This program will work well when the conversion of char to int variable is removed. The conversion also occurs automatically while comparing a character variable with its ascii code. For e.g. comparing ch>=65 is possible even when ch is char data type. This step has been given here to show the implicit conversion separately and making it easier to understand when the comparison is being done.
• There are many ways to write this program. One can see an alternative solution by clicking the alternative solution button.

## Common Errors

• Student often miss the step of adding one in this logic. lc=122-n+1. It is obvious that a range of largest to smallest will give one less count if both numbers have to be included.

Suggested Filename(s): print2z.cpp, print-till-end-alphabet.cpp

sunmitra| Created: 29-Dec-2017 | Updated: 15-Sep-2018|

×