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

Click For Summary
SUMMARY

The discussion focuses on a C program intended to calculate and print the cumulative sum of integers from 1 to 20. The initial code contained a misplaced semicolon in the for loop, which caused the loop to execute without executing the intended code block. The corrected syntax involves removing the semicolon, allowing the loop to function as intended and produce the correct output format.

PREREQUISITES
  • Understanding of C programming syntax
  • Familiarity with control structures, specifically loops
  • Basic knowledge of cumulative sum calculations
  • Experience with debugging common programming errors
NEXT STEPS
  • Review C programming control structures, focusing on loops
  • Learn about debugging techniques in C programming
  • Explore cumulative sum algorithms in programming
  • Practice writing and correcting simple C programs
USEFUL FOR

Beginner C programmers, students learning programming fundamentals, and anyone interested in debugging common coding errors in C.

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
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · 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