Aija Čaure - 8 months ago 79

C++ Question

I am learning C++ and I have a problem with my program. It should print out following if

`n=11`

`*---------*`

-*-------*-

--*-----*--

---*---*---

----*-*----

-----*-----

----*-*----

---*---*---

--*-----*--

-*-------*-

*---------*

This is my code, which works correctly with n=5, but not with greater numbers:

`#include <iostream>`

using namespace std;

int main ()

{

int n;

cout << "Enter size (n x n): " << endl;

cin >> n;

for (int i=0;i<n;i++){

for (int j=0;j<n;j++){

if (i%n==j%n) cout << '*';

else if (i%(n-i)==j%(n-j)) cout << '*';

else cout << '-';

}

cout << endl;

}

return 0;

}

This is being printed out if

`n=11`

`*---------*`

-*----*--*-

--*-----*--

---*---*---

----*------

-----*-----

-*----*--*-

---*---*---

--*-----*--

-*----*--*-

*---------*

I see that I have successfully wrote how to print out one of '*' diagnoles. But something isn't working with other one, which is going backwards.

Unfortunately, I am not being able to resolve this problem and need your advice. What am I doing wrong? How to debug such problems?

Answer

This problem is really simple to debug.

Take a look at the first erroneous `*`

. It appears at the position with `i=1`

, `j=6`

. With `n=11`

, your condition `i%(n-i)==j%(n-j)`

becomes `1%(11-1) == 6%(11-6)`

which is effectively true because the expression evaluates to `1`

on both sides.

What is behind this expression? Why do you use this kind of `if`

to determine whether the cell belongs to the second diagonal? Try to write down each pair `i, j`

which should be printed on the second diagonal, and you should notice a more simple pattern.

P.S. In the expression `if (i%n==j%n)`

you don't have to take operands modulo `n`

, because both of them are less than `n`

, so it is redundant and may be rewritten simply as `if (i == j)`

.

Source (Stackoverflow)