130k views
2 votes
write a short C function that takes an integer n and returns the sum of all integers smaller than n.?

User Suguna
by
4.6k points

2 Answers

3 votes

int sumAllNumbersSmallerThanN(int n){

int sum=0;

int i;

for(i=1; i<n; i++){

sum += i;

}

return sum;

}

We simply declared a variable, sum, that will store the result, and set it to zero. Then, we loop all numbers from 1 to n-1, and we sum all these numbers to our sum. When the counter reaches n, the loop stops, and we will have added all numbers from 1 to n-1 in the variable sum.

User Kingsley Ijomah
by
4.6k points
3 votes

"int sumofintegers (int n)

{

int cnt , sum;

sum = 0;

for (cnt = 0; cnt<n; cnt++)

{

sum = sum + cnt;

}

return sum;

}

The above function receives the ‘n’ as input and then initialize two variable cnt is used for looping and sum variable to add the numbers which are smaller than the given number.

A for loop is run from 0 to n (not including n since we need to add integers less than n) and then add each value. When the counter reaches n, for loop is exited and the sum is returned to the calling portion.

User Fmagno
by
5.6k points