I am writing this program in c++ and unable to determine what am I doing wrong. This nested loop is supposed to print a matrix with rows and columns and for some reason its stuck at row 0 and column 0 when asking for user input. Thanks in advance.
#include <iostream>
using namespace std;
int main ()
{
//program to print the input values in rows and columns of two dimensional array in revserse roder using loop
//decalre the vraibles and array
int array [3][3],rows,cols,maxrows = 3,maxcols = 3;
//use for loop to intiiate the array and input values from users
for (rows = 0; rows < maxrows;rows = rows++ )
{
for (cols = 0; cols < maxcols;cols = cols++ )
{
cout << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;
cin >> array [rows][cols] ;
}
}
//display the values entered in array starting with bottom row first and then the rest
for ( rows = 0 ; rows < maxrows ; rows ++ )
{
for ( cols = 0 ; cols < maxcols ; cols ++ )
{
cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
}
}
}
You already have your answer, but I thought I should point out that the style of variable declaration. Namely, int array [3][3],rows,cols,maxrows = 3,maxcols = 3;
This is bad because it is not very readable. The type of the row and column variables are incorrect in the strictest sense, see why size_t is better when using it as an array index. Additionally, a case could be made for why you should favour pre-increment instead of post-incrementing unless you have a good reason not to (++i instead of i++), although in this particular case it does not matter since the operator is not overloaded. Furthermore, using constants appropriately makes code more readable and eliminates certain types of bugs. Lastly, give your variables a sensible value as soon as possible to eliminate undefined behaviour.
#include <iostream>
using namespace std;
int main ()
{
//program to print the input values in rows and columns of two dimensional array in revserse roder using loop
//decalre the vraibles and array
int array [3][3] = {};
const size_t maxrows = 3,
const size_t maxcols = 3;
//use for loop to intiiate the array and input values from users
for (size_t rows = 0; rows < maxrows; ++rows )
{
for (size_t cols = 0; cols < maxcols; ++cols )
{
cout << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;
cin >> array [rows][cols] ;
}
}
//display the values entered in array starting with bottom row first and then the rest
for ( size_t rows = 0; rows < maxrows ; ++rows)
{
for ( size_t cols = 0; cols < maxcols ; ++cols)
{
cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
}
}
}
The comments hinted at the problem, but did not state it explicitly: the statement
rows = rows++
is ambiguous because the right-side is incremented after fetching the value which is then assigned to the left-side. With suitable warnings enabled for g++, it says
foo.c:26: warning: operation on ‘rows’ may be undefined
In effect, it says that some compilers may give differing results, such as making it no different from
rows = rows
If it did that, it would cause an infinite loop. (With g++, by the way, the value does get incremented).
Related
code can be run/compiled here https://onlinegdb.com/9yhzLeVu3
this code will only print value 4 for all the values if tested on a 2x2 matrix
[1][2]
[3][4]
I believe its with the cout statement, I am fairly convinced it is saving the values to the matrix but, am not seeing it print correctly.
If could please tell me what I am not seeing? this syntax is very new to me, this program functions as functional programming but, is difficult once I start converting it to methods/functions.
#include <iostream>
using namespace std;
// Create a matrix based graph representation.
// It will need to support the following operations.
// Ask the user how many points there are. DONE
// Ask the user to label those points, ie "ABC", "XYZ", "C12"... DONE
// Define the matrix as a square matrix (2 dimensional array) based on the number of points, also keep an array of the labels. DONE
// Repeatedly ask the user to define edges between two points. Add these edges to the matrix. DONE
// Have a list method that will list out all of the edges in the graph.
// REFERENCE
// https://www.geeksforgeeks.org/how-to-access-elements-of-a-square-matrix/
// https://www.geeksforgeeks.org/comparison-between-adjacency-list-and-adjacency-matrix-representation-of-graph/
// https://www.cplusplus.com/reference/utility/make_pair/
// https://www.tutorialspoint.com/cplusplus-program-to-implement-adjacency-matrix
// https://stackoverflow.com/questions/2828648/how-to-pass-a-multidimensional-array-to-a-function-in-c-and-c
// https://www.techiedelight.com/pass-2d-array-function-parameter-cpp/
// https://www.tutorialspoint.com/Passing-two-dimensional-array-to-a-Cplusplus-function
// https://stackoverflow.com/questions/71907069/my-print-function-does-not-print-correctly-when-passing-a-2d-array-please-tell/71907317#71907317
// one possible implementation would be make pair to track the label for edge cout statement for user input
// Code is formatted to be best read with labels the size of 3 this is hard coded per implementation requirements.
int main()
{
// PROTOTYPE
void printMatrix(string *labelArray, int *matrix, int rowIndex, int columnIndex, int size);
int size ;
cout << "How many points would you like this to be. Points meaning -size- of matrix: ";
cin >> size;
// example 2x2 matrix
// A B
// A [][]
// B [][]
// determine size, and modulo to create matrix form
string label; // labeling convention for determining assignments
string labelArray[size]; // label containing array to track for printing and labeling purposes
int edgeYesOrNo;
int counter = 0;
cout << "Will now ask to label the points of graph matrix.\n";
int *matrix = new int[size * size]; // this is how to define a 2d array
int rowIndex; // these are to access individual elements
int columnIndex; // ^^
for(int i=0; i<size; i++)
{
cout << "Enter label: "; // enter the label here to insure that there is no redundancy
cin >> label;
labelArray[i] = label;
}
// Get the square matrix
cout << "Enter 1 for edge 0 for no edge" << endl;
for (rowIndex = 0; rowIndex < size; rowIndex++)
{
for (columnIndex = 0; columnIndex < size; columnIndex++)
{
cout << "Is there an edge to: " << labelArray[counter] << " and " << labelArray[columnIndex] << ": ";
cin >> edgeYesOrNo;
matrix[rowIndex * size + columnIndex] = edgeYesOrNo;
}
counter++;
}
printMatrix(labelArray, matrix, rowIndex, columnIndex, size);
delete[] matrix;
return 0;
}
// Display the matrix
void printMatrix(string *labelArray, int *matrix, int rowIndex, int columnIndex, int size)
{
cout << "The matrix is\n" << endl;
cout << " ";
for(int i=0; i<size; i++)
{
cout << labelArray[i] << " "; // To print the labels so its understandable
}
cout << endl;
for (rowIndex = 0; rowIndex < size; rowIndex++)
{
cout << labelArray[rowIndex] << " ";
for (columnIndex = 0; columnIndex < size; columnIndex++)
{
cout << matrix[rowIndex * size + columnIndex] << " ";
}
cout << endl;
}
return;
}
What do you think these lines are going to do:
matrix[size * size] = edgeYesOrNo;
cout << matrix[size * size] << " ";
I find it far more likely you need rowIndex * size + colIndex in both places.
I'll explain the difference. You've already allocated your array when you did this:
int *matrix = new int[size * size];
This is not a 2D array. It's a single dimension array. But that's okay. If size is four, size * size is 16, so you allocated space for 16 integers.
matrix[rowIndex * size + colIndex]
This is how I use it in both my places. What this means is you'll store them kind of like this:
[ 0][ 1][ 2][ 3]
[ 4][ 5][ 6][ 7]
[ 8][ 9][10][11]
[12][13][14][15]
That is, row 0, col 0 is thus in the 0'th index. row 1, col 1, is in the row * size + col location, or 5.
Does that make sense now?
C++ doesn't actually have 2D arrays. You can simulate it. This is one way to do so.
What you were doing was using (for size == 4) the 16th spot each time, which is actually one slot past the end. You were stepping on who knows what.
So I've been working on problem 15 from the Project Euler's website , and my solution was working great up until I decided to remove the cout statements I was using for debugging while writing the code. My solution works by generating Pascal's Triangle in a 1D array and finding the element that corresponds to the number of paths in the NxN lattice specified by the user. Here is my program:
#include <iostream>
using namespace std;
//Returns sum of first n natural numbers
int sumOfNaturals(const int n)
{
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
void latticePascal(const int x, const int y, int &size)
{
int numRows = 0;
int sum = sumOfNaturals(x + y + 1);
numRows = x + y + 1;
//Create array of size (sum of first x + y + 1 natural numbers) to hold all elements in P's T
unsigned long long *pascalsTriangle = new unsigned long long[sum];
size = sum;
//Initialize all elements to 0
for (int i = 0; i < sum; i++)
{
pascalsTriangle[i] = 0;
}
//Initialize top of P's T to 1
pascalsTriangle[0] = 1;
cout << "row 1:\n" << "pascalsTriangle[0] = " << 1 << "\n\n"; // <--------------------------------------------------------------------------------
//Iterate once for each row of P's T that is going to be generated
for (int i = 1; i <= numRows; i++)
{
int counter = 0;
//Initialize end of current row of P's T to 1
pascalsTriangle[sumOfNaturals(i + 1) - 1] = 1;
cout << "row " << i + 1 << endl; // <--------------------------------------------------------------------------------------------------------
//Iterate once for each element of current row of P's T
for (int j = sumOfNaturals(i); j < sumOfNaturals(i + 1); j++)
{
//Current element of P's T is not one of the row's ending 1s
if (j != sumOfNaturals(i) && j != (sumOfNaturals(i + 1)) - 1)
{
pascalsTriangle[j] = pascalsTriangle[sumOfNaturals(i - 1) + counter] + pascalsTriangle[sumOfNaturals(i - 1) + counter + 1];
cout << "pascalsTriangle[" << j << "] = " << pascalsTriangle[j] << '\n'; // <--------------------------------------------------------
counter++;
}
//Current element of P's T is one of the row's ending 1s
else
{
pascalsTriangle[j] = 1;
cout << "pascalsTriangle[" << j << "] = " << pascalsTriangle[j] << '\n'; // <---------------------------------------------------------
}
}
cout << endl;
}
cout << "Number of SE paths in a " << x << "x" << y << " lattice: " << pascalsTriangle[sumOfNaturals(x + y) + (((sumOfNaturals(x + y + 1) - 1) - sumOfNaturals(x + y)) / 2)] << endl;
delete[] pascalsTriangle;
return;
}
int main()
{
int size = 0, dim1 = 0, dim2 = 0;
cout << "Enter dimension 1 for lattice grid: ";
cin >> dim1;
cout << "Enter dimension 2 for lattice grid: ";
cin >> dim2;
latticePascal(dim1, dim2, size);
return 0;
}
The cout statements that seem to be saving my program are marked with commented arrows. It seems to work as long as any of these lines are included. If all of these statements are removed, then the program will print: "Number of SE paths in a " and then hang for a couple of seconds before terminating without printing the answer. I want this program to be as clean as possible and to simply output the answer without having to print the entire contents of the triangle, so it is not working as intended in its current state.
There's a good chance that either the expression to calculate the array index or the one to calculate the array size for allocation causes undefined behaviour, for example, a stack overflow.
Because the visibility of this undefined behaviour to you is not defined the program can work as you intended or it can do something else - which could explain why it works with one compiler but not another.
You could use a vector with vector::resize() and vector::at() instead of an array with new and [] to get some improved information in the case that the program aborts before writing or flushing all of its output due to an invalid memory access.
If the problem is due to an invalid index being used then vector::at() will raise an exception which you won't catch and many debuggers will stop when they find this pair of factors together and they'll help you to inspect the point in the program where the problem occurred and key facts like which index you were trying to access and the contents of the variables.
They'll typically show you more "stack frames" than you expect but some are internal details of how the system manages uncaught exceptions and you should expect that the debugger helps you to find the stack frame relevant to your problem evolving so you can inspect the context of that one.
Your program works well with g++ on Linux:
$ g++ -o main pascal.cpp
$ ./main
Enter dimension 1 for lattice grid: 3
Enter dimension 2 for lattice grid: 4
Number of SE paths in a 3x4 lattice: 35
There's got to be something else since your cout statements have no side effects.
Here's an idea on how to debug this: open 2 visual studio instances, one will have the version without the cout statements, and the other one will have the version with them. Simply do a step by step debug to find the first difference between them. My guess is that you will realize that the cout statements have nothing to do with the error.
i'm a complete beginner to programming and I started with C++. I'm on arrays now and i'm trying to create a simple ten times table. I succeeded with the following code but i's sceptical i did the right thing since there are no square brackets:
#include <iostream>
using namespace std;
int main() {
int product;
for(int i = 1; i < 11; ++i) {
for(int j = 1; j < 11; ++j) {
product = i*j;
cout << product << "\t" << flush;
}
cout << endl;
}
return 0;
}
After messing about a bit i came up with the following:
#include <iostream>
using namespace std;
int main() {
int row = 11;
int col = 11;
int table[row][col];
for(row = 1; row < 11; ++row) {
for(col = 1; col < 11; ++col) {
table[row][col] = row*col;
cout << table[row][col] << "\t" << flush;
}
cout << endl;
}
return 0;
}
Both give the desired output, my question is why? I'm also curious to know if the first really is an array, if not what is it? Any advice on my basic code writing will also be greatly appreciated.
The first example does not use an array. You are printing out the 10x tables but you are not storing that information in the program. This means that after the loop, the program will not remember what the table looks like.
In the second example the variable table is the multidimensional array.
After the look you could call cout << table[4][6] << endl; for example, and 24 would be printed, without re-computing what 4*6 is. This is because you saved the information in the multidimensional array.
(also as the comments mentioned, arrays in programming start at 0, meaning that ideally you should makes your loops for(row = 0; row <= 10; ++row) {. This way the first slot in the array is not being wasted.
Also as the comments are mentioning, 'vectors' are nice but if you are learning programming, you should understand how an array works, and I would suggest not getting into vectors until you understand the basics of an array)
Both give the desired output, my question is why?
Because in both cases you print the same value.
In first case, you save the value in a variable
product = i*j;
and print the variable
cout << product << "\t" << flush;
In second case, you save the same value (row has the same value as i, col has the same value as j; so row * col has the same value as i * j) in a variable
table[row][col] = row*col;
(this time is a variable inside an array of array, that depends from row and col) and you print the same variable
cout << table[row][col] << "\t" << flush;
I'm also curious to know if the first really is an array, if not what is it?
Do you mean product?
No: product is a simple integer variable.
A variable that change value at every iteration of product = i*j;
It's the table variable in the second example that is an array; or better, an array of arrays.
The difference is that at the end of the double for, product maintain only the value of the last calculated product when table maintain all the calculated product.
Any advice on my basic code writing will also be greatly appreciated.
First of all, as explained from Some programmer dude, the code
int row = 11;
int col = 11;
int table[row][col];
isn't correct C++ because you can't use non constant values for array dimensions.
You can use directly 11
int table[11][11];
or you can define row and col as constants
int const row = 11;
int const col = 11;
int table[row][col];
or better (starting from C++11) as constexpr constants
constexpr int row { 11 };
constexpr int col { 11 };
int table[row][col];
Second: IMHO it's better avoid (when possible) using namespace std; but explicating the namespace; so
std::cout << table[row][col] << "\t" << std::flush;
This avoid risks of name collisions when you use other libraries.
I'm trying to convert a for loop to while loop in c++ and do some checking for duplicates in a random number generator for generating lotto numbers so far all the stuff i'm trying seems to make the compiler very unhappy and I could really use a few pointers. It's the for loop in the Harray() function that feeds the Balls[] array
that i want to convert to a while loop.
#include<iostream>
#include<cstdlib> // to call rand and srand.
#include<ctime> // to make rand a bit more random with srand(time(0)) as first call.
#include<iomanip> // to manipulate the output with leading 0 where neccesary.
using namespace std;
// Hrand() function create and return a random number.
int Hrand()
{
int num = rand()%45+1; // make and store a random number change 45 for more or less Balls.
return num; // return the random number.
}
// Harray() function create and fill an array with random numbers and some formatting.
void Harray()
{
int Balls[6]; // change the number in Balls[6] and in the for loop for more or less nrs. a row.
for(int x=0; x<=6; x++) //the loop to fill array with random numbers.
{
int a; // made to pass the Balls[x] data into so i can format output.
int m = Hrand(); // calling the Hrand() function and passing it's value in int m.
Balls[x] = m; // throwing it into the array tought i did this because of an error.
a = Balls[x]; // throwing it into int a because of an type error.
cout<<"["<<setfill('0')<<setw(02)<<a<<"]"; //format output with leading 0 if neccesary.
}
cout<<endl; // start new row on new line.
}
// Main function do the thing if compiler swallows the junk.
int main() // start the program.
{
int h; // int to store user cchoice.
srand(time(0)); // make rand more random.
cout<<"How many rows do you want to generate?"<<endl; // ask how many rows?
cin>>h; // store user input.
for(int i=h; h>0; h--) // produce rows from user input choice.
{
Harray(); // calling Harray function into action.
}
return 0; // return zero keep the comipler happy.
}
I would like to always have six diffrent numbers in a row but i don't see how to get there with the for loops i think the while loop is way to go but am open to any suggestion that will work. I'm just starting with c++ i might have overlooked some options.
int x=0;
while(x<6)
{
int a;format output.
int m = Hrand();value in int m.
Balls[x] = m; because of an error.
a = Balls[x];
cout<<"["<<setfill('0')<<setw(02)<<a<<"]";
x++;
}
Here, I also fixed a bug. Since Balls has 6 elements, the last element will be 5. Thus you want x<6 instead of x<=6. That goes for the for loop too.
One drawback of while loops is that you cannot declare local variables with them.
First of all, you should realize that the difference between a for loop and a while loop is mostly syntactic--anything you can do with one, you can also do with the other.
In this case, given what you've stated as your desired output, what you probably really want is something like this:
std::vector<int> numbers;
std::set<int> dupe_tracker;
while (dupe_tracker.size() < 6) {
int i = Hrand();
if (dupe_tracker.insert(i).second)
numbers.push_back(i);
}
The basic idea here is that dupe_tracker keeps a copy of each number you've generated. So, you generate a number, and insert it into the set. That will fail (and return false in retval.second) if the number is already in the set. So, we only add the number to the result vector if it was not already in the set (i.e., if it's unique).
How convert for-loop to while-loop
#include <iostream>
class T545_t
{
// private data attributes
int j;
public:
int exec()
{
// A for-loop has 3 parameters, authors often fill 2 of them with magic
// numbers. (magic numbers are usually discouraged, but are expected
// in for-loops)
// Here, I create names for these 3 for-loop parameters
const int StartNum = 2;
const int EndNum = 7;
const int StrideNum = 2;
std::cout << std::endl << " ";
for (int i = StartNum; i < EndNum; i += StrideNum ) {
std::cout << i << " " << std::flush;
}
std::cout << std::flush;
// A while-loop must use / provide each of these 3 items also, but
// because of the increased code-layout flexibility (compared to
// for-loop), the use of magic numbers should be discouraged.
std::cout << std::endl << " ";
j = StartNum;
do {
if (j >= EndNum) break;
std::cout << j << " " << std::flush;
j += StrideNum;
} while(true);
std::cout << std::flush;
std::cout << std::endl << " ";
j = StartNum;
while(true) {
if (j >= EndNum) break;
std::cout << j << " " << std::flush;
j += StrideNum;
}
std::cout << std::flush;
std::cout << std::endl << " ";
j = StartNum;
while(j < EndNum) {
std::cout << j << " " << std::flush;
j += StrideNum;
}
std::cout << std::endl;
return 0;
}
}; // class T545_t
int main(int , char** )
{
T545_t t545;
return(t545.exec());
}
Ask me where 'j' is declared?
This code is marked as C++, so in this case, I have declared 'j' in the private data attribute 'section' of this class definition. That is where you'd look for it, right?
If your c++ code does not have class, what's the point?
I am attempting to print out a histogram of values that correspond to the amount of times a pixel value appears in a .pgm file. I know I am reading in the values correctly, it's when I try to print them where I have issues.
int pixelHold[product];
for(long int i = 0; i < product; i++)
{
pixelHold[pixels[i]]++;
//cout << pixels[i] << ' ' << endl;
}
for(long int j = 0; j < product; j++)
{
cout << pixelHold[j] << ' ';
}
"product" is the Width x Height pixel value, which corresponds to the size of the vector I'm using to store all of the values. "pixelHold" is just an array that I'm using to increment every time it comes across a pixel value. For example, it if came across "222" 3 times, it would print a "3" for the "222" slot.
However, the issue is that, when I print the histogram, I get a bunch of zeroes, and then garbage for the last 100 slots or so. When I change the parameters of the for loop to a smaller number, like "221", it prints out the correct histogram up to that point.
Any help is much appreciated!
You always need to initalize your arrays - otherwise they contain absolutely arbitrary contents - the contents of RAM where the compiler decided to put your array.
Also, your histogram table should have the dimensions of 256 - since that's how many (8-bit) colors there are in a greyscale image.
The following code should do the trick:
const int histogramLevels = 256;
int pixelHold[histogramLevels];
for (int i=0; i<histogramLevels; i++) pixelHold[i] = 0;
for(long int i = 0; i < product; i++)
{
pixelHold[pixels[i]]++;
//cout << pixels[i] << ' ' << endl;
}
for (int i=0; i<histogramLevels; i++) {
cout << pixelHold[j] << ' ';
}