Home > database >  how to print this pattern and swap values in nested loop?
how to print this pattern and swap values in nested loop?

Time:12-01

1 2
4 3
5 6
8 7
9 10

I want to print this pattern but don't know how to use swap with one value k

me trying this --

cin >> n;

while (i <= n) {
    int j = 1;
    while (j <= 2) {
        if (k % 2 == 0 || k == 1) {
            cout << k;
        }
        else {
            temp = k;
        }
        k  ;
        j  ;
    }
    cout << "\n";
    i  ;
}

CodePudding user response:

There's obviously lots of ways to do this, but your code is getting too complicated for a simple task. Here's some working code

#include <iostream>

bool is_odd(int n)
{
    return n%2;
}

int main()
{
    int n;
    std::cin >> n; // assume n is even
    for (int row = 0; row < n/2;   row)
    {
        if (is_odd(row))
            std::cout << 2*row 2 << ' ' << 2*row 1 << '\n';
        else
            std::cout << 2*row 1 << ' ' << 2*row 2 << '\n';
    }
}

I am assuming that n is the highest number that you want to print. I am also assuming the n is even as it's not clear from your example how you want to handle an odd number.

But if n is the number of rows, then it's a very simple modification of the above code to make that work as well.

CodePudding user response:

You are thinking too complicated. Actually I did not understand your code after reading it 1.5 times. Why is there a n a k and i and j ? There is also temp that gets a value assigned but is not used then. What are all these variables? Why do they not have names? Why do you need a nested loop?

In the code for this task I would expect a loop like this:

for (int row = 0; row < nrows;   row) {
    ...

Then in each iteration one row of two numbers is printed, ie either

std::cout << (row 1)*2 - 1 << (row 1)*2  << "\n";

or

std::cout << (row 1)*2 << (row 1)*2 - 1 << "\n";

CodePudding user response:

Here's a branch-free and division-free version -- well, except for the loop and the ostream, obviously.

inline void printPairs(std::ostream& os, std::uint64_t const n) {
  std::uint64_t offset = 0;
  for (std::uint64_t i = 1; i <= 2*n; i  = 2) {
    std::uint64_t const next = !offset;
    os << i offset << ' ' << i next << '\n';
    offset = next;
  }
}

int main() {
  std::uint64_t n;
  std::cin >> n;
  printPairs(std::cout, n);
}

I took the liberty to turn n into an unsigned type because you might run into undefined behaviour territory with a signed int.

  • Related