C Program To Find First and Second Biggest Element In An Array using Recursion

Lets write a C program to find first and second biggest element/number in an array, without sorting it, and by using recursion.

Related Read:
Basics of Pointers In C Programming Language
Introduction To Arrays: C Programming Language

Important Video Tutorial
C Programming: Arrays, Pointers and Functions

Example: Expected Output

Enter 5 integer numbers
5
2
6
4
3
First Big: 6
Second Big: 5

Visual Representation

First and Second Biggest Element In An Array using Recursion

Video Tutorial: C Program To Find First and Second Biggest Element In An Array using Recursion


[youtube https://www.youtube.com/watch?v=UqNZrOZa9u0]

YouTube Link: https://www.youtube.com/watch?v=UqNZrOZa9u0 [Watch the Video In Full Screen.]

Source Code: C Program To Find First and Second Biggest Element In An Array using Recursion

#include<stdio.h>

#define N 5

void fsBig(int *num, int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*num > first)
        {
            second = first;
            first  = *num;
        }
        else if(*num > second && *num != first)
            second = *num;

        fsBig(--num, --n, first, second);
    }
}

int main()
{
    int a[N], i, first, second, count = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < N; i++)
    {
        if(a[i] != a[0])
        {
            ( (a[0] > a[i]) ?
              (first = a[0], second = a[i]) :
              (first = a[i], second = a[0]) );
            break;
        }
        else
            count++;
    }

    if(count == N)
    {
        printf("Biggest: %d\nSmallest: %d\n", a[0], a[0]);
        return 0;
    }

    fsBig(&a[N - 1], N - 1, first, second);

    return 0;
}

Output 1:
Enter 5 integer numbers
5
5
4
2
1
First Big: 5
Second Big: 4

Output 2:
Enter 5 integer numbers
5
5
5
5
5
Biggest: 5
Smallest: 5

Logic To Find First and Second Biggest Element In An Array using Recursion

We ask the user to enter N integer numbers and store it inside the address of array variable a[N]. Next we assign the biggest value between a[0] and a[1] to variable first and second biggest value to variable second. Then we pass the last elements address and length of the array and variables first and second to a function fsBig().

Inside function fsBig()

void fsBig(int *num, int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*num > first)
        {
            second = first;
            first  = *num;
        }
        else if(*num > second && *num != first)
            second = *num;

        fsBig(--num, --n, first, second);
    }
}

First we write the base condition or the termination condition: Once the length of the array or the variable n value is less than 2, we print the value present in variable fbig and sbig, and the control exits the function fsBig();

Note: We are checking till n < 2, because variables first and second already has values present at index 0 and 1, so need not compare them again against themselves.

Inside else block we write the actual logic to find the first and second biggest element in the array. First we check if the value present in pointer variable *num is greater than value present in variable fbig. If true, then there is a element which is bigger than fbig, that means, now whatever is present in fbig becomes second biggest element – so we transfer value present in fbig to sbig, and then transfer the new found biggest element of the array to variable fbig.

If a number is not greater than fbig, it can still be greater than sbig. So we check for that condition in else if. If its true, then we transfer the value of *num to sbig.

Recursive call
Next we call the same method fsBig() with new values. i.e., we reduce the address of num by 1, we reduce the value of index n by 1, and we pass the new values of fbig and sbig. This keeps on iterating until value of n is less than 2. Once the value of n is less than 2, the base condition is met and the control executes the printf() statement and exits the function fsBig().

Using array variable to receive base address from main method

#include<stdio.h>
#define N 5

void fsBig(int num[], int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(num[n] > first)
        {
            second = first;
            first  = num[n];
        }
        else if(num[n] > second && num[n] != first)
            second = num[n];

        fsBig(num, --n, first, second);
    }
}

int main()
{
    int a[N], i, first, second, count = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < N; i++)
    {
        if(a[i] != a[0])
        {
            ( (a[0] > a[i]) ?
              (first = a[0], second = a[i]) :
              (first = a[i], second = a[0]) );

             break;
        }
        else
            count++;
    }

    if(count == N)
    {
        printf("Biggest: %d\nSmallest: %d\n", a[0], a[0]);
        return 0;
    }

    fsBig(a, N - 1, first, second);

    return 0;
}

Output 1:
Enter 5 integer numbers
5
4
5
2
1
First Big: 5
Second Big: 4

