Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Array arithmetic in C?

  1. Oct 19, 2005 #1
    int f[5];

    Is it possible to do


    inside a valid for loop?

    If not than how can I increment integers stored in an arrary for each i in C?

  2. jcsd
  3. Oct 19, 2005 #2


    User Avatar
    Homework Helper

    I don't see anything wrong with it, but I tried it and it works just fine.
  4. Oct 19, 2005 #3


    User Avatar

    Staff: Mentor

    Sure, so long as i has a valid value for an index to that array, namely in the range 0...4.

    Actually, a C compiler will cheerfully let you use a value of i outside that range, but then you'll be incrementing the contents of some memory location outside the array. This sort of thing produces bugs that can be very difficult to track down unless you step through the code with a debugger.
  5. Oct 19, 2005 #4
    One of the best ways to learn C is to test these sorts of questions.

    Code (Text):

    #include <stdio.h>

      int f[5]={0}, i;
        printf("               i = %d \n", i);
        printf("            f[i] = %d \n", f[i]);
            printf("incremented f[1] = %d \n", f[i]);

    Don't be afraid to test these things when you have a question. A simple program like the one above will usually clear things up in a jiffy.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Threads - Array arithmetic Date
Java Representation of two-dimensional arrays in the memory Dec 27, 2017
Python Array Indexing Nov 8, 2017
C/++/# Allocating a huge boolean array fails Oct 14, 2017
C/++/# Library that supports multidimensional Arrays Jul 17, 2017
Fortran programming help arrays and arithmetic Jun 5, 2014