102k views
4 votes
Given a two-dimensional array of integers named q, with 2 rows and 4 columns, write some code that puts a zero in every element of q. Declare any variables needed to help you.

1 Answer

0 votes

Answer:

By choosing a programming language such as Java, the codes that puts a zero in every element of the two-dimensional array, q can be as follows:

  1. public class HelloWorld{
  2. public static void main(String []args){
  3. int q[][] = new int[2][4];
  4. for(int i = 0; i < 2; i++)
  5. {
  6. for(int j = 0; j < 4; j++)
  7. {
  8. q[i][j] = 0;
  9. }
  10. }
  11. }
  12. }

Step-by-step explanation:

  • Line 5 - Declare a variable q and specify two indices 2 and 4 within the square brackets. This will create an array with a size of 2 rows and 4 columns.
  • Line 7 - Write an outer for-loop that iterate through the rows
  • Line 9 - Write an inner for-loop that iterate through the columns
  • Line 11 - Assign zero to the element of q at a specific index, i (current row number) and j (current column number). This line of code will run repeatedly and assign zero to q[0][0], q[0][1], q[0][2] .... q[1][0], q[1][1]....,q[1][3]

We can also verify our result by adding some codes (Lines 15 - 21) to print every element of q and check if all of the elements are set to zero:

  1. public class HelloWorld{
  2. public static void main(String []args){
  3. int q[][] = new int[2][4];
  4. for(int i = 0; i < 2; i++)
  5. {
  6. for(int j = 0; j < 4; j++)
  7. {
  8. q[i][j] = 0;
  9. }
  10. }
  11. for(int i = 0; i < 2; i++)
  12. {
  13. for(int j = 0; j < 4; j++)
  14. {
  15. System.out.println(q[i][j]);
  16. }
  17. }
  18. }
  19. }

We will see the Line 19 will print out zero for each element of q.

User Ovidiu Buligan
by
5.2k points