0

I want to fill a 2D array but it's not guaranteed to be filled entirely. Normally I would use a nested for loop, as follows:

for(i = 0; i < 10; i++)
{
  for(j = 0; j < 10; j++)
  {
    array[i][j] = 1;
  }
}

In this case I'm filling it entirely.

However, I don't know at first how many elements I have to put inside. I thought about a while with a sentinel value, but then I should put inside a control statement to make sure the value won't exceed the size of the array, is that correct?

The code I put here is just an example, I'm actually curious about a different way to fill arrays since I've always seen for or nested for and I was wondering if there are other ways to do it. Thanks in advance.

6
  • 1
    Refer the question stackoverflow.com/questions/17288859/… This might be useful for you. Commented Jul 8, 2018 at 22:29
  • you do know the boundaries of your array and want to fill it completely, or just up to a certain point? Commented Jul 8, 2018 at 22:30
  • 2
    I think you still need a for loop, you just need to limit the end condition of your loop based upon your known size. e.g. for(I=0;i<ZZZ;++I) where ZZZ is the most you want to fill. Also look at dynamic arrays using malloc() Commented Jul 9, 2018 at 1:41
  • @R.S. I know the dimension of the array at the beginning since it's static, but I want to know, in case I don't have to completely fill the array, what kind of command could I use instead of a for loop with a break? Commented Jul 9, 2018 at 11:38
  • 1
    Iteration between values can be achieved in many ways. For, while, do, recursion etc. You just have to understand them and pick the best for your situation. I don't think I understand your question to be honest. Mostly in this case for would be appropriate and well understood by anyone reading the code Commented Jul 9, 2018 at 12:20

1 Answer 1

-1

Store them in an 1D array first then you can transfer from 1D array to 2D array and in your nested forloop you can check whether there are elements in 1D array. Does this solves it?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.