4
#include <iostream>
#include <cmath>
using namespace std;
int main() {

int i = 0;
int square = 0;

// Write a while loop here:

while ((i <= 9) && square == pow(i, 2)) {
    cout << i << square;
    i++;


}
}

  //Why is this not printing out 
/* 0   0
   1   1
   2   4
   3   9
   4   16
   5   25
   6   36
   7   49
   8   64
   9   81
          */

/Can someone explain to me thoroughly as to why this while loop fails to print out this sequence of numbers.
I don't understand why this only prints out 00 instead of that list of numbers. Can someone explain to me as why this while loop does not work properly?
/

JJL
  • 71
  • 4

3 Answers3

3

You probably wanted to do:

while (i <= 9) {
    square = pow(i, 2);
    cout << i << square;
    i++;
}

Or:

while (i <= 9 && (square = pow(i, 2))) {
    cout << i << square;
    i++;
}

Otherwise as soon as the square == pow(i, 2) is false the loop is ended and you seem to want to asign square and not compare it

Buddy Christ
  • 1,364
  • 8
  • 22
  • The second version is incorrect without adding some brackets to fix the precedence issues. And I wouldn't recommend assigning in a loop condition in any case. – john May 24 '20 at 06:40
1

You should do it like this:

// For version
double square;

for (int i = 0 ; i <= 9 ; i++) {
    square = pow(i, 2);
    cout << i <<" "<< square <<"\n";
}
//While version
double square;
int i = 0;

while (i <= 9) {
    square = pow(i, 2);
    cout << i <<" "<< square <<"\n";
    i++;
}

pow returns answer in double.

I have written double square because it may happen that for some numbers, the square of it may get truncated/ round off when you are assigning it to integer variable. See this question for more info.

KL_KISNE_DEKHA_HAI
  • 649
  • 11
  • 26
1

The reason is that you do not update "square" value in each iteration and it is always equal to zero, and hence your while loop immediately terminates by i = 1, because square = 0 and pow(i,2) = 1 . You should notice that the square == pow(i,2) condition does NOT assign the right-hand-side value to square variable. It only compares them. From your desired output I understand that you may want something like this:

i = 0;
while (i <= 9) {
    cout << i << "     " << pow(i, 2);
    i++;
}