Thread: What is the difference between the two for loops?

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    33

    What is the difference between the two for loops?

    Hi,

    I'm reading this programming book and it gives a sample code:
    Code:
    int get_maxpos(int x[], int eff_size)
    {
      int i, maxpos = 0;
    
      for (i = 0; i < eff_size; i++)
        maxpos = x[i] > x[maxpos] ? i: maxpos;
      return maxpos;
    
    }
    I thought the book has made a mistake so i type the code into my compiler as:
    Code:
    int get_maxpos(int x[], int eff_size)
    {
      int i, maxpos = 0;
    
      for (i = 0; i < eff_size; i++)
      {
        maxpos = x[i] > x[maxpos] ? i: maxpos;
      }
    
      return maxpos;
    }
    My correction turn out to be wrong since the results are different. Can you please explain to me what is the difference from having the bracket and not have a bracket?

    Also, for this part: "maxpos = x[i] > x[maxpos] ? i: maxpos; " what does the "? i:" means?

    Thank you

  2. #2
    #C-help
    Join Date
    Jun 2007
    Location
    Las Vegas
    Posts
    53

    A simple one

    The brackets separate the rest of the code from the for loop code! If you have only one line of code for the for loop, you do not need to put brackets! However, I think you are required to have them when you have more lines of code for a loop
    <<deleted because of colour and size abuse>>

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    33
    For this part: "maxpos = x[i] > x[maxpos] ? i: maxpos; "

    Can someone explains to me what "? i:" means?

    Thank you!!

  4. #4

  5. #5
    Registered User
    Join Date
    Aug 2007
    Posts
    33
    ahhh...thank you!

  6. #6
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    My correction turn out to be wrong since the results are different.
    So putting the braces in the for loop gave you different results? That doesn't make sense. From what I can see, the for loop should act the same with or without the braces.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Finding the difference in two times
    By muthus in forum C++ Programming
    Replies: 4
    Last Post: 01-24-2008, 06:36 PM
  2. Difference Equations / Recurrence Relations
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 10-05-2007, 10:26 AM
  3. What's the difference between var++ and ++var
    By ulillillia in forum C Programming
    Replies: 6
    Last Post: 05-31-2007, 02:27 AM
  4. Replies: 6
    Last Post: 08-26-2006, 11:09 PM
  5. Difference between macro and pass by reference?
    By converge in forum C++ Programming
    Replies: 2
    Last Post: 02-26-2002, 05:20 AM