96: ***(Syntax)*** Functions and Global Variables


functions

1: Use using namespace std; above all the functions: 

#include <iostream>
using namespace std;
void happybday()
{
    cout << "Happy birthday to you\n";
    cout << "Happy birthday to you\n";
    cout << "Happy birthday dear you\n";
    cout << "Happy birthday to you\n";
}
int main()
{
    happybday();
    cout << endl;
    happybday();

    return 0;
}


2: Enter just variable name that you want to pass to function in main(){} like happybday(name); but also pass datatype in function declaration e.g. void happybday(string name) :

#include <iostream>
using namespace std;
void happybday(string name)
{
    cout << "Happy birthday to " << name << endl;
    cout << "Happy birthday to " << name << endl;
    cout << "Happy birthday dear " << name << endl;
    cout << "Happy birthday to " << name << endl;
}
int main()
{  
    string name;
    cout << "Enter your name: ";
    getline(cin, name);

    happybday(name);
    cout << endl;
    happybday(name);

    return 0;
}


3: Function Prototype: 

    You can also write the body of the function below the int main(){} but you just have to declare that function above main like void happybday(string name); so that compiler knows that specific function exists in program.

#include <iostream>
using namespace std;

void happybday(string name);

int main()
{
    string name;
    cout << "Enter your name: ";
    getline(cin, name);

    happybday(name);
    cout << endl;
    happybday(name);

    return 0;
}

void happybday(string name)
{
    cout << "Happy birthday to " << name << endl;
    cout << "Happy birthday to " << name << endl;
    cout << "Happy birthday dear " << name << endl;
    cout << "Happy birthday to " << name << endl;
}


4: If you have to pass more than one variable to function, separate each with a ,  . Also, write its datatype in the function declaration.

  • int sum(int a, int b); is acceptable.
  • int sum(int a, b); is not acceptable ie you have to enter datatype also.
  • int sum(int, int); is also acceptable but only in the function prototype. You have to declare variables while writing the id and body of the function int sum(int a, int b){}.

    In this program, the variables used in the function ie a and b are called formal parameters while the values that we pass to the functions ie num1 and num2 are called actual parameters.

    Formal parameters take value from the actual parameters.

#include <iostream>
using namespace std;
int sum(int a, int b);
int main()
{
    int num1 = 5, num2 = 10, addition;
    addition = sum(num1, num2);
    cout << "Sum of " << num1 << " and " << num2 << " is: " << addition;

    return 0;
}

int sum(int a, int b)
{
    int sum;
    sum = a + b;
    return sum;
}


5: You can choose which type of value you need from the function and change void to that data type like float .

#include <iostream>
using namespace std;
float square(float length);
float cube(float length);

int main()
{
    float length, area, volume;
    cout << "Enter the length: ";
    cin >> length;

    area = square(length);
    cout << "Area: " << area << "cm^2" << endl;

    volume = cube(length);
    cout << "Volume: " << volume << "cm^3" << endl;

    return 0;
}

float square(float length)
{
    return length * length;
}

float cube(float length)
{
    return length * length * length;
} 


6: You should always use different variables in the function declarations from int main( ) so that you don't get confused while passing values to the functions because function variables are destroyed once used:

For example: 
   In int sum(int a, int b); int a and int b have been used but you can pass any variable when you call this function like here in int main( ) we have passed num1 and num2sum(num1, num2); 

#include <iostream>
using namespace std;
int sum(int a, int b);
int main()
{
    int num1 = 5, num2 = 10, addition;
    addition = sum(num1, num2);
    cout << "Sum of " << num1 << " and " << num2 << " is: " << addition;

    return 0;
}

int sum(int a, int b)
{
    int sum;
    sum = a + b;
    return sum;
}


7: Pass by value: 

        When you pass a value to a function, the value passed is the copy of the actual argument. This can be confirmed if we try to swap the actual values by using a function.

        The value will not be swapped from the original variables num1 and num2 because only the copies of actual arguments were passed to the user-defined function. No matter what happens to variables in the function, they will not be affected in the main function.

Thus, for swapping you will need to pass value by reference.

#include <iostream>
using namespace std;
void swap(int x, int y);
int main()
{
    int num1 = 1, num2 = 2;
    cout << "Before swaping num1 = " << num1 << " and num2 = " << num2 << endl;
    swap(num1, num2);
    cout << "After swaping num1 = " << num1 << " and num2 = " << num2 << endl;
   
    return 0;
}

void swap(int x, int y)
{
    int temp = x;
    x = y;
    y = temp;
}


8: Call by reference using C++ reference variable: 

        &  is known as ' address of ' and is used to pass the address of a variable to the function. If we do not use  &  in the function definition and declaration and see the memory address of the same variables in the main function and user-defined function, it will be different showing that the same memory is not used in the function instead the value is just copied to the function.

#include <iostream>
using namespace std;
void function(int x, int y);

