Click here to Skip to main content
15,891,669 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
See more:
1. Re-implement the following program using the while statement. (Java)
2. Re-implement the following program using the for statement. (Java)
public class MyClass {
public static void main(String args[]) {
int n = 6;
int p = 1;
int i = 1;
do {
p *= i;
i++;
} while (i <= n);

System.out.printf("result = %d%n", p);
}
}

What I have tried:

I understand how each statement works but I am confused on how to apply it to this program. (Java)
Posted
Updated 3-Mar-20 20:54pm

1 solution

Reading the assignment you provided it seems all it asks is to change the program in such a way so it'll output the same result with the given parameters n, p and i.

It's tricky with a do-while loop. Since it always performs the given code once and then later checks the condition. The for and while loop always check first and then run the code.

To get the same functionality, but using a while or for loop, I let the while and for loop run forever but with a condition in the loop to simulate the do-while behavior.

Your code might look like this:

public class MyClass
{
	public static void main(String args[]) 
	{
		int n = 6;
		int p = 1;
		int i = 1;
		do 
		{
			p *= i;
			i++;
		}
		while (i <= n);
		System.out.printf("result = %d%n", p);
		
		
		n = 6;
		p = 1;
		i = 1;
		while(true)
		{
			p *= i;
			i++;
			if (i>n) break;
		}
		System.out.printf("result = %d%n", p);
		
		
		n = 6;
		p = 1;
		i = 1;
		for (;;)
		{
			p *= i;
			i++;
			if (i>n) break;
		}
		System.out.printf("result = %d%n", p);
	}
}

Which outputs this:
result = 720
result = 720
result = 720

I hope this helps you out.
~Catey
 
Share this answer
 
Comments
Richard MacCutchan 4-Mar-20 4:28am    
Doing people's homework for them does not help them, just makes them less likely to try for themselves.
Catey Category 4-Mar-20 9:54am    
Yes, that's true. Perhaps I should have left out the code and just give suggestions on how to fix it themselves.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900