help with functions

Pages: 12
closed account (9G8M4G1T)
There are 6 skills to demonstrate:
1) Use functions. Functions sub-divide programming problems into independent parts.
2) Use function overloading, where several functions have the same name but different parameters.
3) Use pass-by-value and pass-by-reference parameters to functions.
4) Use static local variables, which work like global variables (values persist) and local variables (local scope). Their value persists between function calls, yet they can only be used within the function.
5) Use default parameters, which take on a default value if a parameter is not specified.
6) Use const parameters, which specify that the parameter cannot change. const reference parameters make good sense for strings.


How do I output this?



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
Display the distance between two items: letters, numbers, or points.

Options: l)etter; n)umber; p)oint; q)uit: l
  Enter first letter (a to z): b
  Enter second letter (a to z): f
  (#1) Distance between letters b & f = 4

Options: l)etter; n)umber; p)oint; q)uit: n
  Enter first number (-100, 100): -5.5
  Enter next number (-200, 200): 20.5
  (#1) Units between -5 and 20 = 26.0

Options: l)etter; n)umber; p)oint; q)uit: p
  Enter the first point (x): 0
  Enter the first point (y): 3
  Enter the second point (x): 4
  Enter the second point (y): 0
  (#1) straight line distance between points (0, 3) and (4, 0) is: 5

Options: l)etter; n)umber; p)oint; q)uit: l
  Enter first letter (a to z): 8
    Sorry, try again.
  Enter first letter (a to z): A
  Enter second letter (a to z): z
  (#2) Distance between letters A & z = 25

Options: l)etter; n)umber; p)oint; q)uit: n
  Enter first number (-100, 100): -123.456
    Sorry, out-of-range. Try again.
  Enter first number (-100, 100): -10
  Enter next number (-200, 200): 50
  (#2) Units between -10 and 50 = 60

Options: l)etter; n)umber; p)oint; q)uit: p
  Enter the first point (x): 0
  Enter the first point (y): 0
  Enter the second point (x): 1
  Enter the second point (y): 1
  (#2) straight line distance between points (0, 0) and (1, 1) is: 1.41421

Options: l)etter; n)umber; p)oint; q)uit: q
Good-bye!
Last edited on
If you have the data already and just want to output it then...


std::cout << "Distance: " << variableName;

?
Do you know how to do this using pen and paper? if yes, then what have you tried? Post your current code.
closed account (9G8M4G1T)
is this a good way to start?
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
int main() {
    
   enum menu { letter = 'l', number = 'n', point = 'p', quit = 'q' };

   menu userChoice {};

   cout << "Options: l)etter; n)umber; p)oint; q)uit; ";


   while (userChoice != quit && userChoice != letter) {
      char choice {};
      bool del {};
      std::cin >> choice;
      if (choice == '-') {
         del = true;
         std::cin >> choice;
      }
      userChoice = static_cast<menu>(choice);
      switch (userChoice) {
         case letter:
              cout <<"Enter first letter (a to z): "<<endl;
              cout <<"Enter second letter (a to z): "<<endl;
            break;
            
         case number:
              cout <<"Enter first number (-100, 100): "<<endl;
              cout <<"Enter next number (-200, 200): "<<endl;
            break;
            
         case point:
              cout <<"Enter the first point (x): "<<endl;
              cin >> x1;
              cout <<"Enter the first point (y): "<<endl;
              cin >> y1;
              cout << "Enter the second point (x): "<<endl;
              cin >> x2;
              cout << "Enter the second point (y): ";
              cin >> y2;
            break;
            
         case quit:
            std::cout << "Good-bye!" << '\n';
            break;
// message if user enters a number instead of a letter when letter is selected
         default:
            std::cout << "Sorry, try again.";
            break;
      }
      if (userChoice != quit) {

      }
   }
}
Last edited on
yes that looks reasonable.
little things..
number says next, everything else says second.
you could just say
enter the first value, enter the second value and use that text on all the inputs, moved out of the case statements. Depends on the requirement. If you need specific words in there, then you need them and can't avoid doing something to make that happen... what you have is fine if you have exactly match some output format.

line 54.. what you gonna do there? consider this:
do
{switch)
while(userChoice != quit);

as you have it you can put return 0 in the if statment at 54 but the do while is simpler and elegant.

