How can I alter my program for the desired output? - c++

I am trying to write a program that takes user input for the number of hours worked by 6 employees of a company to store in a two-dimensional array and prints the output in the following format:
Employee Number Hours
01 a
02 b
03 c
04 d
05 e
06 f
where a-f would be the user entered integer values.
I have experimented with several methods but am unable to get my desired output. I am attaching the recent attempt:
#include <iostream>
using namespace std;
int main()
{
int array[6][2]; // 6 by 2 matrix to store employee name and hours worked
int i, j;
cout << "Enter the number of hours worked by 6 employees: " << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> array[i][j];
cout << array[i][j] << "\t" << endl;
break;
}
cout << endl;
}
}
What changes should I make to get the required output?

You should take the input first. Then in order to print with column name you should first print those column names and then print the values.
Your code should be like this -
#include <iostream>
using namespace std;
int main()
{
int array[6][2]; // 6 by 2 matrix to store employee name and hours worked
int i, j;
cout << "Enter the number of hours worked by 6 employees: " << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> array[i][j];
}
}
cout << "Employee Number \t Hours" << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cout << array[i][j] << "\t\t\t ";
}
cout << endl;
}
}
Output:
Edit:
For your requirement from the comment, new code will be
int main()
{
int array[6][2]; // 6 by 2 matrix to store employee name and hours worked
int i, j;
cout << "Enter the number of hours worked by 6 employees: " << endl;
cout << "Employee Number \t Hours" << endl;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> array[i][j];
cout << array[i][j] << "\t\t\t ";
}
cout << endl;
}
}

Related

2D Array. Calculating the average of the student

