Reputation: 37
This is a simple program that reads in a matrix from the command line. The first 2 numbers it reads in represent the rows and columns and then it reads in a matrix of floating point numbers containing 0's. It reads these in line by line and stores the line temporarily in an array of floats. While it reads in the line it checks for non zero numbers and increments nz which stores the number of non zero numbers for each row and nztotal which is the total number of non zero numbers. It then goes back through this array and prints out the index and value of each non zero number. It has to back through the array so that it can print out nz first. Here is the code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[]) {
//puting the rows and columns into ints
int ar = atoi(argv[1]);
int ac = atoi(argv[2]);
//printing out the rows;
cout<< ar;
int nz = 0;
int nztotal = 0;
//creating an array of floats
float* arr = new float[ac];
//reading through line by line
for(int i = 0; i < ar;i++)
{
cout << endl;
nz = 0;
//reading through number by number
for(int j = 0;j < ac; j++)
{
//storing each number in the array
cin>> arr[j];
//checking if the number is non-zero and incrementing nz and nztotal
if(arr[j] != 0)
{
nz++;
nztotal++;
}
}
//printing out nz
cout<< nz;
//reading through the array and printing out the values and index of each non-zero number
for(int j = 0;j < ac; j++)
{
if(arr[j] != 0)
{
int temp = j + 1;
cout<< temp << arr[j];
}
}
}
cout<< nztotal;
}
This is a sample input:
4 4 2 0 3 0 2 0 3 0 2 0 3 0 2 0 3 0
This should produce this as an output:
4
2 1 2 3 3
2 1 2 3 3
2 1 2 3 3
2 1 2 3 3
8
But instead it is generating a runtime error and nothing is getting printed out. I am pretty sure it just me doing something stupid
Upvotes: 0
Views: 400
Reputation: 78
This works better, with the main changes being the corrected initialization of ar and ac, and the first line of the inner loop.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, const char* argv[]) {
//puting the rows and columns into ints
int ar = atoi(argv[1]);
int ac = atoi(argv[2]);
//printing out the rows;
cout<< ar;
int nz = 0;
int nztotal = 0;
//creating an array of floats
float* arr = new float[ac];
//reading through line by line
for(int i = 0; i < ar;i++)
{
cout << endl;
nz = 0;
//reading through number by number
for(int j = 0;j < ac; j++)
{
//storing each number in the array
arr[j] = atoi(argv[(ar * i) + j + 3]);
//checking if the number is non-zero and incrementing nz and nztotal
if(arr[j] != 0)
{
nz++;
nztotal++;
}
}
//printing out nz
cout<< nz;
//reading through the array and printing out the values and index of each non-zero number
for(int j = 0;j < ac; j++)
{
if(arr[j] != 0)
{
int temp = j + 1;
cout<< temp << arr[j];
}
}
}
cout<< nztotal;
}
Upvotes: 0