×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C Programs/ Examples of User-defined Functions (UDF Examples)

Find the solved programs on user-defined functions with explanations.

What are User-defined Functions?

User-defined Functions are created to perform some specific task by the programmer, for example if you want to find the sum of all array elements using your own function, then you will have to define a function which will take array elements as an argument(s) and returns the sum of all elements. The logic/code will be written in the defined function and you have to just call this function within the program by passing actual arguments.

To create a User-defined Functions - You will have to keep following points in your mind.

  • Declare the function with appropriate prototype before calling and defining the function.
  • Function name should be meaningful and descriptive.
  • Keep same argument data type and return data type in Declaration and Defining the function.
  • Pass the same data type arguments which are provided in Declaration and Definition.
  • The arguments/parameters which are used while calling the functions are known as Actual Arguments/Parameters and Arguments/Parameters which are used in the definition of the function are known as Local (Format) Arguments/Parameters.

Here, we made some programs based on User-defined Functions, read the program and try to implement same programs on your system and then try to make different programs based on User-defined Functions.

User-defined Function Programs/Examples in C


1. C program to find SUM and AVERAGE of two integer Numbers using User-defined Functions

/*  
C program to find SUM and AVERAGE of two integer 
Numbers using User-defined Functions.
*/

#include <stdio.h>

/*function declarations*/
int sumTwoNum(int, int); /*to get sum*/
float averageTwoNum(int, int); /*to get average*/

int main()
{
    int number1, number2;
    int sum;
    float avg;

    printf("Enter the first integer number: ");
    scanf("%d", &number1);

    printf("Enter the second integer number: ");
    scanf("%d", &number2);

    /*function calling*/
    sum = sumTwoNum(number1, number2);
    avg = averageTwoNum(number1, number2);

    printf("Number1: %d, Number2: %d\n", number1, number2);
    printf("Sum: %d, Average: %f\n", sum, avg);

    return 0;
}

/*function definitions*/
/*
 * Function     : sumTwoNum
 * Arguments    : int,int - to pass two integer values
 * return type  : int - to return sum of values
*/
int sumTwoNum(int x, int y)
{
    /*x and y are the formal parameters*/
    int sum;
    sum = x + y;
    return sum;
}

/*
 * Function     : averageTwoNum
 * Arguments    : int,int - to pass two integer values
 * return type  : float - to return average of values
*/
float averageTwoNum(int x, int y)
{
    /*x and y are the formal parameters*/
    float average;
    return ((float)(x) + (float)(y)) / 2;
}

Output

Enter the first integer number: 100
Enter the second integer number: 201
Number1: 100, Number2: 201
Sum: 301, Average: 150.500000

2. C program to print Table of an Integer Number using User-defined Function

/*  
C program to print Table of an Integer Number 
using User-defined Functions.
*/

#include <stdio.h>

/*function declaration*/
void printTable(int);

int main()
{
    int number;

    printf("Enter an integer number: ");
    scanf("%d", &number);

    printf("Table of %d is:\n", number);
    printTable(number);

    return 0;
}

/* function definition...
 * Function     :   printTable
 * Argumenets   :   int- to pass number for table
 * Return Type  :   void
*/
void printTable(int num)
{
    int i;

    for (i = 1; i <= 10; i++)
        printf("%5d\n", (num * i));
}

Output

Enter an integer number: 123
Table of 123 is:
    123
    246
    369
    492
    615
    738
    861
    984
    1107
    1230

3. C program to find Sum of all Array Elements by passing array as an argument using User-defined Functions

/*  
C program to find Sum of all Array Elements by passing array 
as an argument using User-defined Functions.
*/

#include <stdio.h>

#define MAX_ELEMENTS 100

/*function declaration*/

int sumOfElements(int[], int);

