Ex No 8
Ex No 8
Ex No 8
Aim:
To write programs using the concept of Function in C language.
Algorithm: 8(a)
1. Start
2. Accept two integers from the user
3. Display the list of operations: addition, subtraction, multiplication, division
4. Accept the user’s choice
5. Call the corresponding function to perform the chosen operation
6. Display the result
7. Stop
Program:
#include<stdio.h>
#include<conio.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);
void main( )
{
int num1, num2, choice;
float result;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
printf("Select operation:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
result = add(num1, num2);
printf("Result: %d\n", (int)result);
break;
case 2:
result = subtract(num1, num2);
printf("Result: %d\n", (int)result);
break;
case 3:
result = multiply(num1, num2);
printf("Result: %d\n", (int)result);
break;
case 4:
if (num2 != 0)
{
result = divide(num1, num2);
printf("Result: %.2f\n", result);
}
else
{
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid choice.\n");
break;
}
getch( );
}
// Function definitions
int add(int a, int b)
{
return a + b;
}
Program:
#include<stdio.h>
#include<conio.h>
int factorial(int n); //Function Declaration
void main( )
{
int num, result;
printf("Enter an integer: ");
scanf("%d", &num);
if (num < 0)
{
printf("Error: Factorial of a negative number doesn't exist.\n");
}
else
{
result = factorial(num);
printf("Factorial of %d = %d\n", num, result);
}
}
Result:
Thus, the programs to implement the concept of Function in C language was done
successfully.