Blog

  • C – File System (I/O)

    In this tutorial, you will learn about file handling in C. You will learn how to read from a file, write to a file. close a file and more.

    File pointers: It is not enough to just display the data on the screen. We need to save it because memory is volatile and its contents would be lost once the program terminated, so if we need some data again there are two ways, one is retyped via keyboard to assign it to a particular variable, and the other is regenerate it via programmatically both options are tedious.

    At such times it becomes necessary to store the data in a manner that can be later retrieved and displayed either in part or in whole. This medium is usually a “file” on the disk.

    Introduction to file

    Until now we have been using the functions such as scanf, printf, getch, putch, etc to read and write data on the variables and arrays for storing data inside the programs But this approach poses the following problems.

    • The data is lost when program terminated or variable goes out of scope.
    • Difficulty to use large volume of data.

    We can overcome these problems by storing data on secondary devices such as Hard Disk. The data is stored on the devices using the concept of “file”. A file is a collection of related records, a record is composed of several fields and a field is a group of characters. The most straightforward use of files is via a file pointer.

    We need to declare the pointer first in a program and is done in the following ways:

    FILE *fp;
    //fp is a pointer to a file.

    The type FILE is not a basic type, instead, it is defined in the header file stdio.h, this file must be included in your program


    Types of Files

    Basically there are two types of file:

    1. Text files: These files are .txt files that contain the plain text when you open it and easy to edit and delete. You can create such files with text editors such as Notepad.
    2. Binary file: These are the .bin files present in the computer. They store the data in a binary form such as in 0’s and 1s instead of plain text. Although it is harder to understand, it gives better security than plain text files.

    File Operation

    • Create a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).
    • Open an existing file (fopen).
    • Read from file (fscanf or fgets).
    • Write to a file (fprintf or fputs).
    • Moving a specific location in a file(Seeking) (fseek, rewind).
    • Closing File (fclose).

    Opening a file:

    fopen() is used to open a file by giving two values such as file_name and mode to which you want to open the file. The various modes are stated below.

    FILE *fp;
    fp = fopen ("file_name", "mode");

    There are various modes to open a file. Check the table given below.

    File ModesDescription
    rread
    wwrite, overwrite file if it exists
    awrite, but append instead of overwrite
    w+read & write, do not destroy file if it exists
    a+read & write, but append instead of overwrite
    b+may be appended to any of the above to force the file to be opened in binary mode rather than text mode.

    Sequential file access is performed with the following library functions: 

    • fopen()  – Create a new file
    • fclose()  – Close file
    • getc()    – Read character from file
    • putc()    – Write a character to a file
    • getw()   – Read Integer from file
    • putw()   – Write Integer to a file
    • fprintf()  – Write set of data values
    • fscanf()  – read set of data values

    Closing a file:

    fclose() function is used to close the file once the operation on file is done. And it is done in a flowing way:

    int fclose( FILE *fp );

    Example on how to use open and close mode.

    //Opens inputs.txt file in read mode
    FILE  *fp;
    fp=fopen("input.txt","r");
    
    //closing inputs.txt file
    fclose(fp); //close file

    Reading from a file:

    Reading operation are performed fgetc(), fgets() and fscanf(). You can use them according to your choice. If you want to read character by character then you may use fgetc() or for line by line, you can use fgets().

    The end of the file is denoted by EOF(end of file) ot NULL character (\0) value at the end. It tells the function that it has reached the end of the file.

    FILE * fp; 
    fp = fopen(“fileName.txt”, “r”);
    fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

    Writing to a file:

    Writing operation in a file can be performed with the use of fprintf, fputc and fputs.

    • fputc(char, file_pointer): It writes a character to the file.
    • fputs(str, file_pointer): It writes a string to the file..
    • fprintf(file_pointer, str, variable_lists): The first value is the file_pointer that points to the String that needs to be printed.
    FILE *fp; 
    fp= fopen(“file_Name.txt”, “w”);
    fprintf(fp, "%s %s %s %d", "This", "is", "new", 2021);

    Example of Writing and closing a file in C programming.

    #include < stdio.h > 
    #include <string.h >
    
      int main()
      {
        //file pointer
        FILE * fp;
    
        // Get the data to be written in file
        char writeData[50] = "Simple2Code: Learn Coding";
    
       //opening file in a write mode
        fp = fopen("TestFile.txt", "w");
    
       //Check for the null
        if (fp == NULL)
        {
          printf("TestFile.txt failed to open.");
        }
        else
        {
          printf("Successfully Opened.\n");
    
          if (strlen(writeData) > 0)
          {
           	//writing in the file using fputs()
            fputs(writeData, fp);
            fputs("\n", fp);
          }
    
         	//Closing the file
          fclose(fp);
    
          printf("The file is now closed.");
        }
    
        return 0;

  • Array in C

    An array is a group or the collection of data having the same data-type stored in a contiguous memory location. It is a simple data structure format where the primitive type of data such as int, char, double, float, etc are stored and accessed randomly through their index number.

    It can also store the collection of derived data types, such as pointers, structure, etc. Elements are arranged inside the array with index numbers starting from zero as the first elements.

    Types of Array in C:

    • One Dimensional Array
    • Two Dimensional Array
    • Multi-Dimensional Array

    One Dimensional Array

    An array with only one subscript is known as a one-dimensional array.
    Example: int arr[10].

    Syntax:

    data-type arrayName [ arraySize ];

    Declaration of on Array:

    For declaration of an array in C, the user needs to specify the type of element and number of elements in an array. Below is the declaration of single-dimensional Array.

    type arrayName [ arraySize ];

    The data-type must be a valid C data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for integer array with 10 elements:

    int arr[10];

    Initialization of an array:

    Array can be initialize by using a single statement or one by one. The Initialization is done within the curly braces {}.

    int arr[5] = {45, 23, 99, 23, 90};
    OR
    int arr[] = {45, 23, 99, 23, 90};

    In the second one of the above example, the array size is not declared so that you can initialize as much value as you want.

    Users can also directly assign the value to the particular element in an array by specifying the index number such as: below shows how to assign the value 23 to the 5th element of an array.

    arr[4] = 23;

    NOTE:
    In the above example, number 4 means the 5th element as the array index starts from 0.

    Accessing an Array:

    As told above, that each array elements are associated with specific number that is the index numbers.

    An array element can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:

    arr[4]; //the 5th element is accessed
    arr[7]; //the 8th element is accessed

    We can also assign the value particular index number to other variable but their data type must be the same such as:

    int numb = arr[4];

    In the above, the value of 5th element from an array arr[] is assigned to the numb variable.


    Example: Demonstration for declaring, initializing, and accessing an array in C

    #include <stdio.h>
    
    int main()
    {
      /*declaration of an array 
      with 10 elements*/
      int arr[10];
      int i, j;
    
      /*Array intitalization */
      for (i = 0; i < 10; i++)
      {
        arr[i] = i + 1;
      }
    
      //accesing the array element and changing its value to 50
      arr[5] = 50;
    
      //Displaying
      for (j = 0; j < 10; j++)
      {
        printf("Element[%d] = %d\n", j, arr[j]);
      }
    
      return 0;
    }

    Output:

    Element[0] = 1
    Element[1] = 2
    Element[2] = 3
    Element[3] = 4
    Element[4] = 5
    Element[5] = 50
    Element[6] = 7
    Element[7] = 8
    Element[8] = 9
    Element[9] = 10

    Index Out of bound Checking: Accessing elements out of its bound.

    Out of bound means, suppose you declare an array with 10 number of elements (index between 0 to 9) and you try to access the 11th element, which is not present in that array such as:

    .........
    ........
    {
    int arr[10];
    
    printf("%d", arr[11]); //11th element not present
    .......
    }

    In the above program, the 11th element is not present but we are trying to print that element. In such cases, the program may run fine but you may get an unexpected output (undefined behavior) from a program.

    There is no index out of bounds checking in C.


    Empty Members in an array

    When we declare an array of size n, that means we can store the n number of elements of in that array. But what happens if we were to store less than n number of elements.

    Consider an example below:

    //size=10
    //stored = 6 elements
    int arr[10] = {19, 10, 8, 45, 2, 87};

    As you can see, the size of an array is 10 but we initialized it with only 6 elements. However, a 10 contiguous memory location is already allocated to this array. What will happen to the remaining un-initialized arrays?

    Now in such cases, random values are assigned by the compiler to the remaining places. And often these random values are 0.


    Advantages of Array in C

    • Less line of codes that is a single array with multiple elements, specifying code optimization.
    • Elements of an array can be accessed randomly with the index number.
    • The elements in an array can be easily traversed.
    • Array’s data are easy to manipulate.
    • Sorting becomes easy in an array with fewer lines of codes.

    Disadvantages of Array in C

    • The array is of fixed size once initialized. We cannot add new elements after initialization.
    • The number of elements you need to store in an array must be known in advance.
    • There may be a wastage of space if more memory is allocated than the required amount.

    Learn in Detail:

    1One-Dimensional Array
    2Two-Dimensional Array
    3Multi-Dimensional Array
    4Passing Array to Function
    5Pointers to Array

  • C – Passing Array to Function

    Passing an array to function in the one-Dimensional array is done through an actual parameter and array variables with subscript are passed as formal arguments. While passing array only the name of the array is passed to the function.

    Same method is applied for the multi-dimensional array.

    There are three methods that can be used to pass an array to a function.

    First Way: As a unsized array

    return_type function(type arrayname[])
    {
      .....    
    }

    Second Way: As a sized array

    return_type function(type arrayname[SIZE])
    {
      .....    
    }

    Third Way: As a pointer

    return_type function(type *arrayname)
     {
      .....    
     }

    Example: Passing a One-Dimensional Array in Function in C

    To find the average of given number.

    #include <stdio.h>
    
    float avgresult(float age[]);
    
    int main()
    {
      float avg, score[] = { 14.4, 23, 19.6, 9, 56.9, 18 };
      avg = avgresult(score); // Only name of an array is passed as an argument
    
      printf("Average Score = %.2f", avg);
      return 0;
    }
    
    //function
    float avgresult(float score[])
    {
      int i;
      float avg, sum = 0.0;
      for (i = 0; i < 6; ++i)
      {
        sum += score[i];
      }
    
      avg = (sum / 6);
      return avg;
    }

    Output:

    Average Score = 23.48

    Example: Passing a Multi-Dimensional Array in Function in C

    Program takes an input from the user and a function is used to display the array.

    #include <stdio.h>
    
    void displayArray(int arr[3][2]);
    
    int main()
    {
      int arr[3][2];
      printf("Enter 6 numbers for an array:\n");
      for (int i = 0; i < 3; ++i)
        for (int j = 0; j < 2; ++j)
          scanf("%d", &arr[i][j]);
    
      // passing multi-dimensional array to a function
      displayArray(arr);
      return 0;
    }
    
    void displayArray(int arr[3][2])
    {
      printf("Displaying the Entered Number: \n");
    
      for (int i = 0; i < 3; ++i)
      {
        for (int j = 0; j < 2; ++j)
        {
          printf("%d\n", arr[i][j]);
        }
      }
    }

    Output:

    Enter 6 numbers for an array:
    56
    22
    67
    88
    2
    8
    Displaying the Entered Number:
    56
    22
    67
    88
    2
    8

  • Pointer to an Array in C

    The basic idea of Pointer to an Array is that a pointer is used in with array that points to the address of the first element of that array.

    Before we begin, you need to have the knowledge of following C programming:


    Consider the following:

    double *ptr;		
    double arr[10];
    
    ptr = arr;

    In the above example, the variable arr will provide the base address, which is a constant pointer pointing to the first element of the array that is to arr[0]. And hence the arr will contain the address of arr[0]. Thus, the above program fragment assigns ptr with the address of the arr.

    Once the address of the first element is stored in the pointer ‘p’, we can access other elements of array elements using *p, *(p+1), *(p+2), and so on.

    Now lets apply it in a programs.

    Example 1: Array and Pointers in C

    #include <stdio.h>
    
    int main()
    {
      int i;
      int arr[5] = { 30, 42, 35, 4, 52 };
      int *p = arr;
    
      //displaying using pointer
      for (i = 0; i < 5; i++)
      {
        printf("Element at %d = %d\n", i, *p);
        p++;
      }
    
      return 0;
    }

    Output:

    Element at 0 = 30
    Element at 1 = 42
    Element at 2 = 35
    Element at 3 = 4
    Element at 4 = 52

    Example 2: Array and Pointers in C

    #include <stdio.h>
    
    int main() 
    {
      int arr[6] = {10, 20, 30, 40, 50, 60};
      int *ptr;
    
      //4th element address is assigned
      ptr = &arr[3]; 
    
      printf("Value pointed by *ptr: %d \n", *ptr);   // 40
      printf("Value pointed by *(ptr+1): %d \n", *(ptr+1)); // 50
      printf("Value pointed by: *(ptr-1): %d", *(ptr-1));  // 30
    
      return 0;
    }

    Output:

    Value pointed by *ptr: 40 
    Value pointed by *(ptr+1): 50 
    Value pointed by: *(ptr-1): 30

    In the above example array(arr) 4th element’s address is assigned to the pointer(ptr) and through that, we can print the value that the pointer points to by simply incrementing decrementing the pointer value such as by using ptr+1 or ptr-2, etc.


  • C – Multi-Dimensional Array in C

    What is Multi-Dimensional Array in C?

    In C programming, Multi-Dimensional Arrays refer to as array of arrays. This could be of 2D or 3D (two-dimensional or three-dimensional) Array. These arrays are stored in the form of a table (with rows and columns).

    The general form of multi-dimensional array:

    data-type array_name [size1][size2]...[sizeN];

    The data type must be a valid C data type, a unique name must be specified to each array and the size must be of an integer constant.


    Declaration of 2d and 3d Array in C.

    int arr1[3][4]; //2D Array
    OR
    int arr2[3][4][3]; //3D Array

    Initialization of multidimensional array.

    We can initialize a Multi Dimensional Array (two-dimensional or three-dimensional) in the following ways in C.

    1. Initialization of 2d Array

    //Method1
    //initializing with 5 rows and 3 columns
    int arr[5][3] = {
            {1, 2, 3},
            {2, 3, 4},
            {3, 4, 5},
            {4, 5, 6}, 
            {7, 8, 9}
         };
    OR
    //Method2
    int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

    2. Initialization of 3d Array

    //Method1
    int arr[2][3][4] = {
        {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
        {{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
    OR
    //method2
    int arr[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
                     11, 12, 13, 14, 15, 16, 17, 18, 19,
                     20, 21, 22, 23};

    Accessing Multi-Dimensional Array Elements in C

    Accessing 2d Array:

    An array can be accessed by using a specific index number. It can be achieved by placing the particular index number within the brackets [][]. Such as:

    arr[2][3]; //the 4th element of the third row is accessed
    arr[3][2]; //the 3rd element of the fourth row is accessed
    OR
    int val = arr[2][3]; // assigning the element to val

    Accessing 3d Array:

    Accessing 3-dimensional array is also as same as a two-dimensional array, the only difference is that in 3d array we have to specify 3 subscripts with a required index number.


    Example of two -dimensional Array in C:

    Displaying the elements with index number from 2D Arrays.

    #include <stdio.h>
    
    int main()
    {
      //Array with 4 rows and 2 columns
      int arr[4][2] = {
        { 0, 1 },
        { 2, 3 },
        { 4, 5 },
        { 6, 7 }
      };
    
      int i, j;
    
      //Displaying the elements
      printf("Elements with index numbers:\n");
      for (i = 0; i < 4; i++)
      {
        for (j = 0; j < 2; j++)
        {
          printf("a[%d][%d] = %d\n", i, j, arr[i][j]);
        }
      }
    
      return 0;
    }

    Output: After executing the above code, the following result will be displayed.

    arr[0][0]: 0
    arr[0][1]: 1
    arr[1][0]: 2
    arr[1][1]: 3
    arr[2][0]: 4
    arr[2][1]: 5
    arr[3][0]: 6
    arr[3][1]: 7

    Example of three-dimensional Array in C:

    Displaying the elements with index number from 3D Arrays.

    #include <stdio.h>
    
    int main()
    {
      int arr[2][3][2] = { 
            { {0,1}, {2,3}, {4,5} }, 
            { {6,7}, {8,9}, {10,11} } 
        };
      int i, j, k;
    
     // Display with index number
      printf("Elements with index number: \n");
      for (i = 0; i < 2; ++i)
      {
        for (j = 0; j < 3; ++j)
        {
          for (k = 0; k < 2; ++k)
          {
            printf("Element at [%d][%d][%d] = %d\n", i, j, k, arr[i][j][k]);
          }
        }
      }
    
      return 0;
    }

    Output: After executing the above code, the following result will be displayed.

    Element at arr[0][0][0] = 0
    Element at arr[0][0][1] = 1
    Element at arr[0][1][0] = 2
    Element at arr[0][1][1] = 3
    Element at arr[0][2][0] = 4
    Element at arr[0][2][1] = 5
    Element at arr[1][0][0] = 6
    Element at arr[1][0][1] = 7
    Element at arr[1][1][0] = 8
    Element at arr[1][1][1] = 9
    Element at arr[1][2][0] = 10
    Element at arr[1][2][1] = 11

    As we saw the examples of 2D and 3D arrays, in a similar we can create any number dimension as required. However, the most used multidimensional array is a two-dimensional array.


  • C – Two Dimensional Array

    What is Two Dimensional Array in C?

    Array with two subscripts is known as two dimensional Array. The 2D array is organized as the collection of rows and columns to form a matrix. 2D arrays are created to manipulate data structures.

    Example: int arr[][];

    Declaration of 2D array.

    The following shows the syntax for declaring 2D Array.

    data_type array_name[rows][columns];

    The data-type must be a valid C data type, a unique name must be specified to each array and the arraySize must be of an integer constant. The 2D array is considered as the table with a specified number of rows and columns.

    Consider the following example of 2D integer type array with 5 rows and 3 columns:

    int arr[5][3];

    Initialization of 2D array.

    2D array is initialized using the curly braces {}. Such as:

    //initializing with 5 rows and 3 columns
    int arr[5][3] = {
            {1, 2, 3},
            {2, 3, 4},
            {3, 4, 5},
            {4, 5, 6}, 
            {7, 8, 9}
         };
    OR
    int arr[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

    Accessing Two-Dimensional Array Elements in C

    An array can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket [][]. Such as:

    arr[2][3]; //the 4th element of the third row is accessed
    arr[3][2]; //the 3rd element of the fourth row is accessed
    OR
    int val = arr[2][3]; // assigning the element to val

    Example of 2D Array in C.

    Displaying the elements with index number from 2D Arrays.

    #include <stdio.h>
    
    int main()
    {
      //Array with 4 rows and 2 columns
      int arr[4][2] = {
        { 0, 1 },
        { 2, 3 },
        { 4, 5 },
        { 6, 7 }
      };
    
      int i, j;
    
      //Displaying the elements
      printf("Elements with index numbers:\n");
      for (i = 0; i < 4; i++)
      {
        for (j = 0; j < 2; j++)
        {
          printf("a[%d][%d] = %d\n", i, j, arr[i][j]);
        }
      }
    
      return 0;
    }

    Output: After executing the above code, the following result will be displayed.

    arr[0][0]: 0
    arr[0][1]: 1
    arr[1][0]: 2
    arr[1][1]: 3
    arr[2][0]: 4
    arr[2][1]: 5
    arr[3][0]: 6
    arr[3][1]: 7

  • C – One Dimensional Array

    What is One Dimensional Array in C?

    An array with only one subscript is known as a one-dimensional array.
    Example: int arr[10].

    Syntax:

    data-type arrayName [ arraySize ];

    Declaration of 1D Array in C:

    For declaration, the programmer needs to specify the type of element and number of elements in an array.

    Certain rules for declaring One Dimensional Array

    • The declaration must have a data type(int, float, char, double, etc.), variable name, and subscript.
    • The subscript represents the size of the array. If the size is declared as 10, programmers are allowed to store only 10 elements (index 0 to 9).
    • An array index always starts from 0 as its first element. For example, if an array variable is declared as arr[10], then it ranges from 0 to 9.
    • Each array element stored in a separate memory location.
    type arrayName [ arraySize ];

    The data-type must be a valid C data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for integer array with 10 elements:

    int arr[10];

    Initialization of 1D array in C:

    Array can be initialize by using a single statement or one by one. The Initialization is done within the curly braces {}.

    int arr[5] = {45, 23, 99, 23, 90};
    OR
    int arr[] = {45, 23, 99, 23, 90};

    On second one the array size is not declared so that you can initialize as much value as you want.

    Users can also directly assign the value to the particular element in an array by specifying the index number such as: below shows how to assign the value 23 to the 5th element of an array.

    arr[4] = 23;

    NOTE:
    In the above example number 4 means the 5th element as the array index starts from 0.

    Accessing a 1D Array Elements:

    An array can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:

    arr[4]; //the 5th element is accessed
    arr[7]; //the 8th element is accessed

    We can also assign the value particular index number to other variable but their data type must be same such as:

    int numb = arr[4];

    In the above, the value of 5th element from an array arr[] is assigned to the numb variable.

    Example of 1D Array in C.

    Declaring and assigning 5 elements in an array and display them accordingly.

    #include <stdio.h>
    
    void main()
    {
      int arr[5], i;
    
      printf("Enter 5 Elements.\n");
      for (i = 1; i <= 5; i++)
      {
        printf("Element %d = ", i);
        scanf("%d", &arr[i]);
      }
    
      printf("\nElements in an Array:\n");
      for (i = 0; i <= 5; i++)
      {
        printf("%d ", arr[i]);
      }
    }

    Output:

    Enter 5 Elements.
    Element 1 = 23
    Element 2 = 45
    Element 3 = 66
    Element 4 = 90
    Element 5 = 100
    
    Elements in an Array:
    23 45 66 90 100

  • C – Function

    A function refers to a block of code that performs a specific task. We can divide and create a separate function in a program so that each function performs a different specific task and can be called as many times as needed in the program.

    • At least one pre-defined function is always executed by the C compiler that is the main() function.
    • It allows the user to reuse the code as many times without rewriting the code and therefore act as a time saver.
    • The function is declared within the curly braces {}.

    C function is defined into two categories:

    1. Library functions
    2. User-defined functions

    1. Standard Library functions:

    These functions are built-in function in C programming that is already defined in C Library. Example: printf()scanf()strcat() etc. To use these functions an appropriate header needs to be included in the program.

    2. User-defined functions:

    On the other hand, user-defined functions are the ones that are defined by the users while writing the code and they perform the task assigned by the users.

    User-defined functions are used for code re-usability and for saving time and space.


    Defining a function:

    The general way to define a function 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.

    Example:

    /* function that returns the minimum value
    between two number passed*/
    
    int min(int num1, int num2) 
    {
       int finalValue;
     
       if (num1 > num2)
          finalValue = num1;
       else
          finalValue = num2;
     
       return finalValue;
      //return_type is int
    }

    Declaring a Function:

    Declaration of function includes the function name and its return type and 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.

    The function declaration contains:

    return_type function_name( parameter list );

    In the above example the declaration is stated as:

    int min(int num1, int num2);

    Declaration of function is required when the source is on one file and you call that function from different files.

    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 <stdio.h>
    
    //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;
    }

    Functions Arguments

    In a function in c, information is exchanged or passed by the means of argument or parameters. A function is called with an argument or without an argument in C.

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

    • Call by Value.
    • Call by Reference.

    Call by Value in C.

    In this method, the actual argument is copied to the formal parameter of the function. Hence any operation performed on the argument does not affect the actual parameters.

    1. Call by Value: In this method, the actual argument is copied to the formal parameter of the function. Hence any operation performed on the argument does not affect the actual parameters.

    2. Call by Reference: Unlike call by value method, here the address of the actual parameter is passed to a formal parameter rather than a value. Hence any operation performed on formal parameters affects the value of actual parameters.

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


  • C – Call by Value and Call by Reference with Example

    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

    Call by Value in C.

    In this method, the actual argument is copied to the formal parameter of the function. Hence any operation performed on the argument does not affect the actual parameters. By default, C programming uses call by value to pass arguments.

    Since the actual parameter is copied to formal parameters, different memory is allocated for both parameters.

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

    #include <stdio.h>
    
    //declaration
    void swap(int, int);
    
    int main()
    {
      int a = 100;
      int b = 500;
    
      printf("Before swapping the value of a = %d", a);
      printf("\nBefore swapping the value of b = %d\n", b);
    
      //Calling a function
      swap(a, b);
    
      printf("\nAfter swapping the value of a = %d", a);
      printf("\nAfter swapping the value of b = %d", b);
    }
    
    void swap(int a, int b)
    {
      int temp;
      temp = a;
      a = b;
      b = temp;
    
      //The values interchange here inside function
      //foraml parameters
      printf("\nAfter swapping values of a and b inside function: a = %d, b = %d\n", a, b);
    }

    The output of call by Value:

    Before swapping the value of a = 100
    Before swapping the value of b = 500
    
    After swapping values of a and b inside function: a = 500, b = 100
    
    After swapping the value of a = 100
    After swapping the value of b = 500

    Call by Reference.

    Unlike call by value method, here the address of the actual parameter is passed to a formal parameter rather than value. Hence any operation performed on formal parameters affects the value of actual parameters.

    The memory allocation for both actual and formal parameters are same in this method.

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

    #include <stdio.h>
    
    //declaration
    void swap(int *, int *);
    
    int main()
    {
      int a = 100;
      int b = 500;
    
      printf("Before swapping the value of a = %d", a);
      printf("\nBefore swapping the value of b = %d\n", b);
    
      //Calling a function
      swap(&a, &b);
    
      printf("\nAfter swapping the value of a = %d", a);
      printf("\nAfter swapping the value of b = %d", b);
    }
    
    void swap(int *a, int *b)
    {
      int temp;
      temp = *a;
      *a = *b;
      *b = temp;
    
      //The values interchange here inside function
      //foraml parameters
      printf("\nAfter swapping values of a and b inside function: a = %d, b = %d\n", *a, *b);
    }

    The output of call by Reference:

    Before swapping the value of a = 100
    Before swapping the value of b = 500
    
    After swapping values of a and b inside function: a = 500, b = 100
    
    After swapping the value of a = 100
    After swapping the value of b = 500

  • C – goto statement

    goto statement in c allows the user in the program to jump the execution to the labeled statement inside the function. The label (tag) is used to spot the jump statement.

    NOTE: Remember the use of goto is avoided in programming language because it makes 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 in C

    Syntax of goto statement:

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

    Example of goto statement in C Program.

    #include <stdio.h>
    
    void main()
    {
      int i = 1;
    
      label: do {
      if (i == 8)
      {
         //skip the iteration
          i++;
          goto label;
      }
    
      printf("Value of i: %d\n", i);
      i++;
      } while (i <= 10);
    }

    The output of continue statement.

    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: 7
    Value of i: 9
    Value of i: 10