fork download
  1. /*Да се напише програма, която намира последователност от числа в масив, които имат сума равна на число, въведено от потребителя (ако има такава).*/
  2. #include <stdio.h>
  3.  
  4. int main(void)
  5. {
  6. int magicNumber, magicSum;
  7. printf("Enter the number of elements in the array: ");
  8. scanf("%d", &magicNumber);
  9. printf("Enter the target sum: ");
  10. scanf("%d", &magicSum);
  11.  
  12. int array[magicNumber];
  13. for (int i = 0; i < magicNumber; i++)
  14. {
  15. printf("Enter element: ");
  16. scanf("%d", &array[i]);
  17. }
  18.  
  19. printf("The array:\n");
  20. for (int i = 0; i < magicNumber; i++)
  21. {
  22. printf("array[%d]: %d\n", i, array[i]);
  23. }
  24.  
  25. int currentSum = 0;
  26. for (int i = 0; i < magicNumber; i++)
  27. {
  28. currentSum += array[i];
  29. if (currentSum > magicSum)
  30. {
  31. currentSum = 0;
  32. currentSum += array[i];
  33. }
  34. else if (currentSum == magicSum)
  35. {
  36. printf("You achieved the sum");
  37. break;
  38. }
  39. }
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 5288KB
stdin
45
stdout
Enter the number of elements in the array: Enter the target sum: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: Enter element: The array:
array[0]: 445268464
array[1]: 32764
array[2]: 445268612
array[3]: 32764
array[4]: 0
array[5]: 0
array[6]: 0
array[7]: 0
array[8]: -1494907584
array[9]: 5291
array[10]: 0
array[11]: 0
array[12]: -1
array[13]: 0
array[14]: 0
array[15]: 0
array[16]: 445850320
array[17]: 32764
array[18]: -1494669520
array[19]: 5291
array[20]: 0
array[21]: 0
array[22]: 0
array[23]: 0
array[24]: 445272009
array[25]: 32764
array[26]: 0
array[27]: 0
array[28]: 0
array[29]: 0
array[30]: 0
array[31]: 0
array[32]: 0
array[33]: 0
array[34]: 15774463
array[35]: 0
array[36]: 194
array[37]: 0
array[38]: 445268614
array[39]: 32764
array[40]: 1
array[41]: 0
array[42]: -1496159403
array[43]: 5291
array[44]: 0