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

Click For Summary
The discussion centers on a C program intended to calculate and print the cumulative sum of integers from 1 to 20. The original code contains a misplaced semicolon in the for loop, which prevents the intended block of code from executing correctly. Participants point out that removing the semicolon allows the loop to function as intended, producing the correct output format. The user expresses relief after resolving the issue and considers exploring alternatives without using a loop. The conversation highlights a common programming mistake and the importance of syntax in coding.
charmedbeauty
Messages
266
Reaction score
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.
 
Physics news on Phys.org
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
 
jedishrfu said:
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:)
 
and now try without a loop
 

Similar threads

Replies
7
Views
3K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 19 ·
Replies
19
Views
3K
Replies
9
Views
2K
Replies
22
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K