Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chris200x9

macrumors 6502a
Original poster
Jun 3, 2006
906
0
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:
 

iSee

macrumors 68040
Oct 25, 2004
3,540
272
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 :) )
 

iSee

macrumors 68040
Oct 25, 2004
3,540
272
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...
 

chris200x9

macrumors 6502a
Original poster
Jun 3, 2006
906
0
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?
 

pilotError

macrumors 68020
Apr 12, 2006
2,237
4
Long Island
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.
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.