how to write program that takes a number as its argument and return the sum of 1+2+.. up to argument?
I can’t get the codes right. Can somebody help me?
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char*argv[])
{
int i;
int sum =0;
if(argc !=2){
printf("usage: %s <count> \n", argv[0]);
exit(n);
}
for(i=1; i<=atoi(argv[1]); i++){
sum+=i;
}
First, to answer your question.
You need to actually output the result. Something like:
Or return it to whoever called the program, although that is a little unusual:
But I am providing my own answer here because there is a good reason to consider doing this in a loop… At least until you’ve thought about it a bit more.
Namely, the formula
(n * (n+1)) / 2will overflow 32-bit integers and produce the wrong answer whennbecomes 65536 or greater. But the 32-bit integer can itself store a sum up ton <= 92681. That means the formula by itself produces the wrong answer for roughly 30% of the solution space.So you might think you need to loop, but there’s a little trick here. Because the formula uses both
nandn+1, you can guarantee that one of those numbers is evenly divisible by 2. And therefore you can do it like this:Now you have a simple formula that produces the same answer as the loop, at least for all values of
nthat don’t lead to overflowing the sum.