Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Accepts n different numbers and s which is equal to the sum of the n different numbers

C++ Basic: Exercise-80 with Solution

Write a C++ program that accepts n different numbers (0 to 100) and s which is equal to the sum of the n different numbers.
Your job is to find the number of combination of n numbers and the same number can not be used for one combination.

Example:
Here n = 3 and s = 6:
1 + 2 + 3 = 6
0 + 1 + 5 = 6
0 + 2 + 4 = 6
Output: Number of combination: 3

Pictorial Presentation:

C++ Exercises: Accepts n different numbers and s which is equal to the sum of the n different numbers

Sample Solution:

C++ Code :

#include <iostream>
#define range(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
#define rep(i,n) range(i,0,n)
using namespace std;
 
 
int n,s;
 
long long int dp[10][1010];
 
int main(void){
    dp[0][0]=1LL;
    rep(i,101){
        for(int j=8;j>=0;j--)rep(k,1010){
            if(k+i<=1010)
                dp[j+1][k+i]+=dp[j][k];
        }
    }
    cout << "Input n and s: ";
    cin >> n >> s;
    cout << "\nNumber of combination: ";
    cout << dp[n][s] << endl;

    return 0;
}

Sample Output:

Input n and s: 3 6  
Number of combination: 3

Flowchart:

Flowchart: Accepts n different numbers and s which is equal to the sum of the n different numbers

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to display all the leap years between two given years. If there is no leap year in the given period,display a suitable message.
Next: Write a C++ program to which replace all the words "dog" with "cat".

What is the difficulty level of this exercise?