I can't figure out why I can't calculate the average. The output of the average is same as the other look the details in the picture below. My teacher told me to return the AVG to 0, but I don't know where to put it.
#include <iostream>
using namespace std;
const int ROW = 3;
const int COL = 3;
const int D = 3;
void display(int nums[ROW][COL]);
void show(int ID[D]);
int main()
{
int nums[ROW][COL];
int ID[D];
double AVG = 0;
for (int i = 1; i <= ROW; i++) {
cout << "Enter student ID[" << i << "]: ";
cin >> ID[i];
for (int j = 0; j < COL; j++) {
cout << "Enter student[" << i << "] Grades [" << j + 1 << "]:";
cin >> nums[i][j];
AVG = AVG + nums[i][j];
}
AVG = AVG / 3;
}
for (int i = 1; i <= ROW; i++) {
cout << "Student ID: " << ID[i] << endl;
for (int j = 0; j < COL; j++) {
cout << "Score: " << nums[i][j] << endl;
}
cout << "Average: " << AVG << endl;
}
return 0;
}
You Have some problem regarding this issues:
you take AVG as double but other variable as integer.so there is a datatype error.
2.you have problem doing array indexing.
Here Is the Solution. Here I declare AVG as an integer type array so that it remains same as your code.
#include
using namespace std;
const int ROW = 3;
const int COL = 3;
const int D = 3;
void display(int nums[ROW][COL]);
void show(int ID[D]);
int main ()
{
int nums[ROW][COL];
int ID[D];
int AVG[ROW];
for(int i=1; i<=ROW; i++)
{
cout << "Enter student ID[" << i <<"]: ";
cin>>ID[i];
AVG[i-1]=0;
for(int j=0; j<COL; j++)
{
cout<<"Enter student[" << i << "] Grades [" <<j+1<<"]:" ;
cin>>nums[i-1][j];
AVG[i-1] = AVG[i-1] + nums[i-1][j];
}
AVG[i-1] = AVG[i-1] / 3;
}
for(int i=1; i<=ROW; i++)
{
cout <<"Student ID: " << ID[i] << endl;
for(int j=0; j<COL; j++)
{
cout<<"Score: "<<nums[i-1][j]<<endl;
}
cout << "Average: " << AVG[i-1]<< endl;
}
return 0;
}
Currently you are calculating the average as follows;
First iteration:
(90 + 90 + 90) / 3 = 90
Second iteration:
(90 + 80 + 80 + 80)/3 = 110
Third iteration:
(110 + 70 + 70 + 70)/3 = 106
If you want to get the average of all grades, do this;
double AVG = 0;
double avg_tmp;
for (int i = 1; i <= ROW; i++) {
avg_tmp = 0;
cout << "Enter student ID[" << i << "]: ";
cin >> ID[i];
for (int j = 0; j < COL; j++) {
cout << "Enter student[" << i << "] Grades [" << j + 1 << "]:";
cin >> nums[i][j];
avg_tmp += nums[i][j];
}
AVG += avg_tmp / 3;
}
Your biggest issue is you invoke Undefined Behavior with your loop limits for for (int i = 1; i <= ROW; i++). In C/C++ all array indexes are Zero-Based with valid indexes of 0 <= i < n. So your i loop must be for (int i = 0; i < ROW; i++).
You do NOT need to compute the sum or average in your first set of loops. The first set of nested loops are you Input Loops where you are simply filling the elements of ID and nums. You only need AVG in your second set of nested loops (e.g. your Output Loops) Avoid mixing input and output logic.
Only declare and initialize your variables in the scope where they are needed. This will fix what your professor is talking above. If you only declare and initialize AVG within the first output-loop where the average will be computed, it will automatically be reset to zero for each student.
Putting it altogether, you could do:
#include <iostream>
const int ROW = 3; /* good job on declaring constants */
const int COL = 3;
const int D = 3;
int main()
{
int nums[ROW][COL] = {{0}}; /* initialize all plain-old arrays */
int ID[D] = {0};
for (int i = 0; i < ROW; i++) {
std::cout << "\nEnter student ID[" << i + 1 << "]: ";
/* you must validate EVERY user-input */
if (!(std::cin >> ID[i])) {
std::cerr << "error: invalid integer input.\n";
return 1;
}
for (int j = 0; j < COL; j++) {
if (!j)
std::cout.put('\n');
std::cout << "Enter student[" << i+1 << "] Grades [" << j+1 << "]: ";
if (!(std::cin >> nums[i][j])) { /* ditto */
std::cout << "error: invalid integer input.\n";
return 1;
}
}
}
for (int i = 0; i < ROW; i++) {
double AVG = 0.; /* declare / initialize in scope needed */
std::cout << "\nStudent ID: " << ID[i] << '\n';
for (int j = 0; j < COL; j++) {
std::cout << " Score: " << nums[i][j] << '\n';
AVG += nums[i][j]; /* sum each score */
}
std::cout << "Average: " << AVG / COL << '\n';
}
}
Example Use/Output
$ ./bin/studentavg
Enter student ID[1]: 1
Enter student[1] Grades [1]: 90
Enter student[1] Grades [2]: 89
Enter student[1] Grades [3]: 91
Enter student ID[2]: 2
Enter student[2] Grades [1]: 79
Enter student[2] Grades [2]: 81
Enter student[2] Grades [3]: 80
Enter student ID[3]: 3
Enter student[3] Grades [1]: 71
Enter student[3] Grades [2]: 70
Enter student[3] Grades [3]: 69
Student ID: 1
Score: 90
Score: 89
Score: 91
Average: 90
Student ID: 2
Score: 79
Score: 81
Score: 80
Average: 80
Student ID: 3
Score: 71
Score: 70
Score: 69
Average: 70
Look things over and let me know if you have further questions.
package test;
import java.util.*;
public class DoubleArray {
public static void main(String[] args) {
String[][] arr = {{"Ram", "100"}, {"Mohan", "80"}, {"Ram", "70"}, {"Mohan", "60"}, {"Chitra", "80"}, {"Ram", "88"}};
HashMap<String, Integer> pf = new HashMap<String, Integer>();
List<String> as = new ArrayList<>();
for (int row = 0; row < arr.length; row++) {
if (pf.containsKey(arr[row][0])) {
as.add(arr[row][0]);
pf.put(arr[row][0], ((pf.get(arr[row][0]) + Integer.parseInt(arr[row][1]))));
} else {
as.add(arr[row][0]);
pf.put(arr[row][0], Integer.parseInt(arr[row][1]));
}
}
int value = 0;
for (Map.Entry<String, Integer> entry : pf.entrySet()) {
pf.put(entry.getKey(), entry.getValue() / Collections.frequency(as, entry.getKey()));
value = Collections.max(pf.values());
if (entry.getValue() == value) {
System.out.println(entry.getKey() + "," + entry.getValue());
}
}
}
}

Reversing the order of a for loop output

