Write code for a function that uses a loop to compute the su

Write code for a function that uses a loop to compute the sum of all integers from 1 to n. Do a time analysis, counting each basic operation (such as assignment and ++) as one operation.

Solution

#include <stdio.h>
int main()
{
int n, i, sum = 0;
  
printf(\"Enter a positive integer: \");
scanf(\"%d\",&n);

for(i=1; i <= n; ++i)
{
sum += i; // sum = sum+i;
}

printf(\"Sum = %d\",sum);

return 0;
}

// Precondition: n >= i.
// Postcondition: The value returned is the // sum of all integers from I to n.

For a time analysis, there are two assignment operations (sum = 0 and i = 1). The <= test is executed n + 1 times

Write code for a function that uses a loop to compute the sum of all integers from 1 to n. Do a time analysis, counting each basic operation (such as assignment

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site