首頁 >web前端 >html教學 >列印可以相加得到給定和的元素

列印可以相加得到給定和的元素

PHPz
PHPz轉載
2023-09-07 22:09:151199瀏覽

列印可以相加得到給定和的元素

輸入使用者想要輸入的元素數量,然後輸入使用者想要從給定元素清單計算的總值。

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

演算法

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

範例

#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;
}

輸出

如果我們執行上面的程序,它將產生以下輸出

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
#

以上是列印可以相加得到給定和的元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除