int main()
{
    int a = 5, b = 6;

    cout << "a in main: " << &a << endl; // displaying address of a
    cout << "b in main: " << &b << endl; // displaying address of b

    function(a, b);

    return 0;
}
void function(int x, int y)
{
    cout << endl;
    cout << "a in function: " << &x << endl; // displaying address of x
    cout << "b in function: " << &y << endl; // displaying address of y
}

    Now if we pass the addresses of a and b, the memory address in the main and user-defined function will be the same.

#include <iostream>
using namespace std;
void function(int &x, int &y);

int main()
{
    int a = 5, b = 6;

    cout << "a in main: " << &a << endl; // displaying address of a
    cout << "b in main: " << &b << endl; // displaying address of b

    function(a, b);

    return 0;
}
void function(int &x, int &y)
{
    cout << endl;
    cout << "a in function: " << &x << endl; // displaying address of x
    cout << "b in function: " << &y << endl; // displaying address of y
}

Swap:

You can swap actual arguments by using C++ reference variable. For this just use  &  symbol before variables in the function id.

    The values will be swapped because, in this case, copies of values are not passed to function. Rather, the address of the variable is passed to the function, what happens to the variable in the user-defined function also happens to it in the main function.

#include <iostream>
using namespace std;
void swap(int &x, int &y);
int main()
{
    int num1 = 1, num2 = 2;
    cout << "Before swaping num1 = " << num1 << " and num2 = " << num2 << endl;
    swap(num1, num2);
    cout << "After swaping num1 = " << num1 << " and num2 = " << num2 << endl;
   
    return 0;
}

void swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}


9: Call by reference using pointers:

        You can do the same as in point 8 by calling by reference using pointers.

For this purpose, just add  *  before the variables in the function.

#include <iostream>
using namespace std;
void swap(int *x, int *y);
int main()
{
    int num1 = 1, num2 = 2;
    cout << "Before swaping num1 = " << num1 << " and num2 = " << num2 << endl;
    swap(num1, num2);
    cout << "After swaping num1 = " << num1 << " and num2 = " << num2 << endl;
   
    return 0;
}

void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp; }    


10: Inline function:

    To write the inline function, you just have to add an inline argument before function id. 

If you have very small code in the function like  x * y  and you have to call it like 10 times, every time, its value will be copied in the function and recalled again. So, if you used the inline function, the compiler will paste code  x * y  during compile time saving more time.

    You should only use the inline function when the function code is very small and is called again and again. If the code is large and you make it inline, it will take so much cache memory making our program code inefficient.

Don't use the Inline function with static variables.

#include <iostream>
using namespace std;
inline int product(int x, int y);
int main()
{
    int num1 = 25, num2 = 22, prod;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    cout << "Product of " << num1 << " and " << num2 << " is: " << product(25, 22) << endl;
    return 0;
}

inline int product(int x, int y)
{
    return x * y;
}


11: Static Variables:

        A static variable is initialized once when the function is called for the first time, afterwards, it retains its value and is not initialized again.

    In the following example, the prod( ) function is called various times but the value of  z  is initialized from 0 only when the prod( ) function was called for the first time.

It is advised, you should not use Inline function while using static variables.

#include <iostream>
using namespace std;
int prod(int x, int y);

int main()
{
    int a = 2, b = 3;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    cout << "Product of " << a << " and " << b << " is: " << prod(a, b) << endl;
    return 0;
}

int prod(int x, int y)
{
    static int z = 0;
    z = z + 1;
    return x * y + z;
}


12: Const Parameters in functions:

    const parameter is used where you are sending a value by its reference and you don't want that value to be even accidently changed within the function due to any condition and to make other developers aware that these arguments are read-only.

    In the following program, if const argument is not passed, the values of name and age will be changed, but due to const argument, compiler will show error if these arguments gets changed within the function.

#include <iostream>
using namespace std;
void printinfo(const string x, int y);
int main()
{
    string name = "Umar";
    int age = 20;
    printinfo(name, age);

    return 0;
}
void printinfo(const string x, int y)
{
    x = " ";
    y = 0;
    cout << "Your name is: " << x << endl
         << "Your age is: " << y << endl;
}


13: Recursion: 

        Recursion is calling a function within itself. It is a programming technique where a function invokes itself from within. In it, a complex problem is broken into repeatable single steps.

    Advantages: 
            1. Less code
            2. Cleaner
            3. Useful for sorting and search algorithms.

    Disadvantages: 
            1. Uses more memory
            2. Slower
            3. Same function is invoked again and again
            4. Very difficult to understand most of the times.

Factorial using recursion:
#include <iostream>
using namespace std;
int inum(string x);
int factorial(int x);

int main()
{
    int num = inum("Enter a number: ");
    cout << "Factorial of " << num << " is: " << factorial(num) << endl;
    return 0;
}

int inum(string x)
{
    int y;
    cout << x;
    cin >> y;
    return y;
}
int factorial(int x)
{
    if (x < 2)
    {
        return 1;
    }
    return x * factorial(x - 1);
}

Fibonacci series using recursion: 


14: Overloaded functions:

        Functions that have the same name but different parameters are called Overloaded Functions.
        for example
                i. void bake_pizza(); 
               ii. void bake_pizza(string topping1); 
              iii. void bake_pizza(string topping1, string topping2); 

