+ 1

Use a while loop to calculate the sum of all numbers from 1 to 1000 . Make it print only the sum, not the intermediate values.

HOW TO THIS ?

16th Jan 2018, 8:15 AM
Tanmay Sarkar
Tanmay Sarkar - avatar
3 Antworten
+ 2
int sum=0, i=1 while(i<=1000) { sum +=i; i++; }
16th Jan 2018, 9:03 AM
shobhit
shobhit - avatar
+ 2
@shobhit Technically, your code will result in an infinite loop. Here's an improved version: for(int sum = 0, i = 1; i <= 1000; i++){ sum += i; } System.out.println(sum);
16th Jan 2018, 11:01 AM
blackcat1111
blackcat1111 - avatar
0
oops. that was a mistake but i have edited it. thnx and yes for loop would be a better alternative but question specifically requires a while loop
16th Jan 2018, 3:31 PM
shobhit
shobhit - avatar