Danial Khan Danial Khan - 4 months ago 25
C++ Question

Write a program to read m and n from keyboard and list all possible combinations to get the score m-n

Consider the final score of a football match is m-n where m and n are non-negative integers.
Write a c++ program to read m and n from keyboard and list all possible combinations to get the score m-n.

Example outputs:

input m : 1
input n : 0
Possible combinations:
0-0, 1-0

input m : 4
input n : 0
Possible combinations:
0-0, 1-0, 2-0, 3-0, 4-0


input m : 1
input n : 1
Possible combinations:
0-0, 1-0, 1-1
0-0, 0-1, 1-1


input m : 2
input n : 1
Possible combinations:
0-0, 1-0, 2-0, 2-1
0-0, 1-0, 1-1, 2-1
0-0, 0-1, 1-1, 2-1

input m : 2
input n : 2
Possible combinations:
0-0, 1-0, 1-1, 2-1, 2-2
0-0, 1-0, 1-1, 1-2, 2-2
0-0, 1-0, 2-0, 2-1, 2-2
0-0, 0-1, 1-1, 1-2, 2-2
0-0, 0-1, 1-1, 2-1, 2-2
0-0, 0-1, 0-2, 1-2, 2-2


this is the code that i have tried when user enters m=2 and n=1 this code prints only two combinations like

0-0, 1-0, 2-0, 2-1
0-0, 0-1, 1-1, 2-1



{
int m, n;
cout<<"Enter the finals scores of both teams";
cout<<"\nenter the score for team m :";
cin>>m;
cout<<"Enter the score for team n :";
cin>>n;
if (m < 0 && n < 0){

cout<<"score can't be negative";
cout<<"\nenter the score for team m :";
cin>>m;
cout<<"Enter the score for team n :";
cin>>n;
}
else{
int k=0;
if (n==0){
for (int j = 0; j <= m; j++){
for (k; k <= n; k+=1){

cout<<j<<"-"<<k<<",\t";
}
k--;
}
}
else if(m==1 && n==1){

int i=0;
int k=0;
for (int j = 0; j <= m; j++){
for (k; k <= n; k+=1){

cout<<j<<"-"<<k<<",\t";
}
k--;
}
cout<<endl<<endl;
for (int j = 0; j <= n; j++){

for (i; i <= m; i+=1){

cout<<i<<"-"<<j<<",\t";
}
i--;
}
}
else {
int i=0;
int k=0;
for (int j = 0; j <= m; j++){
for (k; k <= n; k+=1){

cout<<j<<"-"<<k<<",\t";
}
k--;
}

cout<<endl<<endl;
for (int j = 0; j <= n; j++){

for (i; i <= m; i++){

cout<<i<<"-"<<j<<",\t";
}
i--;
}
}

}

}

Answer

Simple answer to use recursion, If you don't know recursion read that first

void print_goals(int m,int n,int i,int j,string s)
{
    if(i == m && j == n)
    {
      cout<<s+char(48+i)+'-'+char(48+j)<<endl;
      return;
    }
    if(i<=m)
    print_goals(m,n,i+1,j,s+char(48+i)+'-'+char(48+j)+',');
    if(j<=n)
    print_goals(m,n,i,j+1,s+char(48+i)+'-'+char(48+j)+',');



}

call it as print_goals(5,2,0,0,""); where m=5 and n=2

Comments