+ 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 ?
3 Réponses
+ 2
int sum=0, i=1
while(i<=1000) {
sum +=i;
i++;
}
+ 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);
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