15,792,386 members
See more:
How to Initialize array with rondom numbers with single statement using C++ ?
Posted

## Solution 2

What's a statement? If you have a `for` statement that contains an assignment statement, is that one statement or two?

I should think that if you don't initialize the array you'd have fairly random numbers. :shrug:

Sounds like homework or a puzzle or something.

progahmed 31-Dec-12 14:56pm
it is not homework,
the interviewer asked me this question today morning for junior c++ developer job
PIEBALDconsult 31-Dec-12 15:12pm
Ah, that sounds like a typical question from someone who doesn't know programming.
My main responses still apply.
I don't see it being done with standard language, but maybe a common add-in library has a class that will do it.

I do C# (not C++) so I can see a library having a class that allows you to instantiate an array and provide a delegate that provides the values.
progahmed 31-Dec-12 14:58pm
he asked me to write one single statement to initialize array with randome number from 0-5 using rand() function
Sergey Alexandrovich Kryukov 31-Dec-12 15:12pm
Best answer so far, my 5. And yes "for" loop with block is one statement :-)
"Don't initialize array" is a pretty sharp idea, but in many cases the values will be 0 or all 0xFs.., not quite random.
Happy New Year!
—SA
PIEBALDconsult 31-Dec-12 15:14pm
" "for" loop with block is one statement "

Not from my point of view. And what if that one statement is a compound statement?

## Solution 5

C++
`int values[5] = { rand() % 5, rand() % 5, rand() % 5, rand() % 5, rand() % 5};`

progahmed 1-Jan-13 13:56pm
thanks thats exactly the required code
Thank you so much

## Solution 1

progahmed 31-Dec-12 14:34pm
dosen't contain solution to my question
thank you

## Solution 3

This page[^] shows an example of using `generate` to fill a vector with random numbers - replace the vector with an array and you might have the answer you were looking for.

Mattias Högström 1-Jan-13 12:38pm
True. Something like this

int myArray[10];
generate(myArray, &myArray[sizeof(myArray)/sizeof(myArray[0])], rand);

For readability, I prefer using normal for-loops.
Easier to debug too.

## Solution 4

You're being fooled by a stupid question.

Who cares about the number of statements in your source code. Does a less number of source code makes your program faster, more stable ?? Well, not at all. It may sometimes cause you problems, or can reduce the performance of your program.

Every program is built on top of another one. For example, .NET is built on top of the Windows API, the Window API is built on top of the Windows Kernel and the Windows Kernel is built on top of a CPU Architecture. They all are related.

Using Visual Basic.NET you will be able to create a windows program without just a single statement. But if you use the Windows API, it will take at least 100 lines to create a program with a window. So which one's better, faster and more stable ??