I am currently writing a task where the user will input a number and it'll output a number of "*" depending on the number. Eg if the user inputted a 5, the answer would be:
*
**
***
****
*****
This is my current code:
#include <iostream>
using namespace std;
int number;
char star = '*';
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
for (int i = 0; i < number; i++)
{
for (int j = i; j < number; j++)
{
cout << star;
}
cout << " " << endl;
}
return 0;
}
If the number 5 was inputted, this would output:
*****
****
***
**
*
How would I go about reversing the order so that it is ascending order rather than descending.
You would need to use the for loop in descending instead of ascending order.
Example:
cout << "Input a number between 1 and 10" << endl;
cin >> number;
for (int i = number -1; i >= 0; i--) {
for (int j = i; j < number; j++) {
cout << star;
}
cout << "*" << endl;
}
return 0;
}
You can do that by just reversing the order of the change of i:
#include <iostream>
using namespace std;
int number;
char star = '*';
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
//for (int i = 0; i < number; i++)
for (int i = number - 1; i >= 0; i--)
{
for (int j = i; j < number; j++)
{
cout << star;
}
cout << "*" << endl;
}
return 0;
}
(Just how to reverse the order of the change of i is shown. The output of this program is not as expected.)
My preference is using i as the number of stars to print and avoiding using gloval variables and using namespace std;:
#include <iostream>
int main()
{
int number;
char star = '*';
std::cout << "Input a number between 1 and 10" << std::endl;
std::cin >> number;
for (int i = 1; i <= number; i++)
{
for (int j = 0; j < i; j++)
{
std::cout << star;
}
std::cout << std::endl;
}
return 0;
}
Just go from number all the way down instead of up:
for (int i = number; i > 0; i--)
{
for (int j = i; j > 0; j--)
{
cout << star;
}
std::cout << '\n';
}
Instead of j<number use j<i and instead of j=i use j=0:
#include <iostream>
using namespace std;
int number;
char star = '*';
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
for (int i = 0; i < number; i++)
{
for (int j = 0; j < i; j++)
{
cout << star;
}
cout << "*" << endl;
}
return 0;
}
there are multiple ways to achieve what you want. You can insert everything inside and array and print the array backwards, insert everything inside an array (starting from last position) and then print it in natural order, you can do it only by using indexes (like i and a lot of other persons did here). I also added a little input check, and put the code in functions for clearness:
#include <iostream>
using namespace std;
int number;
char star = '*';
void version1();
void version2();
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
while(number < 1 || number > 10)
{
cout << "I SAID BETWEEN 1 AND 10, IS EASY, RIGHT?" << endl;
cin >> number;
}
version1();
version2();
return 0;
}
void version1()
{
cout <<"Version 1: "<<endl;
for (int i = 0; i < number; i++)
{
for (int j = i; j < number; j++)
{
cout << star;
}
cout << endl;
}
}
void version2()
{
cout << "Version 2: (only by using indexes)" << endl;
int cap_index = 0;
for (int i = 0; i < number; i++)
{
cap_index = i + 1;
for (int j = 0; j < cap_index; j++)
{
cout << star;
}
cout << endl;
}
}
btw this is a more serious (and simple) way to check input:
do
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
}while(number < 1 || number > 10);
In my case i put it this way:
starting from 0 print '*' up to i + 1 times, this way you have an ascending order print:
first time (from 0 to 1) print '*' -> print once
second time (from 0 to 2) print '*' -> prints twice
and so on up to the inserted number
Obviously this isn't not the best way to do this nor the most elegant, like in nearly every situation there are a lot of possibilities.
ps. i'm not sure, but you have an error in your code, as it prints a '*' more, each time, i don't know how is your output like that
By using a std::string, you can avoid the need of an explicit inner loop.
#include <iostream>
#include <string>
int main()
{
int number;
char star = '*';
std::cout << "Input a number between 1 and 10" << "\n";
std::cin >> number;
for (int i = 0; i < number; i++)
{
std::cout << std::string (i+1, star) << "\n";
}
return 0;
}
Changing the second 'for' loop condition, in your function --
From,
for (int j = i; j < number; j++)
Change it to ,
for (int j = 0; j <= i; j++)

Using for loops to enter data into arrays

