convert do loop into while or for loop

convert this into while loop and for loop,
this solved in do loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
	int num,first,second;
	first=second=0;
	do
	{
		if(num>first)
		{
		second=first;
		first=num;
	   }
		else if(num>second)
		second=num;
	cout<<"Enter the integer 0 to exist:";
	cin>>num;
	}
	while(num!=0);
	cout<<"Second largest number is:"<<second<<endl;
//	cout<<"Largest number is:"<<first<<endl;
}
Last edited on
I'm not sure what #include<conio.h> does but i dont think you need it. Converting a do while into just a while loop is very easy. Copy everything from the do section and place it into the while section. Then erase the do section. Once that is done move the request for numbers at the top of the while loop (so the following calculations can be made with input data). The last step would be moving the cout statements outside the while loop since you only want it displayed once and that too when all the numbers have been checked. Here is the solution since it was very easy but i suggest you practice converting while loops into do while loops and vice versa if you are having issues.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
//#include<conio.h>
using namespace std;
main()
{
	int num = 1,first,second;
	first=second=0;
	
	while(num!=0)
	{
	    cout<<"Enter the integer 0 to exit:";
	    cin>>num;
	    
	    if(num>first)
		{
		    second=first;
		    first=num;
	    }
		else if(num>second)
		{
		    second=num;   
		}
	}
	cout<<"Second largest number is:"<<second<<endl;
	cout<<"Largest number is:"<<first<<endl;
}


** I also made num = 1 since you need the number initialized for the while loop. Many ways of going about this but i wanted to change your code as little as possible**
Last edited on
Thanks....this really help me
Topic archived. No new replies allowed.