Solve Any Linear Equation in One Variable Using C++



Any linear equation in one variable has the form aX + b = cX + d. Here the value of X is to be found, when the values of a, b, c, d are given.

Let's understand this with an example:

//Example 1
If the input equation is 2X + 4 = -9X + 14, the solution is:
=> 2X + 9x = 14 - 4
=> 11X = 10
=> X = 10 / 11 = 1.1

//Example 2
If the input equation is -3X + 5 = 4X - 9 the solution is:
=> -3X + (-4X) = -9 + (-5)
=> -7X = -14    
=> X = -14 / -7 = 2

Linear Equation in One Variable

To solve this, we start with the equation written as aX + b = cX + d. Then, we move all terms with X to one side and constant to the other, which gives us aX - cX = d - b. This simplifies to (a - c)X = (d - b). Based on the values, we get three possible outcomes.

  • If a = c and b = d: The equation has infinite solutions.
  • If a = c and b ? d: The equation has no solution.
  • If a ? c: We solve to find the value of X using formula: X = (d - b) / (a - c)

C++ Program for Linear equation in One Variable

Below is the complete C++ program where we take input from the user for values a, b, c and d. Then, we check for the above cases and solve the equation accordingly and displayed the result.

#include<iostream>
using namespace std;

int main() {
    fl[oat a, b, c, d, X;

    // Ask user to input values for a, b, c, and d
    cout<<"The form of the linear equation in one variable is: aX + b = cX + d"<<endl;
    cout<<"Enter the values of a, b, c, d : "<<endl;
    cin>>a>>b>>c>>d;

    // Show the full equation based on the user's input
    cout<<"The equation is "<<a<<"X + "<<b<<" = "<<c<<"X + "<<d<<endl;

    // Check and display the solution based on the values
    if(a==c && b==d)
        cout<<"There are infinite solutions possible for this equation"<<endl;
    else if(a==c)
        cout<<"This is a wrong equation"<<endl;
    else {
        X = (d-b)/(a-c);
        cout<<"The value of X = "<< X <<endl;
    }]
}

The output of the above program shows the value of X when we enter the values of the linear equation, such as: a = 3, b = 2, c = 5, and d = 3.

The form of the linear equation in one variable is: aX + b = cX + d
Enter the values of a, b, c, d : 
3
2
5
3
The equation is 3X + 2 = 5X + 3
The value of X = -0.5

Time Complexity: O(1)

Space Complexity: O(1)

Updated on: 2025-05-22T19:13:53+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements