C program to subtract two numbers:
In this C program, we will learn how to subtract two user input numbers. This program will take these numbers as inputs from the user and print the subtraction result.
We will learn how to solve this program in two ways, by using a separate function and without using a separate function.
Method 1: C program to subtract two numbers with user input values:
Let’s write a C program that takes two numbers as inputs from the user, finds the subtraction result, and prints it out.
#include <stdio.h>
int main()
{
float firstNum, secondNum, result;
printf("Enter the first number: ");
scanf("%f", &firstNum);
printf("Enter the second number: ");
scanf("%f", &secondNum);
result = firstNum - secondNum;
printf("%.2f - %.2f = %.2f\n", firstNum, secondNum, result);
return 0;
}
In this program,
- We created three float variables, firstNum, secondNum and result to hold the first number, second number and the subtraction result.
- The program asks the user to enter the first and the second numbers. It reads the user-input numbers and assigns these to the firstNum and secondNum variables.
- The subtraction result is calculated and assigned to the result variable.
- The last line is printing the final result.
If you run this program, it will give output as below:
Enter the first number: 13
Enter the second number: 12
13.00 - 12.00 = 1.00
Enter the first number: 1
Enter the second number: 13
1.00 - 13.00 = -12.00
Method 2: C program to subtract two numbers with user input values and by using a separate function:
Let’s use a separate function to find the subtraction of two numbers. This function will take the numbers as the parameters and it will return the subtraction result.
#include <stdio.h>
float subtract(int first, int second)
{
return first - second;
}
int main()
{
float firstNum, secondNum, result;
printf("Enter the first number: ");
scanf("%f", &firstNum);
printf("Enter the second number: ");
scanf("%f", &secondNum);
printf("%.2f - %.2f = %.2f\n", firstNum, secondNum, subtract(firstNum, secondNum));
return 0;
}
Sample output:
Enter the first number: 223
Enter the second number: 22
223.00 - 22.00 = 201.00
This is similar to the previous program. The only difference is that the second program uses a separate function to find the result. As it is a separate function, you can use this function from any other place you want.
You might also like:
- C++ program to solve a quadratic equation in different ways
- 3 ways to find the exponent without using pow() method in C++
- 3 different C++ programs to find electricity bill with user given units
- 2 different C++ program to check if a number is spy number or not
- C++ program to insert an element to an array at any position
- C++ program to find the volume of a cylinder in 3 different ways
- C++ program to find the sum of two numbers using friend function
- C++ program to print the days of the week by using switch case
- C++ program to find the area of a rectangle