![]() |
VOOZH | about |
Here we will build a C program to calculate the sum of natural numbers using 4 different approaches i.e.
We will keep the same input in all the mentioned approaches and get an output accordingly.
Input:
n = 10
Output:
55
Explanation: The sum of natural numbers up to a given number is 0+1+2+3+4+5+6+7+8+9+10=55
The while loop executes the statements until the condition is false
Sum = 55
Time Complexity : O(n) as the loop runs for n iterations
Auxiliary Space : O(1) as only a fixed amount of memory is used.
For loop iterates up to n number of times.
Sum = 55
Time Complexity : O(n) as the loop runs for n+1 iterations.
Auxiliary Space : O(1) as only a fixed amount of memory is used.
Sum = 55
Time Complexity : O(n) as the function is called n+1 times.
Auxiliary Space : O(n) as each function call stores one value in the call stack, which consumes memory.
Sum = 55
Time Complexity : O(n) as the loop runs for n+1 iterations.
Auxiliary Space : O(1) as only a fixed amount of memory is used.
Sum = 55
Time Complexity : O(1) as it performs a fixed number of operations regardless of the input size.
Auxiliary Space : O(1) as only a fixed amount of memory is used.