User-Defined Functions in C
Example 1:
#include <stdio.h> void printCode(); //func declaration void main(){ printf("Hello "); printCode(); //func call } void printCode(){ //func definition printf("Wrote code"); }
Output:
Hello Wrote code
There are 3 things to remember when creating user-defined functions:
1. Function Declaration.
2. Function Call.
3. Function definition
Example 1: Function with No Arguments & No Return Value
#include <stdio.h> // Function declaration + definition void greetings() { printf("Hello! Welcome to C programming.\n"); } int main() { // Function call greetings(); return 0; }
Output:
Hello! Welcome to C programming.
Use:
In real life, it is useful for displaying messages, logging information, or performing simple actions without needing input or output values.
Example 2: Functions with Arguments but No Returns a Value
#include <stdio.h> void addition(int num1, int num2) { // parameters int sum = num1 + num2; printf("The sum is %d", sum); } int main() { int num1 = 10, num2 = 20; // Function call with arguments addition(num1, num2); return 0; }
Output:
The sum is 30
Use:
When we want to perform a task (like printing, modifying global variables, etc.) but don’t need a return value.
Example 3. Functions with No Arguments but Returns a Value
#include <stdio.h> int addition() { int num1, num2; printf("Enter the value of num1: "); scanf("%d",&num1); printf("Enter the value of num2: "); scanf("%d",&num2); // int sum = num1 + num2; // return sum; return num1 + num2; } int main() { int sum = addition(); printf("The sum is %d",sum); return 0; }
Output:
Enter the value of num1: 12 Enter the value of num2: 9 The sum is 21
Use:
When we don’t need to pass any data but need to retrieve a result from the function.
Example: Getting user input, generating a random number, reading sensor values in embedded systems, etc.
Example 4. Function with Arguments & Returns a Value
#include <stdio.h> int addition(int num1, int num2) { return num1 + num2; //return sum } int main() { int num1, num2; printf("Enter the value of num1: "); scanf("%d",&num1); printf("Enter the value of num2: "); scanf("%d",&num2); int sum = addition(num1,num2); //passing arguments printf("The sum is %d",sum); return 0; }
Output:
Enter the value of num1: 12 Enter the value of num2: 9 The sum is 21
Use:
When a function requires input values and needs to return a computed result.
Examples:
Banking System: Function to calculate interest.
Game Development: Function to compute player scores.
E-commerce: Function to calculate total cart price with tax.