In: Computer Science
Write a C++ program to list all solutions of x1 + x2 + x3 = 10.
x1, x2, and x3 are non-negative integers.
C++ code to find and print all the solutions of x1+x2+x3=10 is:
#include<iostream>
using namespace std;
int main(void){
//Declaring three integer variables
int x1,x2,x3;
//Declaring integer variable count to keep count of solutions
int count=0;
cout<<"All possible combinations of x1+x2+x3=10 :"<<endl;
//Using three-layer for loop, each loop for each variable
for(int i=1;i<=8;i++){
for(int j=1;j<=8;j++){
for(int z=1;z<=8;z++){
//If the combination sum become 10,then printing the combination
if(i+j+z==10){
count=count+1;
cout<<count<<". ("<<i<<","<<j<<","<<z<<")"<<endl;
}
}
}
}
}
I have used three-layered for loop to find all possible combinations of three variables whose sum will be 10. I haven't stored the results in an array, instead printed the solution after checking each combination of x1,x2,x3.
I have provided comments in the program explaining the process. I have tested the code and validated output. I am sharing output screenshot for your reference.
All possible combinations will be printed. This process can be used to any number of variables by increasing the number of for loops.
Hope this answer helps you.
Thank you :)