stevenTan stevenTan - 5 months ago 8
Java Question

java how to convert for loop to do while loop

Sorry i'm stuck on converting this to do while loop can anybody help me please. Thanks.

int sum = 0;
int num;

System.out.print("Enter number: ");
num = sc.nextInt();
// Store the user input into variable num

// Complete the for loop to start from 1
// and end at num

for ( int i = 1 ; i <=num ; i++ )
sum += i;

System.out.println("The sum is " + sum);


and this is my do while loop

int sum = 0;
int num;

int i = 1;

do{
sum += i;
System.out.print("Enter number: ");
num = sc.nextInt();
i++;
}
while ( i <=num );

System.out.println("The sum is " + sum);

Answer
int sum = 0;
    int num;
    int i = 0;
    System.out.print("Enter number: ");
    num = sc.nextInt();
    do{
    sum += i;
    i++;
    }
    while ( i <=num );

    System.out.println("The sum is " + sum);

Initialize i to zero, since do-while does first before checking, as opposed to for that checks first before doing. And your do-while will work the same as your for.Or else your do-while will have a sum of 1 even if your num is 0. As opposed to your for that will have sum=0 if num is 0.