Ex No 8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Ex No: 8 IMPLEMENTATION OF FUNCTION

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;
}

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;
}
Algorithm: 8(b)
1. Start
2. Accept a number from the user
3. If the number is negative, display an error message
4. If the number is 0 or 1, return 1 (base case)
5. If the number is greater than 1, call the recursive function factorial
6. Multiply the number by factorial(number - 1)
7. Display the result
8. Stop

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);
}
}

// Recursive function to find factorial


int factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}

Result:
Thus, the programs to implement the concept of Function in C language was done
successfully.

You might also like