Functions help us divide a program into smaller, reusable parts. In this program, four user-defined functions are created to perform the basic arithmetic operations: add(), sub(), mul(), and div(). Each function accepts two numbers as parameters, performs the required operation, and displays the result. The division function also checks whether the second number is zero to avoid division by zero.
How It Works?
stdio.h and conio.h.add(), sub(), mul(), and div().div() function, check whether the second number is zero before dividing.main() function using different values.#include <stdio.h> #include <conio.h> void add(int a, int b) { int k = a + b; printf("Addition of Numbers is: %d", k); } void sub(int a, int b) { int k = a - b; printf("\nSubtraction of Numbers is: %d", k); } void mul(int a, int b) { int k = a * b; printf("\nMultiplication of Numbers is: %d", k); } void div(int a, int b) { if(b != 0) { int k = a / b; printf("\nDivision of Numbers is: %d", k); } else { printf("\nError: Division by zero is not allowed."); } } int main() { clrscr(); add(10, 20); sub(20, 10); mul(5, 5); div(10, 2); div(10, 0); getch(); }
add(), sub(), mul(), and div() to perform arithmetic operations on the numbers 40 and 8. Display the result of each operation.main() function to perform different arithmetic operations.#include <stdio.h> #include <conio.h> void add(int a, int b) { int k = a + b; printf("Addition = %d", k); } void sub(int a, int b) { int k = a - b; printf("\nSubtraction = %d", k); } void mul(int a, int b) { int k = a * b; printf("\nMultiplication = %d", k); } void div(int a, int b) { if(b != 0) { int k = a / b; printf("\nDivision = %d", k); } else { printf("\nDivision by zero is not allowed."); } } int main() { clrscr(); add(40, 8); sub(40, 8); mul(40, 8); div(40, 8); getch(); }
main() function calls all four functions using the values 40 and 8, demonstrating how different functions can be used together in a single program.