打印可以相加得到给定和的元素

PHPz
发布: 2023-09-07 22:09:15
转载
1126人浏览过

打印可以相加得到给定和的元素

输入用户想要输入的元素数量,然后输入用户想要从给定元素列表计算的总值。

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网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号