Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find the solution of linear equation
We can apply the software development method to solve the linear equation of one variable in C programming language. A linear equation of the form ax + b = 0 can be solved by rearranging to find x = -b/a (provided a ? 0).
Syntax
float solve(float a, float b); x = -b / a; // where a != 0
Requirements
- The equation should be in the form of ax + b = 0
- a and b are inputs, we need to find the value of x
- Handle the case where a = 0 (no unique solution)
Analysis
Here −
- Input: Coefficients a and b of the linear equation
- Output: The value of x that satisfies the equation
- Special case: When a = 0, the equation becomes b = 0, which has no unique solution for x
Algorithm
Refer to the algorithm given below to find solution of linear equation −
Step 1: Start
Step 2: Read a, b values
Step 3: Check if a == 0
If true: Print "No unique solution"
Else: Calculate x = -b/a
Step 4: Print the result
Step 5: Stop
Example
Following is the C program to find the solution of linear equation −
#include <stdio.h>
float solve(float a, float b) {
float x;
if (a == 0) {
printf("No unique solution exists (a cannot be zero)
");
return 0;
} else {
x = -b / a;
return x;
}
}
int main() {
float a, b, x;
printf("Enter coefficients a and b: ");
scanf("%f %f", &a, &b);
x = solve(a, b);
if (a != 0) {
printf("For the equation %.2fx + %.2f = 0
", a, b);
printf("The solution is: x = %.2f
", x);
}
return 0;
}
Output
When the above program is executed, it produces the following result −
Enter coefficients a and b: 4 8 For the equation 4.00x + 8.00 = 0 The solution is: x = -2.00
Example with Zero Coefficient
Let's see what happens when a = 0 −
#include <stdio.h>
int main() {
float a = 0, b = 5;
printf("For the equation %.2fx + %.2f = 0
", a, b);
if (a == 0) {
if (b == 0) {
printf("Infinite solutions exist (0 = 0)
");
} else {
printf("No solution exists (%.2f ? 0)
", b);
}
} else {
float x = -b / a;
printf("The solution is: x = %.2f
", x);
}
return 0;
}
For the equation 0.00x + 5.00 = 0 No solution exists (5.00 ? 0)
Key Points
- Always check if the coefficient a is zero to avoid division by zero
- When a = 0 and b ? 0, no solution exists
- When a = 0 and b = 0, infinite solutions exist
- The formula x = -b/a works only when a ? 0
Conclusion
Solving linear equations in C involves basic arithmetic and conditional logic. The key is handling the special case where the coefficient of x is zero, which leads to either no solution or infinite solutions.
Advertisements
