-4

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?

HazemGomaa
  • 1,620
  • 2
  • 14
  • 21
  • 3
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Sep 30 '16 at 20:31
  • Is there a specific reason why you have to solve this with the mod operator? This seems like a weird way of doing it... – Ben Wainwright Sep 30 '16 at 20:42
  • I had a similar exercise that used mod operator. – Aija Čaure Sep 30 '16 at 20:57

1 Answers1

1

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).

Ivan Smirnov
  • 4,365
  • 19
  • 30