Other Languages - C++ Programming - Asked By Najeeb Ullah on 20-Nov-11 01:19 AM

Write a program that reads in a character <char> from the keyboard, and then displays one of the following messages: (i) If <char> is a lower case letter,the message "The upper case character corresponding to <char>" is ...", (ii) if <char> is an upper case letter, the message "The lower case character" corresponding to <char> is ...", or (iii) If <char> is  not a letter, the message "<char> is not a letter". You will need to refer to a able of ASCII characters.
Suchit shah replied to Najeeb Ullah on 20-Nov-11 01:31 AM
#include <cctype>
#include <iostream>
  
using namespace std;
  
int main()
{
  char ch;
  
  cout<<"Enter a character: ";
  cin>> ch;
  
  if ( isalpha ( ch ) ) {
  if ( isupper ( ch ) ) {
    ch = tolower ( ch );
  
    cout<<"The lower case equivalent is "<< ch <<endl;
  }
  else {
    ch = toupper ( ch );
  
    cout<<"The upper case equivalent is "<< ch <<endl;
  }
  }
  else
  cout<<"The character is not a letter"<<endl;
  
  cin.get();
Neha Garg replied to Najeeb Ullah on 20-Nov-11 02:17 AM
Hello Najeeb,

If you don't want to use the functions from <cctype> and you still need something portable then you could write your own.

using namespace std;
  
bool is_upper ( char ch )
{
static char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for ( int i = 0; upper[i] != '\0'; i++ ) {
if ( ch == upper[i] )
return true;
}
return false;
}
bool is_lower ( char ch )
{
static char lower[] = "abcdefghijklmnopqrstuvwxyz";
for ( int i = 0; lower[i] != '\0'; i++ ) {
if ( ch == lower[i] )
return true;
}
return false;
}
  
char to_lower ( char ch )
{
static char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char lower[] = "abcdefghijklmnopqrstuvwxyz";
  
for ( int i = 0; upper[i] != '\0'; i++ ) {
if ( ch == upper[i] )
return lower[i];
}
  
return ch;
}
  
char to_upper ( char ch )
{
static char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char lower[] = "abcdefghijklmnopqrstuvwxyz";
  
for ( int i = 0; lower[i] != '\0'; i++ ) {
if ( ch == lower[i] )
return upper[i];
}
 return ch;
}
 int main()
{
char ch;
 cout<<"Enter a character: ";
cin>> ch;
 if ( is_upper ( ch ) )
cout<<"The lower case equivalent is "<< to_lower ( ch ) <<endl;
else if ( is_lower ( ch ) )
cout<<"The upper case equivalent is "<< to_upper ( ch ) <<endl;
else
cout<<"The character is not a letter"<<endl;
 // Flush the input stream
while ( cin.get ( ch ) && ch != '\n' );
 cin.get();
}