0

Print a sequence of n^n for 1 to 15. This code only prints out 0. What am I doing wrong?

int main()
{
    int i, n;

    i = 0;
    n=1;

    do {
        n = n^n;
        cout << n;
        n++;
        i++;

    }while(i<15);

    return 0;
Michael
  • 1
  • 2
  • Unrelated to the question as asked, but you'll need to add `endl` to that cout statement so your numbers don't jumble up on the same line (unless that is what you wanted to happen ). – RTHarston Feb 07 '20 at 16:56
  • [Arithmetic operators in C++](https://en.cppreference.com/w/cpp/language/operator_arithmetic) – Hawky Feb 07 '20 at 16:56
  • 1
    Note that on some chipsets `a XOR a` where `a` is a register is a faster way of setting the register to 0 rather than an assignment. – Bathsheba Feb 07 '20 at 16:57
  • You are possibly confused about what the `^` operator does. It is not an exponentiation operator (C++ doesn't have one of those)! Rather it is an **exclusive or** (bitwise) operator - and any number XORed with itself is zero. – Adrian Mole Feb 07 '20 at 16:58
  • 3
    @Bathsheba I'd expect a compiler for that platform to know that and produce an XOR operation for such an assignment. Point being you should still write an assignment, because that's the meaning of your program – Asteroids With Wings Feb 07 '20 at 16:58
  • 1
    @RTHarston Why would you pay for a flush if you don't need it? Use `'\n'` instead of `std::endl`. – Thomas Sablik Feb 07 '20 at 17:08
  • @ThomasSablik Good point, thanks for the reminder. I only suggested `std::endl` since Michael wasn't already using a string literal that he could easily add the `\n` to (not that "\n" is any harder to add then std::endl, I just personally prefer the second for cleanliness when not already using a string literal). I completely forgot about the flush (still a bit new with C++), I'll look into that a bit more. – RTHarston Feb 07 '20 at 23:11

0 Answers0