initialize array?

Discussion in 'Mac Programming' started by chris200x9, Dec 19, 2007.

  1. chris200x9 macrumors 6502a

    Joined:
    Jun 3, 2006
    #1
    Hi I have work for school where I have to initialize an integer array called data
    with the values 5,6,-3,2,0 in a single statement. I am not sure if you can initialize arrays with specific numbers I am wondering if it just means to declare it i.e
    Code:
     int data[] = { 5, 6, -3, 2, 0 } 
    or to initialize an array of 4 i.e
    Code:
     for ( int i = 0; i < 4; i++ )        
          data[ i ] = 0; 
    :confused:
     
  2. iSee macrumors 68040

    iSee

    Joined:
    Oct 25, 2004
    #2
    If you can tell me what's wrong with the first statement, I'll help you (can't make it too easy, or I'll be sabotaging your learning :) )
     
  3. chris200x9 thread starter macrumors 6502a

    Joined:
    Jun 3, 2006
    #3
    I'm forgetting a ; at the end?
     
  4. iSee macrumors 68040

    iSee

    Joined:
    Oct 25, 2004
    #4
    Correct!

    So, your first answer is correct. You can initialize an array like that. It would be correct to say that the statement both declares the array "data" and initializes it (with the values 5,6,-3,2,0).

    It sounds like you might have been thinking that "initializing" means setting it to zero, but that isn't necessarily true--it just means setting an initial value. If you thought your professor or book said that, I'd ask the professor for clarification the next time you get a chance.

    Edit: Errr, we are talking about C, right? If not, I might be misleading you...
     
  5. chris200x9 thread starter macrumors 6502a

    Joined:
    Jun 3, 2006
    #5
    c++ but yea i see what you mean

    thank you also I have another question

    my homework says:
    Insert a value into the third element of a one-dimensional array data from
    the keyboard.


    but it also says to do it in one statement.


    I know how to do it like

    Code:
     
    
    int number;
    
    int array[];
    
    cin << number;
    
    cout >> array[3] = number;
    
    
    but how is this possible to do in one statement?
     
  6. pilotError macrumors 68020

    pilotError

    Joined:
    Apr 12, 2006
    Location:
    Long Island
    #6
    Well two things here really.

    One, since elements start from 0 the third element would be...

    Replace number with your array element when doing the input.
     
  7. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #7
    Methinks you have your arrows pointing the wrong direction.

    Todd
     
  8. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #8
    Also, you don't have to declare a new extra variable like you did with number. Perhaps... just perhaps... you already have an int declared somewhere else already...

    Todd
     

Share This Page