Advertisement
Guest User

axiom energy application pseudocode

a guest
Mar 20th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. Compute sum using for loop:
  2.  
  3. public int sumForLoop(list of numbers) {
  4. declare and initialize sum as 0
  5.  
  6. for (each element in list of numbers)
  7. add the current element to sum
  8.  
  9. print sum
  10. }
  11.  
  12.  
  13. Compute sum using while loop:
  14.  
  15. public int sumWhileLoop(list of numbers) {
  16. declare and initialize sum as 0
  17. declare and initialize index as 0
  18.  
  19. while (index < length of numbers list)
  20. add list of numbers[index] to sum
  21.  
  22. print sum
  23. }
  24.  
  25.  
  26. Compute sum using recursion:
  27.  
  28. 0 should be passed initially for index and total
  29.  
  30. function sumRecursion(list of numbers, index, total) {
  31. if (list of numbers is empty)
  32. return 0
  33.  
  34. if (index is equal to the length of list of numbers)
  35. add list of numbers[index] to total
  36. return total
  37.  
  38. return sumRecursionHelper(list of numbers, index + 1, total + list of numbers[index]);
  39. }
  40.  
  41.  
  42. Combine two lists by alternating:
  43.  
  44. if lists are guaranteed to be same length:
  45.  
  46. function(list one, list two) {
  47. declare new array with size of list one length
  48.  
  49. for(i = 0; i < length of list one; i++)
  50. if (i is even)
  51. set new array[i] to list one[i]
  52. if (i is odd)
  53. set new array[i] to list two[i]
  54.  
  55. return new array
  56. }
  57.  
  58.  
  59. Compute first 100 numbers of fibonacci:
  60.  
  61. function() {
  62. for (int i = 0; i < 100; i++)
  63. print fibonacci(i)
  64. }
  65.  
  66. function fibonacci(number) {
  67. if number <= 1
  68. return number
  69.  
  70. return fibonacci(number - 1) + fibonacci(number - 2)
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement