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 the character type using pass-by-value void checkCharacterByValue(char ch) { if (isalpha(ch)) { cout << ch << " is an alphabet." << endl; } else if (isdigit(ch)) { cout << ch << " is a digit." << endl; } else { cout << ch << " is a special character." << endl; } } // Function to check the character type using pass-by-reference void checkCharacterByReference(char ch, string &type) { if (isalpha(ch)) { type = "alphabet"; } else if (isdigit(ch)) { type = "digit"; } else { type = "special character"; } } int main() { char ch; string typeByRef; // Input the character cout << "Enter a character: "; cin >> ch; // Check character type using pass-by-value cout << "Using pass-by-value: "; checkCharacterByValue(ch); // Check character type using pass-by-reference checkCharacterByReference(ch, typeByRef); cout << "Using pass-by-reference: " << ch << " is a " << typeByRef << "." << endl; return 0; } |
Explanation:
- Pass-by-Value (
checkCharacterByValue
):- Function Definition:
void checkCharacterByValue(char ch)
- This function takes the character
ch
as a parameter by value. - It uses
isalpha
to check ifch
is an alphabet,isdigit
to check ifch
is a digit, or considers it a special character otherwise. - The function prints the result directly.
- Function Definition:
- Pass-by-Reference (
checkCharacterByReference
):- Function Definition:
void checkCharacterByReference(char ch, string &type)
- This function takes the character
ch
by value and a reference to astring
variabletype
. - It determines if
ch
is an alphabet, digit, or special character and sets thetype
reference variable accordingly. - The result is updated through the reference variable.
- 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, digit, or special character 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 a digit. Using pass-by-reference: 9 is a digit. |
Example 3:
Input:
- Character:
@
Output:
1 2 3 |
Enter a character: @ Using pass-by-value: @ is a special character. Using pass-by-reference: @ is a special character. |