In: Computer Science
Write an algorithm to input a number n, then calculate 13 +2 3 + 33 + ... + n3, the sum
of the first n cubic numbers, and output the result.
2-Construct a trace table of the algorithm in question 1 with input n=4.
Algorithm:-
cubeNNatural(n)
begin sum := 0 for i in range 1 to n, do sum := sum + i^3 done return sum end
Example:-
#include<stdio.h> long cube_sum_n_natural(int n) { long sum = 0; int i; for (i = 1; i <= n; i++) { sum += i * i * i; //cube i and add it with sum } return sum; } main() { int n; printf("Enter value of n: "); scanf("%d", &n); printf("Result is: %ld", cube_sum_n_natural(n)); }
Output
Enter value of n: 6 Result is: 441
SUM <--0
FOR i ← 1 TO 4
SUM <---SUM+i^3
ENDFOR
trace table :-
i | i^3 | SUM |
0 | ||
1 | 1 | 1 |
2 | 8 | 9 |
3 | 27 | 36 |
4 | 64 | 100 |