Tuesday, December 9, 2014

C++ using Functions and Global and local variables Program



C++ Using Functions

            #include
            #include
            using namespace std;
            void myprint()
            {
                        cout << "Printing from a function.\n";
            }
             int main()
            {
                        myprint();
                        return 0;
            }

Parameters and return
 
            #include
            #include
            using namespace std;
            int add(int output1, int output2)
            {
                        return output1 + output2;
            }
            int main()
            {
                        int answer, input1, input2;
                        cout << "Give a integer number:";
                        cin >> input1;
                        cout << "Give another integer number:";
                        cin >> input2;
                        answer = add(input1,input2);
                        cout << input1 << " + " << input2 << " = " << answer;
                        return 0;
            }

Global and local variables

            #include
            #include
            using namespace std;
            int a, b;
            int add()
            {
                        return a + b;
            }
            int main()
            {
                        int answer;
                        a = 2;
                        b = 2;
                        answer = add();
                        cout << A << " + " << B << " = " << answer;
                        return 0;
            }

Definition

#include
#include
using namespace std;
long factorial(int);
int main()
{
          int counter, n;
     cout<<"Enter the Number :";
     cin>>n;
     cout<
     getch();
     return 0;
 }

Factorial Function

#include
#include
long factorial(int n)
{
    int counter;
    long fact = 1;
     for (int counter = 1; counter <= n; counter++)
     {
         fact = fact * counter;
     }
  return fact;
}

Output

Enter the Number :6
6 Factorial Value Is 720

Addition Function Using Templates


#include
#include
#include
using namespace std;
template type add(type num1, type num2);
int main ()
{
  std::cout << "Please enter integer 1 : ";
  int num1;
  cin >> num1;
  cout << "Please enter integer 2 : ";
  int num2;
  cin >> num2;
  int answer = add(num1, num2);
  cout << "The sum of " << num1 << " & " << num2 << " = " << answer;
  getchar();
  return 0;
}
template type add(type num1, type num2)
{
  type result = num1 + num2;
  return result;
}

No comments:

Post a Comment