1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#include <iostream> using namespace std; // Function to check if a character is an alphabet using pass-by-value bool isAlphabetByValue(char ch) { // Check if the character is an uppercase or lowercase alphabet return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); } // Function to check if a character is an alphabet using pass-by-reference void isAlphabetByReference(char ch, bool &result) { // Check if the character is an uppercase or lowercase alphabet result = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); } int main() { char ch; bool resultByRef; // Input the character cout << "Enter a character: "; cin >> ch; // Check if the character is an alphabet using pass-by-value bool resultByVal = isAlphabetByValue(ch); cout << "Using pass-by-value: "; if (resultByVal) { cout << ch << " is an alphabet." << endl; } else { cout << ch << " is not an alphabet." << endl; } // Check if the character is an alphabet using pass-by-reference isAlphabetByReference(ch, resultByRef); cout << "Using pass-by-reference: "; if (resultByRef) { cout << ch << " is an alphabet." << endl; } else { cout << ch << " is not an alphabet." << endl; } return 0; } |
Explanation:
- Pass-by-Value (
isAlphabetByValue
):- Function Definition:
bool isAlphabetByValue(char ch)
- This function takes the character
ch
as a parameter by value. - It checks if
ch
falls within the range of uppercase (‘A’ to ‘Z’) or lowercase (‘a’ to ‘z’) alphabets. - It returns
true
ifch
is an alphabet; otherwise, it returnsfalse
.
- Function Definition:
- Pass-by-Reference (
isAlphabetByReference
):- Function Definition:
void isAlphabetByReference(char ch, bool &result)
- This function takes the character
ch
by value and the result by reference. - It performs the same check as
isAlphabetByValue
but updates theresult
reference variable. result
is set totrue
ifch
is an alphabet, andfalse
otherwise.
- Function Definition:
- Main Function (
main
):- The program prompts the user to input a character.
- It then checks and displays whether the character is an alphabet using both methods.
Example Outputs:
Example 1:
Input:
- Character:
A
Output:
1 2 3 |
Enter a character: A Using pass-by-value: A is an alphabet. Using pass-by-reference: A is an alphabet. |
Example 2:
Input:
- Character:
9
Output:
1 2 3 |
Enter a character: 9 Using pass-by-value: 9 is not an alphabet. Using pass-by-reference: 9 is not an alphabet. |
Example 3:
Input:
- Character:
*
Output:
1 2 3 |
Enter a character: * Using pass-by-value: * is not an alphabet. Using pass-by-reference: * is not an alphabet. |