Well, variables are made up of a certain number of bytes. For instance, an int is generally 4 bytes (32 bits) so the largest number it can hold before overflowing is 2^32-1.
If you forget about the large number support, you could do something like this:
Code:
itsme@dreams:~/C$ cat accumulate.c
#include <stdio.h>
int accumulate(int n)
{
int sum = 0;
int i;
for(i = 2;i < n;++i)
sum += i;
return sum;
}
int main(void)
{
int n;
do
{
printf("Enter number: ");
fflush(stdout);
scanf("%d", &n);
if(n < 3)
puts("Please enter a number greater than 2");
} while(n < 3);
printf("accumulate(n) = %d\n", accumulate(n));
return 0;
}
Code:
itsme@dreams:~/C$ ./accumulate
Enter number: 9
accumulate(n) = 35
itsme@dreams:~/C$ ./accumulate
Enter number: 2934848
accumulate(n) = -1187273761
You can see the overflow in action with the second run.
If you want to be able to have large numbers you'll have to use some tricks. Something like this:
Code:
itsme@dreams:~/C$ cat accumulate2.c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXLEN 4096
void big_add(char *s1, char *s2, char *buf)
{
char temp[MAXLEN];
char *p, *q, *t;
int num, carry = 0;
p = s1 + strlen(s1) - 1;
q = s2 + strlen(s2) - 1;
t = temp;
while(p >= s1 || q >= s2)
{
num = carry;
num += p >= s1 ? *p - '0' : 0;
num += q >= s2 ? *q - '0' : 0;
if((carry = num / 10))
num -= 10;
*t++ = num + '0';
p--;
q--;
}
if(carry && t - temp < MAXLEN)
*t = '1';
else
t--;
while(t >= temp)
*buf++ = *t--;
*buf = '\0';
}
char *accumulate(char *n)
{
static char sum[MAXLEN];
char ctr[MAXLEN] = "2";
char buf[MAXLEN];
strcpy(sum, "0");
while(strcmp(ctr, n))
{
big_add(sum, ctr, buf);
strcpy(sum, buf);
big_add(ctr, "1", buf);
strcpy(ctr, buf);
}
return sum;
}
int main(void)
{
char input[MAXLEN], *p;
for(;;)
{
printf("Enter number: ");
fflush(stdout);
fgets(input, sizeof(input), stdin);
for(p = input;isdigit(*p);p++)
;
*p = '\0';
if(p - input == 1 && input[0] < '3')
puts("Please enter a number greater than 2");
else
break;
}
printf("accumulate(n) = %s\n", accumulate(input));
return 0;
}
Code:
itsme@dreams:~/C$ ./accumulate2
Enter number: 5
accumulate(n) = 9
itsme@dreams:~/C$ ./accumulate2
Enter number: 7234724
accumulate(n) = 26170612060725
EDIT: I'll let you figure out how to add the f() function