Pages

Showing posts with label 5. Functions. Show all posts
Showing posts with label 5. Functions. Show all posts

Tuesday, July 24, 2012

Function that returns a value and Passes data from one function to another


Function that returns a value and Passes data (Passing of Arguments) from one function to another

A function may send data to another function using parameters or arguments.
Arguments are data within the opening and closing parenthesis of the functions. They are like variable storing information that can be access outside of the function. Remember that variable inside the function is only accessible in that function and cannot be used outside the function.

Syntax:

datatype functionname(datatype param1, datatype param2,…)
{
    //body of a function with return value.
}

Sample Program: Bank Transaction Simulation using function that returns a value and passes data from one function to another

#include<iostream>
using namespace std;

float withdraw(float balance)
{
float wamount;
    cout<<"Amount to withdraw: ";
    cin>>wamount;
    return (balance – wamount);
}

float deposit(float balance)
{
float damount;
    cout<<"Amount to deposit: ";
    cin>>damount;
    return (balance – damount);
}

float BalanceInquiry(float balance)
{
    return balance;
}

int main()
{
char opt;
float obalance;
float rebalance;
cout<<"Enter your opening balance: ";
cin>>obalance;
cout<<endl<<endl;
    cout<<"Choose your Action: "<<endl
         <<"\t<W>ithdraw"<<endl
         <<"\t<D>eposit"<<endl
         <<"\t<B>alance Inquiry"<<endl
         <<"Action -> ";

    cin>>opt;

    switch(opt)
    {
         case 'w':
        case 'W': rbalance = withdraw(obalance);
                  break;
        case 'd': rbalance = deposit(obalance);
                  break;
        case 'b':
        case 'B': rbalance = BalanceInquiry();
break;
        default:  cout<<"Invalid input!"<<endl;
         system("pause");
                  return 0;
                  break;
  }
  cout<<"Remaining balance: "<<rbalance<<endl<<endl;
 
  system("pause");
  return 0;
}

Wednesday, May 9, 2012

Function that returns a value


Function that returns a value

A function that is declared with a data type other than void returns a value.

Syntax:

Datatype functionname()
{
    //body of a function with return value.
}

The returned value of a function depends on the data type. For example, if a function is declared with a numeric data type, therefore the returned value must also be a numeric type.

Sample Program: Calculator using function that returns a value

#include<iostream>
using namespace std;

float sum()
{
    float s,a,b;

    cout<<"First Number: ";
    cin>>a;
    cout<<"First Number: ";
    cin>>b;

    s = a + b;

    return s;
}

float difference()
{
    float a,b;

    cout<<"First Number: ";
    cin>>a;
    cout<<"First Number: ";
    cin>>b;

    return (a-b);
}

float product()
{
    float a,b;

    cout<<"First Number: ";
    cin>>a;
    cout<<"First Number: ";
    cin>>b;

    return (a*b);
}

float quotient()
{
    float a,b;

    cout<<"First Number: ";
    cin>>a;
    cout<<"First Number: ";
    cin>>b;

    return (a-b);
}

int remainder()
{
    int a,b;

    cout<<"First Number: ";
    cin>>a;
    cout<<"First Number: ";
    cin>>b;

    return (a%b);
}

int main()
{
char opt;
    cout<<"Choose your option: "<<endl
         <<"\t<S>um"<<endl
         <<"\t<D>ifference"<<endl
         <<"\t<P>roduct"<<endl
         <<"\t<Q>uotient"<<endl
         <<"\t<R>emainder"<<endl
         <<"Option -> ";

    cin>>opt;

switch(opt)
{
case 's':
case 'S': cout<<"The sum is: "<<sum()<<endl;
          break;
case 'd':
case 'D': cout<<"The difference is: "<<difference()<<endl;
          break;
case 'p':
case 'P': cout<<"The product is: "<<product()<<endl;
          break;
case 'q':
case 'Q': cout<<"The quotient is: "<<quotient()<<endl;
          break;
case 'r':
case 'R': cout<<"The remainder is: "<<remainder()<<endl;
          break;
default:  cout<<"Invalid input!"<<endl;
          system("pause");
          return 0;
          break;
}

system("pause");
return 0;
}

Wednesday, November 23, 2011

Void Function


A function must have a data type when declaring. The data type determines if a function returns a value or not. A function that is declared as void does not return a value and a function that is declared other than void returns a value.

Void Function

A void function is used if the function does not need to return a value after a computation or displaying some strings such as list, menus, options, etc.

Syntax:
void functionname()
{
//body of the function
}

Sample program 1:
           
#include<iostream>
using namespace std;
void myfunction()
{
cout<<"***************************"<<endl
    <<"* This is from a function *"<<endl
    <<"***************************"<<endl;
}

int main()
{
myfunction();

return 0;
}

Sample program 2:
           
#include<iostream>
using namespace std;
void myfunction()
{
cout<<"\t\t\t   JD and D Company"<<endl
    <<"\t\t\t  Salary Computation"<<endl
    <<"\t\t<E>mployee <M>anager <S>upervisor"<<endl;
}

int main()
{
char pos;
myfunction();
cout<<”Position -> “;
cin>>pos;

if(pos ==’e’ || ‘E’)
{
cout<<”You have selected a position of Employee”<<endl;
}
else if(pos ==’m’ || ‘M’)
{
cout<<”You have selected a position of Manager”<<endl;
}
else if(pos ==’s’ || ‘S’)
{
cout<<”You have selected a position of Supervisor”<<endl;
}

return 0;
}

Wednesday, November 2, 2011

Functions

Modular programming
            Uses routines, procedures, methods or functions that divides program into subprograms (specific task) that is easier to manage, maintain and troubleshoot.

Functions (User Defined)
            In C++, functions are the very essence of the program. Function works by grouping meaningful program codes together give them a simple name that later will called somewhere in the program. The very example of a function is actually we’ve been doing even from the start when we created our first program in c++. This function is called the main function.

            The main function, if you notice, will be crowded when we put all our codes there. By introducing a sub function (function other than the main function), we will be able to divert some of the codes in our main function to avoid having troubles in finding the fault in the program. In order to use a function, calling it is necessary.

A function may call another function. A function that calls a function is known as the calling function and a function that is called is known as the called function. This is usually happens in the main function when it calls another function or from one sub function to another sub function.

Syntax:
            DataType functionname( )
            {
            //body of the function
            }

If you notice, it is exactly similar to our main function ( int main( ) ).

Two types of declaration:

1.      Declaring and defining at the same time
DataType functionname( )
{
//body of the function
}

2.      Declaring and defining separately
DataType functionname( );

DataType functionname( )
{
//body of the function
}

The first one is the simplest form where it is declared and defined at the same time. The problem with this is you need to be aware of the hierarchy of your function. If a calling function calls a function that is declared (using the first form) after it will give you an error message. This is due to the fact that the function being called is the function that is not yet declared when it is called.
The second form will answer the problem mentioned above where functions are declared first at the top before defining them.
Still, it will be your preference that will be followed. Just don’t forget the syntax to avoid confusion in your program.

Sample Program for form 1:

#include<iostream>
using namespace std;
void firstfunction( ) //declaring a function
{
            cout<”This is from the function using form 1”<<endl;
}

int main( )
{
            firstfunction( );
            return 0;
}

Sample Program for form 2:

#include<iostream>
using namespace std;
void firstfunction( ); //declaring a function
void firstfunction( ) //defining a funciton
{
            cout<”This is from the function using form 2”<<endl;
}

int main( )
{
            firstfunction( ); //calling a function
            return 0;
}

Note: void refers to non returning value. This refers to the ability of a function that can return a value or not.