1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Aug 15, 2012 #1
    1. The problem statement, all variables and given/known data

    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

    2. Relevant equations



    3. 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.
     
  2. jcsd
  3. Aug 15, 2012 #2

    jedishrfu

    Staff: Mentor

    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
     
  4. Aug 15, 2012 #3
    Ohh wow that worked... I was stuck on that for a while... no pun intended:)
     
  5. Aug 15, 2012 #4
    and now try without a loop
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Help simple c program with loop, not running through each integer.
Loading...