Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Compute sum using for loop:
- public int sumForLoop(list of numbers) {
- declare and initialize sum as 0
- for (each element in list of numbers)
- add the current element to sum
- print sum
- }
- Compute sum using while loop:
- public int sumWhileLoop(list of numbers) {
- declare and initialize sum as 0
- declare and initialize index as 0
- while (index < length of numbers list)
- add list of numbers[index] to sum
- print sum
- }
- Compute sum using recursion:
- 0 should be passed initially for index and total
- function sumRecursion(list of numbers, index, total) {
- if (list of numbers is empty)
- return 0
- if (index is equal to the length of list of numbers)
- add list of numbers[index] to total
- return total
- return sumRecursionHelper(list of numbers, index + 1, total + list of numbers[index]);
- }
- Combine two lists by alternating:
- if lists are guaranteed to be same length:
- function(list one, list two) {
- declare new array with size of list one length
- for(i = 0; i < length of list one; i++)
- if (i is even)
- set new array[i] to list one[i]
- if (i is odd)
- set new array[i] to list two[i]
- return new array
- }
- Compute first 100 numbers of fibonacci:
- function() {
- for (int i = 0; i < 100; i++)
- print fibonacci(i)
- }
- function fibonacci(number) {
- if number <= 1
- return number
- return fibonacci(number - 1) + fibonacci(number - 2)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement