lundi 19 novembre 2018

Adding rows in a 2D array

A user inputs a desired array of desired rows and columns . The code needs to look through the array and find all the rows with at least one negative number. If found , then the code adds a new row of zeros below the founded row.

Code

#include <pch.h>
#include <iostream>

using namespace std;

int main()
{
int rows, columns;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
std::cout << "Enter the number of columns: ";
std::cin >> columns;


int **array = new int*[rows];                  //Generating a 2-D array
for (int i = 0; i < rows; i++)
    array[i] = new int[columns];

std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < columns; i++)              //loop for input array 
    for (int j = 0; j < rows; j++)             //elements
        std::cin >> array[i][j];

for (int i = 0; i < columns; i++) {            //print the array
    for (int j = 0; j < rows; j++) {
        std::cout << array[i][j] << " ";
    }
    std::cout << "\n";
}
for (int i = 0; i < columns; i++) {             //finding rows with negative
    for (int j = 0; j < rows; j++) {            //numbers and adding a new 
        if (array[i] < 0) {                     // row of zeros below
            array[i + 1][j] = 0;
            std::cout << array[i][j] << " ";
        }
    }
    std::cout << "\n";
}

return 0;
}

For instance
If we enter an array like
1 1 1 1 1
2 -2 2 -2 2
3 3 3 3 3
4 -4 -4 4 4
5 5 5 5 5
The answer should be
1 1 1 1 1
2 -2 2 -2 2
0 0 0 0 0 -----> new rows added
3 3 3 3 3
4 -4 -4 4 4 ------> new rows added
0 0 0 0 0
5 5 5 5 5
But my code doesn't do it ?

Aucun commentaire:

Enregistrer un commentaire