What are these lines of code doing in this program?

This is a discussion on What are these lines of code doing in this program? within the C++ Programming forums, part of the General Programming Boards category; This line: int j = (n-1)/2, k, l; This line: k=(i) ? (i-1) : (n-1); and This line: l=(j) ? ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    84

    What are these lines of code doing in this program?

    This line: int j = (n-1)/2, k, l;
    This line: k=(i) ? (i-1) : (n-1);
    and
    This line: l=(j) ? (j-1) : (n-1);




    #include<iostream.h>
    #include<iomanip.h>

    const int SIZE = 7;

    void main(int n)
    {

    int Magic[SIZE][SIZE];
    cin>>n;
    if(!(n%2))
    {
    cout<<"n is even"<<endl;
    return;
    }
    else{
    for(int i = 0; i < n; i++)
    for(int j=0; j<n; j++) Magic[i][j] = 0;
    Magic[0][(n-1)/2]=1;//Middle of first row
    //(i,j) is the current position.
    int j = (n-1)/2, k, l;
    for(int key = 2; key <= n*n; key++){
    //Move up and left. Teh next two if statements
    //may be replaced by the % operator if -1%n is
    //implemented to have value n-1.
    k=(i) ? (i-1) : (n-1);
    l=(j) ? (j-1) : (n-1);

    if (Magic[k][l]) i = (i + 1) %n;
    else
    {// Magic[k][l] is empty.
    i = k;
    j = l;
    }
    Magic[i][j] = key;
    }
    //Output the magic square
    for(i=0; i<n; i++){
    for(j=0; j<n; j++)
    cout<<setw(5)<<Magic[i][j];
    cout<<endl;
    }
    }
    }

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    This line: int j = (n-1)/2, k, l;

    how about if it had been written ....

    int k,l;
    int j= (n-1)/2;

    This line: k=(i) ? (i-1) : (n-1);

    this could be rewritten as ....

    if ( i != 0) k=i-1;
    else
    k=n-1;

    This line: l=(j) ? (j-1) : (n-1);

    this similarly could be rewritten as....

    if (j != 0) l=j-1;
    else
    l=n-1;
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 30
    Last Post: 06-19-2006, 12:35 AM
  2. large program code ,please help
    By Ash1981 in forum C Programming
    Replies: 14
    Last Post: 01-30-2006, 05:16 AM
  3. Please test my program: Code Black
    By PhoenixC++ in forum Windows Programming
    Replies: 15
    Last Post: 04-29-2004, 07:18 PM
  4. Lines from Unix's source code have been copied into the heart of Linux????
    By zahid in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 05-19-2003, 03:50 PM
  5. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 11:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21