Is there any way by which I can initialize all the elements of an array(already declared) in one statement?? That is, without using loops

You can't initialise anything that has already been declared. You can only initialise something at the time it is created, after that it becomes assignment.

And to answer the spirit of your question no there is no way to assign to all members of an existing array without recourse to a for loop (with the exception of using memset on an array of char).

hey there,
And if you want to ask is if we can initialize at the time of declaration we do it like this,

int a[10]={1,2,3,4,5};

To assign a value later to any element of the array code will be,

a[1]=33;
a[4]=55;

Anirudh

If you want to initialize all the elements of an array to 0, you can use this

#define SIZE 5
int my_array[SIZE] = {0};

Check out memset and memcpy also.

You can't initialise anything that has already been declared. You can only initialise something at the time it is created, after that it becomes assignment.

Not true. By setting a value, (for example- a loop counter before a while loop) is initializing the value.

Not true. By setting a value, (for example- a loop counter before a while loop) is initializing the value.

When you do that, aren't you declaring that variable?? That makes the guy you quoted correct.

I guess the terminology has changed, then. For the past 35 years initializing a variable has been setting it to a know value just before entering a piece of code (like a loop) that does some kind of processing. When did that change?

What you call initializing I always called defining.

I've been learning just about 1-2 years now, but initializing has always been basically assigning a value when the variable, or whatever it is, is being declared.

I've don't know how you put a counter before a while loop. I know about IN the for loop though, so I guess we are WAY different

I think The initializer for an array is a comma-separated list of constant expressions enclosed in braces ({ }). The initializer is preceded by an equal sign (=). You do not need to initialize all elements in an array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type.


for eg:
Element Value Element Value
matrix[0][0] 1 matrix[1][2] 0
matrix[0][1] 2 matrix[1][3] 0
matrix[0][2] 0 matrix[2][0] 5
matrix[0][3] 0 matrix[2][1] 6
matrix[1][0] 3 matrix[2][2] 0
matrix[1][1] 4 matrix[2][3] 0


-------------------------------------------
<URL SNIPPED>

commented: spammer -1

We have to used
Syntax data type array[]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.