Print the elements that can be added to give a given sum

PHPz
Release: 2023-09-07 22:09:15
forward
1175 people have browsed it

Print the elements that can be added to give a given sum

Enter the number of elements the user wants to enter, followed by the total value the user wants to calculate from the given list of elements.

Input : N=5
   Enter any 5 values : 3 1 6 5 7
   Enter sum you want to check : 10
Output : 3 1 6
Copy after login

Algorithm

START
STEP1-> Take values from the user
STEP2-> Take the sum a user want to check in the set.
STEP3-> For i = 0; i < n; i++
STEP4-> Check If sum - *(ptr+i) >= 0 then,
   STEP4.1-> sum -= *(ptr+i);
   STEP4.2-> Print the value of *(ptr+i)
END If
END For
STOP
Copy after login

Example

#include <stdio.h>
int main(int argc, char const *argv[]){
   int *ptr, n, i, sum;
   printf("Enter number of digits you want to enter");
   scanf("%d", &n);
   ptr = (int*)malloc(sizeof(int)*n); //Dynamically allocating the memory of int
   type
   printf("Enter %d elements", n);
   for(i = 0; i < n; i++) {
      scanf("%d", (ptr+i)); //Inputting the value in dynamically
      //allocated array
   }
   printf("Enter the sum you want to check");
   scanf("%d", &sum);
   for ( i = 0; i < n; i++) {
      if(sum - *(ptr+i) >= 0) { //Checking the values which can be added to form the sum
         X
         sum -= *(ptr+i); //Updating the value of sum
         printf("%d ", *(ptr+i)); //Printing the Values which can be summed up to form sum
      }
   }
   return 0;
}
Copy after login

Output

If we run the above program, it will generate the following output

Enter number of digits you want to enter
5
Enter 5 elements
3
1
6
5
7
Enter the sum you want to check
10
3 1 6
Copy after login

The above is the detailed content of Print the elements that can be added to give a given sum. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template