Greater Example


Explanation

A function can return a value after performing a calculation. In this program, the user-defined function greater() accepts three numbers as parameters and returns the greatest 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 function greater(int a, int b, int c) that accepts three integer values.
  • Step 2: Declare the variable g to store the greatest number.
  • Step 3: Compare the three numbers using the if-else if statement.
  • Step 4: Store the greatest number in g.
  • Step 5: Return the value of g using the return statement.
  • Step 6: In the main() function, call the greater() 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 greater(int a, int b, int c)
{

    int g;

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

        g = a;

    }

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

        g = b;

    }

    else
    {

        g = c;

    }

    return g;

}

int main()
{

    int a, b;

    clrscr();

    a = greater(3, 6, 9);

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

    b = greater(15, 16, 19);

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

    getch();

}

Output

9
19

Practice Exercises

Task 1: Write a C program using a user-defined function greater() that accepts three numbers and returns the greatest 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 greatest of three numbers.

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

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

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

    int g;

    if(a > b && a > c)
    {
        g = a;
    }

    else if(b > a && b > c)
    {
        g = b;
    }

    else
    {
        g = c;
    }

    return g;

}

int main()
{

    int a, b;

    clrscr();

    a = greater(25, 18, 12);

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

    b = greater(30, 45, 40);

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

    getch();

}

Output
Greatest = 25
Greatest = 45
Explanation: The program creates a user-defined function greater() that compares three numbers and returns the greatest value. The function is called twice from the main() function with different sets of numbers. The returned values are stored in variables and displayed, showing how a function can return data back to the calling function.