Carrying out a c++ 2d array - c++

My array is supposed to accept 3 values for 3 salespersons, store and print the array but somehow I can't get it going. I'm not too familiar with c++ 2d arrays so this is a tad bit new to me. The code is supposed to accept user input, and then output the prices of the products into table like format.

I had to clean up a lot of code to get this to even begin to compile. There were many cases where the closing } of a block was not present. These mistakes are easy to make, but they're also easy to spot if you're disciplined about maintaining a consistent indentation style.
Once I indented the code it became fairly obvious where the errors were, but identifying these in the original is very hard.
Here's the cleaned up code:
#include <iostream>
#include <iomanip>
int main( ) {
const int salesPersonCount =3, productCount = 3;
int rows = 5, columns = 5;
int sales[rows][columns];
double total;
for (int p = 1; p <= salesPersonCount; p++) {
std::cout << "\n \n Information for SalesPsn"<< p <<" : \n \n";
//Sales Person
for (int m = 1; m <=productCount; m++) {
//Product Number
std::cout << "\n Please enter sales value of product "<< m << ":";
std::cout << "\n ";
for (int i=0;i<rows;i++) {
for (int j=3;j<columns; j++) {
std::cout << "\nThe 2-D Array is:\n";
for (int i=0;i<2;i++) {
for (int j=0;j<2;j++) {
std::cout << "\t" << sales[i][j];
}
std::cout << "Sale " << std::setw (17) << "Salespsn1" << std::setw (22)<< "Salespsn2"
<< std::setw (27)<< "Salespsn3" << std::setw (32) << "Total" << std::endl;
}
std::cout << std::endl;
}
}
}
}
return 0;
}
Note this still has a lot of problems you're going to need to resolve, like how you're capturing sales and information into variables p and m which are also used for iterators, plus how nothing actually puts data into the sales structure, but at least you've got something you can fix.
My advice: When you get into a deep hole, stop digging. If you can't figure out what to do, clean up your code. I've solved many problems in the course of better organizing what I've done, in adding comments to parts that should work yet don't. There's no shame in being stuck, but if you're stuck because of a mess you didn't clean up that's on you.

I went over the code and this is the final product... Turns out no input was needed I was overthinking. Thanks for the help #tadman For anyone who is interested:
#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <math.h>
#define ROW 3 //number of rows
#define COL 3 // number of columns
//Function Prototype section
void enterItems(double salesArray[][COL]);
void getRowTotal (double Sales[][3], double total[][3]);
void getColTotal (double Sales[][3], double total[][3]);
void DisplayArray (double Sales[][3], double total[][3]);
using namespace std;
int main (){ //function main begins program execution
//storing 3 sales person and 3 different product
//Declares Arrays
double Sales[ROW][COL] = { {250,200,300 }, {500,350,220 },{150,600,450 }};
double total[2][3] = {0};
//Calls Functions getRowTotal, getColTotal and DisplayArray
getRowTotal (Sales, total);
getColTotal(Sales, total);
DisplayArray (Sales, total);
//Signifies that program is successfully executed
return 0;
}
//variables
int z = 0, j = 0;
//Declares And Defines getRowTotal
void getRowTotal (double Sales[][3], double total[][3]){
for(z = 0; z < 3; z++)
total[0][z] = Sales[0][z] + Sales[1][z] + Sales[2][z];
}
//Declares and Defines getColTotal
void getColTotal(double Sales[][3], double total[][3]){
for(z = 0; z < 3; z++){
total[1][z] = Sales[z][0] + Sales[z][1] + Sales[z][2];
}
}
//function DisplayArry
void DisplayArray (double Sales[][3], double total[][3]){
//Table Headings
cout << left << setw(10) << "Title" << setw(15) << "SalesPerson1 " << setw(15) << "SalesPerson2 " << setw(15) << "SalesPerson3 " << "Total";
cout << "\n_______________________________________________________________________________________________\n";
cout << fixed << setprecision(2) << showpoint;
//Displays the Sales and row headings
for(z = 0; z < 3; z++){
cout << setw(8) << "Product " << z + 1 << setw(1) << " ";
for(j = 0; j < 3; j++)
cout << setw(17) << Sales[j][z];
cout << setw(17) << total[0][z];
cout << endl;
}
cout << setw(8) << "Total";
for( z = 0; z < 3; z++)
cout << setw(19) << total[1][z];
cout << "\n_______________________________________________________________________________________________\n";
}

Related

How can I print 2D arrays with four columns

