do while loop

So I have a do while loop, how do i convert it to a regular while loop ?

1
2
3
4
5
6
7
8
9
10
11
12
 {
	int sum=0, hours;
	do
	{
		cin>>hours;
		if(hours==-99)
		break;
		sum=sum+hours;
	}while(hours!=-99);
	return(sum);
}
Firstly, with the do-while loop, line 6 and 7 will not be necessary. If the user inputs -99, the program will exit the loop automatically. The use of an if-statement and break is redundant.

Turning this into a while-loop is very simple. Remember, the only real difference between a while and do-while is that in a while the test comes first, then it enters the loop depending on if it passed the test. In a do-while, it will enter the loop and the test happens at the end. Thus, a do-while guarantees at least 1 iteration around the loop.

So to turn this into a while loop, just put the test (while hours !=-99) before the opening brace, and remove the semi-colon. Again, an if-statement and break will not be necessary.
Last edited on
Topic archived. No new replies allowed.