Output 2:
Enter 5 integer numbers
5
5
4
4
2
First Big: 5
Second Big: 4

Here we do not alter the value of num while recursively calling the method fsBig(), as we compare with all the elements of the array by changing the value of index variable n.

Whenever we use array variable, compiler converts it to pointer as below

#include<stdio.h>

#define N 5

void fsBig(int num[], int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*(num + n) > first)
        {
            second = first;
            first  = *(num + n);
        }
        else if(*(num + n) > second && *(num + n) != first)
            second = *(num + n);

        fsBig(num, --n, first, second);
    }
}

int main()
{
    int a[N], i, first, second, count = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < N; i++)
    {
        if(a[i] != a[0])
        {
            ( (a[0] > a[i]) ?
              (first = a[0], second = a[i]) :
              (first = a[i], second = a[0]) );

             break;
        }
        else
            count++;
    }

    if(count == N)
    {
        printf("Biggest: %d\nSmallest: %d\n", a[0], a[0]);
        return 0;
    }

    fsBig(a, N - 1, first, second);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
5
5
First Big: 5
Second Big: 3

Whenever compiler encounters array variable like this a[i] or num[n] it converts it into *(a + i) and *(num + n).
i.e., Variable_name[array_index] = *(Base_address + array_index)
Note that, Variable_name holds Base_address. So Variable_name = Base_address.

Its faster to work with address than with variables. This example proves that arrays are pointers in disguise. i.e., arrays use pointers internally.

Explanation With Example

N = 5;
a[N] = {5, 4, 6, 2, 3};
first = 5;
second = 4;
n = N -1 = 5 – 1 = 4;

void fsBig(int num[], int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*(num + n) > first)
        {
            second = first;
            first  = *(num + n);
        }
        else if(*(num + n) > second && *(num + n) != first)
            second = *(num + n);

        fsBig(num, --n, first, second);
    }
}
nnum[n]–nfbigsbig
43354
32254
26165

First Big: 6
Second Big: 5

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Smallest Element in An Array using Recursion

Write a C program to find smallest element / number in an array using pointers and recursion.

We have covered both these logic in this video tutorial
1. Recursive function with no return type.
2. Recursive function with return type.

Related Read:
C Program To Find Smallest Element In An Array
Recursive Functions In C Programming Language
Basics of Pointers In C Programming Language
Introduction To Arrays: C Programming Language

Important Video Tutorial
C Programming: Arrays, Pointers and Functions

Example: Expected Output

Enter 5 integer numbers
5
2
6
4
3
Smallest Element In The Array: 2

Visual Representation

Smallest Element In An Array using Recursion

Video Tutorial: C Program To Find Smallest Element in An Array using Recursion