So I have this C++ program that contains .h file and main.cpp. In .h I have this class:
class Plaza
{
public:
int length;
double x;
double y;
Plaza();
~Plaza();
};
In main.cpp, I am trying to enter the data using for loop, and I manage to store data for int i = 0 state, but when i is increased, no data that has been entered is being stored into array. For the inside loop, I tried to put j < n, j < n-1 and j < n+1, but it's not working. How can I store all the data and print it out?
#include <iostream>
#include "Plaza.h"
using namespace std;
int main() {
int n;
Plaza *obj1;
cout << "Enter limit number (N): ";
cin >> n;
obj1 = new Plaza[n];
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
for (int i = 0; i < n; i++) {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " Length=" << obj1[i].length;
}
delete[] obj1;
system("pause");
return 0;
}
This is the print I get:
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
Here's your culprit. Get rid of the inner for-loop (not the cin-statements, just the for... line and its closing bracket) and replace obj[j] with obj[i]. You are currently repeatedly writing to obj[0].
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
Why there is a need of second for loop., if you check the j value, it is always 0 so only one value is inserted.,
try this
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
cin >> obj1[i].length;
cin >> obj1[i].x >> obj1[i].y;
}
}

Getting the Average,Min, and Max of numbers in 2D array

I have a problem with getting the min,max, and average of an elements of 2D array.
I have a 2D array which contains Students and Grades.
I am generating the grades with rand. For example When I enter 2,2 it prints me out
Courses : 01 02 Average Min Max
ID
01 8 50 29
02 74 59 29
, My average function takes the first ones average and doesnt take the others average.
Here is my code ;
int A[30][30];
int findAverage(int noOfStudents ,int noOfGrades ){
float sum,average;
for (int i = 0 ; i < noOfGrades ; i++) {
for (int j = 0; j<noOfStudents; j++) {
sum += A[i][j];
}
average = sum / noOfGrades;
// cout << " " << format(average);
sum = 0;
return format(average);
}
and here how I use it
int main() {
int noOfCourses , noOfStudents;
cin >> noOfCourses >> noOfStudents;
cout << "Courses : " ;
for (int i = 0; i < noOfCourses; i++) {
if (i+1 >= 10) {
cout << i+1 << " ";
}else{
cout <<"0" << i+1 << " ";
}
}
cout << "Average Min Max";
for(int i=0; i<noOfStudents; i++) { //This loops on the rows.
for(int j=0; j<noOfCourses; j++) { //This loops on the columns
A[i][j] = genGrade();
}
}
cout << "\n ID " << endl;
for(int i=0; i<noOfStudents; i++) { //This loops on the rows.
if (i+1 >= 10) {
cout <<" " << i+1 << " ";
}else{
cout <<" 0" << i+1 << " ";
}
//cout <<" 0" << i+1 << " ";
for(int j=0; j<noOfCourses; j++) { //This loops on the columns
if (A[i][j] >= 10 && A[i][j] <=99) {
cout <<" " << A[i][j] << " ";
}
if(A[i][j] < 10) {
cout <<" " << A[i][j] << " ";
}
if (A[i][j] == 100) {
cout << A[i][j] << " ";
}
}
cout <<" "<<findAverage(noOfStudents,noOfCourses);
cout << endl;
}
}
What am I doing wrong ? Also How could I get the min,max of the per array?
I would strong recommend using containers for this task. For example you could do the following
typedef std::vector<float> grades;
std::vector<grades> student_grades;
//populate
for(const grades& gr : student_grades) {
float min, max, avg;
std::tie(min, max)=std::minmax(gr.begin(), gr.end());
avg=std::accumulate(gr.begin(), gr.end(), 0.0) / gr.size());
std::cout << "Min" << min << " Max: " << max << " Avg: " << avg << std::endl;
}
http://en.cppreference.com/w/cpp/algorithm/minmax
http://en.cppreference.com/w/cpp/algorithm/accumulate
http://en.cppreference.com/w/cpp/utility/tuple/tie
For starters, you are returning from inside your loop:
for (int i = 0 ; i < noOfGrades ; i++) {
for (int j = 0; j<noOfStudents; j++) {
...
}
...
return ...;
}
Can you see how the outer loop will only ever execute once?
The problem is that in your findAverage function you have a return statement within the loop that is looping through the rows. If you want a very simple fix add another parameter to the findAverage function that indicates which row to calculate the average for.
int findAverage(int course ,int noOfGrades ){
float sum,average;
for (int j = 0; j<noOfStudents; j++) {
sum += A[course][j];
}
average = sum / noOfGrades;
return format(average);
}
and call it like this
cout <<" "<<findAverage(i,noOfCourses);

