Skip to main content

Practical-09

Write a program which explains the use of nesting of functions.

Introduction

In this program, we will learn to write a program which explains the use of nesting of functions.

Algorithm

  1. Start
  2. Declare a function to calculate square of a number.
  3. Declare a function to calculate cube of a number.
  4. Take input from user and store it in number.
  5. Call the square function to calculate the square of the given number.
  6. Call the cube function to calculate the cube of the given number.
  7. Print the square and cube of the given number.
  8. End

Code

Practical-09.c

/* Program to demonstrate nesting of functions */

#include <stdio.h>

// define a function to calculate square of a number
int square(int num)
{
int result = num*num;
return result;
}

// define a function to calculate cube of a number
int cube(int num)
{
// calling another function within this function
int result = square(num)*num;
return result;
}

void main()
{
int number = 5; //take number as input
int result1 = square(number);
int result2 = cube(number);

// print square and cube of the number
printf("Square of %d is %d\n", number, result1);
printf("Cube of %d is %d\n", number, result2);


}

Output

Square of 5 is 25
Cube of 5 is 125
Explanation

In this program, we have defined two functions, square and cube. The square function calculates the square of a number and returns the result. The cube function calculates the cube of a number and returns the result. The cube function calls the square function within it. The main function calls the square and cube functions and prints the result.