About Array Index

This is a discussion on About Array Index within the C Programming forums, part of the General Programming Boards category; #include <stdio.h> void main() { int array[9]={1,2,3,4,5,6,7,8,9}; int i=-1; while (i<8) { printf("The Element is %d and its index is ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    Question About Array Index

    #include <stdio.h>
    void main()
    {
    int array[9]={1,2,3,4,5,6,7,8,9};
    int i=-1;
    while (i<8)
    {
    printf("The Element is %d and its index is %d\n", array[i],++i);
    }
    }

    In the above program, the loop starts with -1. But in the output , the index starts from 0 to 8. I couldn't understand the concept behind it. Can anybody explain it?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    36
    >printf("The Element is %d and its index is %d\n", array[i],++i);
    i=-1
    1. ++i, i==0 now.
    2. printf("The Element is %d and its index is %d\n",array[0],0);
    ........

  3. #3
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,856
    I'm not sure if you got the difference.

    i++ increments AFTER the operation/test of the logical operator

    ++i increments BEFORE the operation.
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,546
    > Can anybody explain it?
    It's broken code - pure and simple.

    Read this
    http://www.eskimo.com/~scs/C-faq/s3.html

    > void main()
    Read the rest of that FAQ to find out why this is broken as well.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [C] Sorting an array and preserving the original index
    By frodo_jedi in forum C Programming
    Replies: 10
    Last Post: 04-06-2009, 06:51 AM
  2. Reversing character array without accessing thro' index.
    By Roaring_Tiger in forum C Programming
    Replies: 8
    Last Post: 08-28-2004, 10:52 AM
  3. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  4. Array Program
    By emmx in forum C Programming
    Replies: 3
    Last Post: 08-31-2003, 12:44 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM

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