function name + its parameters ie bake_pizza(string topping1) are together called Function Signature.

#include <iostream>
using namespace std;
void bake_pizza();
void bake_pizza(string topping1);
void bake_pizza(string topping1, string topping2);
int main()
{
    bake_pizza();
    bake_pizza("pepperoni");
    bake_pizza("pepperoni", "cheese");

    return 0;
}

void bake_pizza()
{
    cout << "Here is your Pizza!\n";
}
void bake_pizza(string topping1)
{
    cout << "Here is your " << topping1 << " Pizza!\n";
}
void bake_pizza(string topping1, string topping2)
{
    cout << "Here is your " << topping1 << " and " << topping2 << " Pizza!\n";
}


15: Boolean Functions:

        You use Boolean functions when there is a yes or no questions. If you have to list perfect numbers within a range you will check if the number is a perfect number using a boolean function and if it is true you will print the number otherwise you will leave that number. This will save you a large amount of code.

  • The return type will be bool 
  • The values you return will be 
    • true
    • false
  • You should not use 0 and 1 because it is also int datatype whereas true and false are only boolean datatypes.

#include <iostream>
using namespace std;
bool isPositive(int x);

int main()
{
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (isPositive(num))
    {
        cout << num << " is positive\n";
    }
    else
    {
        cout << num << " is negative\n";
    }

    return 0;
}

bool isPositive(int x)
{
    if (x >= 0)
    {
        return true;
    }

    else
    {
        return false;
    }
}

  • You can also write if-statement as: if (isPositive(num) == 1) and it will work the same.
  • You can also declare a bool variable before and check it into the if statement and it will work the same

bool b = isPositive(num);
    if (b)
    {
        cout << num << " is positive\n";
    }
    else
    {
        cout << num << " is negative\n";
    }

  • You can also in the function store your result in a variable and return that variable, it will work the same.

bool isPositive(int x)
{
    bool result;
    if (x >= 0)
    {
        result = true;
    }
    else
    {
        result = false;
    }
    return result;
}

  • You can also return the condition that will give 1 and 0 as the answer and it will work the same.

bool isPositive(int x)
{
    return x >= 0;
}

This is the shortest way of writing a boolean function.


16: Generic functions:

        Sometimes we need functions with different datatypes. In this case, you can either copy that same function just with a different datatype for every datatype or you can use a single generic function and pass the datatype to this function. This saves a large amount of code.

#include <iostream>
using namespace std;
int quotient(int x, int y);

int main()
{
    int num1 = 5, num2 = 3;

    cout << "Qoutient of " << num1 << " with " << num2 << " is: " << quotient(num1, num2);
    return 0;
}

int quotient(int x, int y)
{
    return x / y;
}

Now if you want to get a floating value, you will have to make the same function with float datatype:

#include <iostream>
using namespace std;
float quotient(int x, int y);

int main()
{
    int num1 = 5, num2 = 3;

    cout << "Qoutient of " << num1 << " with " << num2 << " is: " << quotient(num1, num2);
    return 0;
}

float quotient(int x, int y)
{
    return x / y;
}

Or

You can make a generic function by:

  • using template <typename T> before function and using T at places where you want to add that data type.
  • #include <iostream>
    using namespace std;
    template <typename T>
    T quotient(T x, T y);

    int main()
    {
        float num1 = 5, num2 = 3;
        cout << "Qoutient of " << num1 << " with " << num2 << " is: "
             << quotient<float>(num1, num2);
        return 0;
    }

    template <typename T>
    T quotient(T x, T y)
    {
        return x / y;
    }
  • Add <float> or any other datatype you want while calling the function.
  • If you don't write <float> the datatypes of variables that you are passing will be passed to T 


18: Global variables:

    Local variables are located inside a function or a block like int main(){} or void bake_pizza(){} etc. 

Functions cannot look into one another ie cannot take its variable unless we pass it as a parameter.
So, in this case, you can make a global variable also. A global variable is written outside every function and block, usually at the top of the program.

But if the same variable is present in a block or function also ie as a local variable, the compiler will prefer the local variable.

=> If you want to use a global variable in a function or a block just use :: before the variable name.

#include <iostream>
using namespace std;
void print_num();

int num = 1;

int main()
{
    int num = 2;
    cout << "My number in main is: " << num << endl;

    print_num();

    cout << "My number in Global Variable is: " << ::num << endl;    

    return 0;
}

void print_num()
{
    int num = 3;
    cout << "My number in function is: " << num << endl;
}


19: fflush: 

    Use:
     cin.clear();      fflush(stdin);

on top of do while loop to stop infinity loop when user enteres some invalid input. 






Comments

Popular posts from this blog

88: Using switch statement Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: // Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F

205: Book Catalog: Define a struct to represent a book with attributes like title, author, and publication year. Write a program to create a catalog of books by taking user input and display books published after a certain year.

15: Take input of age and name of 3 people by user and determine oldest and youngest among them with his age. -_-_-_-_-_-_-_-_-(line with spaces input concept)-_-_-_-_-_-_-_-_