-1
int a[100][100]; //globally declared array
int main()
{
    while(testcases--)
    {
        a[100][100]={0};
        //rest of code
    }
    return 0;
}

This code works only for first testcase. For next testcases, it doesn't set the elements to zero.

I can't afford to run a loop to run a loop and iterate all the elements. I want to perform this task in O(1). Is it possible?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
rishi_07
  • 17
  • 1
  • 2
  • 7

3 Answers3

1

You are using the same array between runs and you want to reset it to zero. You cannot avoid iterating on all the cells and setting them to zero. Even when initializing to zero on decleration, there's no such thing as promising O(1). The way the compiler initializes is up to the compiler.

gbehar
  • 1,229
  • 10
  • 10
1

First, you seem to have a slight misunderstanding of terms.

This is an initialization:

int a = b;

This is an assignment:

int a;
a = b;

You can initialize an array to zeroes using following code:

int array[10][20] = {0};

Or:

int array[10][20] = {};

Or:

int array[10][20] {};

Keep in mind that global (and static) arrays are zero-initialized by default.

You can fill array with zeroes after it was created like this:

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

Or:

for (int (&a)[100] : array) // or  for (auto &a : array)
    for (int &b : a) // or  for (auto &b : a)
        b = 0;

Or:

std::memset(array, 0, sizeof array);

P.S.

You can't fill an array with zeroes at runtime for O(1).

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

Your array is zero-initialized "for the first testcase" simply because it is declared with static storage duration. And such array with static storage duration begins its life zero-initialized.

Your

a[100][100]={0};

line has nothing to with it. This is actually a mere a[100][100] = 0, which is writing a single 0 into a non-existing (out of bounds) element of your array. (The behavior is undefined).

If you wan to reinitialize your array with zeros on each iteration, you have to do it either manually or using a library-level solution, since there is no core-language-level feature that would do it for you. In your case (an array of integers) you can even use the old-fashioned

std::memset(a, 0, sizeof a);

You can also use something clever-but-inefficient like

decltype(a) zeros{};
std::swap(a, zeros);

on each iteration, but it's probably not worth it.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765