Author: saqibkhan

  • Return array from function

    Functions in C help the programmers to adapt modular program design. A function can be defined to accept one or more than one arguments, it is able to return a single value to the calling environment. However, the function can be defined to return an array of values. In C, a function can be made to return an array by one of following methods −

    • Passing the array as argument and returning the pointer
    • Declaring a static array in a function and returning its pointer
    • Using malloc() function

    Embedding the array inside a struct variable and passing it to a function

    We implement these methods to calculate the square, the cube and the square root of a given number.

    Pass array by reference

    In the following example, we declare an uninitialized array in main() and pass it to a function, along with an integer. Inside the function, the array is filled with the square, cube and square root. The function returns the pointer of this array, using which the values are access and printed in main() function.

    Example

    #include <stdio.h>#include <math.h>intarrfunction(int,float*);intmain(){int x=100;float arr[3];arrfunction(x, arr);printf("Square of %d: %f\n", x, arr[0]);printf("cube of %d: %f\n", x, arr[1]);printf("Square root of %d: %f\n", x, arr[2]);return0;}intarrfunction(int x,float*arr){
       arr[0]=pow(x,2);
       arr[1]=pow(x,3);
       arr[2]=pow(x,0.5);}

    Output

    Square of 100: 10000.000000
    cube of 100: 1000000.000000
    Square root of 100: 10.000000
    

    Return static array

    Instead of passing an empty array from main(), we can declare an array inside the called function itself, fill it with the required values, and return its pointer. However, returning a pointer of a local variable is not acceptable, as it points to a variable that no longer exists. Note that a local variable ceases to exist as soon as the scope of the function is over. Hence, we need to use a static array inside the called function (arrfunction) and return its pointer back to main().

    Example

    #include <stdio.h>#include <math.h>float*arrfunction(int);intmain(){int x=100, i;float*arr =arrfunction(x);printf("Square of %d: %f\n", x,*arr);printf("cube of %d: %f\n", x, arr[1]);printf("Square root of %d: %f\n", x, arr[2]);return0;}float*arrfunction(int x){staticfloat arr[3];
       arr[0]=pow(x,2);
       arr[1]=pow(x,3);
       arr[2]=pow(x,0.5);return arr;}

    Output

    Square of 100: 10000.000000
    cube of 100: 1000000.000000
    Square root of 100: 10.000000
    

    Now, consider the following function which will generate 10 random numbers and return them using an array and call this function as follows −

    Example

    #include <stdio.h>#include <time.h>#include <stdlib.h>/* function to generate and return random numbers */int*getRandom(){staticint  r[10];int i;/* set the seed */srand((unsigned)time(NULL));for( i =0; i <10;++i){
    
      r&#91;i]=rand();printf("r&#91;%d] = %d\n", i, r&#91;i]);}return r;}/* main function to call above defined function */intmain(){/* a pointer to an int */int*p;int i;
    p =getRandom();for( i =0; i <10; i++){printf("*(p + %d) : %d\n", i,*(p + i));}return0;}

    When the above code is compiled together and executed, it produces the following result −

    Output

    r[0] = 2110147662
    r[1] = 1427553496
    r[2] = 1243625529
    r[3] = 857484361
    r[4] = 513293736
    r[5] = 964923407
    r[6] = 36104419
    r[7] = 1248464892
    r[8] = 1838450240
    r[9] = 2096489563
    *(p + 0) : 2110147662
    *(p + 1) : 1427553496
    *(p + 2) : 1243625529
    *(p + 3) : 857484361
    *(p + 4) : 513293736
    *(p + 5) : 964923407
    *(p + 6) : 36104419
    *(p + 7) : 1248464892
    *(p + 8) : 1838450240
    *(p + 9) : 2096489563
    

    Using malloc() function

    The malloc() function is available as a library function in stdlib.h header file. It dynamically allocates a block of memory during the runtime of a program. Normal declaration of variables causes the memory to be allocated at the compile time.

    void*malloc(size_t size);

    The malloc() function returns a generic void pointer. To assign values of a certain data type in the allocated memory, it must be typecast to the required type. For example, to store an int data, it must be typecast to int * as follows −

    int*x =(int*)malloc(sizeof(int);

    Let us allocate a block of memory sufficient to store three float values corresponding to square, cube and square root of a number, and return the float pointer to main(), inside which the computed values are displayed.

    Example

    #include <stdio.h>#include <math.h>#include <stdlib.h>float*arrfunction(int);intmain(){int x=16, i;float*arr =arrfunction(x);printf("Square of %d: %f\n", x, arr[0]);printf("cube of %d: %f\n", x, arr[1]);printf("Square root of %d: %f\n", x, arr[2]);return0;}float*arrfunction(int x){float*arr =(float*)malloc(3*sizeof(float));
       arr[0]=pow(x,2);
       arr[1]=pow(x,3);
       arr[2]=pow(x,0.5);return arr;}

    Output

    Square of 16: 256.000000
    cube of 16: 4096.000000
    Square root of 16: 4.000000
    

    Using array element in struct

    In this method, we will declare a struct, inside which there is an float array as its element. The called function (myfunction) declares a struct variable, populates the array element with square, cube and the square root of the argument received by it, and returns it to the main() function.

    Example

    #include <stdio.h>#include <math.h>structmystruct{float arr[3];};structmystructmyfunction(int x);intmain(){int x =9;structmystruct s =myfunction(x);printf("Square of %d: %f\n", x, s.arr[0]);printf("cube of %d: %f\n", x, s.arr[1]);printf("Square root of %d: %f\n", x, s.arr[2]);return0;}structmystructmyfunction(int x){structmystruct s1;
       s1.arr[0]=pow(x,2);
       s1.arr[1]=pow(x,3);
       s1.arr[2]=pow(x,0.5);return s1;}

    Output

    Square of 9: 81.000000
    cube of 9: 729.000000
    Square root of 9: 3.000000
    

    Return string from function

    Using the same approaches, you can pass and return a string to a function. A string in C is an array of char type. In the following example, we pass the string with a pointer, manipulate it inside the function, and return it back to main().

    Inside the called function, there is a local string. The string passed is concatenated with the local string before returning.

    Example

    #include <stdio.h>#include <string.h>#include <stdlib.h>char*hellomsg(char*);intmain(){char* name ="TutorialsPoint";char*arr =hellomsg(name);printf("%s\n", arr);return0;}char*hellomsg(char*x){char*arr =(char*)malloc(50*sizeof(char));strcpy(arr,"Hello ");strcat(arr, x);return arr;}

    Output

    Hello TutorialsPoint
    
  • Passing Arrays as Function Arguments

    If you want to pass an array to a function, you can use either call by value or call by reference method. In call by value method, the argument to the function should be an initialized array, or an array of fixed size equal to the size of the array to be passed. In call by reference method, the function argument is a pointer to the array.

    Pass array with call by value method

    In the following code, the main() function has an array of integers. A user−defined function average () is called by passing the array to it. The average() function receives the array, and adds its elements using a for loop. It returns a float value representing the average of numbers in the array.

    Example

    #include <stdio.h>floataverage(int arr[5]);intmain(){int arr[]={10,34,21,78,5};float avg =average(arr);printf("average: %f", avg);}floataverage(int arr[5]){int sum=0;int i;for(i=0; i<5; i++){printf("arr[%d]: %d\n", i, arr[i]);
    
      sum+=arr&#91;i];}return(float)sum/5;}</code></pre>

    Output

    arr[0]: 10
    arr[1]: 34
    arr[2]: 21
    arr[3]: 78
    arr[4]: 5
    average: 29.600000
    

    In the following variation, the average() function is defined with two arguments, an uninitialized array without any size specified. The length of the array declared in main() function is obtained by divising the size of the array with the size of int data type.

    Example

    #include <stdio.h>floataverage(int arr[],int length);intmain(){int arr[]={10,34,21,78,5};int length =sizeof(arr)/sizeof(int);float avg =average(arr, length);printf("average: %f", avg);}floataverage(int arr[],int length){int sum=0;int i;for(i=0; i<length; i++){printf("arr[%d]: %d\n", i, arr[i]);
    
      sum+=arr&#91;i];}return(float)sum/length;}</code></pre>

    Output

    arr[0]: 10
    arr[1]: 34
    arr[2]: 21
    arr[3]: 78
    arr[4]: 5
    average: 29.600000
    

    Pass array with call by reference

    To use this approach, we should understand that elements in an array are of similar data type, stored in continuous memory locations, and the array size depends on the data type. Also, the address of the 0th element is the pointer to the array.

    In the following example −

    int a[5]={1,2,3,4,5};

    The size of the array is 20 bytes (4 bytes for each int)

    Int *x = a;

    Here x is the pointer to the array. It points to the 0th element. If the pointer is incremented by 1, it points to the next element.

    Example

    #include <stdio.h>intmain(){int a[]={1,2,3,4,5};int*x = a, i;for(i=0; i<5; i++){printf("%d\n",*x);
    
      x++;}return0;}</code></pre>

    Output

    1
    2
    3
    4
    5
    

    Let us use this characteristics for passing the array by reference. In the main() function, we declare an array and pass its address to the max() function. The max() function traverses the array using the pointer and returns the largest number in the array, back to main() function.

    Example

    #include <stdio.h>intmax(int*arr,int length);intmain(){int arr[]={10,34,21,78,5};int length =sizeof(arr)/sizeof(int);int maxnum =max(arr, length);printf("max: %d", maxnum);}intmax(int*arr,int length){int max=*arr;int i;for(i=0; i<length; i++){printf("arr[%d]: %d\n", i,(*arr));if((*arr)>max)
    
         max =(*arr);
      arr++;}return max;}</code></pre>

    Output

    arr[0]: 10
    arr[1]: 34
    arr[2]: 21
    arr[3]: 78
    arr[4]: 5
    max: 78
    

    The max() function receives the address of the array from main() in the pointer arr. Each time, when it is incremented, it points to the next element in the original array.

    The max() function can also access the array elements as a normal subscripted array as in the following definition −

    intmax(int*arr,int length){int max=*arr;int i;for(i=0; i<length; i++){printf("arr[%d]: %d\n", i, arr[i]);if(arr[i]>max)
    
         max = arr&#91;i];}return max;}</code></pre>

    Pass two−dimensional array to function

    You can also pass the pointer of a two-dimensional array to a function. Inside the function, the two dimensional array is traversed with a nested for loop construct

    Example

    #include <stdio.h>inttwoDarr(int*arr);intmain(){int arr[][3]={10,34,21,78,5,25};twoDarr(*arr);}inttwoDarr(int*arr){int max=*arr;int i, j;for(i=0; i<2; i++){for(j=0; j<3; j++){printf("%d\t", arr[i]);
    
         arr++;}printf("\n");}}</code></pre>

    Output

    10      34      21
    5       25      16
    

    Function to compare string lengths

    In the following program, two strings are passed to compare() functions. In C, as string is an array of char data type. We use strlen() function to find the length of string which is the number of characters in it.

    Example

    #include <stdio.h>#include <string.h>intcompare(char*,char*);intmain(){char  a[]="BAT";char  b[]="BALL";int ret =compare(a, b);return0;}intcompare(char*x,char*y){int val;if(strlen(x)>strlen(y)){printf("length of string a is greater than or equal to length of string b");}else{printf("length of string a is less than length of string b");}}

    Output

    length of string a is less than length of string b
    
  • Multi-dimensional Arrays

    The array is declared with one value of size in square brackets, it is called one dimensional array. In a one dimensional array, each element is identified by its index or subscript. In C, you can declare with more indices to simulate a two, three or multidimensional array.

    Multidimensional Arrays in C

    Multi-dimensional arrays can be termed as nested arrays. In such a case, each element in the outer array is an array itself. Such type of nesting can be upto any level. If each element in the outer array is another one-dimensional array, it forms a two-dimensional array. In turn, the inner array is an array of another set of one dimensional array, it is a three-dimensional array, and so on.

    Declaration of Multidimensional Arrays

    Depending on the nesting level, the multi-dimensional array is declared as follows −

    type name[size1][size2]...[sizeN];

    For example, the following declaration creates a three dimensional integer array −

    int threedim[3][3][3];

    A multidimensional array can have any number of dimensions. In this tutorial, we will learn about the two commonly used types of multidimensional arrays:

    1. Two-dimensional Array
    2. Three-dimensional Array

    Two-dimensional Array in C

    A two-dimensional array in an array of one-dimensional arrays. Each element of a two-dimensional array is an array itself. It is like a table or a matrix. The elements can be considered to be logically arranged in rows and columns. Hence, the location of any element is characterised by its row number and column number. Both row and column index start from 0.

    two_dimensional_arrays

    Declaration and Initialization of Two-dimensional Array

    The following statement declares and initializes a two-dimensional array −

    int arr[3][5]={1,2,3,4,5,10,20,30,40,50,5,10,15,20,25};

    The arr array has three rows and five columns. In C, a two dimensional array is a row−major array. The first square bracket always represents the dimension size of rows, and the second is the number of columns. Obviously, the array has 3 X 5 = 15 elements. The array is initialized with 15 comma−separated values put inside the curly brackets.

    Elements are read into the array in a row−wise manner, which means the first 5 elements are stored in first row, and so on. Hence, the first dimension is optional in the array declaration.

    int arr[][5]={1,2,3,4,5,10,20,30,40,50,5,10,15,20,25};

    To increase the readability, elements of each row can be optionally put in curly brackets as follows −

    int arr[][5]={{1,2,3,4,5},{10,20,30,40,50},{5,10,15,20,25}};

    The numbers are logically arranged in a tabular manner as follows −

    12345
    1020304050
    510152025

    The cell with row index 1 and column index 2 has 30 in it.

    Example of Printing Elements of Two-dimensional Array

    The program below displays the row and column indices of each element in a 2D array −

    #include <stdio.h>intmain(){/* an array with 5 rows and 2 columns*/int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};int i, j;/* output each array element's value */for( i =0; i <5; i++){for( j =0; j <2; j++){printf("a[%d][%d] = %d\n", i,j, a[i][j]);}}return0;}

    Output

    a[0][0] = 0
    a[0][1] = 0
    a[1][0] = 1
    a[1][1] = 2
    a[2][0] = 2
    a[2][1] = 4
    a[3][0] = 3
    a[3][1] = 6
    a[4][0] = 4
    a[4][1] = 8
    

    In case of a two or multi-dimensional array, the compiler assigns a memory block of the size which is the product of dimensions multiplied by the size of the data type. In this case, the size is 3 X 5 X 4 = 60 bytes, 4 being the size of int data type.

    Even though all the elements are stored in consecutive memory locations, we can print the elements in row and column format with the use of nested loops.

    Example of Printing Two-dimensional Array as Matrix in Row and Columns

    The following program prints a two-dimensional array in row and columns.

    #include <stdio.h>intmain(){int arr[3][5]={1,2,3,4,5,10,20,30,40,50,5,10,15,20,25};int i, j;for(i=0; i<3; i++){for(j=0; j<5; j++){printf("%4d", arr[i][j]);}printf("\n");}return0;}

    Output

       1   2   3   4   5
      10  20  30  40  50
       5  10  15  20  25
    

    Three-dimensional Array in C

    A three-dimensional array is an array of two-dimensional arrays, where each element is a two-dimensional array. A 3D array needs three subscripts to define depth, row, and column.

    Imagine the students appearing for an exam are seated in five halls, each hall having twenty rows of desks, and each row has 5 tables. Such an arrangement is represented by a three dimensional array such as −

    Students[hall][row][column]

    To locate each student, you need to have three indices, hall number, row and column of his table in the hall.

    Example of Three-dimensional Array

    The following program stores numbers in a 3 X 3 X 3 array −

    #include<stdio.h>intmain(){int i, j, k;int arr[3][3][3]={{{11,12,13},{14,15,16},{17,18,19}},{{21,22,23},{24,25,26},{27,28,29}},{{31,32,33},{34,35,36},{37,38,39}},};printf("Printing 3D Array Elements\n");for(i=0;i<3;i++){for(j=0;j<3;j++){for(k=0;k<3;k++){printf("%4d",arr[i][j][k]);}printf("\n");}printf("\n");}return0;}

    Output

    Printing 3D Array Elements
      11  12  13
      14  15  16
      17  18  19
    
      21  22  23
      24  25  26
      27  28  29
    
      31  32  33
      34  35  36
      37  38  39
    

    Row-wise Sum of Multidimensional Array’s Elements

    You can find the sum of all elements row-wise or column-wise by accessing the elements using indices. In the case of a three-dimensional array, you need to use depth, row, and column indices. And, in the case of a two-dimensional array, you need to use row and column indices. Here, we are using a two-dimensional array.

    Example: Row-wise Sum of Numbers

    In the following program, sum of integer elements in each row of a two-dimensional array is displayed.

    #include <stdio.h>intmain(){int arr[3][5]={{1,2,3,4,5},{10,20,30,40,50},{5,10,15,20,25}};int i, j;int sum;for(i=0; i<3; i++){
    
      sum=0;for(j=0; j&lt;5; j++){
         sum+=arr&#91;i]&#91;j];}printf("Sum of row %d: %d\n", i, sum);}return0;}</code></pre>

    Output

    Sum of row 0: 15
    Sum of row 1: 150
    Sum of row 2: 75
    

    Matrix Multiplication

    Matrix algebra is a branch of mathematics, where a matrix is a 2D array of numbers arranged in rows and columns. Multiplication of two matrices is possible only if the number of columns of the first matrix is equal to the number of rows of the second matrix. The product of two compatible matrices is equal to the dot products between rows of the first matrix and columns of the second matrix.

    If the two matrices are of size a[m][n] and b[p][q], the result of their multiplication is a matrix of the size (the multiplication is possible only if n is equal to p) is c[m][q].

    The product of two matrices, is the sum of the products across some row of matrix A with the corresponding entries down some column of matrix B.

    Example of Multiplication of Two-dimensional Array (Matrix)

    The following program performs the multiplication of two matrices.

    #include<stdio.h>intmain(){int mat1[3][3]={{2,4,1},{2,3,9},{3,1,8}};int mat2[3][3]={{1,2,3},{3,6,1},{2,4,7}};int mat3[3][3], sum=0, i, j, k;for(i=0; i<3; i++){for(j=0; j<3; j++){
    
         sum=0;for(k=0; k&lt;3; k++)
            sum = sum + mat1&#91;i]&#91;k]* mat2&#91;k]&#91;j];
         mat3&#91;i]&#91;j]= sum;}}printf("\nMatrix 1 ...\n");for(i=0; i&lt;3; i++){for(j=0; j&lt;3; j++)printf("%d\t", mat1&#91;i]&#91;j]);printf("\n");}printf("\nMatrix 2 ...\n");for(i=0; i&lt;3; i++){for(j=0; j&lt;3; j++)printf("%d\t", mat2&#91;i]&#91;j]);printf("\n");}printf("\nMultiplication of the two given Matrices: \n");for(i=0; i&lt;3; i++){for(j=0; j&lt;3; j++)printf("%d\t", mat3&#91;i]&#91;j]);printf("\n");}return0;}</code></pre>

    Output

    Matrix 1 ...
    2       4       1
    2       3       9
    3       1       8
    
    Matrix 2 ...
    1       2       3
    3       6       1
    2       4       7
    
    Multiplication of the two given Matrices:
    16      32      17
    29      58      72
    22      44      66
    
  • Properties of Array

    Arrays are a very important data structure in C. Use of array in C program makes it easier to handle large amount of data. Arrays have a number of advantages over singular variables as a result of their number of properties. Most of the important properties of array are a result of its composition − that an array is a collection of values of same data type, and in a continuous block of memory.

    Array properties may change in the different programming languages. In C programming language, the following are the main properties of arrays:

    • Collection of Same Data Type
    • Contiguous Memory Allocation
    • Fixed Size
    • Length Depends on Type
    • Indexing
    • Pointer Relationship
    • Lower and Upper Bounds
    • Multi-dimensional Array
    • Implementation of Complex Data Structures

    Let us discuss each property in detail.

    Collection of Same Data Type

    All elements of an array must be of the same data type. This ensures consistent access and operations on the data.

    If an array is declared as follows −

    int arr[]={50,67.55,"hello",21};

    Compiler issues a warning −

    initialization of 'int' from 'char *' makes integer from pointer without a cast 
    [-Wint-conversion]|

    Contiguous Memory Allocation

    All elements of an array are stored in contiguous memory locations, meaning they occupy a block of memory next to each other. This allows for efficient random access and memory management.

    Contiguous Memory Allocation

    Fixed Size

    The size of an array is fixed at the time of declaration and cannot be changed during the program’s execution. This means you need to know the maximum number of elements you need beforehand. In C, an array cannot have a size defined in terms of a variable.

    //This is accepted

    #define SIZE = 10int arr[SIZE];

    //This is also accepted

    const SIZE =10;int arr[SIZE];

    //This is not accepted

    int SIZE =10;int arr[SIZE];

    //The size must be an integer. This will give error

    float num[10.5]={50,55,67,73,45,21,39,70,49,51};

    Length Depends on Type

    Since an array can store all the elements of same type, the total memory occupied by it depends on the data type.

    Example

    #include<stdio.h>intmain(){int num[10]={50,55,67,73,45,21,39,70,49,51};int size =sizeof(num)/sizeof(int);printf("element at lower bound num[0]: %d \n", num[0]);printf("at upper bound: %d byte \n", num[size-1]);printf("length of int array: %ld \n",sizeof(num));double nm[10]={50,55,67,73,45,21,39,70,49,51};
       size =sizeof(nm)/sizeof(double);printf("element at lower bound nm[0]: %f \n", nm[0]);printf("element at upper bound: %f \n", nm[size-1]);printf("byte length of double array: %ld \n",sizeof(nm));return0;}

    Output

    element at lower bound num[0]: 50 
    at upper bound: 51 byte 
    length of int array: 40 
    element at lower bound nm[0]: 50.000000 
    element at upper bound: 51.000000 
    byte length of double array: 80
    

    Indexing

    Each element in an array has a unique index, starting from 0. You can access individual elements using their index within square brackets. Usually, array is traversed with a for loop running over its length and using the loop variable as the index.

    Example

    #include <stdio.h>intmain(){int a[]={1,2,3,4,5};int i;for(i=0; i<4; i++){printf("a[%d]: %d \n", i, a[i]);}return0;}

    Pointer Relationship

    The name of an array is equivalent to a constant pointer to its first element. This lets you use array names and pointers interchangeably in certain contexts.

    Example

    #include <stdio.h>intmain(){int num[10]={50,55,67,73,45,21,39,70,49,51};printf("num[0]: %d Address of 0th element: %d\n", num[0],&num[0]);printf("Address of array: %d", num);return0;}

    Output

    num[0]: 50 Address of 0th element: 6422000
    Address of array: 6422000
    

    Lower and Upper Bounds

    Each element in an array is identified by an index starting with 0. The lower bound of and array is the index of its first element, which is always 0. The last element in the array size -1 as its index.

    Example

    #include <stdio.h>intmain(){int num[10]={50,55,67,73,45,21,39,70,49,51};int size =sizeof(num)/sizeof(int);printf("element at lower bound num[0]: %d at upper bound: %d Size of array: %d", 
       num[0], num[size-1], size);return0;}

    Output

    element at lower bound num[0]: 50 at upper bound: 51 Size of array: 10
    

    Multi-dimensional Array

    The array is declared with one value of size in square brackets , it is called one dimensional array. In a one dimensional array, each element is identified by its index or subscript. In C, you can declare with more indices to simulate a two, three or multidimensional array.

    Example

    For example, following is the example of a two−dimensional array −

    int a[3][3]={{1,2,3},{11,22,33},{111,222,333}};

    You can think of a one dimensional array as a list, and a two dimensional array as a table or a matrix. Theoretically, there is no limit to the number of dimensions of an array, but in practice, two−dimensional arrays are used in design of spreadsheets, databases etc.

    Implementation of Complex Data Structures

    We can use an array in the construction of a struct data type to implement data structures such as stack, linked list and trees.

    Example

    typedefstructstack{int top;int arr[10];}  Stack;

    Thus, array is an important tool in the armoury of the programmer, as it can be used for different applications. The concept of array in C is implemented by many subsequent programming languages such as C++, C#, Java etc.

  • Arrays in C

    Arrays in C are a kind of data structure that can store a fixed-size sequential collection of elements of the same data type. Arrays are used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

    What is an Array in C?

    An array in C is a collection of data items of similar data type. One or more values same data type, which may be primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array. In C, the type of elements in the array should match with the data type of the array itself.

    The size of the array, also called the length of the array, must be specified in the declaration itself. Once declared, the size of a C array cannot be changed. When an array is declared, the compiler allocates a continuous block of memory required to store the declared number of elements.

    Why Do We Use Arrays in C?

    Arrays are used to store and manipulate the similar type of data.

    Suppose we want to store the marks of 10 students and find the average. We declare 10 different variables to store 10 different values as follows −

    int a =50, b =55, c =67,...;float avg =(float)(a + b + c +...)/10;

    These variables will be scattered in the memory with no relation between them. Importantly, if we want to extend the problem of finding the average of 100 (or more) students, then it becomes impractical to declare so many individual variables.

    Arrays offer a compact and memory-efficient solution. Since the elements in an array are stored in adjacent locations, we can easily access any element in relation to the current element. As each element has an index, it can be directly manipulated.

    Example: Use of an Array in C

    To go back to the problem of storing the marks of 10 students and find the average, the solution with the use of array would be −

    #include <stdio.h>intmain(){int marks[10]={50,55,67,73,45,21,39,70,49,51};int i, sum =0;float avg;for(i =0; i <=9; i++){
    
      sum += marks&#91;i];}
    avg =(float)sum /10;printf("Average: %f", avg);return0;}

    Output

    Run the code and check its output −

    Average: 52.000000
    

    Array elements are stored in contiguous memory locations. Each element is identified by an index starting with “0”. The lowest address corresponds to the first element and the highest address to the last element.

    Arrays

    Declaration of an Array in C

    To declare an array in C, you need to specify the type of the elements and the number of elements to be stored in it.

    Syntax to Declare an Array

    type arrayName[size];

    The “size” must be an integer constant greater than zero and its “type” can be any valid C data type. There are different ways in which an array is declared in C.

    Example: Declaring an Array in C

    In the following example, we are declaring an array of 5 integers and printing the indexes and values of all array elements −

    #include <stdio.h>intmain(){int arr[5];int i;for(i =0; i <=4; i++){printf("a[%d]: %d\n", i, arr[i]);}return0;}
    Output

    Run the code and check its output −

    a[0]: -133071639
    a[1]: 32767
    a[2]: 100
    a[3]: 0
    a[4]: 4096
    

    Initialization of an Array in C

    At the time of declaring an array, you can initialize it by providing the set of comma-separated values enclosed within the curly braces {}.

    Syntax to Initialize an Array

    data_type array_name [size]={value1, value2, value3,...};

    Example to Initialize an Array

    The following example demonstrates the initialization of an integer array:

    // Initialization of an integer array#include <stdio.h>intmain(){int numbers[5]={10,20,30,40,50};int i;// loop counter// Printing array elementsprintf("The array elements are : ");for(i =0; i 
    Output
    The array elements are :1020304050
    
    Example of Initializing all Array Elements to 0
    To initialize all elements to 0, put it inside curly brackets
    #include <stdio.h>intmain(){int arr[5]={0};int i;for(i =0; i <=4; i++){printf("a[%d]: %d\n", i, arr[i]);}return0;}
    
    Output
    When you run this code, it will produce the following output −
    a[0]:0
    a[1]:0
    a[2]:0
    a[3]:0
    a[4]:0
    
    Example of Partial Initialization of an Array
    If the list of values is less than the size of the array, the rest of the elements are initialized with "0".#include <stdio.h>intmain(){int arr[5]={1,2};int i;for(i =0; i <=4; i++){printf("a[%d]: %d\n", i, arr[i]);}return0;}
    
    Output
    When you run this code, it will produce the following output −
    a[0]:1
    a[1]:2
    a[2]:0
    a[3]:0
    a[4]:0
    
    Example of Partial and Specific Elements Initialization
    If an array is partially initialized, you can specify the element in the square brackets.#include <stdio.h>intmain(){int a[5]={1,2,[4]=4};int i;for(i =0; i <=4; i++){printf("a[%d]: %d\n", i, a[i]);}return0;}
    
    Output
    On execution, it will produce the following output −
    a[0]:1
    a[1]:2
    a[2]:0
    a[3]:0
    a[4]:4
    
    Getting Size of an Array in C
    The compiler allocates a continuous block of memory. The size of the allocated memory depends on the data type of the array.
    Example 1: Size of Integer Array
    If an integer array of 5 elements is declared, the array size in number of bytes would be "sizeof(int) x 5"#include <stdio.h>intmain(){int arr[5]={1,2,3,4,5};printf("Size of array: %ld",sizeof(arr));return0;}
    
    Output
    On execution, you will get the following output −
    Size of array:20
    
    The sizeof operator returns the number of bytes occupied by the variable.
    Example 2: Adjacent Address of Array Elements
    The size of each int is 4 bytes. The compiler allocates adjacent locations to each element.#include <stdio.h>intmain(){int a[]={1,2,3,4,5};int i;for(i =0; i <4; i++){printf("a[%d]: %d \t Address: %d\n", i, a[i],&a[i]);}return0;}
    
    Output
    Run the code and check its output −
    a[0]:1 	 Address:2102703872
    a[1]:2 	 Address:2102703876
    a[2]:3 	 Address:2102703880
    a[3]:4 	 Address:2102703884
    
    In this array, each element is of int type. Hence, the 0th element occupies the first 4 bytes 642016 to 19. The element at the next subscript occupies the next 4 bytes and so on.
    Example 3: Array of Double Type
    If we have the array type of double type, then the element at each subscript occupies 8 bytes
    #include <stdio.h>intmain(){double a[]={1.1,2.2,3.3,4.4,5.5};int i;for(i =0; i <4; i++){printf("a[%d]: %f \t Address: %ld\n", i, a[i],&a[i]);}return0;}
    
    Output
    Run the code and check its output −
    a[0]:1.100000 	 Address:140720746288624
    a[1]:2.200000 	 Address:140720746288632
    a[2]:3.300000 	 Address:140720746288640
    a[3]:4.400000 	 Address:140720746288648
    
    Example 4: Size of Character Array
    The length of a "char" variable is 1 byte. Hence, a char array length will be equal to the array size.#include <stdio.h>intmain(){char a[]="Hello";int i;for(i=0; i<5; i++){printf("a[%d]: %c address: %ld\n", i, a[i],&a[i]);}return0;}
    
    Output
    Run the code and check its output −
    a[0]: H address:6422038
    a[1]: e address:6422039
    a[2]: l address:6422040
    a[3]: l address:6422041
    a[4]: o address:6422042
    
    Accessing Array Elements in C
    Each element in an array is identified by a unique incrementing index, stating with "0". To access the element by its index, this is done by placing the index of the element within square brackets after the name of the array. 
    The elements of an array are accessed by specifying the index(offset) of the desired element within the square brackets after the array name. For example −
    double salary = balance[9];
    
    The above statement will take the 10th element from the array and assign the value to the "salary".
    Example to Access Array Elements in C
    The following example shows how to use all the three above-mentioned concepts viz. declaration, assignment, and accessing arrays.#include <stdio.h>intmain(){int n[5];/* n is an array of 5 integers */int i, j;/* initialize elements of array n to 0 */for(i =0; i <5; i++){
    
      n&#91;i]= i +100;}/* output each array element's value */for(j =0; j &lt;5; j++){printf("n&#91;%d] = %d\n", j, n&#91;j]);}return0;}
    Output On running this code, you will get the following output − n[0]=100 n[1]=101 n[2]=102 n[3]=103 n[4]=104 The index gives random access to the array elements. An array may consist of structvariables, pointers and even other arrays as its elements. More on C Arrays Arrays, being an important concept in C, need a lot more attention. The following important concepts related to arrays should be clear to a C programmer − Sr.No Concept & Description 1 Multi-dimensional arrays C supports multidimensional arrays. The simplest form of an multidimensional array is the two-dimensional array.2 Passing arrays to functions You can pass to the function a pointer to an array by specifying the array's name without an index.3 Return array from a function C allows a function to return an array.4 Pointer to an array You can generate a pointer to the first element of an array by simply specifying the array name, without any index.

    Print Page

  • Global Variables

    Global Variables

    In C programming language, the global variables are those variables that are defined outside all functions, usually at the top of a program. Global variables hold their values throughout the lifetime of a program, and they can be accessed inside any of the functions defined for the program.

    If a function accesses and modifies the value of a global variable, then the updated value is available for other function calls.

    If a variable is defined in a certain file, then you can still access it inside another code module as a global variable by using the extern keyword. The extern keyword can also be used to access a global variable instead of a local variable of the same name.

    Declaring Global Variable

    The declaration of a global variable in C is similar to the declaration of the normal (local) variables but global variables are declared outside of the functions.

    Syntax

    Consider the following syntax to declare a global variable:

    data_type variable_name;// main or any functionintmain(){}

    Example of Global Variable in C

    The following program shows how global variables are used in a program:

    #include <stdio.h>/* global variable declaration */int g =10;intmain(){/* local variable declaration */int a;/* actual initialization */
       a = g *2;printf("Value of a = %d, and g = %d\n", a, g);return0;}

    Output

    When you run this code, it will produce the following output −

    Value of a = 20, and g = 10
    

    Accessing Global Variables

    Global variables are accessible in all the functions in a C program. If any function updates the value of a global variable, then its updated value will subsequently be available for all the other functions.

    Example

    The following example demonstrates the example of accessing global variables in C language:

    #include <stdio.h>/* global variable declaration */int g =10;intfunction1();intfunction2();intmain(){printf("Value of Global variable g = %d\n", g);function1();printf("Updated value of Global variable g = %d\n", g);function2();printf("Updated value of Global variable g = %d\n", g);return0;}intfunction1(){
       g = g +10;printf("New value of g in function1(): %d\n", g);return0;}intfunction2(){printf("The value of g in function2(): %d\n", g);
       g = g +10;return0;}

    Run the code and check its output −

    Value of Global variable g = 10
    New value of g in function1(): 20
    Updated value of Global variable g = 20
    The value of g in function2(): 20
    Updated value of Global variable g = 30
    

    Scope and Accessibility of Global Variables

    Global variables are available to only those functions that are defined after their declaration. Global variables are declared outside of any function, so they can be accessed by all functions within the same file by default.

    Example

    In this example, we declared a global variable (x) before the main() function. There is another global variable y that is declared after the main() function but before function1(). In such a case, the variable y, even thought it is a global variable, is not available for use in the main() function, as it is declared afterwards. As a result, you get an error.

    #include <stdio.h>/* global variable declaration */int x =10;intfunction1();intmain(){printf("value of Global variable x= %d y=%d\n", x, y);function1();return0;}int y =20;intfunction1(){printf("Value of Global variable x = %d y = %d\n", x, y);}

    When you run this code, it will produce an error −

    Line no 11: error: 'y' undeclared (first use in this function)
       11 | printf ("Value of Global variable x = %d y = %d\n", x, y);
    
      |                                                     ^

    Accessing Global Variables With extern Keyword

    If you want to access a global variable when a local variable with same name is also there in the program, then you should use the extern keyword.

    Example

    In this C Program, we have a global variable and a local variable with the same name (x). Now, let’s see how we can use the keyword “extern” to avoid confusion −

    #include <stdio.h>// Global variable xint x =50;intmain(){// Local variable xint x =10;{externint x;printf("Value of global x is %d\n", x);}printf("Value of local x is %d\n", x);return0;}

    Output

    When you run this code, it will produce the following output −

    Value of global x is 50
    Value of local x is 10
    

    Avoid Using Global Variables

    Global variables can simplify the programming logic. They can be accessed across functions, and you need not use a parameter-passing technique to pass variables from one function to another. However, it is not wise or efficient to have too many global variables in a C program, as the memory occupied by these variables is not released till the end of the program.

    Using global declaration is not considered a good programming practice because it doesn’t implement a structured approach. Global declarations are also not advised from a security point of view, as they are accessible to all the functions. Finally, using global declarations can make a program difficult to debug, maintain, and scale up.

  • Static Variables

    By default, a C variable is classified as an auto storage type. A static variable is useful when you want to preserve a certain value between calls to different functions. Static variables are also used to store data that should be shared between multiple functions.

    Static Variables

    The static variables belong to the static storage class, they are initialized only once and preserve the values till the end of the program, The static keyword is used to declare the static variables.

    Features of Static Variables

    The following are some of the features of static variables in C programming language −

    • The compiler allocates space to a static variable in the computers main memory.
    • Unlike auto, a static variable is initialized to zero and not garbage.
    • A static variable is not re-initialized on every function call, if it is declared inside a function.
    • A static variable has local scope.

    Declare a Static Variable

    To declare a static variable in C language, use the static keyword and assign the initial value. Following is the syntax to declare a static variable:

    static datatype var = value;

    Here,

    • datatype represents the type of variable like int, char, float, etc.
    • var is the name of variable given by user.
    • value is any value given to initialize the variable. By default, it is zero.

    Examples of Static Variables in C

    Example: Using Static Variable

    Here is an example of how you can use a static variable in C language −

    #include <stdio.h>intmain(){autoint a =-28;staticint b =8;printf("The value of auto variable: %d\n", a);printf("The value of static variable b: %d\n",b);if(a !=0)printf("The sum of static variable and auto variable: %d\n",(b+a));return0;}

    Output

    When you run this code, it will produce the following output −

    The value of auto variable: -28
    The value of static variable b: 8
    The sum of static variable and auto variable: -20
    

    Example: Create Counter Function W/O Using Static Variable

    In this example, x is an auto variable by default and initialized to 0 every time when the counter() function is called. On each subsequent call, it gets re-initialized.

    #include <stdio.h>intcounter();intmain(){counter();counter();counter();return0;}intcounter(){int x;printf("Value of x as it enters the function: %d\n", x);
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    Run the code and check its output −

    Value of x as it enters the function: 0
    Incremented value of x: 1
    Value of x as it enters the function: 0
    Incremented value of x: 1
    Value of x as it enters the function: 0
    Incremented value of x: 1
    

    However, when the variable x in the counter() function is declared as static, it is initialized to “0” when the counter() function is called for the first time. On each subsequent call, it is not re-initialized. Instead, it retains the earlier value.

    Example: Create Counter Using Static Variable

    Change the declaration of “x” to “static int x = 0;” and run the program again −

    #include <stdio.h>intcounter();intmain(){counter();counter();counter();return0;}intcounter(){staticint x =0;printf("Value of x as it enters the function: %d\n", x);
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    Now, when you run this code, it will produce the following output −

    Value of x as it enters the function: 0
    Incremented value of x: 1
    Value of x as it enters the function: 1
    Incremented value of x: 2
    Value of x as it enters the function: 2
    Incremented value of x: 3
    

    Passing Static Variable to Function

    You can pass a static variable to a function. However, a formal parameter cannot be declared as static, as C uses the function parameters as local auto variables inside a function.

    Example

    In this code, we pass a static variable to a function. However, the change in its value is not reflected in the calling function.

    #include <stdio.h>intmyfunction(int x);intmain(){staticint x =5;myfunction(x);printf("in main - x:%d\n", x);return0;}intmyfunction(int x){
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    Run the coce and check its output −

    Incremented value of x: 6
    in main - x:5
    

    Similarities Between Static and Global Variables

    A static variable has certain similarities with a global variable. Both of them, if not explicitly initialized, both are initialized to “0” (for numeric types) or “null pointers” (for pointers).

    The scope of a static variable is restricted to the function or the block in which it is declared. This is unlike a global variable, which is accessible throughout the program. Also, a static variable can be imported in another code file, as we do by using the extern keyword.

    Example

    You can declare a global variable as static too. Take a look at the following example −

    #include <stdio.h>intmyfunction();staticint x =5;intmain(){myfunction(x);printf("Inside the main function, x: %d\n", x);return0;}intmyfunction(){
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    When you run this code, it will produce the following output −

    Incremented value of x: 6
    Inside the main function, x: 6
    

    It is better to use static variables to be accessible only within a file. On the other hand, use global (with extern) variables to be accessible from anywhere in a program (if declared extern in other files).

  • Scope Rules

    A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language −

    • Inside a function or a block which is called local variables.
    • Outside of all functions which is called global variables.
    • In the definition of function parameters which are called formal parameters.

    Let us understand what are local and global variables, and formal parameters.

    Local Variables

    Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own.

    Example

    The following example shows how local variables are used. Here all the variables a, b, and c are local to main() function.

    #include <stdio.h>intmain(){/* local variable declaration */int a, b;int c;/* actual initialization */
      a =10;
      b =20;
      c = a + b;printf("value of a = %d, b = %d and c = %d\n", a, b, c);return0;}

    Global Variables

    Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.

    A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.

    Example

    The following program show how global variables are used in a program.

    #include <stdio.h>/* global variable declaration */int g;intmain(){/* local variable declaration */int a, b;/* actual initialization */
      a =10;
      b =20;
      g = a + b;printf("value of a = %d, b = %d and g = %d\n", a, b, g);return0;}

    A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an example −

    Example

    #include <stdio.h>/* global variable declaration */int g =20;intmain(){/* local variable declaration */int g =10;printf("value of g = %d\n",  g);return0;}

    When the above code is compiled and executed, it produces the following result −

    value of g = 10
    

    Formal Parameters

    Formal parameters, are treated as local variables with-in a function and they take precedence over global variables. Following is an example −

    Example

    #include <stdio.h>/* global variable declaration */int a =20;intmain(){/* local variable declaration in main function */int a =10;int b =20;int c =0;printf("value of a in main() = %d\n",  a);
      c =sum( a, b);printf("value of c in main() = %d\n",  c);return0;}/* function to add two integers */intsum(int a,int b){printf("value of a in sum() = %d\n",  a);printf("value of b in sum() = %d\n",  b);return a + b;}

    When the above code is compiled and executed, it produces the following result −

    value of a in main() = 10
    value of a in sum() = 10
    value of b in sum() = 20
    value of c in main() = 30
    

    Initializing Local and Global Variables

    When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −

    Data TypeInitial Default Value
    int0
    char‘\0’
    float0
    double0
    pointerNULL

    It is a good programming practice to initialize variables properly, otherwise your program may produce unexpected results, because uninitialized variables will take some garbage value already available at their memory location.

  • Predefined Identifier __func__

    The predefined identifier __func__ in C programming is a special identifier introduced in the C99 standard. It provides the name of the current function as a string literal, making error tracking and debugging more convenient.

    Debugging and logging frequently require identifying where an issue occurs in the code. To simplify the process, the C99 standard introduced the predefined identifier __func__.

    A Simple Example of Using __func__ in a C Program

    Before we start discussing __func__ in detail, let us write a sample program and predict its output. The following C program to shows a glimpse of how the Predefined Identifier __func__ works −

    #include <stdio.h>intmain(){// %s read the stringprintf("%s",__func__);return0;}

    When you run this code, it will produce the following output −

    main
    

    The predefined identifier “__func__” represents the name of the current function as a string. Inside main(), it expands to “main“, so the program prints the function’s name.

    What is __func__ ?

    __func__ is a predefined identifier which is automatically available inside every function. It expands to a const char[] containing the name of the current function.

    staticconstchar__func__[]="function-name";

    Unlike other predefined macros such as __FILE__ or __LINE__, __func__ is not a macro, but rather a predefined identifier.

    Here is its syntax. It can be used directly inside any function to gets its name as a string.

    __func__

    Example: Basic Usages

    In this example, we use the __func__ identifier to display the function name −

    #include <stdio.h>voidgreet(){printf("Currently in function: %s\n",__func__);}intmain(){printf("Currently in function: %s\n",__func__);greet();return0;}

    Following is the output of the above code −

    Currently in function: main
    Currently in function: greet
    

    Error Logging with __func__

    Error logging is the process of recording information about error, warning, or unusual behavior that occurs while a program is running.

    Rather than terminating execution or displaying a general error message, programs log the details of the error in a file, console, or logging system. This information helps developers in determining what and where the error occurred.

    Example: Error Logging with __func__

    In this example, we use __func__ to log error details on the console −

    #include <stdio.h>#define LOG_ERROR(msg) \
       printf("Error in function %s: %s\n", __func__, msg)voiddisplayData(int x){if(x <0){LOG_ERROR("Negative value not allowed");return;}printf("Processing value: %d\n", x);}intmain(){displayData(10);displayData(-5);return0;}

    Here is its output −

    Processing value: 10
    Error in function displayData: Negative value not allowed
    

    Key Features of __func__

    Given below are some of the key features of __func__ −

    • Automatic Availability − It is built into the language. There is no need to include the header file for it.
    • Function Scope − Available only inside the function in which it appears.
    • String Literal − Represents the function name as a const char[].
    • Debugging Friendly − Often used in logging systems to report the exact function where an error occurs.

    Conclusion

    The predefined identifier __func__, introduced in the C99 standard, provides the name of the current function as a string literal. It is a basic but effective feature that improves debugging, error logging, and program monitoring by allowing developers to quickly identify the code where an error occurred.

  • Recursion

    Recursion is the process by which a function calls itself. C language allows writing of such functions which call itself to solve complicated problems by breaking them down into simple and easy problems. These functions are known as recursive functions.

    What is a Recursive Function in C?

    A recursive function in C is a function that calls itself. A recursive function is used when a certain problem is defined in terms of itself. Although it involves iteration, using iterative approach to solve such problems can be tedious. Recursive approach provides a very concise solution to seemingly complex problems.

    Syntax

    This is how a general recursive function looks like −

    voidrecursive_function(){recursion();// function calls itself}intmain(){recursive_function();}

    While using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.

    Why Recursion is Used in C?

    Recursion is used to perform complex tasks such as tree and graph structure traversals. Popular recursive programming solutions include factorial, binary search, tree traversal, tower of Hanoi, eight queens problem in chess, etc.

    A recursive program becomes concise, it is not easily comprehendible. Even if the size of the code may reduce, it needs more resources of the processor, as it involves multiple IO calls to the function.

    Factorial Using Recursion

    Recursive functions are very useful to solve many mathematical problems such as calculating the factorial of a number, generating Fibonacci series, etc.

    The most popular example of recursion is calculation of factorial. Mathematically, a factorial is defined as −

     
    n!= n X(n-1)!

    It can be seen that we use factorial itself to define factorial. Hence this is a fit case to write a recursive function. Let us expand the above definition for calculating the factorial value of 5.

    5!=5 X 4!5 X 4 X 3!5 X 4 X 3 X 2!5 X 4 X 3 X  2 X 1!5 X 4 X 3 X  2 X 1=120

    While we can perform this calculation using a loop, its recursive function involves successively calling it by decrementing the number till it reaches 1.

    Example: Non-Recursive Factorial Function

    The following program shows how you can use a non-recursive function to calculate the factorial of a number −

    #include <stdio.h>#include <math.h>// function declarationintfactorial(int);intmain(){int a =5;int f =factorial(a);printf("a: %d \n", a);printf("Factorial of a: %d", f);}intfactorial(int x){int i;int f =1;for(i =5; i >=1; i--){
    
      f *= i;}return f;}</code></pre>

    Output

    When you run this code, it will produce the following output −

    a: 5 
    Factorial of a: 120
    

    Example: Recursive Factorial Function

    Let us now write a recursive function for calculating the factorial of a given number.

    The following example calculates the factorial of a given number using a recursive function −

    #include <stdio.h>#include <math.h>/* function declaration */intfactorial(int i){if(i <=1){return1;}return i *factorial(i -1);}intmain(){int a =5;int f =factorial(a);printf("a: %d \n", a);printf("Factorial of a: %d", f);return0;}

    Output

    Run the code and check its output −

    a: 5 
    Factorial of a: 120
    

    When the main() function calls the factorial() function by passing the variable "a", its value is stored in "i". The factorial() function successively calls itself.

    In each call, the value of "i" is multiplied by its earlier value after reducing it by 1, till it reaches 1. As it reaches 1, the product of all the values between the initial value of the argument and 1 is returned to the main() function.

    Binary Search Using Recursion

    Let us have a look at another example to understand how recursion works. The problem at hand is to check whether a given number is present in an array.

    While we can perform a sequential search for a certain number in the list using a for loop and comparing each number, the sequential search is not efficient, especially if the list is too long.

    The binary search algorithm checks if the index "start" is greater than the index "end". Based on the value present at the variable "mid", the function is called again to search for the element.

    We have a list of numbers arranged in ascending order. Then we find the midpoint of the list and restrict the checking to either left or right of the midpoint, depending on whether the desired number is less than or greater than the number at the midpoint.

    Example: Recursive Binary Search

    The following code implements the recursive binary searching technique −

    #include <stdio.h>intbSearch(int array[],int start,int end,int element){if(end >= start){int mid = start +(end - start )/2;if(array[mid]== element)return mid;if(array[mid]> element)returnbSearch(array, start, mid-1, element);returnbSearch(array, mid+1, end, element);}return-1;}intmain(void){int array[]={5,12,23,45,49,67,71,77,82};int n =9;int element =67;int index =bSearch(array,0, n-1, element);if(index ==-1){printf("Element not found in the array ");}else{printf("Element found at index: %d", index);}return0;}

    Output

    Run the code and check its output −

    Element found at index: 5
    

    Fibonacci Series Using Recursion

    In Fibonacci series, a number is the sum of its previous two numbers. To generate Fibonacci series, the ith number is the addition of i−1 and i−2.

    Example

    The following example generates the first 10 numbers in the Fibonacci series for a given number using a recursive function −

    #include <stdio.h>intfibonacci(int i){if(i ==0){return0;}if(i ==1){return1;}returnfibonacci(i-1)+fibonacci(i-2);}intmain(){int i;for(i =0; i <10; i++){printf("%d\t\n",fibonacci(i));}return0;}

    Output

    When the above code is compiled and executed, it produces the following result −

    0	
    1	
    1	
    2	
    3	
    5	
    8	
    13	
    21	
    34
    

    Implementing recursion in a program is difficult for beginners. While any iterative process can be converted in a recursive process, not all cases of recursion can be easily expressed iteratively.