int main()
{
    int N, i, sum;
    int arr[MAX_ELEMENTS];

    printf("Enter total number of elements(1 to %d): ", MAX_ELEMENTS);
    scanf("%d", &N);

    if (N > MAX_ELEMENTS) {
        printf("You can't input larger than MAXIMUM value\n");
        return 0;
    }
    else if (N < 0) {
        printf("You can't input NEGATIVE or ZERO value.\n");
        return 0;
    }

    /*Input array elements*/
    printf("Enter array elements:\n");
    for (i = 0; i < N; i++) {
        printf("Enter element %4d: ", (i + 1));
        scanf("%d", &arr[i]);
    }

    /*function calling*/
    sum = sumOfElements(arr, N);

    printf("\nSUM of all Elements: %d\n", sum);

    return 0;
}

/* function definition...
 * Function     :   sumOfElements
 * Argument(s)  :   int [], int - An integer array, Total No. of Elements
 * Return Type  :   int - to return integer value of sum
*/

int sumOfElements(int x[], int n)
{
    int sum, i;
    sum = 0;

    for (i = 0; i < n; i++) {
        sum += x[i];
    }

    return sum;
}

Output

First Run:
Enter total number of elements(1 to 100): 5
Enter array elements:
Enter element    1: 11
Enter element    2: 22
Enter element    3: 33
Enter element    4: 44
Enter element    5: 55

SUM of all Elements: 165

Second Run:
Enter total number of elements(1 to 100): 120
You can't input larger than MAXIMUM value

Third Run:
Enter total number of elements(1 to 100): -10
You can't input NEGATIVE or ZERO value.

4. C program to find Length of the String by passing String/ Character Array as an Argument using User-defined Functions

/*  
C program to find Length of the String by passing String/ Character Array 
as an argument using User-defined Functions.
*/

#include <stdio.h>

/*function declaration*/
int stringLength(char*);

int main()
{
    char text[100];
    int length;

    printf("Enter text (max- 100 characters): ");
    scanf("%[^\n]s", text);
    /*we can also use gets(text) - To read complete text untill '\n'*/

    length = stringLength(text);

    printf("Input text is: %s\n", text);
    printf("Length is: %d\n", length);

    return 0;
}

/* function definition...
 * Function     :   stringLength
 * Argument(s)  :   char * - Pointer of character arrar
 * Return Type  :   int - Length of the string (integer type)
*/
int stringLength(char* str)
{
    int len = 0;

    /*calculate string length*/
    for (len = 0; str[len] != '\0'; len++)
        ;

    /*return len*/
    return len;
}

Output

Enter text (max- 100 characters): Hello World.
Input text is: Hello World.
Length is: 12

5. C program to find Total Amount of purchased Items by Passing Structure as an Argument using User-defined Functions

/*  
C program to find Total Amount of purchased Items by Passing Structure
as an argument using User-defined Functions.
*/

#include <stdio.h>

/*declaration of structure*/
struct Item {
    char itemName[30];
    int quantity;
    float price, totalAmount;
};

/*function declaration*/
float getTotalAmount(struct Item);

int main()
{
    /*structure variable declaratio*/
    struct Item IT;
    float tAmount; /*total amount*/

    printf("Enter Item Name (max 30 characters): ");
    scanf("%[^\n]s", IT.itemName);
    /*we can also use gets(IT.itemName) - To read complete text untill '\n'*/

    printf("Enter price: ");
    scanf("%f", &IT.price);

    printf("Enter quantity: ");
    scanf("%d", &IT.quantity);

    /*calling function by passing structure Item's variable "IT"*/
    tAmount = getTotalAmount(IT);

    printf("Item Name: %s\nPrice: %f\nQuantity: %d\n", IT.itemName, IT.price, IT.quantity);
    printf("\nTotal Price of all quanities: %f\n", tAmount);
    return 0;
}

/* function definition...
 * Function     :   getTotalAmount
 * Argument(s)  :   struct Item - Item Structure name
 * Return Type  :   float - Total amount
*/
float getTotalAmount(struct Item item)
{
    /* remember Item - Is structure and "item" is structure variable name
     * which is formal here*/

    item.totalAmount = item.price * (float)item.quantity;

    return (item.totalAmount);
}

Output

Enter Item Name (max 30 characters): Pen
Enter price: 12.50
Enter quantity: 11
Item Name: Pen
Price: 12.500000
Quantity: 11

Total Price of all quanities: 137.500000

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.