Assume you are given a boolean variable named isNegative and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that assign true to isNegative if more integer elements in entire 2-dimensional array are negative than not.

Respuesta :

Answer:

#include <iostream>

using namespace std;

int main(){

   int rows, cols;

   bool isNegatives;

   cout<<"Rows: ";

   cin>>rows;

   cout<<"Columns: ";

   cin>>cols;

   int a2d[rows][cols];

   for(int i =0;i<rows;i++){

   for(int j =0;j<cols;j++){

       cin>>a2d[i][j];}    }

   int negatives, others = 0;

   for(int i =0;i<rows;i++){

   for(int j =0;j<cols;j++){

       if(a2d[i][j]<0){

           negatives++;}

       else{

           others++;}}    }

   if(negatives>others){

       isNegatives = true;}

   else{

       isNegatives = false;}

   cout<<isNegatives;  

   return 0;

}

Explanation:

For clarity and better understanding of the question, I answered the question from the scratch.

This line declares number of rows and columns

   int rows, cols;

This line declares the Boolean variable

   bool isNegatives;

This line prompts user for rows

   cout<<"Rows: ";

This line gets the number of rows

   cin>>rows;

This line prompts user for columns

   cout<<"Columns: ";

This line gets the number of columns

   cin>>cols;

This line declares the array

   int a2d[rows][cols];

This line gets user input for the array

   for(int i =0;i<rows;i++){

   for(int j =0;j<cols;j++){

       cin>>a2d[i][j];}    }

This line declares and initializes number of negative and others to 0

   int negatives, others = 0;

The following iteration counts the number of negatives and also count the number of non negative (i.e. others)

   for(int i =0;i<rows;i++){

   for(int j =0;j<cols;j++){

       if(a2d[i][j]<0){

           negatives++;}

       else{

           others++;}}    }

This checks of number of negatives is greater than others

   if(negatives>others){

If yes, it assigns true to isNegatives

       isNegatives = true;}

   else{

If otherwise, it assigns false to isNegatives

       isNegatives = false;}

This prints the value of isNegatives

   cout<<isNegatives;  

See attachment

Ver imagen MrRoyal