This is a C++ Program that Solves any Linear Equation in One Variable.
The Problem states that given a linear equation in one variable of the form aX + b = cX + d where a,b,c,d are provided as input, we need to determine the appropriate value of X.
Solving the equation aX + b = cX + d, we get
=> aX – cX = d – b
=> X = (d-b) / (a-c)
So we can solve the equation by applying the above formula. But, we need to figure out following 2 cases of inputs:
Case-1:
Now if a==c but b!=d, the equation will reduce to: X = (d-b)/0 Hence this value is invalid.
Case-2:
Now if a==c but b==d, the equation will reduce to: aX = cX => X = X (Since a=c) Hence, any value of X will satisfy the equation and we get infinite number of solutions.
Case-1:
a=2,b=4,c=8,d=16 X=-2
Case-2:
a=2,b=5,c=2,d=5 Infinite Solutions
Case-3:
a=2,b=5,c=2,d=3 Wrong Equation: No Solution
Here is source code of the C++ Program to Solve any Linear Equation in One Variable. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <bits/stdc++.h>
using namespace std;
void solve(float a, float b, float c, float d)
{
if(a==c && b==d)
cout<<"Infinite Solutions"<<endl;
else if(a==c)
cout<<"Wrong Equation: No Solution"<<endl;
else
{
float X = (d-b)/(a-c);
cout<<"Solution is X = "<<X<<endl;
}
}
int main()
{
float a, b, c, d;
cout<<"For a linear equation in one variable of the form aX + b = cX + d"<<endl;
cout<<"Enter the value of a : ";
cin>>a;
cout<<"Enter the value of b : ";
cin>>b;
cout<<"Enter the value of c : ";
cin>>c;
cout<<"Enter the value of d : ";
cin>>d;
solve(a, b, c, d);
}
main() – In this function, we take the inputs of a,b,c,d and we compute the result inside the function solve().
solve() – Inside this, we check for the cases defined above and we provide appropriate solution.
Case-1: $ g++ Variable_Linear_Eq.cpp $ ./a.out For a linear equation in one variable of the form aX + b = cX + d Enter the value of a : 2 Enter the value of b : 4 Enter the value of c : 4 Enter the value of d : 8 Solution is X = -2 Case-2: $ ./a.out For a linear equation in one variable of the form aX + b = cX + d Enter the value of a : 2 Enter the value of b : 5 Enter the value of c : 2 Enter the value of d : 5 Infinite Solutions Case-3: $ ./a.out For a linear equation in one variable of the form aX + b = cX + d Enter the value of a : 2 Enter the value of b : 5 Enter the value of c : 2 Enter the value of d : 3 Wrong Equation: No Solution
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy C++ Books
- Apply for C++ Internship
- Buy Computer Science Books
- Practice Programming MCQs
- Practice Computer Science MCQs