0

Why is this do while loop infinitely executing?

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
unsigned int base;
cout << "Base: ";
cin >> base;
for (int i = 1; i <= base; i++) {
    int j = 0;
    do {
        cout << "#";
        j++;
    } while (j = i);
    cout << endl;
};
system("pause");
// keep on building up until you reach 'base'
return 0;
}

I am really confused about this. This program is supposed to create a triangle like this

#
##
###

(user inputs bottom number, so in this example the base = 3) Anybody help fix my rookie mistake?

Niellles
  • 868
  • 10
  • 27

1 Answers1

2

You might wanna try while (j == i);.

j = i is a variable declaration/assignment which will always be true as long as it succeeds. It seems like you want to compare the two, so use the equal to operator: ==.

Edit: Made a typo and therefore the same mistake as your question shows. Fixed that.

Niellles
  • 868
  • 10
  • 27
  • Thanks it fixed the infinite loop, but it isn't doing what it's suppose to do. Back to the drawing board I go. – AdamIsAProgrammer Jul 03 '18 at 15:13
  • Can't help you with that, I accidentally stumbled upon this question and probably have written less c++ than this question contains. – Niellles Jul 03 '18 at 15:18
  • @AdamIsAProgrammer Does `cout` always start a new line perhaps? – Niellles Jul 03 '18 at 15:20
  • It returns ## # # # # if I input 5 (new line after every #, except first one) which is really confusing. Because I don't know how ## gets there – AdamIsAProgrammer Jul 03 '18 at 15:22
  • I see the `cout << endl;` now. Only thing I could think of is `cout << "\n";` as an attempt for a new line. Otherwise you may have to fiddle around for a bit and perhaps ask a new question. – Niellles Jul 03 '18 at 15:30
  • can't ask another question for two days, 'cos people downvoted this question. Rip – AdamIsAProgrammer Jul 03 '18 at 16:46
  • Ah, I took a break, and came back to it, and found out what went wrong. I thought in do while loops, if the condition is true it would break the loop. However that was false, and if the condition is true it would repeat the loop. If it's false it would break the loop. So all I had to do was add a simple (!(j == i)) to fix it. – AdamIsAProgrammer Jul 04 '18 at 18:32