Arrays

Hi

If i have a number sequence for Example
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 and maximum columns in the array is 5. if i input the above then the program should display in 2D array formats as below choice for the use is to key board input the values.

TABLE: 1 5 9 12 15
2 6 10 13 16
3 7 11 14 17
4 8

How To Do This Part?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <vector>
using namespace std;

void inputRoutine( vector<int> &a )
{
   const int MAXNUM = 17;
   // Whatever you like, but for now just formulaic
   for ( int i = 1; i <= MAXNUM; i++ ) a.push_back( i );
}


void printRoutine( vector<int> a )
{
   const int COLS = 5;
   int size = a.size();                                         // total number of elements
   int fullrows = size / COLS;                                  // number of full rows
   int leftover = size % COLS;                                  // number of non-empty columns in last row
   int rows = fullrows + ( leftover != 0 );                     // total number of rows

   cout << "TABLE:\n";
   for ( int i = 0; i < rows; i++ )                             // loop through the rows
   {
      int indexTop = 0;                                         // the 1-d index at the top of a column
      for ( int j = 0; j < COLS; j++ )
      {
         int index = indexTop + i;                              // the 1-d index at a particular element
         if ( i < fullrows || j < leftover ) cout << a[index];  // where possible, print the vector element
         cout << '\t';                                          // spacer
         if ( j < leftover ) indexTop += rows;                  // update the top-of-column 1-d index for the number in this column
         else                indexTop += fullrows;              //
      }
      cout << '\n';
   }
}
 

int main()
{
   vector<int> a;
   inputRoutine( a );
   printRoutine( a );
}

TABLE:
1	5	9	12	15	
2	6	10	13	16	
3	7	11	14	17	
4	8	

Thank You For Your Help. lastchance.
There is one more thing
Using the above sample data for various values of C, below out put has to be delivered and any zero value should exit the program. any idea with below.

C ROW SUMS

5 42 47 52 12
************************************
1 , 153
************************t***********
2 11 13. 15 17 19 21 23 25 9
************************************
(Sum Of The above 2D table has to be printed)
Last edited on
Your English is rather hard to interpret ... and the statement of your problem even harder to follow.

In the first example, I assume you mean 5 columns and the individual row sums are 42, 47, 52, 12 as in the table given.

In the second example, if there is only 1 column then there are 17 rows - 153 seems to be referring to a column sum, not row sum, in this instance.

Your third example is made difficult to read by your extra period(.). Presumably, 2 columns, and these are the row sums.


If you want to vary the number of columns then you can make COLS a parameter of the printRoutine function routine, rather than the const int that it is in my sample code. You can do the row sums by summing elements for each pass of the i-loop.
Last edited on
HI lastcance

I sent you a PM with complete details. Hope thats Ok With you.
Sorry, Seanderik - the forum is to provide public resource (with a chance for others to correct my mistakes or add their own contributions and improvements). In this respect it does an excellent job, as I have learnt most of my C++11 by carefully reading others' posts, sharing code for interest and improvement, and, on occasion, deservedly getting my knuckles rapped. I don't use the PM system for transferring code and I think that this is your homework.

I suggest that:
- you modify my code sample to meet your own needs (presumably you will have a different input routine, anyway)
- you make C (in my code, COLS) a user-supplied variable, so that you can change the number of columns;
- you introduce a vector<int> rowsum(rows) so that you can add up the elements in a row (you can increment it as you pass through the j-loop)
- define the output the way you want it.
Last edited on
Hi lastchance

I am trying to modify your sample program to give the values 1-17 as keyboard input could you please tell me what change has to be done.
Use cin >>
(preferably prompting the user for what you want first).

See
http://www.cplusplus.com/doc/tutorial/basic_io/
Hi Lastchance

Thank You for your time. i was able to solve the keyboard input. One more thing can you please mention how to terminate the program when a user enters no value.
Last edited on
Well, according to your original specification:
and any zero value should exit the program
Last edited on
Hi

i tried to do the second part the sum part, but couldn't, can you help me out with that?
In the routine where you construct and print a table:

- before the loops, declare a vector<int> rowsum(rows); once declared then (for your purposes) you can treat it as a normal array;
- at the start of each pass through the i-loop, set rowsum[i] = 0;
- for each element in the j-loop that you actually print out, add this element to rowsum[i];

Once you have finished all the loops print out all the rowsum[i].

HI Last Chance

Could you tell me what change can be done for the below code to get the output that i require. it prints the sums in separate tables not in one table separated by stars. hope you could help out with the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

void inputRoutine( vector<int> &a )
{
   const int MAXNUM = 17;
   for ( int i = 1; i <= MAXNUM; i++ ) a.push_back( i );
}

void printRoutine(int COLS, vector<int> a, vector<int>& row_sum)
{
   int size = a.size();                                         
   int fullrows = size / COLS;                                 
   int leftover = size % COLS;                                  
   int rows = fullrows + ( leftover != 0 );                    

   // Set the size of the row_sum buffer
   row_sum.resize(rows);

   cout << "TABLE:\n";
   for ( int i = 0; i < rows; i++ )                            
   {
      int indexTop = 0;                                         
      for ( int j = 0; j < COLS; j++ )
      {
         int index = indexTop + i;                              
         if ( i < fullrows || j < leftover )
         {
            cout << a[index];


            row_sum[i] += a[index];
         }
         cout << '\t';                                          
         if ( j < leftover ) indexTop += rows; 
         else                indexTop += fullrows;              
      }
      cout << '\n';
   }

   
   if (COLS == 1)
   {
      row_sum[0] = std::accumulate(std::begin(row_sum), std::end(row_sum), 0);
      row_sum.resize(1);
   }
}

int main()
{
   vector<int> a;
   inputRoutine( a );

   for (int COLS = 1; COLS < 6; ++COLS) 
   {
      vector<int> row_sum; 
      printRoutine( COLS, a, row_sum );

      std::cout << '\n' << COLS << '\t';
      for (int i : row_sum)
         std::cout << i << ' ';
      std::cout << std::endl << std::endl;
   }
}
Last edited on
taking a slightly different approach using std::vector<std::vector<int>>:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>

constexpr auto COL = 5;//number of columns

int main()
{
    std::vector<std::vector<int>> myVec{};

    int num{};
    std::vector<int> tempVec;
    size_t col{};
    do
    {
        std::cin >> num;
        if(num)
        {
            tempVec.push_back(num);
            ++col;
        }
        if(col == COL)//a row of 5 completed
        {
            myVec.push_back(std::move(tempVec));//move the complete vector
            tempVec.clear();//clear tempVec from its stable but undefined state
            col = 0;//reset col
        }
        if(!num)//num == 0
        {
            myVec.push_back(std::move(tempVec));//move the incomplete vector as is
        }

    }while (num);//num != 0

    auto completeRows = std::count_if(myVec.cbegin(), myVec.cend(),
                        [](const std::vector<int>& v){return v.size() == COL;});
    //count number of complete rows

    std::cout << completeRows << " ";
    for (const auto& elem : myVec)
    {
        if (elem.size() == COL)std::cout << std::accumulate (elem.cbegin(), elem.cend(), 0) << " ";
    }
    std::cout << " \n************************** \n";
}

OP: if unfamiliar with any of the functions please google them
Last edited on
Hi lastchance

when i include the above code with previous code it gives errors. Please check below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <utility>
using namespace std;

constexpr auto COL = 5;//number of columns

void inputRoutine( vector<int> &a )
{
   const int MAXNUM = 17;
   for ( int i = 1; i <= MAXNUM; i++ ) a.push_back( i );
}

void printRoutine(int COLS, vector<int> a, vector<int>& row_sum)
{
   int size = a.size();                                         
   int fullrows = size / COLS;                                 
   int leftover = size % COLS;                                  
   int rows = fullrows + ( leftover != 0 );                    

   // Set the size of the row_sum buffer
   row_sum.resize(rows);

   cout << "TABLE:\n";
   for ( int i = 0; i < rows; i++ )                            
   {
      int indexTop = 0;                                         
      for ( int j = 0; j < COLS; j++ )
      {
         int index = indexTop + i;                              
         if ( i < fullrows || j < leftover )
         {
            cout << a[index];

            // Add the value to the row sum. We do the add here, since
            // if it should be printed it should also be added
            row_sum[i] += a[index];
         }
         cout << '\t';                                          
         if ( j < leftover ) indexTop += rows; // top-of-column 1-d index for the number in this column
         else                indexTop += fullrows;              
      }
      cout << '\n';
   }

   // Special case for COLS == 1
   if (COLS == 1)
   {
      row_sum[0] = std::accumulate(std::begin(row_sum), std::end(row_sum), 0);
      row_sum.resize(1);
   }
}

int main()
{
    std::vector<std::vector<int>> myVec{};

    int num{};
    std::vector<int> tempVec;
    size_t col{};
    do
    {
        std::cin >> num;
        if(num)
        {
            tempVec.push_back(num);
            ++col;
        }
        if(col == COL)//a row of 5 completed
        {
            myVec.push_back(std::move(tempVec));//move the complete vector
            tempVec.clear();//clear tempVec from its stable but undefined state
            col = 0;//reset col
        }
        if(!num)//num == 0
        {
            myVec.push_back(std::move(tempVec));//move the incomplete vector as is
        }

    }while (num);//num != 0

    auto completeRows = std::count_if(myVec.cbegin(), myVec.cend(),
                        [](const std::vector<int>& v){return v.size() == COL;});
    //count number of complete rows

    std::cout << completeRows << " ";
    for (const auto& elem : myVec)
    {
        if (elem.size() == COL)std::cout << std::accumulate (elem.cbegin(), elem.cend(), 0) << " ";
    }
    std::cout << " \n************************** \n";
}
Last edited on
@seanderik

I think the idea of us providing code samples is that you examine them, make the effort to understand what they mean, and write your own code.

You don't take two completely different codes, in completely different styles, and cobble them together hoping that the sum of the parts will be the answer to your problem.

Let's go back to your previous version - the one headed
Could you tell me what change can be done for the below code to get the output that i require. it prints the sums in separate tables not in one table separated by stars. hope you could help out with the code

It is hard to interpret exactly what you want, but you appear NOT to want the columnated table, but just the column count and row sums. IF that is the case, then just comment out the lines IN THAT PREVIOUS CODE:
1
2
3
4
5
   cout << "TABLE:\n";
...
   cout << a[index];
...
   cout << '\n';

You can comment them out simply by sticking
//
at the start of the relevant lines. I suggest commenting them out as you keep changing your mind about what you want.

Then just replace the slightly bizzare
std::cout << std::endl << std::endl;
in main() by
cout << "\n************************** \n";


My last contribution on this thread, I'm afraid.

Topic archived. No new replies allowed.