In: Computer Science
Suppose you have declared a character array called board of size 9 for a game by the declaration char board[9] and you want to initialize it with a loop so that each array member has a space character each at the beginning of the game. Which one of the following loops is the correct initialization?
The below-given loop is the correct initialization:
for(int i=0; i<3; i++) /*outer loop for accessing ith row of the board*/ { for(int j=0;j<3;j++) /*inner loop for accessing jth column or element of the particular ith row of the board*/ { board[i][j] = ' '; /* intialize each element of the board with space enclosed between ''*/ } }
Explanation: I have written comments to explain the code. Please refer to them for a better understanding. Since it is a board game with a board size of 9, it means that there would be the same number of rows and columns in the board because a board is usually a square containing rows and columns. Means, it should be a 2-dimensional array of order [nXn] elements So, in order to have same number of rows and columns, there will be 3 rows and 3 columns respectively to have a total of 9 elements. And also, since it is a character array, so each array member will be initialized with a space character by including a space enclosed between ' '. (like ' <space> '). Just hit the space button enclosed between the ' ' to initialize them.
This is because a variable/element of character datatype is initialized with the desired character enclosed between ' '.
Thanks!