Thread: Compare integers in an array

  1. #1
    Registered User
    Join Date
    Jun 2021
    Posts
    1

    Compare integers in an array

    Hello. I'm new to C programming and attending a web course. We learned about arrays but I still struggle to understand how to compare values in an array. Say I have
    Code:
    {2 4 6 1 5}
    and I want to compare index 0 with index 1,2,3,4 not by typing
    Code:
    array[0]
    and
    Code:
    array[1]
    but
    Code:
    array[k] with array[?]
    .

    Thank you in advance, Mike

  2. #2
    Registered User
    Join Date
    Apr 2021
    Posts
    39
    I'm going to assume that you're trying to compare "every element to every other element" or some such. This is a use case that occurs frequently in dealing with arrays.

    To do this, you'll want two variables. Traditionally, these are i and j. When you get to a third variable, that will be k. (This comes from Fortran, where variable type (integer, real, etc) was determined by the first letter.)

    Code:
    extern SomeType a[];
    extern size_t alen;
    
    for (int i = 0; i < alen; ++i) {
        for (int j = i + 1; i < alen; ++j) {
            // do something with a[i], a[j]        
        }
    }

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    502
    Quote Originally Posted by emikash View Post
    Hello. I'm new to C programming and attending a web course. We learned about arrays but I still struggle to understand how to compare values in an array. Say I have
    Code:
    {2 4 6 1 5}
    and I want to compare index 0 with index 1,2,3,4 not by typing
    Code:
    array[0]
    and
    Code:
    array[1]
    but
    Code:
    array[k] with array[?]
    .

    Thank you in advance, Mike
    Code:
    int main(void)
    {
        int array[5] = {2, 4, 6, 1, 5};
        int j, k;
    
        for (j =0; j < 5; j++)
          for (k = 0; k < 5; k++)
          {
              char compare;
              if (array[j] < array[k])
                 compare = '<';
              else if (array[j] > array[k])
                 compare = '>';
              else
                  compare = '=';
    
              printf(array[%d] %c array[%d]\n", j, compare, k);
          }
    
    }
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 03-29-2015, 05:30 AM
  2. Replies: 4
    Last Post: 01-31-2014, 09:27 PM
  3. Replies: 3
    Last Post: 03-26-2012, 10:50 AM
  4. Replies: 9
    Last Post: 04-07-2010, 10:03 PM
  5. Replies: 7
    Last Post: 05-11-2008, 10:57 AM

Tags for this Thread