lines 16-21 are weird. it looks like a band-aid or debugging tool? What is that all about? Its like a back door into your own code, an undocumented menu option that lets you do something magic and then pretends you entered an invalid choice... (you read in a new value for choice but userchoice isnt updated, and - isnt a valid choice). If you want this magical undocumented input behavior, you could use the continue keyword to set 'del' and then skip the switch and loop again. You don't offer a way to set del back though? The whole thing seems... dubious.

userChoice = static_cast<menu>(choice);
is that necessary? letters are integers, you can switch off them. Its nice that you did it, but it may be pointless.
Last edited on
closed account (9G8M4G1T)
@jonnin thanks for the reply...I messed around based on your suggestions and wasn't able to come up with something different.

Can anyone help me out with calculating distance between letters, numbers, as well as an error message when a number is required but a letter is entered? Right now if the wrong thing is entered it just prints out the rest of my cout.


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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
void displayDistance(double distance);
int main() {
    // numbers need double
    // points need 4 doubles
    // letters need char
   char a, b;
   double distance, x1, x2, y1, y2;
   enum menu { letter = 'l', number = 'n', point = 'p', quit = 'q' };
   menu userChoice {};
   cout << "Options: l)etter; n)umber; p)oint; q)uit; ";
   while (userChoice != quit && userChoice != letter) {
      char choice {};
      bool del {};
      std::cin >> choice;
      if (choice == '-') {
         del = true;
         std::cin >> choice;
      }
      userChoice = static_cast<menu>(choice);
      switch (userChoice) {
         case letter:
              cout <<"Enter first letter (a to z): "<<endl;
              cin >> a;
              cout <<"Enter second letter (a to z): "<<endl;
              cin >> b;
              cout << "The distance between letters "<< a
              << " & " << b << " is: " << endl;
            break;
            
         case number:
              cout <<"Enter first value (-100, 100): "<<endl;
              // cin >>
              cout <<"Enter second value (-200, 200): "<<endl;
              // cin >>
              //cout << "The units between = "
            break;
            
         case point:
              cout <<"Enter the first point (x1): "<<endl;
              cin >> x1;
              cout <<"Enter the first point (y1): "<<endl;
              cin >> y1;
              cout << "Enter the second point (x2): "<<endl;
              cin >> x2;
              cout << "Enter the second point (y2): ";
              cin >> y2;
              distance = pow(pow((x1 - x2), 2) +pow((y1-y2),2),0.5);
              cout <<"The straight line distance between points ("
              << x1 <<","<< y1 << ")"<< " and ("
              << x2 << ","<<y2<<") is: "
              << distance<< " units.";
            break;
          case quit:
               cout <<"Goodbye!"<<endl;
             break;

      }
      if (userChoice != quit) {
 cout << "\nOptions: l)etter; n)umber; p)oint; q)uit; ";
      }
   }
}
Last edited on
Unless I'm missing something, isn't the distance between ch1 and ch2 simply ch2 - ch1? and for d1 and d2 simply d2 - d1?

For the points, the mathematical distance formula is:

dist = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))

closed account (9G8M4G1T)
@seeplus yes they both seem to work
closed account (9G8M4G1T)
This is what I have of my code so far

Where can I put these overloaded display functions?
// void display(const string &msg, char ch1, char ch2); // display letters and letter distance
// void display(const string &msg, double d1, double d2); // display numbers and number distance
// void display(const string &msg, double x1, double y1, double x2, double y2); // display points and point distance.





I need 3 overloaded input functions, 3 overloaded distance functions, and 3 overloaded display functions. Can you help provide the correct parameter type?:
//char input(parameter_type prompt_text, parameter_type error_message_text); // for getting a letter
//double input(parameter_type min_number, parameter_type max_number, parameter_type prompt_text, parameter_type error_message_text); // for getting a number
// void input(parameter_type x, parameter_type y, parameter_type prompt_text); // for getting a point (x, y)


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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
void printMenu(){
    cout << "Options: l)etter; n)umber; p)oint; q)uit;" << endl;
}
void errorMessage(){
    cout << "This is not an option, try again!" << endl;
}
//void printMenu() {cout << "Options: l)etter; n)umber; p)oint; q)uit; “;}

