call functions

Please i am new to C++ and need to understand basics....i have got a major assignment that would bee needing handing in by next week and still having problems of calling functions......this example below is something i just thought of out of the blues to use as an example to get explanations on how to call functions and also to avoid using the goto in coding as i hear that is bad practice........

can someone please put me through on calling functions and avoiding using goto in d example below:



#include <iostream>
#include <string>

using namespace std;


float psquare (float a)
{
return (4*a);
}

float prectangle (float w, float l)
{
return ((2*w)+(2*l));
}

int main()
{
float d,a,w,l;
char n;
cout << "Please choose from options below:\t";
cout << "1. Square\n";
cout << "2. Rectangle\n";
cin >> d;
if ( d == 1 )
{
cout << "length of side:\t";
cin >> a;
{return psquare;}
goto end;
}
else if ( d == 2 )
{
cout << "length of side:\t";
cin >> w,l;
{return prectangle;}
goto end;
}
else
{
cout << "invalid input, Please try again\n\n";
return main ();
}

end:
cout <<"Do you want to calculate an other shape? (y / n):";
cin >>n;
if (n == 'y')
{ return main();}
system("pause");
return 0;
}


please i need help as i am really confused....please......
If you have a function
1
2
3
float psquare (float a){
    return 4*a;
}

You can call it like this: float p = psquare(my_a);. float p = part is optional, but you need to store the result somewhere. my_a is either a variable or a constant.

Now, in your code you probably want to print that perimeters, not return them. cout << "the perimeter is " << psquare(a) << '\n'; would do that.

In your code, goto end; doesn't do anything. If you removed it, the program would behave the same way.
Never call main(). You need a loop here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main(){
   while(true){
      //ask for input
      if(d == 1){//...
      }else if(d == 2){//...
      }else{
         cout << "invalid!";
         continue;//skip the rest of the loop. you could also just
          //have another while loop around this if else block.. 
      }

      cout << "again?";
      cin >> n;
      if(n == 'n') break;//exit the loop if use enters 'n'
   }
   return 0;
}
Topic archived. No new replies allowed.