All in Java How would you sum up the first X numbers in cod
*All in Java*
- How would you sum up the first X numbers (in code)? Hint: loops
- Write a for-loop that does the above with X being a user input.
- Write the same code using a while-loop and a do-while-loop.
- What are the differences between the 3 loops? When do you use each one?
Solution
int X = 10;
int sum = 0;
int i=1
for(i=1;i<=X;i++)
sum = sum + i;
i = 1;
sum = 0;
while(i++<=X)
sum = sum+i;
i = 0;
sum = 0;
do
{
sum = sum+i;
i = i+1;
}while(i<=X);
Differences between 3 loops :
for loop initialization,loop condition check and increment happens at one place.
while loop first initialization happens then we do the error checking and then increment.
do while loop, loop will execute atleast once which is not the case in for and while loop.
If you want to execute your loop atleast once then use do while else all 3 can do the job.
