Jump to content

Easy One

- - - - -

  • Please log in to reply
6 replies to this topic

#1
yourmom615

yourmom615

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
So I am trying to convert the below for loop to produce the same result using a while loop. As of now no luck in getting the same result. See below code and any advice would greatly be appreciated.

int sum = 0;

for (int i = 0; i <= 1000; i=i+2) sum += i;

System.out.println(sum);

For my while loop this is the best I have come up with and I am unable to get it to compile.

        int sum = 0;

        int i = 0;

        while (i < 1000); {

        i=i+2;sum += i;

        System.out.println(sum);

        }

Any help would be greatly appreciated!!!

Edited by yourmom615, 12 March 2011 - 04:35 PM.


#2
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
int sum = 0;

int i = 0;

while (i <= 1000); {

    sum += i;

    i=i+2;

}


System.out.println(sum);


This should work but I haven't tried it.

#3
yourmom615

yourmom615

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
My complier is telling me there is an empty statement after the while but there is obviously a semi colon right there. ??????

#4
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
ouch, yeah. just get rid of it.

int sum = 0;

int i = 0;

while (i <= 1000) {

    sum += i;

    i=i+2;

}


System.out.println(sum);


#5
yourmom615

yourmom615

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
Yeah, that fixed it real nice. So simply put what was I doing wrong keeping the program from running the while loop?

#6
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
Java interprets a semicolon as an empty instruction. So, when you had the semicolon after the while statement, your program executed an empty instruction (no instruction) a thousand times. After that, it executed the 3 instructions:

sum += i;

i=i+2;

System.out.println(sum);

The brackets are simply ignored.

#7
yourmom615

yourmom615

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
Thanks for the help!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users