Print till Z with while loop boundary crossing – Computer Sir Ki Class
  

Login
[lwa]



Code Learning #CPP#2038 siteicon   siteicon   siteicon  

Print till Z with while loop boundary crossing

As user enters a lower case or upper case alphabet the program prints from that alphabet till z using the faster technique of while loop iteration and checking for outside boundary condition

Learning Objectives

  • Use of while loop with over crossing the boundary condition.

Source Code

TC++ #2038

Source Code

#include <iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter an alphabet :";
cin>>ch;
if(ch>=65 && ch<=90)
while(ch!=91) cout<< ch++;
else if(ch>=97 && ch<=122)
while(ch!=123) cout<< ch++;
else cout<<"Entry was not an alphabet";
return 0;
}

Test it !
Alternate (?) :

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

Here we will use a simple if-else-if ladder for checking of uppercase or lowercase alphabet and if it is not a an alphabet we shall come out of program.

if(ch>=65 && ch<=90) while(ch!=91) cout<< ch++;
Here we check for uppercase alphabet which is in ascii code range 65 to 90 (both inclusive). Incidentally the value 91 is just outside the boundary of the last condition. Here we use this outside boundary condition as a check condition for the while loop so that the loop can run till the bouundary and as soon as it reaches outside boundary it terminates. Since boundary is at character Z so the character from the current character till the last character is printed since with every iteration using ch++ it is reaching the next character. It is interesting to note that ++ operator is working on char data type also as for arithmetic operation the char data type is treated just like an integer numeric value.

else if(ch>=97 && ch<=122) while(ch!=123) cout<< ch++;
Here the check for lower case character are done in the ascii range 97 to 122. The just outside last boundary condition is 123 here for termination of while loop

else cout<<“Entry was not an alphabet”;
Here the non-alphabet condition message is being given.

 

Notes

  • The just outside boundary check for loops is possible in this case as a valid ascii code exists for 91 and 123. This kind of checking may not always be possible if the similar thing is being done for array boundaries.
  • This program is fast, but students may tend to check for wrong conditions and loops may become non-terminating.
  • There are many ways to write this program. One can see an alternative solution by clicking the alternative solution button.

Common Errors

  • Loop boundary conditions should be correctly set after understanding it correctly else endless loops can make your programming environment hang.


Suggested Filename(s): print2zwb.cpp



Share

sunmitra| Created: 30-Dec-2017 | Updated: 30-Dec-2017|






Back