[youtube https://www.youtube.com/watch?v=sGGxml1TCBI]

YouTube Link: https://www.youtube.com/watch?v=sGGxml1TCBI [Watch the Video In Full Screen.]

Source Code: C Program To Find Smallest Element in An Array using Recursion

Method 1: With No Return Type

#include<stdio.h>

#define N 5

void smallest(int *num, int n, int small)
{
    if(n < 0)
        printf("Smallest Element In The Array: %d\n", small);
    else
    {
        if(small > *num)
            small = *num;

        smallest(++num, --n, small);
    }
}

int main()
{
    int a[N], i;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    smallest(a, N - 1, a[0]);

    return 0;
}

Output:
Enter 5 integer numbers
2
1
3
4
5
Smallest Element In The Array: 1

Logic To Find Smallest Element In An Array using Recursion

We ask the user to enter N integer numbers and store it inside array variable a[N]. We pass base address(address of first element in the array) of the array, which is present in &a[0] or a, and last index of the array(indicating size of the array, from index 0), and first element of the array(assuming first element itself as smallest element).

Inside Recursive function
Base Condition: This is the condition to terminate the recursive call. Here we check if the size of the array is less than zero. If it’s less than zero, then we display the value present inside variable small, which holds the smallest element in the array.

void smallest(int *num, int n, int small)
{
    if(n < 0)
        printf("Smallest Element In The Array: %d\n", small);
    else
    {
        if(small > *num)
            small = *num;

        smallest(++num, --n, small);
    }
}

We need to take a pointer variable to accept the base address. Next we’ll have base condition. If base condition isn’t met – we check if the value present in variable small is greater than value present at *num. If it’s true, then we transfer the value of *num to small. Next we increment the address of num by 1 and decrement the value of n by 1 and pass them to the same function(recursive call) along with the value of small. This is called recursive function call.

Once value of n is less than 0, we display the value of variable small, which holds the smallest element of the array.

Important Note:

1. Array elements are always stored in contiguous memory location.
2. A pointer when incremented always points to an immediately next location of its own type.

Source Code: Find Smallest Element of An Array using Recursion: With Return Value

Method 2: With Return Type

#include<stdio.h>

#define N 5

int smallest(int num[], int n, int small)
{
    if(n < 1)
        return small;
    else
    {
        if(num[n] < small)
            small = num[n];

        return smallest(num, --n, small);
    }
}

int main()
{
    int a[N], i;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    printf("Smallest Element In The Array: %d\n", smallest(a, N - 1, a[0]));

    return 0;
}

Output:
Enter 5 integer numbers
2
1
0
3
5
Smallest Element In The Array: 0

After repeatedly incrementing value of num and decrementing the value n, we’ll reach a point where value of n will be less than 0. That’s when all the comparisons end, and variable small will have smallest element of the array. This result will be returned to the calling function, which in turn returns the result to the calling function and so on ..until the result is returned to the first function call, which was from with in main method – where we print the value of variable small.

Source Code: Using Array Variable In Recursive Function

Find Smallest Element of An Array using Recursion

#include<stdio.h>

#define N 5

void smallest(int num[], int n, int small)
{
    if(n < 0)
        printf("Smallest Element In The Array: %d\n", small);
    else
    {
        if(small > num[n])
            small = num[n];

        smallest(num, --n, small);
    }
}

int main()
{
    int a[N], i;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    smallest(a, N - 1, a[0]);

    return 0;
}

Output:
Enter 5 integer numbers
1
0
2
-5
4
Smallest Element In The Array: -5

Here we are taking array variable to receive the base address. We keep checking if num[n] is smaller than value present at variable small. If true, then we transfer num[n] value to variable small, and then recursively call the same function by decrementing the value of n by 1, and also pass the new value of small.

Once the value of n is less than 0, we return the value present in variable small, which holds the smallest element of the array.

Explanation With Example

N = 5;
a[N] = {5, 2, 6, 4, 3};
n = N – 1 = 5 – 1 = 4;
num = a[0] = 5;
big = a[0] = 5;

smallest(num, --n, small);
nnum[n]small
433
343
263
122
052
-12

Smallest Element in the array: 2

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Biggest Element of An Array using Recursion

Write a C program to find biggest element / number in an array using pointers and recursion.

We have covered both these logic in this video tutorial
1. Recursive function with no return type.
2. Recursive function with return type.

Related Read:
C Program To Find Biggest Element of An Array
Recursive Functions In C Programming Language
Basics of Pointers In C Programming Language
Introduction To Arrays: C Programming Language

Important Video Tutorial
C Programming: Arrays, Pointers and Functions

Example: Expected Output

Enter 5 integer number
5
2
6
4
3
Biggest Element in the array: 6

Visual Representation

Biggest Element In An Array using Recursion

Video Tutorial: C Program To Find Biggest Element In An Array using Recursion


[youtube https://www.youtube.com/watch?v=-Cdp8QanJv8]

YouTube Link: https://www.youtube.com/watch?v=-Cdp8QanJv8 [Watch the Video In Full Screen.]

Source Code: Find Biggest Element of An Array using Recursion: With No Return Type

Method 1: With No Return Type

#include<stdio.h>

#define N 5

void biggest(int *num, int n, int big)
{
    if(n < 0)
        printf("Biggest element is %d\n", big);
    else
    {
        if(*num > big)
            big = *num;

        biggest(++num, --n, big);
    }
}

int main()
{
    int a[N], i;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    biggest(a, N - 1, a[0]);

    return 0;
}

Output:
Enter 5 integer number
1
2
3
4
5
Biggest Element in the array: 5

Logic To Find Biggest Element of An Array using Recursion

We ask the user to enter N integer numbers and store it inside array variable a[N]. We pass base address(address of first element in the array) of the array, which is present in &a[0] or a, and last index of the array(indicating size of the array, from index 0), and first element of the array(assuming first element itself as big).

Inside Recursive function
Base Condition: This is the condition to terminate the recursive call. Here we check if the size of the array is less than zero. If it’s less than zero, then we display the value present inside variable big, which holds the biggest element in the array.

void biggest(int *num, int n, int big)
{
    if(n < 0)
        printf("Biggest element is %d\n", big);
    else
    {
        if(*num > big)
            big = *num;

        biggest(++num, --n, big);
    }
}

We need to take a pointer variable to accept the base address. Next we’ll have base condition. If base condition isn’t met – we check if the value present in variable big is less than value present at *num. If it’s true, then we transfer the value of *num to big. Next we increment the address of num by 1 and decrement the value of n by 1 and pass them to the same function along with the value of big. This is called recursive function call.

Once value of n is less than 0, we display the value of variable big, which holds the biggest element of the array.

Important Note:

1. Array elements are always stored in contiguous memory location.
2. A pointer when incremented always points to an immediately next location of its own type.

Source Code: Find Biggest Element of An Array using Recursion: With Return Value

Method 2: With Return Type

#include<stdio.h>

#define N 5

int biggest(int *num, int n, int big)
{
    if(n < 0)
        return big;
    else
    {
        if(big < *num)
            big = *num;

        return biggest(++num, --n, big);
    }
}

int main()
{
    int a[N], i;

    printf("Enter %d integer number\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    printf("Biggest Element in the array: %d\n", biggest(a, N - 1, a[0]));

    return 0;
}

Output:
Enter 5 integer number
1
2
5
3
4
Biggest Element in the array: 5

After repeatedly incrementing value of num and decrementing the value n, we’ll reach a point where value of n will be less than 0. That’s when all the comparisons end, and variable big will have biggest element of the array. This result will be returned to the calling function, which in turn returns the result to the calling function and so on ..until the result is returned to the first function call, which was from with in main method – where we print the value of variable big.

Source Code: Using Array Variable In Recursive Function

Find Biggest Element of An Array using Recursion

#include<stdio.h>

#define N 5

int biggest(int num[], int n, int big)
{
    if(n < 0)
        return big;
    else
    {
        if(big < num[n])
            big = num[n];

        return biggest(num, --n, big);
    }
}

int main()
{
    int a[N], i;

    printf("Enter %d integer number\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    printf("Biggest Element in the array: %d\n", biggest(a, N - 1, a[0]));

    return 0;
}

Output:
Enter 5 integer number
10
56
83
978
4
Biggest Element in the array: 978

Here we are taking array variable to receive the base address. We keep checking if a[n] is biggest than value present at variable big. If true, then we transfer a[n] value to variable big, and then recursively call the same function by decrementing the value of n by 1, and also pass the new value of big.

Once the value of n is less than 0, we return the value present in variable big, which holds the biggest element of the array.

Explanation With Example

N = 5;
a[N] = {5, 2, 6, 4, 3};
n = N – 1 = 5 – 1 = 4;
num = a[0] = 5;
big = a[0] = 5;

biggest(num, --n, big);
nnum[n]big
435
345
266
126
056
-16

Biggest Element in the array: 6

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Count Digit k in Number n using Recursion

Lets write a C program to count the number of occurrences of digit k in user input positive integer number n, using recursion.

For Example:

If user inputs n = 12235, and k = 2, then our C program should find how many times digit 2 is present in number 12235.

Note: (num % 10) fetches last digit in num. If num = 1234; (num%10) fetches the last digit from right, which is 4.

(num/10) removes the last number from right. If num = 1234; (num/10) removes last digit i.e., 4 and the result of (num/10) will be 123.

Related Read:
C Program To Count Digit k in Number n

Video Tutorial: C Program To Count Digit k in Number n using Recursion


[youtube https://www.youtube.com/watch?v=sZhIRYXkquk]

YouTube Link: https://www.youtube.com/watch?v=sZhIRYXkquk [Watch the Video In Full Screen.]

Source Code: C Program To Count Digit k in Number n using Recursion

#include<stdio.h>

int occurrence(int, int);

int main()
{
    int n, k;

    printf("Enter a positive integer number\n");
    scanf("%d", &n);

    printf("Which digits occurrence you want to check for?\n");
    scanf("%d", &k);

    printf("\n%d has appeared %d times in %d.\n", k, occurrence(n, k), n);

    return 0;
}

int occurrence(int num, int k)
{
    if(num == 0)
        return 0;
    else if(k == (num%10))
        return(1 + occurrence(num/10, k));
    else
        return(occurrence(num/10, k));
}

Output:
Enter a positive integer number
12555
Which digits occurrence you want to check for?
5

5 has appeared 3 times in 12555.

Source Code: C Program To Count Digit k in Number n using Recursion and Ternary or Conditional Operator

#include<stdio.h>

int occurrence(int, int);

int main()
{
    int n, k;

    printf("Enter a positive integer number\n");
    scanf("%d", &n);

    printf("Which digits occurrence you want to check for?\n");
    scanf("%d", &k);

    printf("\n%d has appeared %d times in %d.\n", k, occurrence(n, k), n);

    return 0;
}

int occurrence(int num, int k)
{
    return( (num == 0)? 0 :
            (k == (num%10)) ?
            (1 + occurrence(num/10, k)) :
            (occurrence(num/10, k)));
}

Output:
Enter a positive integer number
155555061
Which digits occurrence you want to check for?
5

5 has appeared 5 times in 155555061.

To know more about Ternary or Conditional Operator visit:
Ternary Operator / Conditional Operator In C.

Logic To Count Digit k in Number n using Recursion

First we write the base condition i.e., if num is 0, then our function returns 0 to the calling function. Else if num%10 is equal to the value of k, then we return (1 + occurrence(num/10, k)). That way we count or increment by 1 for each time we found a digit which is equal to k, and then we reduce the num by one digit from right by doing num/10. k value will remain same throughout the program execution.

If num%10 is not equal to k, then we simply divide the num by 10, and reduce the value of num by one digit from right.

Example:

Lets assume that user input value for n and k:
n = 1223; k = 2;

n(n%10) == kcountn/10
1223False122
122True112
12True1+1=21
1False1+1=20

So, 2 appeared 2 times in 1223.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Sum of Squares of Digits using Recursion

Write a C program to find sum of squares of digits of a positive integer number input by the user, using recursive function.

Example:

If user inputs num value as 123. Then we fetch the individual digits present in 123 i.e., 3, 2 and 1, square it and add it to get the final result.

i.e., (3 x 3) + (2 x 2) + (1 x 1) = 14.

So, sum of squares of digits of 123 is 14.

Video Tutorial: C Program To Find Sum of Squares of Digits using Recursion


[youtube https://www.youtube.com/watch?v=7YaJ2pIkzKc]

YouTube Link: https://www.youtube.com/watch?v=7YaJ2pIkzKc [Watch the Video In Full Screen.]

Source Code: C Program To Find Sum of Squares of Digits using Recursion

#include<stdio.h>

int square(int num)
{
    if(num == 0)
        return 0;
    else
        return( (num%10) * (num%10) + square(num/10) );
}

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

Output:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Source Code: C Program To Find Sum of Squares of Digits using Recursion and pow() method

#include<stdio.h>
#include<math.h>

int square(int num)
{
    if(num == 0)
        return 0;
    else
        return( pow((num%10), 2) + square(num/10) );
}

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

Output:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Here we are making use of pow() method present inside math.h library file. pow() takes base value as first argument and exponent value as its second argument.

Source Code: C Program To Find Sum of Squares of Digits using Recursion, Ternary/Conditional Operator and pow() method

#include<stdio.h>
#include<math.h>

int square(int);

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

int square(int num)
{
    return( (num == 0) ? 0 : ( pow((num % 10), 2) + square(num/10) ));
}

Output 1:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Output 2:
Enter a positive integer number:
2103
Sum of squares of digits of 2103 is 14.

Output 3:
Enter a positive integer number:
456
Sum of squares of digits of 456 is 77.

Output 4:
Enter a positive integer number:
2020
Sum of squares of digits of 2020 is 8.

Output 5:
Enter a positive integer number:
2021
Sum of squares of digits of 2021 is 9.

To know more about Ternary or Conditional Operator visit:
Ternary Operator / Conditional Operator In C.

Dry Run: Example

Lets assume that user has input num value as 123.

num(num%10)2num/10(num%10)2+square(num/10)
123(3)2129+square(12)
12(2)214+square(1)
1(1)201+square(0)

Value Returning – Control Shifting back.

Return ValueToResult
return 0;square(0)1+0=1
1square(1)4+1=5
5square(12)9+5=14

So, sum of squares of digits of 123 is 14.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert