Nested Functions in C

Introduction

We have already worked on this topic in our previous examples where we call functions made by us in the ‘main’ function. We can call a function inside other functions. Moreover, calling a user-defined function inside another user-defined function is also valid. These type of functions are called nested functions in C.

Example

#include<stdio.h>
int div_2 ( int x )
{
            if (x%2==0)
            {
                        return 1;
            }
            else
            {
                        return 0;
            }
}
int div_6 ( int y)
{
            if ( div_2(y)==1 && y%3==0 )
            {
                        printf("the number is divisible by 6.\n");
            }
            else
            {
                        printf("the number is not divisible by 6.\n");
            }
}
int main()
{
            int a;
            printf("enter a value to check divisibility with 6\n");
            scanf("%d",&a);
            div_6(a);
               return 0;
}

 

Output

Nested functions in c

Explanation

The goal of the above program is to check whether the input given by the user is divisible by 6 or not. As we know, a number is divisible by 6 if it is divisible by 2 and 3 both.

First, we made a function ‘div_2’, which takes an ‘int’ type parameter as an argument. It will return 1 if the condition (x%2==0) is true else 0.

Secondly, a function named ‘div_6’ is defined, which takes ‘y’ as an ‘int’ type parameter.

if ( div_2(y)==1 && y%3==0 ), Function call is made to ‘div_2’ function in this condition block. This ‘if’ statement having two different arguments, will return 1 only if both the arguments are true. If div_2(y)==1 returns 1, it means the number is divisible by 2, and if y%3==0 returns 1, it means ‘y’ is divisible by 3.

Since 93 is divisible by 3 but not by 2, it is also not divisible by 6.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.