C++ Programming (2D Array)

Hey guys. I need help in adding the values stored in the columns and rows of an array. I'm having a hard time with this, I don't know what I should add to the code. Can you please help me with this?

Here is what we need to do. (I'll just put it here in case it gets confusing. Sorry if I have a lot of errors I'm just a beginner.)

The rows represent the bus routes and the columns represent the days that the buses run. The numbers in the slots of the array show the number of passenger that were on a given route on a given day.

Prepare a program that will:
a.) Print the number of passengers per day.
b.) Print the total passengers for Monday.
c.) Print the total number of passengers stored in Row 0.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream.h>
#include<conio.h>
main()
{
  clrscr();
  int nums[4][5],x,y;
  cout<<"No. of Passengers: "<<endl;
  for(x=0;x<4;x++)
    for(y=0;y<5;y++)
      cin>>nums[x][y];
  for(x=0;x<4;x++)
  {
    for(y=0;y<5;y++)
      cout<<nums[x][y]<<"\t";

  cout<<endl;
  }
  getch();
  return 0;
} 
Last edited on
To print the passengers you need to have a nested for loop with the outer for loop iterating over the columns and the inner loop iterating over the rows, which you can do by simply swapping x and y like so:
nums[x][y] becomes nums[y][x]. Within the innermost loop you keep a running sum of each row (passengers per day), and inside the outer for loop you can then print the sum for each day.

The other two are trivial. You just need one for loop, and for b) the column value is constant and for c) the row value is constant.
Topic archived. No new replies allowed.