Answer: In a for loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the for loop as shown below.
Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop.
Answer: In a for loop you declare and initialize the variable(s), specify the condition, and specify how the loop variable(s) change in the header of the for loop as shown below.
Answer: You need to specify the declarations and initializations of the loop variables(s) before the Boolean condition. You need to do the change(s) at the end of the body of the loop.
The following code should print the values from 1 to 10 (inclusive) but has errors. Fix the errors so that the code works as intended. If the code is in an infinite loop you can refresh the page in the browser to stop the loop and then click on Load History and move the bar above it to see your last changes.
Answer: On line 6 it should be while (x <= 10). Add line 9 at the end of the loop body to increment x so that the loop ends (isnβt an infinite loop).
Answer: You can use a for loop as shown below. Start x at 100, loop while it is greater or equal to 0, and subtract 10 each time after the body of the loop executes.
public class Test1
{
public static void main(String[] args)
{
for (int x = 10; x >= 1; x--)
{
if (x % 2 == 0)
{
System.out.println(x + " is even");
}
else
{
System.out.println(x + " is odd");
}
}
}
}
Finish the following code so that it prints a string message minus the last character each time through the loop until there are no more characters in message.
Answer: Add a while loop and loop while there is still at least one character in the string. At the end of the body of the loop reset the message to all characters except the last one.
Answer: Use a while loop. Loop while x has been found in the message (using indexOf). Remove the x (using substring). Use indexOf again to get the position of the next x or -1 if there are none left in the message.
Answer: Use nested for loops. The outer loop controls what is printed on each row and the number of rows. The inner loop controls the number of values printer per row.
public class Test1
{
public static void main(String[] args)
{
for (int x = 5; x >= 1; x--)
{
for (int y = x; y > 0; y--)
{
System.out.print(x);
}
System.out.println();
}
}
}