Thread: Would anyone please explain me this logic ?

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    76

    Would anyone please explain me this logic ?

    Code:
    int main()
     
    {
     
    int i=0, j=0, NUM=3;
     
    for(i=-NUM; i<=NUM; i++)
     
    {
     
    for(j=-NUM; j<=NUM; j++)
     
    {
     
    if( abs(i)+abs(j)<=NUM) // Change this condition
     
     { cout<<"*"; }
     
    else { cout<<" ";}
     
    }
     
    cout<<endl;
     
    }
    return 0;
    }
    I copied this code from crazyprogrammer's blog. If anyone please explain me why the programmer used negative values here?
    I have seen many such great programs on internet without any explanation. I would ask the same question to the programmer himself but he has been inactive on Internet since two years and his blog is dead.

  2. #2
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    One thing that might help, can you post the output of the program?

    And if I had to guess negative values, it'd because i and j loop through -num to +num and make a pretty pattern when everything is printed.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    76
    Code:
    *
    ***
    *****
    *******
    *****
    ***
    *
    the program prints a diamond shape.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,323
    Right. Now, trace through the program. What happens on the first iteration of the loop? What about the second? Etc.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Sep 2008
    Posts
    76
    thanks laserlight

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 01-16-2014, 09:58 AM
  2. Help with logic !
    By noririco in forum C Programming
    Replies: 16
    Last Post: 12-03-2013, 12:20 PM
  3. Replies: 10
    Last Post: 06-09-2012, 11:55 AM
  4. Can someone explain the logic of the program
    By chibi.coder in forum C Programming
    Replies: 5
    Last Post: 12-25-2011, 09:23 AM
  5. Replies: 2
    Last Post: 10-14-2009, 07:45 AM