How to turn a while loop into a do while loop? [closed]
I have this:
#include <iostream>
using namespace std;
int main()
{
char ch, max = 0;
int n = 0;
cout << "Enter number of characters! :";
cin >> n;
cout << "Enter the number";
while (n>0)
{
cin >> ch;
if(max<ch)
max = ch;
n=n-1;
}
cout << "max is : " << max;
}
I'm trying to turn it into a do while loop - here's what I have:
int main()
{
char ch, max = 0;
int n = 0;
cout << "enter character";
cin >> n;
cout << "enter two";
cin >> ch;
do
(max<ch);
while
(max = ch);
(n>0);
n= n - 1;
cout << "max is : " <开发者_开发问答< max;
}
How do I fix this?
The first program needs to check for EOF or other failures after the extractor is used:
#include <iostream>
using namespace std;
int main()
{
char ch, max = 0;
int n = 0;
cout << "Enter number of characters: ";
cin >> n;
cout << "Enter the number: ";
while (n > 0 && cin)
{
if (cin >> ch && max < ch)
max = ch;
n = n - 1;
}
cout << "max is : " << max << endl;
return 0;
}
I note that there is nothing in the code that enforces 'it is a number' beyond the hint in the prompt. Further, most interfaces that make the user count something that the computer could count instead are misguided.
There is very little point in converting the code to use a do ... while
loop, but if you must, then it ends up looking like:
#include <iostream>
using namespace std;
int main()
{
char ch, max = 0;
int n = 0;
cout << "Enter number of characters: ";
cin >> n;
cout << "Enter the number: ";
if (n > 0 && cin)
{
do
{
if (cin >> ch && max < ch)
max = ch;
n = n - 1;
} while (n > 0 && cin);
}
cout << "max is : " << max << endl;
return 0;
}
Note the condition that appeared at the top of the while
loop is now a separate if
condition and is repeated in the do ... while (...)
condition. This alone tells you that do ... while
is inappropriate here; you only want to go through the loop if there is work to do, but a do ... while
loop forces you through the loop once regardless.
while (test) block;
is equivalent to
if (test) {
do block
while (test);
}
so your while loop would be changed into
if (n>0) {
do {
cin >> ch;
if(max<ch)
max = ch;
n=n-1;
} while (n>0);
}
精彩评论