Smaller Example


Explanation

A user-defined function can return a value after performing a comparison. In this program, the smallest() function accepts three numbers as parameters and returns the smallest number using the if-else if statement. The returned value is stored in a variable and displayed using printf().

How It Works?

  • Step 1: Create a user-defined function smallest(int a, int b, int c) that accepts three integer values.
  • Step 2: Declare the variable s to store the smallest number.
  • Step 3: Compare the three numbers using the if-else if statement.
  • Step 4: Store the smallest number in s.
  • Step 5: Return the value of s using the return statement.
  • Step 6: In the main() function, call the smallest() function with different values.
  • Step 7: Store the returned value in variables and display the result.

Example Program


#include <stdio.h>
#include <conio.h>

int smallest(int a, int b, int c)
{

    int s;

    if(a < b && a < c)
    {

        s = a;

    }

    else if(b < a && b < c)
    {

        s = b;

    }

    else
    {

        s = c;

    }

    return s;

}

int main()
{

    int a, b;

    clrscr();

    a = smallest(3, 6, 9);

    printf("\n %d", a);

    b = smallest(15, 16, 19);

    printf("\n %d", b);

    getch();

}

Output

3
15

Practice Exercises

Task 1: Write a C program using a user-defined function smallest() that accepts three numbers and returns the smallest number. Call the function twice with different values and display the returned result.

Goal: Learn how to create a function that returns a value and use the if-else if statement to find the smallest of three numbers.

💡 Hint: Create a function smallest(int a, int b, int c). Compare the three numbers using if-else if, return the smallest number, store the returned value in a variable, and display it using printf().
💡 Show Solution

#include<stdio.h>
#include<conio.h>

int smallest(int a, int b, int c)
{
    int s;

    if(a < b && a < c)
    {
        s = a;
    }
    else if(b < a && b < c)
    {
        s = b;
    }
    else
    {
        s = c;
    }

    return s;
}

int main()
{
    int a, b;

    clrscr();

    a = smallest(12, 8, 20);
    printf("\n Smallest = %d", a);

    b = smallest(35, 18, 25);
    printf("\n Smallest = %d", b);

    getch();
}

Output
Smallest = 8
Smallest = 18
Explanation: The program defines a user-defined function smallest() that compares three numbers and returns the smallest value. The function is called twice from the main() function with different sets of numbers. The returned values are stored in variables and displayed using printf(), demonstrating how functions can return values to the calling function.