A Multi-Function Program
This example demonstrates a multi-function program that showcases user-defined functions:
Example:
#include <stdio.h>
// Function prototypes
void greet(); // Function to display a greeting message
int add(int a, int b); // Function to add two integers
void displayResult(int result); // Function to display the result
int main() {
greet(); // Call the greet function
int sum = add(5, 10); // Call the add function with arguments 5 and 10
displayResult(sum); // Call the displayResult function to show the result
return 0; // Indicate that the program ended successfully
}
// Function to display a greeting message
void greet() {
printf("Welcome to the Multi-Function Program!\n"); // Print greeting
}
// Function to add two integers
int add(int a, int b) {
return a + b; // Return the sum of a and b
}
// Function to display the result
void displayResult(int result) {
printf("The result is: %d\n", result); // Print the result
}
Output
Welcome to the Multi-Function Program!
The result is: 15
This program demonstrates three functions:
greet: Displays a welcome message to the user.
add: Takes two integers as input and returns their sum. The return type of this function is int
.
displayResult: Takes an integer result as input and prints it to the console.
By organizing these operations into functions, the program becomes clearer and easier to follow.
2: Multi-Function Program with Arithmetic Operations
#include <stdio.h>
// Function declarations
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
int main() {
int num1, num2, choice;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Choose an operation:n");
printf("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Result: %d\n", add(num1, num2));
break;
case 2:
printf("Result: %d\n", subtract(num1, num2));
break;
case 3:
printf("Result: %d\n", multiply(num1, num2));
break;
case 4:
if (num2 != 0) {
printf("Result: %.2f\n", divide(num1, num2));
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
float divide(int a, int b) {
return (float)a / b;
}
Output
Enter two numbers: 8 2
Choose an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Result: 10
- Explanation
- Arithmetic Functions:
add()
: Returns the sum of two integers.subtract()
: Returns the difference of two integers.multiply()
: Returns the product of two integers.divide()
: Returns the quotient of two integers as a float.
- main():
- Accepts two numbers and a choice of operation from the user.
- Uses a
switch
statement to call the appropriate function based on user input.