int main() {
    //used for Letter option
   char firstLetter, secondLetter;
    //used for Point option
    //distance used for all 3 options
   double distance, x1, x2, y1, y2;
    // used for Number option
    double firstValue, secondValue;
    // menu for options
   enum menu { letter = 'l', number = 'n', point = 'p', quit = 'q' };
   menu userChoice {};
    //print menu options to user
    printMenu();
    while (userChoice != quit) {
          char choice {};
          std::cin >> choice;
        userChoice = static_cast<menu>(choice);
      switch (userChoice) {
         case letter:
              cout <<"Enter first letter (a to z): "<<endl;
              cin >> firstLetter;
              cout <<"Enter second letter (a to z): "<<endl;
              cin >> secondLetter;
              distance = secondLetter - firstLetter;
              cout << "The distance between letters "<< firstLetter
              << " & " << secondLetter << " is: "<< distance <<endl;
            break;
            
         case number:
              cout <<"Enter first value (-100, 100): "<<endl;
              cin >> firstValue;
              cout <<"Enter second value (-200, 200): "<<endl;
              cin >> secondValue;
              distance = secondValue - firstValue ;
              cout << "The units between " << firstValue
              << " and " << secondValue << " = " << distance <<endl;
            break;
            
         case point:
              cout <<"Enter the first point (x1): "<<endl;
              cin >> x1;
              cout <<"Enter the first point (y1): "<<endl;
              cin >> y1;
              cout << "Enter the second point (x2): "<<endl;
              cin >> x2;
              cout << "Enter the second point (y2): "<<endl;
              cin >> y2;
              distance = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
              cout <<"The straight line distance between points ("
              << x1 <<","<< y1 << ")" << " and ("
              << x2 << ","<<y2<<") is: "
              << distance << " units." <<endl;
            break;
          case quit:
               cout <<"Goodbye!"<<endl;
             break;
              // message for user if they input an invalid option from menu
          default:
              errorMessage();
                break;

      }
      if (userChoice != quit) {
          //print the menu options to user again
          printMenu();
      }
   }
}



Overall my code must demostrate 6 skills:
1) Use functions. Functions sub-divide programming problems into independent parts.
2) Use function overloading, where several functions have the same name but different parameters.
3) Use pass-by-value and pass-by-reference parameters to functions.
4) Use static local variables, which work like global variables (values persist) and local variables (local scope). Their value persists between function calls, yet they can only be used within the function.
5) Use default parameters, which take on a default value if a parameter is not specified.
6) Use const parameters, which specify that the parameter cannot change. const reference parameters make good sense for strings.
Last edited on
cmath is C++'s math.h. use cmath; math.h is for C programs. You should not use both.

you can put your functions anywhere (but not inside main)... if you put them above main, and in an order where dependency is higher (that is, if main needs x, and x needs y, your file looks like this:)
z() //z cannot call x or y. they have not been 'seen' yet.
y() //its above x, and above main, so both x and main can see it, and it can see/call z
x()
main()
or you can put them out of order and use headers(placed at the top of the file, and main never gets a header).
a header is just a copy of the function's definition with a ;
eg
int foo(double d, string s);

the parameters are what you think they would be...
for distance,
char:
int distance(char c1, char c2);
double distance (double d1, double d2)
double distance (point d1, point d2) //or doubles x1 y1 x2 y2 if you don't know how to make a point yet

