0

The following is the code, i have tried al the other styles mentioned in the comments one by one but none worked to remove the garbage value, Although "jugaad" works but it's not performance wise good. Couldn't figure out what's wrong !

#include <bits/stdc++.h>
using namespace std;
int main() {
int n,m;
cin>>n>>m;
//    Other styles
//    int data[n+1][m+1] = {0,0};
//    int data[n+1][m+1] = {0};
//    int data[n+1][m+1] = {{0,0}};
int data[n][m] = {0};
//    Jugaad start:
for(int i=0;i<m;i++){
    data[0][i] = 0;
}
// Jugaad end
cout<<"\n";
    for(int x=0;x<n;x++){
        for(int y=0;y<m;y++){
            cout<<data[x][y]<<"\t";
        }
        cout<<"\n";
    }
cout<<"\n";
return 0;
}    

Screenshot of code and output

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • 4
    Not the answer, `int data[n][m]` is not valid C++, the array size must be known at compile-time. If it works for you, then your compiler supports it as an extenstion. You should probably be using `std::vector`. – HolyBlackCat Apr 10 '20 at 15:57
  • See [Why should I not #include ?](https://stackoverflow.com/q/31816095),[Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721) and [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/q/1887097). – prapin Sep 19 '22 at 13:42

1 Answers1

0
for(int i=0;i<n;i++)
{
    for(int j=0;j<n;j++)
      {
         data[i][j] = 0;
      }
 ``}

This will set all values of your array to zero

Genso
  • 29
  • 1
  • 6
  • Yes, but its not good performance-wise when its about competitive progrraming, and why : int arr[n][m] = {0}; not working ? – Prashant Rawat Apr 10 '20 at 16:39
  • @PrashantRawat `int arr[n][m] = {0};` is not valid C++. The size of an array must be known at compile time. Therefore there are no rules for this in C++. If your compiler supports it, you should check the documentation of your compiler. We can't help without knowing the compiler and compiler version. – Thomas Sablik Apr 10 '20 at 22:40
  • The following article will be helpful for you : https://stackoverflow.com/questions/16064820/what-is-the-time-complexity-of-array-initialization#:~:text=This%20is%20still%20O(n,it%20does%20for%20initialized%20variables%5D. – Prashant Rawat Sep 19 '22 at 14:47