简体   繁体   中英

Need help converting to do while loop

I am new to programming and I have an assignment to do in C++. I need to convert this to do while loop. Can someone help me out? Thanks in advance.

#include <iostream>
using namespace std;

int main()
{
int num;
float input, sum=0, avg;

cout<<"Input the amount of numbers: ";
cin >> num; 

for(int i = 1; i <= num; i++){
  cout<<"Enter a number: ";
  cin >> input;
  sum += input;
}

avg = sum / num;
cout << "The average is = " << avg << endl;

return 0;
}

Really simple. Just put the header statements of your old for loop in the following places: before the new loop, in the while condition of the new loop, and inside the new loop as the last line of code, respectively.

Here is your old loop code:

for(int i = 1; i <= num; i++){
  cout<<"Enter a number: ";
  cin >> input;
  sum += input;
}

And here is the new code:

int i = 1;
do {
  cout<<"Enter a number: ";
  cin >> input;
  sum += input;
  i++;
} while (i <= num);

Don't submit the assignment until you understand what I did, or you'll only be cheating yourself:) Check out this page for more info on a do...while loop. And it sounds like you could use some understanding on for loops as well, so check them out here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM