You are here:

C++/How to hold the right data into an array

Advertisement


Question

  Hello Zlatko, the following program output a matrix data with the sum of each number of a row, later the user choose his
own size of a matrix to get from this matrix the rows with a number in a column chosen by him together with the smallest
sum, highest sum and the numbers in and/or out of that matrix, later the user enter and output five numbers in the
returned matrix together with sum of each row.

   I created:
      1) The array foundSums[] to hold the sums of numbers of each row of a matrix, column and number chosen by the user
so this way with  the help of the bool foundTheNumber = true get the smallest sum and highest of that matrix.
      2) The array foundRows[] to hold the rows of a matrix, column and number chosen by the user so this way with the help
of the bool foundTheNumber = true output this rows together with the row enter by the user.
   It is impossible to choose the real size for this two arrays because theirs sizes are known at run time. May be in this case
the only solution is to use Dynamic Allocation of Arrays for this two arrays or may be there is another solution for the
arrays foundSums[] and foundRows[] in the program so this way they hold what they have to. Can you help me, once again
Thanks. This is the program:

#include <iostream>
#include <iomanip>
#include <sstream>

int rows=10;
const int rowMax=15;
const int columns=5;
int wishedNumber;
int rowNumber;
int columnNumber;

using namespace std;

int getHighestSum( int t[], int n);
int getSmallestSum(int t[], int n);
int getWishedNumber();
void displayCombination(int [], int);
void printHeading();
void shiftDownOneRow(int theArray[][columns]);

int main()
{
   cout<<endl;
   int smallestSum;
   int highestSum;
   int foundSums[11];
   memset(foundSums, 0, sizeof(foundSums));
   int foundRows[11];
   memset(foundRows, 0, sizeof(foundRows));
   int userSumNumbersInRow[2];
   memset(userSumNumbersInRow, 0, sizeof(userSumNumbersInRow));
   int foundList[57];
   memset(foundList, 0, sizeof(foundList));
   int sumNumbersInRow[rows];
   memset(sumNumbersInRow, 0, sizeof(sumNumbersInRow));
   bool foundTheNumber = false;
   char choice;
   int count = 0;
   int counting = 0;
   stringstream inMatrix;
   stringstream outMatrix;
   stringstream outputRow;

   int array[rowMax][columns] ={
   {2, 15, 18, 20, 39},
   {7, 11, 14, 15, 34},
   {1, 31, 33, 34, 50},
   {8, 18, 45, 47, 50},
  {1, 10, 12, 32, 36},
  {3, 4, 15, 27, 37},
  {1, 2, 13, 19, 27},
  {12, 17, 21, 23, 30},
  {11, 36, 37, 41, 55},
  {4, 12, 13, 21, 27 }};

   printHeading();
  for(int i=0; i< rows; i++)
  {
      cout<<setw(23)<<i<<")    |";
      for(int j=0; j< columns; j++)
      {
          cout<<setw(8)<<array[i][j];
          sumNumbersInRow[i]= sumNumbersInRow[i] + array[i][j];
      }
      cout << inMatrix.str();
       cout<<setw(8 - inMatrix.str().length())<<"|"; // print spaces based on remaining length
       inMatrix.str(""); // clear the string stream contents.
      cout<<"    "<< sumNumbersInRow[i]<<endl;
  }
  cout<<endl;

   do
   {
       cout<<"    Enter a number of row to create a matrix (rows x columns): ";
       cin>>rowNumber;
   do
   {
       cout<<"    Enter a number of column (0,1,2,3 or 4) of the "
             "matrix ("<< rowNumber <<" x 5): ";
       cin>>columnNumber;
   do
   {
       memset(foundSums, 0, sizeof(foundSums));
       memset(foundRows, 0, sizeof(foundRows));
       memset(userSumNumbersInRow, 0, sizeof(userSumNumbersInRow));
       memset(foundList, 0, sizeof(foundList));
       foundTheNumber = false;
       counting = 0;

       getWishedNumber();
       cout<<endl<<endl;
       cout<<setw(42)<<"Number "<<wishedNumber<<" in column ("<< columnNumber <<") "
                       "in " <<rowNumber<<" rows"<<endl;
       cout<<setw(84)<<"----------------------------------------"
                       "---------------------\n";
       printHeading();

       for(int i= 0; i< rowNumber; i++)
       {
           if(array[i][columnNumber] == wishedNumber)
           {
               foundTheNumber = true;
               ++counting;
               cout<<setw(23)<< i <<")    |";

               stringstream inMatrix;

               displayCombination(array[i], columns);

               cout << inMatrix.str();
               cout<<setw(8 - inMatrix.str().length())<<"|";
               inMatrix.str("");

               cout<<setw(6)<< sumNumbersInRow[i] <<endl;

               foundSums[i]= sumNumbersInRow[i];
      
               for(int j = 0; j < columns; ++j)
               {
                   foundList[array[i][j]] = 1;
               }
               for(int j = 0; j< columns; ++j)
               {
                   foundRows[array[i][j]] = array[i][j];
               }
           }
       }
       cout<<endl;

      if(foundTheNumber)
      {
          for(int i=0; i< rowNumber; i++)
          {
              smallestSum = getSmallestSum(foundSums, i);
              highestSum = getHighestSum(foundSums, i);
          }
          cout<<setw(62)<<"The smallest total is: "<< smallestSum<<endl;
          cout<<setw(61)<<"The highest total is: "<< highestSum<<"\n\n";

          stringstream outMatrix;
          stringstream outputRow;
          count=0;
          for(int i = 1; i < 57; ++i)
          {
              if (foundList[i] == 0)
              {
                  outMatrix << setw(4) << i;
               // print out 15 to a line
                  if (++count % 15 == 0)
                  {
                      outMatrix << endl;
                  }
              }
          }
           cout<<setw(39)<<"There are "<<count<<" numbers OUT of "
                           "the matrix ("<<counting<<" x "<<columns<<")\n";
           cout<<setw(84)<<"----------------------------------------"
                           "---------------------\n";
           if(count <= 15)
           {
               outputRow <<setw(168)<< outMatrix.str()<<endl;
               cout << outputRow.str() << endl;
           }
           else
           {
               cout<<endl;
               outputRow << outMatrix.str() <<endl;
               cout << outputRow.str() << endl;
           }

           shiftDownOneRow(array);
           cout<<"\n    Enter 5 numbers: ";

           for(int j=0; j<columns; j++)
           {
               cin>> array[0][j];  // just use 0 for the row
               userSumNumbersInRow[0] = userSumNumbersInRow[0] + array[0][j];
           }
           cout<<endl;
           printHeading();

           for(int i=0; i< 1; i++)
           {
               cout<<setw(24)<< i <<")   |";
               for(int j=0; j< columns; j++)
               {
                   cout<<setw(8)<< array[0][j];
               }
               cout << inMatrix.str();
               cout<<setw(8 - inMatrix.str().length())<<"|";
               inMatrix.str("");

               cout<<"    "<< userSumNumbersInRow[0]<<endl;
           }
           for(int i=1; i< rows; i++)
           {
               cout<<setw(24)<< i <<")   |";
               for(int j = 0; j< columns; ++j)
               {
                   cout<<setw(8)<<foundRows[array[i][j]];
               }
               cout << inMatrix.str();
               cout<<setw(8 - inMatrix.str().length())<<"|";
               inMatrix.str("");

               cout<<"    "<<foundSums[i-1]<<endl;
           }
      }
       if (! foundTheNumber)
       {
           cout<<setw(42)<<"NUMBER " << wishedNumber << " is not in the "
                      "column ("<< columnNumber <<")\n";
       }
       cout<<"\n    Would you like to look up another "
             "number in column ("<< columnNumber <<") (y/n)? : ";
       cin >> choice;
   }   while (choice == 'y'|| choice == 'Y');

       cout<<"    Would you like to look up another column (y/n)? : ";
       cin >> choice;
   }   while (choice == 'y'|| choice == 'Y');

       cout<<"    Would you like to analized another size of a matrix (y/n)? : ";
       cin >> choice;
   }   while (choice == 'y'|| choice == 'Y');

   return 0;
}

void shiftDownOneRow(int theArray[][columns])
{
  for(int shiftRow = rows-1; shiftRow >= 0; --shiftRow)
  {
      for(int col = 0; col < columns; ++col)
      {
          theArray[shiftRow + 1][col] = theArray[shiftRow][col];
      }
  }
  ++rows;
}
void printHeading()
{
   cout<<endl;
   cout<<setw(86)<<" Rows          (0)     (1)     (2)     (3)     (4)         Sums\n";
   cout<<setw(92)<<"------------------------------------------------"
                   "-----------------------------\n";
}
void displayCombination(int array[], int index)
{
   for( int i=0; i < columns; i++)
   {
     cout << setw(8) << array[i];
   }
}
int getHighestSum( int t[], int n)
{
  int highest = t[0];

  for(int i = 1; i < n; i++)
    if ( t[i] > highest)
       highest = t[i];
  return highest;
}

int getSmallestSum(int t[], int n)
{
   int smallest = t[0];

   for(int i = 1; i < n; i++)
      if ( t[i] < smallest)
         smallest = t[i];
   return smallest;
}

int getWishedNumber()
{
   int minWishedNumber = 1;
   int maxWishedNumber = 56;

   cout<<"    Enter the number you are searching for in column "
         "("<<columnNumber<<") of the matrix ("<<rowNumber<<" x 5): ";
   cin >> wishedNumber;

   while (wishedNumber < minWishedNumber || wishedNumber > maxWishedNumber)
   {
      cout<<"\n    I'm sorry, enter a number in the range of " << minWishedNumber;
      cout <<" through " << maxWishedNumber << ": ";
      cin >> wishedNumber;
      cout<<endl;
   }
return wishedNumber;
}  

Answer
Hello Raul.

If you know the array size at runtime only, then the best option is to allocate memory dynamically. The second option is to declare a large array and hope that is will always be large enough for your program. However, with the second option, it is always possible that your estimate will be wrong, and one day your program will crash and you'll have no idea why.

Luckily, for single dimension arrays, the solution is very simple.
Instead of having
int foundSums[11];
Do this:
int* foundRows = (int*)malloc(sizeof(int) * 11);

Malloc takes a size specification in bytes, so if you want 11 integers, you need to tell malloc that you want sizeof(int) * 11 bytes. An integer is 4 bytes long, so this would allocate 44 bytes, or 11 integers.

In your program, this line won't compile
int sumNumbersInRow[rows];
because rows is not a constant. You can do the following
int* sumNumbersInRow = (int*)malloc(sizeof(int)*rows);

For one dimensional arrays allocated with malloc, you access the elements with square brackets the way you are used to, so no other changes are needed.

That is the answer to your question. I don't know if you wanted me to look at your program, but I suggest you fix it so it compiles, and then try to run it and debug it if it has problems. Then, if you need more help, let me know.

Bye for now.
Zlatko

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.