I am creating an algorithm to count natural numbers however the output is a long number:
1532752%
Here is what I have tried:
#include <stdio.h>
#include <stdlib.h>
int sumN(int N){
int S = 0;
int I = 1;
int *p = &I;
for(int i = *p; i < N; i ){
S = S i;
I = i 1;
if( i <= N){
continue;
}
}
return S;
}
int main(void){
int N = 15;
printf("%i", sumN(N));
return EXIT_SUCCESS;
}
I am new to C and would appreciate feedback because I am likely missing much technical information.
CodePudding user response:
Simple version
int sum =0;
For (int i =1; i<=N; i ){
sum = i;
}
This ignores the even simpler n*(n 1)/2 formula
CodePudding user response:
#include <stdio.h>
#include <stdlib.h>
int sumN(int N)
{
return N*(N 1)/2;
}
int sumN2(int N)
{
int sum = 0;
for(int i=1; i<=N; sum =i );
return sum;
}
int main(void){
int N = 15;
printf("%i\n", sumN(N));
printf("%i\n", sumN2(N));
return EXIT_SUCCESS;
}
Output
120
120
because 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 = 120