Initialization of 2D Array.

Dear friends
In my code I am initializing the value of bottom wall and top wall as shown in the code. But the compile is applying the later value to both the walls.
However they both have different conditions.
Can some one guide me?

1
2
3
4
5
6
7
8
 for (i = 0; i <= grid; i++) // Bottom Wall
{
	u_star[i][0] = 0;
}
for (i = 1; i < (grid); i++)  //  Top Wall 
{
        u_star[i][grid] = 1.0;
}
Last edited on
closed account (E0p9LyTq)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

int main()
{
   //  set an arbitrary value for your array size
   const int grid = 5;

   int u_star[grid][grid];

   for (int row = 0; row < grid; row++)
   {
      u_star[row][0] = 0;

      for (int col = 1; col < grid; col++)
      {
         u_star[row][col] = 1;
      }
   }

   for (int row = 0; row < grid; row++)
   {
      for (int col = 0; col < grid; col++)
      {
         std::cout << u_star[row][col] << ' ';
      }

      std::cout << '\n';
   }
}
0 1 1 1 1
0 1 1 1 1
0 1 1 1 1
0 1 1 1 1
0 1 1 1 1


Lack of sleep and no coffee makes it easy to not read completely what the requirements are. Is this closer to what you need?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

int main()
{
   //  set an arbitrary value for your array size
   const int grid = 5;

   // initialize the entire array
   int u_star[grid][grid] { 0 };

   for (int row = 0; row < grid; row++)
   {
      for (int col = 1; col < grid; col++)
      {
         if (row == 0 || row == grid - 1)
         {
            u_star[row][col] = 1;
         }
      }

      u_star[row][0]        = 1;
      u_star[row][grid - 1] = 1;
   }

   for (int row = 0; row < grid; row++)
   {
      for (int col = 0; col < grid; col++)
      {
         std::cout << u_star[row][col] << ' ';
      }

      std::cout << '\n';
   }
}
1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
Last edited on
If it is square, shouldn't line 7 be: u_star[i][grid-1] = 1.0;
If the grid size is known at compile time, favour using range-based loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip>

int main()
{
    constexpr int GRID_SZ = 9 ;
    double u_star[GRID_SZ][GRID_SZ] {} ; // initialise to all zeropes

    // fill top row with 3.3
    // range based loop: http://www.stroustrup.com/C++11FAQ.html#for
    for( double& v : u_star[0] ) v = 3.3 ;

    // fill bottom row with 9.9
    for( double& v : u_star[GRID_SZ-1] ) v = 9.9 ;

    // print u_star
    std::cout << std::fixed << std::setprecision(1) ;
    for( const auto& row : u_star )
    {
        for( double v : row ) std::cout << v << "  " ;
        std::cout << "\n\n" ;
    }
}

http://coliru.stacked-crooked.com/a/a8e093e4cfcc7a1f
Damn JLBorges, I'm glad I stopped to read that topic, that faq link is really resourceful!
Thanks guys.
Topic archived. No new replies allowed.