you don't need all that crap they asked for, but they asked for it :)
you need to contrive a way to do 3 (pass by reference for something) and 4 (static for something) and 5 (default something) and 6 (good habit to make things constant when you don't need to modify them, so for the pass by reference you can make it a const to protect the original..) you don't NEED 3,4, or 5 but you can work them in to make teacher happy.
Last edited on
closed account (9G8M4G1T)
Ahh I see thank you. I'm still learning what libraries to use.

I'm just having trouble coming up with what functions to use besides the two very simple ones that I have.
I can't really move on to function overloading if I don't even know where would be a good spot to create a functions.

I also haven't figured out how to display and error message in situations where a letter is needed but a number is inputed and vice versa.
Last edited on
save error handling for last. it can be tricky.

have you seen a class or struct yet?

anyway... here is a sample of overloading the distance functions. I put a print so you can see that it is using them both where appropriate, the prints need to come back out once you test it and see what I did.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;


void printMenu()
{
    cout << "Options: l)etter; n)umber; p)oint; q)uit;" << endl;
}
void errorMessage()
{
    cout << "This is not an option, try again!" << endl;
}

double distance(char c1, char c2)
{
	cout << "\n dist char\n";
	return abs(c2-c1);
}

double distance(double c1, double c2)
{
	cout << "\n dist double\n";
	return abs(c2-c1);
}

int main() 
{
    //used for Letter option
   char firstLetter, secondLetter;
    //used for Point option
    //distance used for all 3 options
   double dist, x1, x2, y1, y2;
    // used for Number option
    double firstValue, secondValue;
    // menu for options
   enum menu 
{ letter = 'l', number = 'n', point = 'p', quit = 'q' };
   menu userChoice {};
    //print menu options to user
    printMenu();
    while (userChoice != quit) 
{
          char choice {};
          std::cin >> choice;
        userChoice = static_cast<menu>(choice);
      switch (userChoice) 
       {
         case letter:
              cout <<"Enter first letter (a to z): "<<endl;
              cin >> firstLetter;
              cout <<"Enter second letter (a to z): "<<endl;
              cin >> secondLetter;              
              cout << "The distance between letters "<< firstLetter
              << " & " << secondLetter << " is: "<< distance(firstLetter,secondLetter) <<endl;
            break;
            
         case number:
              cout <<"Enter first value (-100, 100): "<<endl;
              cin >> firstValue;
              cout <<"Enter second value (-200, 200): "<<endl;
              cin >> secondValue;              
              cout << "The units between " << firstValue
              << " and " << secondValue << " = " << distance(secondValue,firstValue) <<endl;
            break;
            
         case point:
              cout <<"Enter the first point (x1): "<<endl;
              cin >> x1;
              cout <<"Enter the first point (y1): "<<endl;
              cin >> y1;
              cout << "Enter the second point (x2): "<<endl;
              cin >> x2;
              cout << "Enter the second point (y2): "<<endl;
              cin >> y2;
              dist = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
              cout <<"The straight line distance between points ("
              << x1 <<","<< y1 << ")" << " and ("
              << x2 << ","<<y2<<") is: "
              << dist << " units." <<endl;
            break;
          case quit:
               cout <<"Goodbye!"<<endl;
             break;
              // message for user if they input an invalid option from menu
          default:
              errorMessage();
                break;

      }
      if (userChoice != quit) 
	  {
          //print the menu options to user again
          printMenu();
      }
   }
}
Last edited on
Do these do the same thing? I don't know I'm having a hard time understanding...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
double distance(char c1, char c2)
{
	cout << "\n dist char\n";
	return abs(c2-c1);
}

double distance(double c1, double c2)
{
	cout << "\n dist double\n";
	return abs(c2-c1);
}

________________________________

   char firstLetter, secondLetter;


   double dist, x1, x2, y1, y2;

    double firstValue, secondValue;
Last edited on
A char and a double are not the same thing. Therefore, if you tried to call distance('a', 'c') without the first version of the function, it would tell you that you're giving it invalid arguments - and vice versa.

They both logically do the same thing - find the "difference", but the types are different.
@zapshe

oh I see now. So the double is only needed for the options that require a number input since the options are more than one character and char is only needed for the letter option since the input will always only be 1 character long.

How do I correctly input my cout with that though? or can I leave the cout blank and keep the cout that is within my switch statement?
yes, they do the same thing. if you didn't have the char version, it would probably automatically upcast the chars to doubles (chars are just 1-byte integers, if you didn't know that yet) and give a warning but work, depending on how cranky your compiler is feeling. It may even downcast the doubles to chars if you force it to. So you could get away with 1 function here but the assignment asked for 3.
So the double is only needed for the options that require a number input since the options are more than one character and char is only needed for the letter option since the input will always only be 1 character long

Yes kinda, so if you tried to give it (10, 21) with just the char function available, it would actually literally take those numbers and cast them to a char - as jonnin mentioned - as dictated by the ASCII table.

10 would become Line Feed and 21 would become... I don't even know what that is. The output will be 11.

However, try something like this:

cout << distance(241, 121);

And you'll overflow the char (char is 1 byte, but can hold negative values as well - so 2^8 / 2 is the max positive integer).


With distance(double, double), you won't have any crazy issues like that:

1
2
3
4
5
6
7
8
9
10
double distance(double c1, double c2)
{
	cout << "\n dist double\n";
	return abs(c2 - c1);
}

int main()
{
	cout << distance(-50.0, -100.0);
}


Notice I put the .0 to indicate that those values are doubles, otherwise the compiler may be confused on which function to call. -50 and -100 are integers, which it also recognizes char as many times.



The real importance of having them as separate functions is that the distance(char, char) one wouldn't work with decimal numbers and wouldn't work with numbers that are too big. It could be argued that you don't actually need the char version of the function.
Last edited on
As C++20, possibly something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <concepts>
#include <iostream>
#include <cmath>

