I have a for loop, a very simple one, in my program, and I want it to loop through and do something for some minimum number of times. However, the loop simply...stops. But does not move on to the next thing in the program. For instance, when min is 9, it runs for i=0 to i=8, then freezes. It should exit the for loop, but it does not execute the next print instruction, nor does it execute the loop again. It just stops. The program hangs, doing absolutely nothing as far as I can tell. I don't understand why this is.
The merged.put() function I want to execute just puts x or y in merged, depending on the condition. That part works. This is just a small part of a much larger program. sp1, sp2, and merged are all defined elsewhere.
int i;
int x;
int y;
for(i=0; i < min; i++)
{
cout << " here " + convert(i);
x = sp1.get_num(i);
y = sp2.get_num(i);
if(x >= y) {
merged.put(x);
}
else {
merged.put(y);
}
cout << " end" << endl;
}
cout << "out";
EDIT: I'm not posting the entire code, it's several hundred lines long. Type of min is int. The reply down there was helpful, when << endl was added to the last print statement, it printed. My problem now appears to be here, getting stuck on the second while, because I was not incrementing i. Shame on me...thanks for the help. (This comes directly after the above code)
if (sp_large == 2) {
cout << "1" << endl;;
while (i < sp2.get_size()) {
merged.put(sp2.get_num(i));
}
}
else {
while (i < sp1.get_size()) {
merged.put(sp1.get_num(i));
}
cout << "2" << endl;
}
EDIT: Problem solved, thanks for the help.
I'm betting that it's actually a later part of the program that is hanging.
This line:
cout << "out";
just puts "out" on the output-buffer, and won't actually print "out" until the output-buffer gets flushed. (Which could happen immediately, but is not likely to.) Change that line to this:
cout << "out" << endl;
and "out" will be printed as soon as that line is run. This will help you figure out if the program is hanging before it gets to that line, or somewhere later on.
Related
the question!!
Justify your answer.
for (int i = 0; i < 100; i++)
{
cout << i;
cout << 2 * i;
cout << 4-1;
}
the answer that I have!!!
assuming the cout for the following is 3 but since the output is long not so sure. 0031232433634835103612371438163918310203112231224313263142831530316323173431836319383204032142322443234632448325503265232754328563295833060331623326433366334683357033672337743387633978340803418234284343863448834590346923479434896349983501003511023521043531063541083551103561123571143581163591183601203611223621243631263641283651303661323671343681363691383701403711423721443731463741483751503761523771543781563791583801603811623821643831663841683851703861723871743881763891783901803911823921843931863941883951903961923971943981963991983
I'm pretty sure I'm wrong so someone pls help.
Let's run through the first interation, where i is 0:
for (int i = 0; i < 100; i++)
{
cout << i;
cout << 2 * i;
cout << 4-1;
}
Looks like for the first iteration through the loop, the cout operation is executed 3 times (because there are 3 cout statements).
Let's go another iteration. We have 3 more cout operations for a total of 6 so far.
Another iteration, another 3 more operations for a total of 9.
Looks like there are 3 cout operations performed for each iteration of the loop.
So to find the total, you should determine the maximum iterations of the loop, then multiply by 3.
If the owner's of the question are considering that a cout operation doesn't finish until the output is displayed, then that's difficult to answer. The answer could be zero if the buffers are not flushed. Could be one if the cout buffer is flushed only at the end of the program. Or the cout could flush its buffer when the buffer gets full; so this depends on the size of the buffer. Hard to answer without a clear definition of "a cout operation".
So I have a stack example I created following a tutorial using the stack library
stack<string> custs;
custs.push("george");
custs.push("louie");
custs.push("florence");
// cout << "size" << custs.size() << endl;
if (!custs.empty()) {
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
}
I ran this and got the output:
florence
louie
My question is why isn't it outputting George as well? The program outputs the top data then pops it. This means it should output Gorge then pop it after. Why doesn't this happen? initially the code was i < cust.size so I thought because i is not less than 1 it would not ouput. So I switched it to <= and it still doesn't output George. How come?
It is because you are both increasing i and reducing the size of the stack in the loop.
You can rewrite your loop like this:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop()
}
Here is a step by step explanation of what is happening so you can understand it better:
First, i starts as 0, and custs.size() returns 3. Since 0 <= 3 is true, the body of the loop executes, printing "florence" and removing it from the stack.
On the second iteration, i equals 1, and custs.size() returns 2, because you had 3 items but you removed one. Since 1 <= 2 is true, the body of the loop executes again, printing "louie" and removing it from the stack.
Then, i equals 2, and custs.size() returns 1, because you already removed 2 elements. Since 2 <= 1 is false, the body of the loop doesn't execute, and the loop ends.
As you can see, the problem is that your loop's condition changes on each iteration. There are a couple of ways to fix this:
int s = custs.size();
for (int i = 0; i < s; i++) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you store the original size of the stack, so you can iterate without problems.
Another solution would be to check if the stack is empty on each iteration with a while loop:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you check if there are any elements left to print each time.
Hope this helps!
When you use for loop like this
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
it loops directly till the size of stack which decreases in each iteration.
which in my opinion is the main reason your code is not working. I rewrite this as
int z = custs.size() ;
for(int i=0;i<=z;i++)
{
cout<<custs.top()<<endl;
custs.pop();
}
and it worked perfectly fine. In my opinion, the best approach is to use while loop like this
while(!custs.empty())
{
cout<<custs.top()<<endl;
custs.pop();
}
This question already has answers here:
'do...while' vs. 'while'
(31 answers)
Closed 8 years ago.
I would like someone to explain the difference between a while and a do while in C++
I just started learning C++ and with this code I seem to get the same output:
int number =0;
while (number<10)
{
cout << number << endl;
number++
}
and this code:
int number=0;
do
{
cout << number << endl;
number++
} while (number<10);
The output is both the same in these both calculations. So there seem to be no difference.
I tried to look for other examples but they looked way to difficult to understand since it contained mathemetical stuff and other things which I haven't quite learned yet. Also my book gives a sort of psychedelic answer to my question.
Is there an easier example to show the difference between these 2 loops?
I was quite curious
The while loop first evaluates number < 10 and then executes the body, until number < 10 is false.
The do-while loop, executes the body, and then evaluates number < 10, until number < 10 is false.
For example, this prints nothing:
int i = 11;
while( i < 10 )
{
std::cout << i << std::endl;
i++;
}
But this prints 11:
int j = 11;
do
{
std::cout << j << std::endl;
j++;
}
while( j < 10 );
The while loop is an entry control loop, i.e. it first checks the condition in the while(condition){ ...body... } and then executes the body of the loop and keep looping and repeating the procedure until the condition is false.
The do while loop is an exit control loop, i.e. it checks the condition in the do{...body...}while(condition) after the body of the loop has been executed (the body in the do while loop will always be executed at least once) and then loops through the body again until the condition is found to be false.
Hope this helps :)
For Example:
In case of while loop nothing gets printed in this situation as 1 is not less than 1, condition fails and loop exits
int n=1;
while(n<1)
cout << "This does not get printed" << endl;
Whereas in case of do while the statement gets printed as it doesn't know anything about the condition right now until it executes the body atleast once and then it stop because condition fails.
int n=1;
do
cout << "This one gets printed" << endl;
while(n<1);
If you consider using a different starting value you can more clearly see the difference:
int number = 10;
while (number<10)
{
cout << number << endl;
number++
}
// no output
In the first example the condition immeditately fails, so the loop won't execute. However, because the condition isn't tested until after the loop code in the 2nd example, you'll get a single iteration.
int number = 10;
do
{
cout << number << endl;
number++
}
while (number<10);
// output: 10
The while loop will only execute of the conditions are met. Whereas the do while loop will execute the first time without verifying the conditions, not until after initial execution.
friends. I have a problem.
Problem: the computer must pick randomly one string out of an array of 36 strings. If by any chance it picks strings #34 or #35 (the two last ones), it has to draw two more random strings from the same array. I tried a do-while solution, and it "almost" works (see code below).
The randomization works fine - called srand inside main(). There is a forced "x2" draw (for testing reasons), so the computer draws two more strings. These two new random picks are NOT "x2", but still the loop kicks again - but just one more time! This time the computer picks two more "chits", which aren't "x2" either, so, as expected, it returns the "The chits have been drawn" sentence and the function is terminated. Why is the same code running twice with the same results but different if/else behavior? Thank you very much in advance.
string mortalityCalc ()
{
string mortalityChits[36] = {"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","27","28","29","30","-","-","-","-","x2","x2"};
int mortalityResult;
// mortalityResult = rand() %36;
mortalityResult = 35; // for testing only. Delete afterwards.
string drawnChit = mortalityChits[mortalityResult];
string drawnChit1;
string drawnChit2;
if (drawnChit != "-" && drawnChit != "x2")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'.";
return returnText;
}
else if (drawnChit == "-")
{
string returnText = string("The computer has drawn the chit '") + drawnChit + "'. No senators died this year.";
return returnText;
}
do
{
cout << "The computer has drawn the 'x2' chit." << endl;
cout << "Two more chits will be drawn.\n" << endl;
mortalityResult = rand() %36;
drawnChit1 = mortalityChits[mortalityResult];
cout << "The first draw is the chit '" << drawnChit1 << "'. ";
mortalityResult = rand() %36;
drawnChit2 = mortalityChits[mortalityResult];
cout << "The second draw is the chit '" << drawnChit2 << "'." << endl;
} while (drawnChit1 == "x2" || drawnChit2 == "x2");
return "The mortality chits have been drawn. The corresponding senators are dead.";
}
UPDATE: Tried running this code isolated from the rest of the program and it behave as expected. So I guess it's important to post what comes before it:
cout << "If you are a lazy bastard, the computer can pick one senator randomly for you.\nAre you a lazy bastard? [y/n]" << endl;
string lazyBastard;
cin >> lazyBastard;
cout << endl;
if (lazyBastard == "y" || lazyBastard == "Y" || lazyBastard == "yes" || lazyBastard == "YES" || lazyBastard == "Yes")
{
mortalityCalc ();
cout << mortalityCalc () << endl;
cout << "Very well. Now, imminent wars become active (Only one of each match)." << endl;
cout << "Get ready for the next phase." << endl;
My guess, from reading some other questions here, is that somehow the cin is messing with the loop behavior, even though they are not related and there's no user input whatsoever in the loop's statements or conditions. Is that possible? If so, why and how to remedy it?
Thank you again.
In the first loop you are forcing an 'x2' so your are entering the do-while loop. The result of the two calls for 'rand())%36' is always 19 and a number between 30 and 34. The point is that the random number generator generates always the same sequence of numbers, if you don't give him a seed 'srand(...)'.
do {
// ...
cout << rand()%36;
// ...
} while( /*...*/ )
See http://ideone.com/zl8ggH
You have to create random numbers and your code does what you expect.
Finally! I thought it would be a stupid thing! I just realized that I called the mortalityCalc() function twice! That's why it was looping twice!
Thanks to all who tried to help!
So, I'm getting the above error (in the title) but for some reason it's only throwing this error on the second loop. Notice the first and second loop I have using the customer variable works absolutely fine, no errors thrown or anything. But on that last loop, the output[customer][charge] array, there is a red line under output[customer] that says "Subscripted value is not an array, pointer or vector". I am using xcode, Mavericks OSX. All of my arrays are defined elsewhere, and have worked perfectly the whole length of the program until now. There are some other operations going on in the program, but they have nothing to do with this loop, so I just posted the code that was giving the error. Again I'll say, the charges[customer][month][charge] loop works fine, but the output[customer][output] is not working.
P.S. You probably will think the logic behind keeping all this data in numerically indexed arrays is dumb, but it is for a school project. So don't lecture me about how this program is logically inconsistent or whatever. Thanks!
string headings[3][7];
string chargeLabels[3] = {"Electricity :","Water: ","Gas: "};
string outputLabels[5] = {"Subtotal: ","Discount: ","Subtotal: ","Tax: ","Total: "};
double charges[3][3][3];
double output[3][5];
for(int customer=0; customer<3; customer++)
{
for(int heading=0; heading<5; heading++)
{
cout << headings[customer][heading];
}
for(int month=0; month<3; month++)
{
cout << chargeLabels[month];
for(int charge=0; charge<3; charge++)
{
cout << charges[customer][month][charge] << ", ";
}
cout << endl;
}
for(int output=0; output<5; output++)
{
cout << outputLabels[output];
//error is below this comment
cout << output[customer][output] << endl;
}
}
Inside the for statement:
for(int output=0; output<5; output++)
{
You declared another variable int output which shadows the double output[3][5] with the same name outside the for statement.
Here's your problem:
double output[3][5];
for(int output=0; output<5; output++)
You're reusing output as a variable name twice.
So when you try to access it here:
cout << output[customer][output] << endl;
You're accessing the local output, which is just an int.