Is there another way to stop this do while loop mid-loop?

without the break statement, the output would exceed 100 once before it stops.
eg: Multiply= 5
Multiply=25
(this is where the break statement would have happen)
Multiply= 125
(loop stops)

My lecturer said there was another method to stop the loop before it exceeds 100 by using if else statements.
Can anyone show me how to do it?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
	//Local variable declaration
	int multiply;
	cout << "Please enter a number: ";
	cin >> multiply;

	//do loop execution
	do { 
		multiply = multiply * 5;
		if (multiply >99) //conditional break
		{
			break;
		}
		cout << "Multiply= "<< multiply<< endl;
		} while (multiply < 100);
		cout << "The multiplied result exceeds 100"<<endl;
	return 0;
}
Do you want the value of multiply to be 99, 100, or 125 after the for loop?

Something along the lines of ...

1
2
3
4
5
6
	//do loop execution
	do { 
		cout << "Multiply= "<< multiply<< endl;
		multiply = multiply * 5;
	} while (multiply < 100);
	


or
1
2
3
4
5
6
7
	//do loop execution
	do { 
		cout << "Multiply= "<< multiply<< endl;
		multiply = multiply * 5;
		if (multiply > 100)
			multiply = 100;
	} while (multiply < 100);
Last edited on
I just want the final output to be less than 100.
the user can input any number and it will keep multiplying until the final output is less than 100.
and does the top version of Ganado's code not do that for you?
You could simply not print anything if the loop is at termination condition. This, I think, is the most likely meaning:

1
2
3
4
5
6
7
do {
  multiply = multiply * 5;
  if (multiply < 100)
  {
    cout << "Multiply= " << multiply << endl;
  }
} while (multiply < 100);

You should note that Ganado’s code modifies the behavior of your loop. He is usually more careful than that; perhaps he was tired when he posted.

In any case, part of learning to program is using the most appropriate construct. I would have written:

1
2
3
4
while ((multiply *= 5) < 100)
{
  cout << "Multiply= " << multiply << endl;
}

There are other ways as well. Hope this helps.
Last edited on
@jonnin I overlooked it and it does do that.

I didn't know having the formula before the output line would make such a huge difference.
Last edited on
@Ganado thanks

@Duthomas thanks too. How will Ganado code modify the loop?
I thought it was about the actual result of multiply and not just what was printed. Yeah I wasn't sure, glad you also responded Duthomhas.
Topic archived. No new replies allowed.