Summing all the numbers in a matrix revised

Hello I had recently asked a question about how to do the following:
Write a function that sums all the integers in a matrix of integers using the following header:
const int SIZE = 4;
double sumMatrix (const double m [] [SIZE] , int rowSize, int columnSize) ;
Write a test program that reads a 4-by-4 matrix and displays the sum of all its elements. Heres a sample run:
Enter a 4by4 matrix row by row:
1 2 3 4 [Enter]
5 6 7 8 [Enter]
9 10 11 12 [Enter]
13 14 15 16 [Enter]
Sum of the matrix is 136
I tried to use all the suggestions I could but the problem maybe that I just need to go back to the basic and learn some basic things I have skipped over, but heres what I have so far. Corrections and solutions, and help in any form would be highly appreciated.
#include <iostream>
using namespace std;
const int COLUMN_SIZE = 4;
int sum(const int a[] [COLUMN_SIZE], int rowSize)
{
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += a[row][column];
}
}
return total;
}
int main()
{
int m[4][4]=
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
cout<< "Sum of the matrix"<< sum(m,4) << endl;
return 0;
}
The read function that you need will look almost the same as your print function:
void read(const int a[] [COLUMN_SIZE], int rowSize)
{
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
cout << "Enter number for [" << row << "][" << column << "]: ";
cin >> a[row][column];
}
}
}
(As a footnote: if you can generalise the looping and have one function that you pass 'read' or 'sum' to you're well on your way to being awesome)
edit: guess I didn't read the 'row by row' bit of the question. shrug.
Three years later, haha, but you can enter cols elements separating them with spaces and use enter to get elements of other row.
Improving your code. Just see and understand. A didactic program is better than a thousand words :p
#include <iostream>
using namespace std;
const int COLUMN_SIZE = 4;
int sum(const int a[] [COLUMN_SIZE], int rowSize)
{
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += a[row][column];
}
}
return total;
}
void showmatrix(const int a[] [COLUMN_SIZE], int rowSize, const char *name)
{
int row_index, col_index;
cout<< name << " [" << rowSize << "][" << COLUMN_SIZE << "] =" << endl;
for(row_index = 0; row_index < rowSize; row_index++)
{
for(col_index = 0; col_index < COLUMN_SIZE; col_index++)
{
if(col_index == 0)
{
if(row_index ==0)
{
cout<< "\t /";
}
else if(row_index == rowSize - 1)
{
cout<< "\t \\";
}
else
{
cout<< "\t|";
}
}
cout<< "\t" << a[row_index][col_index];
if(col_index == 3)
{
if(row_index ==0)
{
cout<< "\t\\";
}
else if(row_index == rowSize - 1)
{
cout<< "\t/";
}
else
{
cout<< "\t |";
}
}
}
cout<< endl;
}
cout<< endl;
}
int main()
{
int m[4][4]=
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
int row_index, col_index;
cout<< "There is a stored matrix on that program. It is shown below: " << endl << endl;
showmatrix(m, 4, "Stored_Matrix");
cout<< "The sum of elements of that stored matrix is: "<< sum(m,4) << endl << endl;
cout<< "Now, let's enter another 4 x 4 matrix." << endl << endl;
cout<< "(Note: You can use <space> character to separate column elements or <enter>" << endl;
cout<< "key to enter a new row.)" << endl;
cout<< "(Note 2: Really, you can use both to separate each one of the 16 matrix" << endl;
cout<< "elements, but do not enter more than that or the program will do some error)." << endl << endl;
for(row_index = 0; row_index < 4; row_index++)
{
for(col_index = 0; col_index < 4; col_index++)
{
cin>> m[row_index][col_index];
}
}
cout<< endl;
cout<< "The entered matrix is below:" << endl << endl;
showmatrix(m, 4, "Entered_Matrix");
cout<< "The sum of elements of that entered matrix is: "<< sum(m,4) << endl << endl;
//only to do not close console window on Windows
cout<< "Program ended." << endl << endl << "Press something to exit.";
cin.get();
cin.get();
return 0;
}
I hope you can use it on your reborn or after developing a time machine to use that idea on your 2010 homework.
As you use C++ Builder tag for that question, you can create a new console application and copy-paste the code above overwriting generated one. Use F9 to compile and run.