Write a function int sumint n which will return the sum of 1
Write a function int sum(int n); which will return the sum of 1+2+…+n where n is a positive integer.
Write the precondition and postcondition of above function (in above question)
Solution
Answer:
The function int sum(int n) is defined as below :
int sum(int n){
int i, total=0;
for(i=1; i<=n; i++){
total+=i;
}
return total;
}
The precondition of of above function is execute the function only when the value of n>0 i.e if(n>0) and post condition is return sum after summation of all values from 1 to n i.e return total; .
