Functions

I am trying to write a funtion for a program called nextLetter. This function needs to take the user input (in this case a letter) and tell the user what the next letter in the alphabet is. I have this code and it is working however, Im not sure if I am doing this the correct way. Can someone please look at my code and tell me if I am right or not?

Thanks for all of your help!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <conio.h>

using namespace std;

void nextLetter(char &input)
{
	char charac;
	cin >> charac;
	cout << (char)(charac+1) << endl;
}


void main()
{
	nextLetter;
	char charac;
cout << "Enter your letter : " << endl;
cin>>charac;
cout << "The following letter is : " << endl;
cout << (char)(charac+1) << endl;
getch();
}

You are on the right track, although there are a few problems.

First of all - is it a requirement that your function must do input and output, or just that it must convert a letter to the next letter? If the function is not required to do the input/output (the program of course would be required to do this, but not necessarily the function), then you should avoid it. Ideally the purpose of the function should be to take a character as an argument, and return the next character. The main function should get the input, pass this input to the nextLetter function, receive the returned value, and print it out. In your current code you are mixing the functionality of the nextLetter function and main - each should have a separate responsibility. Both are doing input and output, and both are doing the conversion, whereas ideally the function should do the conversion and the main should do the input/output. In the case where it is REQUIRED for you to do the input/output in the function itself, then the purpose of main would just be to simply call the function and nothing else.

Next - you defined a function called nextLetter, but nowhere in your main do you actually call this function. You have a statement nextLetter; but this will do nothing since you are not passing it the argument it needs (you defined it as requiring a char).

Finally, you should consider the case where the user inputs 'z' or 'Z'... what should the answer be there? If you add 1 to 'z' or 'Z', you will not get a letter back..

Let's look at an example of something similar. Here we have a function that takes an integer and returns the square of that number.

[code=c++]
#include <iostream>
using namespace std;
int x_squared( int x ); // function prototype

int main() {
int input;
int result;
cout << "Enter an integer: " << endl;
cin >> input;
result = square( input ); // call the square function on our input, get the result back
cout << "The square of " << input << " is " << result << endl;

return 0;
}

int square( int x ) {
int x_squared;
x_squared = x * x; // square the number
return x_squared;
}
[/code]
Last edited on
Topic archived. No new replies allowed.