Just a little help to beginners about initializing arrays!! Run-time error

Hello everyone,

I’ve seen a lot of beginners struggling with runtime errors, most of the time the reason for those runtime errors is very simple. Let’s say a question problem involves an array, and we need to store that array. Beginners struggle with that, recently in 2 days, I’ve seen 2 people doing the same mistake e.g initializing the array
as

                           int[1000], 

irrespective of the constraints, end up getting those runtimes errors. Let me explain to beginners why they get that error and why initializing the array with random numbers isn’t a good practice!! Let’s say you already initialized the array with the size of 1000 elements, and then you create a for loop asking the user to enter the elements of that array. Now, you already had the array as size 1000 but user wants 1001 elements in it

                     for(int i = 0;i<size;i++)  
                         array[i] = user input   

Pay attention!! Now, you haven’t created the memory for 1001 elements, you have only created an array of 1000 elements, now there is no space to store your 1001st element. Just a quick example - Let say you’re a builder and you made a home for a family, Let’s say in that house only one person can live in one room. So, as a good builder, you should ask them “Hey!! how many people are in your family?” And then build the house!! Let’s say you’re a bad builder and you didn’t ask the number of family members. And you build the house with 3 rooms, but there were 4 members in the family, Now, there is not enough space for everyone to stay!! Same with the arrays.

So just a little advice for beginners -

Nearly all of the problems at Codechef ask you to get the user to input the size of the array first, and then ask for each element using for loop! Get the size of the array first before initializing the array,
initializing the array as random numbers consider bad habit in programming!! Instead of doing this int[1000], ask the user for the size of the array and based on the size you can create your array as int[size]; And please don’t create arrays like int[1000000000] by doing this you might be wasting so much memory!!

Hope this helps!

3 Likes

how can i get the size from the question like in c code…
The only line of input contains integers n and k (1 ≤ k ≤ n ≤ 1012).