Blog

  • C# Call by Reference

    Here reference refers t the addresses but not the actual value. In this method, we pass the reference of the argument to the formal parameter. To pass the parameters in C#, we have a keyword called ref.

    It passes a reference to a memory location rather the actual value, so the changes made to this passed parameters are reflected o the main program that is their value can be modified permanently.


    Example: C# call by reference

    using System;
    
    namespace Programs
    {
       class Swapping
       {
          //swapping function (user-defined)
          public void swapFunc(ref int x, ref int y)
          {
             int temp;
    
             temp = x;
             x = y;
             y = temp;
          }
    
          //main method
          static void Main(string[] args)
          {
             Swapping swapObj = new Swapping();
    
             int a = 10, b = 20;
    
             Console.WriteLine("Before swapping, a: {0}", a);
             Console.WriteLine("Before swapping, b: {0}", b);
    
             //calling swap funciton with ref keyword
             swapObj.swapFunc(ref a, ref b);
    
             Console.WriteLine("\nAfter swapping, a: {0}", a);
             Console.WriteLine("After swapping, b: {0}", b);
    
          }
       }
    }

    Output:

    Before swapping, a: 10
    Before swapping, b: 20
    
    After swapping, a: 20
    After swapping, b: 10

    Unlike call by value (from the previous tutorial), the swapped value of a and b can be seen in the output above.


  • C# Call By Value

    This is passing parameters by Value. These value-type parameters in C# copy the actual parameters to the function (known as formal parameters) rather than referencing it.

    Whenever a method is called by passing value, a new storage location is created for each value parameter. The copies of these values are stored, hence the changes made in the formal parameter have no effect on the actual argument.


    Example: C# call by value

    using System;
    
    namespace Programs
    {
       class Swapping
       {
         	//swapping function (user-defined)
          public void swapFunc(int x, int y)
          {
             int temp;
    
             temp = x;
             x = y;
             y = temp;
          }
    
         	//main method
          static void Main(string[] args)
          {
             Swapping swapObj = new Swapping();
    
             int a = 10, b = 20;
    
             Console.WriteLine("Before swapping, a: {0}", a);
             Console.WriteLine("Before swapping, b: {0}", b);
    
            	//calling swap funciton by passing a and b
             swapObj.swapFunc(a, b);
    
             Console.WriteLine("\nAfter swapping, a: {0}", a);
             Console.WriteLine("After swapping, b: {0}", b);
    
          }
       }
    }

    Output:

    Before swapping, a: 10
    Before swapping, b: 20
    
    After swapping, a: 10
    After swapping, b: 20

    As you can see the value of a and b is not changed, even though the two value are swapped inside a function.


  • C# Methods

    A method refers to a block of code (or a group of statements) that performs a specific task. It takes some inputs, does some computation based on that input and returns the output. They are also known as functions.

    The use of function in a program helps in many ways such as reuse of code, Optimization of Code. The function is declared within the curly braces {}.

    Every C# program has at least one function which is always executed and that is the main function from where the execution of the program begins.

    In order to use a method in a program, you need to:

    • define a method
    • call a method

    Defining Methods in C#

    Defining a method means to write its structure with all of its components. Generally, the function is defined in following way in C#:

    <Access Specifier> <Return Type> <Method Name>(Parameter List) 
    {
       //Method Body
    }

    Followings are the list of component present in a method.

    • Access Specifier: It defines its visibility to the other class, which means it specifies the variables and methods accessibility in the program.
    • Return type: A function may return a value unless it is a void function, which does not return any type of value. return_type is a data type of the function. It could return arithmetic values (int, float, etc.), pointers, structures, etc.
    • Function name: Function name refers to identifiers through which function can be identified uniquely. It is a function’s name that is stated to function by following some naming rules.
    • Parameter list: Parameter is also referred to as Argument. We can pass the values through the parameter when the function is invoked. The parameter list refers to the type, order, and number of the parameters of a function
    • Function Body: The function body is enclosed within the curly braces’{}’. It defines the task of a method within the curly braces.

    Remember that you can also leave the parameter list empty if you are not passing any value to the function.


    Calling Methods in C#

    To call a method means to execute the method and to do that we need to write a function name by passing the values as parameters (if any) within the two parentheses () and semicolon.

    Following is the syntax t call a function.

    function_name( parameter_list );

    Example: C# example of method

    let us see an example in C# where we create an addition function and pass the value to add and return the result to the main function. We will see the use of defining and calling a method in C#.

    using System;  
    
    namespace MethodExam  
    {  
        class Program  
        {  
            //defining a method  
            public int addFunc(int x, int y) 
            {  
                return x+y;
            }  
            
            //main Function 
            static void Main(string[] args)  
            {  
                int result;
                
                // Creating Object 
                Program program = new Program();  
                
                // Calling Function 
                result = program.addFunc(5, 10);  
                Console.WriteLine("The result of addition: {0}", result);
            }  
        }  
    }
    //Output:
    
    The result of addition: 15

    Example:

    Let us see the use of Access Specifier in the C# program. The program below will have two classes and the method of one class can be accessed by another class by using the instance of the class. We need to use the public Access Specifier.

    using System;
    
    namespace MethodExample
    {
       //class1
       class Class1
       {
          // User defined function without return type  
          public int largestFunc(int num1, int num2) 
          {
             if (num1 > num2)
                return num1;
             else
                return num2;
          }
       }
    
       //class2
       class Class2
       {
          static void Main(string[] args)
          {
             int largest;
    
             // Creating Object 
             Class1 class1 = new Class1();
    
             // Calling Function 
             largest = class1.largestFunc(100, 80);
             Console.WriteLine("The largest of two number is: {0}", largest);
          }
       }
    }

    Output:

    The largest of two number is: 100

    How to pass Parameter in Methods?

    We need to pass the values to a method in order to calculate just like an example shown above, we can do that in three different ways in C#.

    • call by value
    • call by reference
    • out parameter

    We will got through each of them in next tutorial.


  • Call by Value and Call by Reference in C++

    There are two ways in which the argument can be passed through a function in C++ Programming.

    1. Call by Value
    2. Call by Reference

    Let’s go through call by value and call by reference in C++ language one by one.


    C++ call by value

    The method of call by value copies the actual argument to the formal parameter of the function. In this case, the changes made to the formal parameters within the function will not be affect the actual argument that is original value is not modified.

    By default, C++ programming uses call by value to pass arguments.

    Let us understand the call by value with an example in C++

    Example: Swap the values of two variables in C++ Programming:

    #include <iostream>
    using namespace std;
    
    // function declaration and definition together
    void swapFunc(int x, int y)
    {
       int temp;
    
       temp = x;
       x = y;
       y = temp;
    
       return;
    }
    
    //main function
    int main()
    {
       int a = 10;
       int b = 20;
    
       cout << "Before swap, a: " << a << endl;
       cout << "Before swap, b: " << b << endl;
    
       //calling function by passing a and b
       swapFunc(a, b);
    
       cout << "\nAfter swap, a: " << a << endl;
       cout << "After swap, b: " << b << endl;
    
       return 0;
    }

    Output:

    Before swap, a: 10
    Before swap, b: 20
    
    After swap, a: 10
    After swap, b: 20

    C++ Call by Reference

    Here reference refers t the addresses but not the actual value. In this method, we pass the reference of the argument to the formal parameter.

    Since the actual and formal parameters share the same address, the changes made inside the function will be reflected outside the function too. Hence, the original value is modified.

    we know that the reference that is the is dealt through the pointers in a program. to understand the call by reference type, you need to have basic knowledge of pointers.

    Let us understand the call by reference with an example in C++

    Example: Swap the values of two variables in C++ Programming:

    #include <iostream>
    using namespace std;
    
    //user-defined function
    void swap(int *x, int *y)
    {
       int swap;
    
       swap = *x;
       *x = *y;
       *y = swap;
    }
    
    //main function
    int main()
    {
       int a = 100, b = 200;
    
       cout << "Before swap, a: " << a << endl;
       cout << "Before swap, b: " << b << endl;
    
       //calling a value by passing reference  
       swap(&a, &b);
    
       cout << "\nAfter swap, a: " << a << endl;
       cout << "After swap, b: " << b << endl;
       return 0;
    }

    Output:

    Before swap, a: 100
    Before swap, b: 200
    
    After swap, a: 200
    After swap, b: 100

  • C++ Functions

    A function refers to a block of code (or a group of statements) that performs a specific task. A function takes some inputs, does some computation based on that input and returns the output. The function can be called many times by passing different values each time.

    For example, let us say that you need to compute a complex multiplication for different values on a different part of a program. One thing you can do is repeat the block of code for computation again and again, which is not a good practice as a programmer and makes the program complex and time-consuming. Better you can create a function and call that function every time you need by passing the different values.

    Every C++ program has at least one function which is always executed and that is the main function from where the execution of the program begins. The function is declared within the curly braces {}.


    Advantages of functions in C++

    There are many advantages of using function in C++.

    Reusability of code: As mention above in the example, we can reuse the function by calling it again and again as required in the program.

    Optimization of Code: Use of functions makes the program short and simple to understand. You only need to write the logic of the calculation once and use it several times.


    C++ function is defined into two categories:

    1. Standard Library Functions
    2. User-defined functions


    1. C++ Standard Library Functions

    These are the pre-defined function in a C++ program, like a main function. These built-in functions are already defined and written in C++, to use them you just need to invoke or call them directly.

    Some common library functions in C++ are sqrt()abs()isdigit(), etc.

    To use these library functions an appropriate header file needs to be included in the program. Example: to use math functions such as sqrt(), you need to include cmath header file.

    Example of C++ Standard Library Functions:

    #include <iostream>
    #include <cmath>  //math header file to use maths library function
    using namespace std;
    
    int main()
    {
       double number, square_result;
    
       cout << "Enter the number: ";
       cin >> number;
    
       //here sqrt() is a library function that calculates the square root
       square_result = sqrt(number);
    
       cout << "The square root of " << number << " is: " << square_result;
       return 0;
    }
    //Output:
    
    Enter the number: 625
    The square root of 625 is: 25

    2. C++ User-defined functions

    These are the functions created by the programmer in order to use it as many times as required. The user or programmer writes a block of code inside a body of a function to do some specific task.

    These functions can also be called or invoke from any part of the program and code inside the body of that function will be executed.

    We will see the examples of both Library Functions and User-defined functions below in this article.

    Example of C++ User-defined Functions:

    #include <iostream>
    using namespace std;
    
    //user-defined function
    int sum(int a, int b = 5)
    {
       int result;
       result = a + b;
    
       return result;
    }
    
    //Main function
    int main()
    {
       int a = 10, b = 20, result;
    
       // calling a function by passing a and b
       result = sum(a, b);
       cout << "Sum result: " << result << endl;
    
       // calling a function again by passing only a
       //In this case b will be added through the function defined above
       result = sum(a);
       cout << "Sum result: " << result << endl;
    
       return 0;
    }
    //Output:
    
    Sum result: 30
    Sum result: 15

    Function Declaration or Prototype:

    Declaring a function means telling the compiler about the function name and its return type and parameters (if any). it is like stating the prototype of the function.

    In C++, the function declaration declares a function without a body. It is important to declare the function when you are using one of the source file function to another file. We declare the function at the top of the program.

    The syntax for function declaration:

    return_type function_name( parameter list );

    Example:

    int max(int, int);
    
    //function that takes a ponter and integer
    int *swap(int*,int);

    Note: Also note that, if you defined the function before the main function then the separate function declaration is not required in a program else you need to mention the declaration. Example: In the syntax below, a declaration is not required

    #include <iostream>
    using namespace std;
    
    //user-defined function
    int sum(int a, int b = 5)
    {
    
       ...........
       ...........
    
     
       return result;
    }
    
    //Main function
    int main()
    {
       .............
       .............
    
       // calling a function
       result = sum(a, b);
       ............
       .............
    
       return 0;
    }

    Function Definition

    Generally, the function is defined in following way in C++:

    return_type function_name( parameter_list ) {
       body of the function;
    }

    Each part of a function:

    • Return type: A function may return a value unless it is a void function, which does not return any type of value. return_type is a data type of the function. It could return arithmetic values (int, float, etc.), pointers, structures, etc.
    • Function name: Function name refers to identifiers through which function can be identified uniquely. It is a function’s name that is stated to function by following some naming rules.
    • Parameter list: Parameter is also referred to as Argument. We can pass the values through the parameter when the function is invoked. The parameter list refers to the type, order, and number of the parameters of a function
    • Function Body: The function body is enclosed within the curly braces’{}’. It defines the task of a method within the curly braces.

    Note: The function declaration and definition is for the user-defined type function only because the library function is already declared and defined. We just need to call the library function in order to use it.


    Function Call

    We need to call the function in order to use it. To call a function we simply write the function name by passing the values as parameters (if any).

    When the function is called, the execution control passes to the function and does some specific task. When the return statement of the function is executed or when it executes the end braces, it means the program control is returned to the main function.

    Following is the syntax t call a function.

    function_name( parameter_list );

    Example: How to declare and define a function and call the function in C++

    #include <iostream>
    using namespace std;
    
    //declaring a function
    int sumFunc(int, int);
    
    //Main FUnction
    int main()
    {
       int x, y, sum;
    
       cout << "Enter two numbers to add: ";
       cin >> x >> y;
    
       //calling a function by passing x and y
       sum = sumFunc(x, y);
    
       cout << "The addition of " << x << " and " << y << " is: " << sum;
       return 0;
    }
    
    //function definition
    int sumFunc(int num1, int num2)
    {
       int result = num1 + num2;
       return result;  //returning the result to main funciton
    }

    Output:

    Enter two numbers to add: 10 20
    The addition of 10 and 20 is: 30

    Function Arguments

    The function is called by passing some values, and the function must declare variables in order to accept those values of the argument. These variables are called a formal parameters of the function and created during the entry of the function.

    The actual arguments refers to the values passed while calling the function.

    There are two ways in which the argument can be passed through a function:

    • Call by Value.
    • Call by Reference.

    Click here to learn about them in detail.


  • C# goto Statement

    The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. When encountered in a program, it transfers the execution flow to the labeled statement. The label (tag) is used to spot the jump statement.

    NOTE: Although the use of goto is avoided in programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify.

    goto statement Flowchart:

    goto statement in C
    goto statement

    Syntax of goto statement in C#:

    goto label;
    ....
    ....
    label: statement; //label to jump
    ....
    ....
    statements

    Example of C# goto Statement

    // use of goto statement
    using System;
    
    public class GotoStatement
    {
       static public void Main()
       {
          int selected = 3;
          switch (selected)
          {
             case 1:
                //this is the label
                first_case:
                   Console.WriteLine("case: 1");
                break;
    
             case 2:
                Console.WriteLine("case: 2");
                break;
    
             case 3:
                Console.WriteLine("case: 3");
    
                // transfer the flow to case 1
                goto first_case;
    
             default:
                Console.WriteLine("No match found");
                break;
          }
       }
    }

    Output:

    case: 3
    case: 1

  • C# continue Statement

    It is a loop control statement. It is used to continue the loop in the program. The use of continue inside a loop skips the remaining code and transfer the current flow of the execution to the beginning o the loop.

    In case of for loop, the continue statement causes the program to jump and pass the execution to the condition and update expression by skipping further statement. Whereas in the case of while and do…while loops, the continue statement passes the control to the conditional checking expression.

    continue statement Flowchart:

    Continue statement in java
    continue statement

    Syntax of continue statement in C#:

    //continue syntax
    continue;

    Example of C# continue Statement

    using System;
    
    public class ContinueStatement
    {
       public static void Main(string[] args)
       {
          for (int i = 1; i <= 10; i++)
          {
             if (i == 7)
             {
                // 7 is skipped and control passed to for loop
                continue;
             }
    
             Console.WriteLine("Value of i: {0}", i);
          }
       }
    }

    Output:

    Value of i: 1
    Value of i: 2
    Value of i: 3
    Value of i: 4
    Value of i: 5
    Value of i: 6
    Value of i: 8
    Value of i: 9
    Value of i: 10

    Example: C# continue program in nested loops

    using System;
    
    public class ContinueNested
    {
       public static void Main(string[] args)
       {
          //outer loop
          for (int i = 1; i <= 2; i++)
          {
             //inner loop
             for (int j = 1; j <= 2; j++)
             {
                if (i == 1 && j == 2)
                {
                    //skips when i=2 and j=2 and control goes to the outer loop
                   continue;
                }
    
                Console.WriteLine("i: {0}, j: {1}", i, j);
             }
          }
       }
    }

    Output:

    i: 1, j: 1
    i: 2, j: 1
    i: 2, j: 2

    In the above output, i: 1, j: 2 is skipped as the continue statement stopped the further execution after that and transferred the execution control to the beginning of the outer loop.


  • C# break Statement

    break statement in programming is used to come out of the loop or switch statements. It is a jump statement that breaks the control flow of the program and transfers the execution control after the loop.

    The use of break statements in nested loops terminates the inner loop and the control is transferred to the outer loop.

    break statement Flowchart:

    break statement

    Syntax of break statement in C#:

    //break syntax
    break;

    Example C# break Statement

    Use of break statement in a single loop in C#.

    using System;
    
    public class BreakStatement
    {
       public static void Main(string[] args)
       {
          for (int i = 1; i <= 10; i++)
          {
             if (i == 6)
             {
                //stops loop at 6th iteration
                break;
             }
    
             Console.WriteLine("Value of i: {0}", i);
          }
       }
    }

    Output:

    Value of i: 1
    Value of i: 2
    Value of i: 3
    Value of i: 4
    Value of i: 5

    Example: C# break statement with the nested loop.

    using System;
    
    public class BreakNested
    {
       public static void Main(string[] args)
       {
          for (int i = 1; i <= 2; i++)
          {
             for (int j = 1; j <= 2; j++)
             {
                // for i = 1 and j = 2 is skipped in the output
                if (i == 1 && j == 2)
                   break;
    
                Console.WriteLine("i: {0}, j: {1}", i, j);
             }
          }
       }
    }

    Output:

    i: 1, j: 1
    i: 2, j: 1
    i: 2, j: 2

    As you can see in the output that i = 1 and j = 2 is skipped. This is because the break statement breaks the inner loop for i = 1 and j = 2 and transfer the control to the outer loop and the rest iteration continues until the loop condition is satisfied.


  • C++ Loop Control Statements

    If you want to change the execution from the normal sequence or if you want the program to exit loops, for these purposes you need to use loop control statements.

    Loop control statements are also known as Jump statements. It allows you to jump from the loops or if you wish to repeat the loops after some condition is satisfied, jump statements helps you to achieve that.

    C++ supports the following control statements.

    • break statement
    • continue statement
    • goto

    break statement in C++

    break statement terminates the loop and transfers the execution process immediately to a statement following the loop.

    break statement is mostly used in a switch statement to terminate the cases present in a switch statement.

    The use of break statements in nested loops terminates the inner loop and the control is transferred to the outer loop.

    break statement Flowchart:

    break statement

    Syntax of break statement in C++:

     break;

    Click here for example of break statement in C++.


    continue statement in C++

    The continue statement works like a break statement, instead of terminating the loop the continue statement skips the code in between and passes the execution to the next iteration in the loop.

    In case of for loop, the continue statement causes the program to jump and pass the execution to the condition and update expression by skipping further statement. Whereas in the case of while and do…while loops, the continue statement passes the control to the conditional checking expression.

    continue statement Flowchart:

    Continue statement in java
    continue statement

    Syntax of continue statement in C++:

    continue;

    Click here for example of continue statement in C++.


    goto statement in C++

    The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. It jumps to the position where the labeled statement present in the program. The label (tag) is used to spot the jump statement.

    NOTE: Remember the use of goto is avoided in programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify.

    goto statement Flowchart:

    goto statement in C
    goto statement

    Syntax of goto statement in C++

    goto label;
    ....
    ....
    label: statement; //label to jump
    ....
    ....
    statements

    Click here for example of goto statement in C++.


  • C++ goto Statement

    The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. It jumps to the position where the labeled statement present in the program. The label (tag) is used to spot the jump statement.

    NOTE: Remember the use of goto is avoided in programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify.

    goto statement Flowchart:

    goto statement in C
    goto statement

    Syntax of goto statement in C++

    goto label;
    ....
    ....
    label: statement; //label to jump
    ....
    ....
    statements

    Example of C++ goto statement

    The simple example of goto statement in C++ programming.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       //this is the label
       ineligible_label:
    
       int age;
       cout << "Enter your age: ";
       cin >> age;
    
       if (age < 18)
       {
          cout << "You are below 18 and not eligible to vote.\n";
          goto ineligible_label;
       }
       else
       {
          cout << "You are above 18 and eligible to vote.";
       }
    }

    Output:

    Enter your age: 16
    You are below 18 and not eligible to vote.
    Enter your age: 21
    You are above 18 and eligible to vote.

    Avoid the use of goto: However, the use of goto is considered a harmful construct and a bad programming practice in a C++ programming. It makes the program complex and tangled, instead you can achieve the task of goto by using the break and continue statement.