This is a C++ Program that Solves any Linear Equation in One Variable.
Problem Description
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.
Problem Solution
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.
Expected Input and Output
Case-1:
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
Program/Source Code
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); } Program Explanation 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.
Runtime Test Cases
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