I am struggling with printing an array with 4 rows and 4 columns, when I initialized the array and entered all the values. Then, I used for loop to get all the values together so I can print them. But I get is an array that companied all the values in one row.
I have attached the output when I run the code.
Here is a portion of my code, it is long code but I am struggling in specific part:
#include <iostream>
using namespace std;
int main()
{
cout << "The martix before I flipped it: " << endl;
cout << endl;
int array[4][4] = { 16,3,2,13,5,10,11,8,9,6,7,12,4,5,14,1 };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << array[i][j] << " ";
}
}
return 0;
The standard output utility std::cout is a stream from the stl and, as such, its << operator does not usually automagically append a linebreak.
Which is quite practical since, otherwise, you would not be able to print multiple numbers on a single line.
That being, said, you'll need to add the linebreak manually, like so :
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
Alternatively, you can consider printing lines 4 at a time since your matrix is of constant size :
for (int i = 0; i < 4; i++) {
std::cout << array[i][0] << " "
<< array[i][1] << " "
<< array[i][2] << " "
<< array[i][3] << " " << std::endl;
}
Have a great day,

How to display whole numbers without decimals

I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9

How can I set my variable in C++ to 0 and prevent it from getting random?

I am a beginner in programming. I was doing some simple applications. I was already done with my programme when I realised that my variable is getting random, even if I set it to 0. I was trying to figure it out why. My goal is to add 1 to the "cor" variable when the answer is matching the random generated number, the "else" section is working as it has to be. Maybe someone more experienced can help me.
`
#include <iostream>
#include <string>
#include <time.h>
#include <Windows.h>
using namespace std;
int number;
int ynumber[5];
int cor = 0;
int falsed = 0;
int main()
{
cout << "Welcome to our lottery!" << endl;
cout << "We start in ..." << endl;
Sleep(2000);
for (int i = 3; i >= 0; i--)
{
system("cls");
cout << i << endl;
Sleep(1000);
}
system("cls");
srand(time(NULL));
for (int i = 0; i < 6; i++)
{
cout << "Type your " << i+1 << " number below" << endl;
cin >> ynumber[i];
number = rand() % 50 + 1;
cout << "The picked number is: " << number << endl;
Sleep(1000);
if (ynumber[i] == number)
{
cout << "Same same!" << endl;
cor = cor + 1;
}
else
{
cout << "Hope for better luck next time ;)" << endl;
falsed = falsed + 1;
}
}
system("cls");
cout << "Thank you for participating!" << endl << "Correct picked numbers: " << cor << endl << "Wrong picked numbers: " << falsed << endl << endl;
system("pause");
return 0;
}
`
int ynumber[5];
The length of your array is 5
for (int i = 0; i < 6; i++)
{
//...
cin >> ynumber[i];
You loop over the indices 0,1,2,3,4,5. Use your fingers to count the number of indices that you use. You'll notice that you access the array at 6 different fingers. 6 is more than 5. As such, we can conclude that you're accessing the array out of bounds. The consequence is that behaviour of your program is undefined.
Solution: Do not access an array out of bounds. The last index of array of length n is n - 1.
More generally: Don't rely on magic numbers. In this case, you could use instead:
for (int i = 0; i < std::size(ynumber); i++)

Creating a Table of Powers with C++

I'm working on a project to print out a table of exponential numbers using nested for-loops. Users specify the number of rows to print and the number of powers. For example, if the users specifies 2 rows and 3 powers, the program should print 1,1,1 and 2,4,9 (2^1,2,3 etc). I should note this is for class and we aren't allowed to use cmath, otherwise I would use pow(). I can't seem to figure out the correct function in a nested for loop that can change both values of the base and the exponent. Here's what I have so far. Thanks for your help!
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
for (int q = 1; q <= i; q++)
{
a = (q * q); //This only works for static numbers...
cout << setw(8) << a;
}
cout << endl;
}
}
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
int a = 1;
for (int q = 1; q <= r; q++)
{
a = (a * i);
cout << setw(8) << a;
}
cout << endl;
}
Several things to note. First, you can compute the powers by maintaining the variable a and multiplying it by i for each power. Also, I think you want the upper bound on your second loop to be r and not i.
You need couple to change the way accumulate the values of raising a number to a power.
Also, you are using the wrong variable to end the loop in the inner for-loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
a = 1; // Start with 1
for (int q = 1; q <= p; q++) // That needs to <= p, not <= i
{
a *= i; // Multiply it by i get the value of i^q
cout << setw(8) << a;
}
cout << endl;
}
}

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.