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,
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";
}
code:
#include <iostream>
#include <vector>
int main () {
std::cout << "Please, enter the number of iterations: "; //Inputs
int iterations;
std::cin >> iterations;
std::cout << "Which term would you like to know: ";
int term;
std::cin >> term; //End inputs
std::vector<int> series; //definition of vector "series"
for (int n = 1; n <= iterations; n++) { //creation of "series"
int next = (2 * n - 3);
series.push_back(next);
}
std::cout << "The value of term " //prints the n term
<< term
<< " is: "
<< series[term-1] //term-1 "adjust" the indexing
<< std::endl;
std::cout << "The entire serie up to "
<< iterations
<< " terms is: ";
for (int i = 0; i < series.size(); i++) { //prints (elements of vector) "series"
std::cout << series[i] << ' ';
if (i == series.size()-1) { //new line only at the end the series
std::cout << std::endl;
}
}
return 0;
}
I got 9/10 with this comment: "if condition inside loop will only be satisfied once, but checked every time. Move outside of loop".
I really don't how could I place the if statement out of the loop.
The scope of that for-if statement is to add a new line only at the end of the vector "series".
I can't think about anything else but for sure I'm experienced enough and there is another more elegant solution.
I'm asking here because I have to submit another assignment and I don't want to submit it with the same error.
PS: the other comment was: light over-commenting. Did I really commented to much?
You print the endl at the end of the for loop, so you can to add the line of endl when you go out from the loop and remove the line at the for loop, it will give you the same result
The code:
for (int n = 1; n <= iterations; n++) { //creation of "series"
int next = (2 * n - 3);
series.push_back(next);
}
std::cout << "The value of term " //prints the n term
<< term
<< " is: "
<< series[term-1] //term-1 "adjust" the indexing
<< std::endl;
std::cout << "The entire serie up to "
<< iterations
<< " terms is: ";
for (int i = 0; i < series.size(); i++) { //prints (elements of vector) "series"
std::cout << series[i] << ' ';
}
std::cout << std::endl;
return 0;
}
What you are trying to do is to print a newline after the last element. Here, you are checking for each element if it is the last. However, you don't need to do that.
Another way to do "After the last element" is "after all elements", so after the loop. Just process all the elements with the for loop, then print the newline.
I'm not giving the code, since it is an assignment, but this should be clear enough.
As for commenting: don't document the obvious. Of course, for different levels, obvious is something different. But for the declaration of the "series" vector, the comment doesn't add anything to the code, for instance.
I am trying to build a 2D array which has dynamic dimensions. I could use the vector class for this, but my assignment prohibits it. So I came up with the following code :
#include <iostream>
using namespace std;
int main() {
cout << "1" << endl;
int** 2DArr = new int*[5];
cout << "2" << endl;
for(unsigned int index = 0; index < 5; index++)
{
2DArr[index] = new int[5];
cout << "3";
}
cout <<"\n4"<<endl;
for(int row = 0; row < 5; row++)
{
cout << "5 " << endl;
for(int col = 0; col < 5; col++)
{
cout << "6 " << endl;
2DArr[row][col] = 1;
cout << "7" << endl;
cout << 2DArr[row][col];
cout << "8" << endl;
}
cout << "8" << endl;
}
cout << "9" << endl;
}
The code above is an example of what I am trying to accomplish, along number at each step. The above code seems to hang right after "6" is printed. Can anyone explain to me why the above code doesn't work and how I could fix it? My understanding is that 2D arrays made of pointers can be accessed using [], yet for some reason, the above hangs at the exact line i'm trying to assign 1 to the 2D array. My guess is that it expects an adress and not an int, but I;m not sure. Please show me howto assign an actual integer at step 6.
Thank you very much.
I am making a 20 questions game in C++ and have everything working, except for the displayWords function. The code I currently have keeps breaking. Any explanation would be appreciated! Thank you!
void displayWords()
{
int x = 0;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
while(x < 50)
{
for (int y = 0; y <= 5; y++)
{
cout << words[x] << ", ";
if(x<50)
x++;
}
cout << endl;
}
}
I would like it to display the list of 50 words in an organized fashion.
By example, as:
for( int x = 0; x<sizeof(words)/sizeof(*words); x++ ) {
if( x%5==0 ) cout << endl; else cout << ", ";
cout << words[x];
}
take into account the problematic of the array's size calculation: see this link How do I find the length of an array?
If I understand correctly, you want your list displayed as 5 columns. Simplest way, use a nested for loop and proper formatting with std::setw (must #include <iomanip>):
for(size_t i = 0; i < 10; ++i)
{
for(size_t j = 0; j < 5; ++j)
{
std::cout << std::setw(20) << std::left << words[i * 5 + j];
}
std::cout << std::endl;
}
Your actual loop is incorrect, as it will lead to repetitions.
Maybe I'm not interpreting your question correctly but if you want to just print out the 50 words then you can use something like the code below. Not sure of the reason that the nested for loop iterating y was there.
Edit
void displayWords()
{
int x;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
for(x = 0; x < words.size();x++)
{
cout << words[x]<< ", ";
}
}
Also some information on how the code is breaking, like are any errors being thrown or has debugging caused issues so far?