Help simple c program with loop, not running through each integer.

  • #1
charmedbeauty
271
0

Homework Statement



I want to create a program that prints the sum of integers k for k(1-20)

ie,

k sum
1 1
2 3
3 6
4 10
5 .
6 .
.
.
.
.
.
20 .

in that format

Homework Equations





The Attempt at a Solution



#include <stdio.h>

int main(int argc,char * argv[]){
int i=0, sum=0, n=20;
for (i=0;i<n;++i);{

sum=sum+i;

printf("%d = %4d\n",i, sum);
}

return 0;
}

I don't want the user to enter an input (hence no scanf) I just want the program to run through integers 1-20 and print there sum.

when I run this it just prints 20 = 20??

help please!

Thanks.
 

Answers and Replies

  • #2
14,294
8,341
you put a semicolon in a bad spot

for ( ... ) ;{ ...code block... }

just runs the for loop but not the code block

try this:

for ( ...) { ...code block... }

this is a famous gotcha that many programmers do at one time or another
 
  • #3
charmedbeauty
271
0
you put a semicolon in a bad spot

for ( ... ) ;{ ...code block... }

just runs the for loop but not the code block

try this:

for ( ...) { ...code block... }

this is a famous gotcha that many programmers do at one time or another

Ohh wow that worked... I was stuck on that for a while... no pun intended:)
 
  • #4
Xitami
129
0
and now try without a loop
 

Suggested for: Help simple c program with loop, not running through each integer.

Replies
6
Views
743
Replies
13
Views
433
Replies
8
Views
128
Replies
8
Views
550
  • Last Post
Replies
4
Views
606
  • Last Post
Replies
2
Views
697
Replies
21
Views
1K
  • Last Post
Replies
5
Views
669
  • Last Post
Replies
1
Views
481
Top