0% found this document useful (0 votes)
11 views

COMP248 Tutorial 06

This document discusses while and do-while loops in Java. It provides examples of while loops and do-while loops with different conditions and outputs. It also provides questions asking to write code using while and do-while loops to print even numbers, sum numbers, and find the smallest positive integer meeting certain criteria.

Uploaded by

wok20902
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

COMP248 Tutorial 06

This document discusses while and do-while loops in Java. It provides examples of while loops and do-while loops with different conditions and outputs. It also provides questions asking to write code using while and do-while loops to print even numbers, sum numbers, and find the smallest positive integer meeting certain criteria.

Uploaded by

wok20902
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Tutorial #6: While and Do…While Loops

Question 1:
What is the output of the following?

A.
int count = 0;
while (count <= 6)
{
System.out.print(count + " ");
count = count + 2;
}
System.out.println( );

B.
int count = 7;
while (count >= 4)
{
System.out.print(count + " ");
count = count - 1;
}
System.out.println( );

C.
int i; int j;
boolean again = true;

for (i = 1; i < 5; i++)


{
again = !again;
for (j = 1; j < 5; j += 2)
{
System.out.print(i + " " + j);
if (again)
System.out.print("-");
else
System.out.print("*");
}
System.out.println();
}

1
D.
int a = 30;
int b = 3;

while (a >= b)
{
System.out.println("while " + a + " " + b);
if ((a % b) == 0)
{
a = a / b;
b++;
}
else
{
a = a - 1;
b = b - 1;
}
}
System.out.println("the end " + a + " " + b);

E.
int i = 5, count = 0;
while (i != 1)
{
System.out.println(count + " " + i);
count++;
if ((i % 2) == 0)
i /= 2;
else
i = 3 * i + 1;
}

2
F.
boolean sign = true;
int sum = 0;
int n = 0;

while (sum < 30)


{
if (sign)
sum = sum + n;
else
sum = sum - n;
System.out.print(sum);
sign = !sign;
n = n + 10;
}

G.
int x = 0;
while (x != 8);
{
System.out.print("Hello");
x = x + 1;
}

H.
int x = 0;
while (x != 8);
{
System.out,print("Hello");
}

Question 2:
Write Java code that uses a do…while loop that prints even numbers from 2
through 10.

3
Question 3:
Write Java code that uses a while loop to print even numbers from 2 through 10.

Question 4:
Write Java code that uses a do while loop to sum the numbers from 1 through
50. Display the total sum to the console.

Question 5:
Write a Java program using a while loop to find and display the smallest positive
integer whose remainder:
• when divided by 3 is 1,
• when divided by 5 is 2, and
• when divided by 7 is 3.

You might also like