auto distance(std::convertible_to<double> auto c1, auto c2) -> decltype(c1) {
	return std::abs(c2 - c1);
}

int main()
{
	std::cout << distance(-50.45, -100.87) << '\n';
	std::cout << distance('c', 'r') << '\n';
	std::cout << distance(40, 90) << '\n';
}



50.42
15
50

closed account (9G8M4G1T)
@seeplus I got an error when I tried to implement that to my code..



I can post my code again but the only thing I have added is
1
2
3
4
5
6
7
8
9
double distance(char c1, char c2)
{
    return abs(c2-c1);
}

double distance(double c1, double c2)
{
    return abs(c2-c1);
}



Last edited on
closed account (9G8M4G1T)
I know how to do this with counters but how can I do it with display functions?

4) Inside in the display functions, use a static local variable to keep a count of how many times the function was called.:

Three overloaded display functions are also needed. They look like this:
void display(const string &msg, char ch1, char ch2); // display letters and letter distance
void display(const string &msg, double d1, double d2); // display numbers and number distance
void display(const string &msg, double x1, double y1, double x2, double y2); // display points and point distance.


Ex: The counter in the last cout

Options: l)etter; n)umber; p)oint; q)uit: l
Enter first letter (a to z): b
Enter second letter (a to z): f
(#1) Distance between letters b & f = 4

Options: l)etter; n)umber; p)oint; q)uit: l
Enter first letter (a to z): 8
Sorry, try again.
Enter first letter (a to z): A
Enter second letter (a to z): z
(#2) Distance between letters A & z = 25



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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

#include <iostream>
#include <cmath>
#include <concepts>
#include <iomanip>
#include<string>


using namespace std;

void printMenu()
{
    cout << "Options: l)etter; n)umber; p)oint; q)uit;" << endl;
}
void errorMessage()
{
    cout << "This is not an option, try again!" << endl;
}

double distance(char c1, char c2)
{
    return abs(c2-c1);
}

double distance(double c1, double c2)
{
    return abs(c2-c1);
}

int main()
{
    //used for Letter option
   char c1, c2;
    //used for Point option
    //distance used for all 3 options
   double dist, x1, x2, y1, y2;
    // used for Number option
    // menu for options
    
    int l_count {}, n_count {}, p_count {};
   enum menu
{ letter = 'l', number = 'n', point = 'p', quit = 'q' };
   menu userChoice {};
    //print menu options to user
    printMenu();
    while (userChoice != quit)
{
          char choice {};
          std::cin >> choice;
        userChoice = static_cast<menu>(choice);
      switch (userChoice)
       {
               //For letters, use toupper or tolower to ignore case.
               //dist(‘A’, ‘c’), dist(‘a’, ‘C’), dist(‘a’, ‘c’) and dist(‘A’, ‘C’) should all be 2
               //The order of the letters should not matter: dist(‘c’, ‘a’) is also 2
         case letter:
            l_count++;
              cout <<"Enter first letter (a to z): "<<endl;
              cin >> c1;
              cout <<"Enter second letter (a to z): "<<endl;
              cin >> c2;
              cout << "(#"<< l_count <<") The distance between letters "<< c1
              << " & " << c2 << " is: "<< distance(c1,c2) <<endl;
            break;
            //For numbers, return the absolute value of the difference.
         case number:
               n_count++;
              cout <<"Enter first value (-100, 100): "<<endl;
              cin >> c1;
              cout <<"Enter second value (-200, 200): "<<endl;
              cin >> c2;
              cout << "(#"<< n_count <<") The units between " << c1
              << " and " << c2 << " = " << distance(c2,c1) <<endl;
            break;
            
         case point:
               p_count++;
              cout <<"Enter the first point (x1): "<<endl;
              cin >> x1;
              cout <<"Enter the first point (y1): "<<endl;
              cin >> y1;
              cout << "Enter the second point (x2): "<<endl;
              cin >> x2;
              cout << "Enter the second point (y2): "<<endl;
              cin >> y2;
              dist = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
              cout << "(#"<< p_count <<") The straight line distance between points ("
              << x1 <<","<< y1 << ")" << " and ("
              << x2 << ","<<y2<<") is: "
              << dist << " units." <<endl;
            break;
          case quit:
               cout <<"Goodbye!"<<endl;
             break;
              // message for user if they input an invalid option from menu
          default:
              errorMessage();
                break;

      }
      if (userChoice != quit)
      {
          //print the menu options to user again
          printMenu();
      }
   }
}
Last edited on
Pages: 12