Confused about 2D arrays in C++ - c++

I'm having problems with creating a 2D boolean array in C++. I wrote a quick program for create and print all the bool array.
#include <iostream>
using namespace std;
int main() {
const int WIDTH = 20;
const int HEIGHT = 20;
bool world [HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++){
for(int j = 0; j < WIDTH; j++){
world[i][j] = true;
}
}
for(int i = 0; i < HEIGHT; i++){
for(int j = 0; j < WIDTH; j++){
if(world[i][j]){
cout << j;
}else{
cout << ' ';
};
}
cout << "-" << i << endl;
}
return 0;
}
And this is his output.
012345678910111213141516171819-0
012345678910111213141516171819-1
012345678910111213141516171819-2
012345678910111213141516171819-3
012345678910111213141516171819-4
012345678910111213141516171819-5
012345678910111213141516171819-6
012345678910111213141516171819-7
012345678910111213141516171819-8
012345678910111213141516171819-9
012345678910111213141516171819-10
012345678910111213141516171819-11
012345678910111213141516171819-12
012345678910111213141516171819-13
012345678910111213141516171819-14
012345678910111213141516171819-15
012345678910111213141516171819-16
012345678910111213141516171819-17
012345678910111213141516171819-18
012345678910111213141516171819-19
It creates a 2D array, set all his values to true, and print the array. This is fine, the problem is when the 2d array get bigger. For example if I change the size of WIDTH and HEIGHT to 30, when i print the array I have the following ouput:
01234567891011121314151617181920212223242526272829-0
01234567891011121314151617181920212223242526272829-1
01234567891011121314151617181920212223242526272829-2
01234567891011121314151617181920212223242526272829-3
01234567891011121314151617181920212223242526272829-4
01234567891011121314151617181920212223242526272829-5
01234567891011121314151617181920212223242526272829-6
01234567891011121314151617181920212223242526272829-7
01234567891011121314151617181920212223242526272829-8
01234567891011121314151617181920212223242526272829-9
01234567891011121314151617181920212223242526272829-10
01234567891011121314151617181920212201234567891011121314151617181920212223242526272829-11
01234567891011121314151617181920212223242526272829-12
01234567891011121314151617181920212223242526272829-13
01234567891011121314151617181920212223242526272829-14
01234567891011121314151617181920212223242526272829-15
01234567891011121314151617181920212223242526272829-16
01234567891011121314151617181920212223242526272829-17
01234567891011121314151617181920212223242526272829-18
01234567891011121314151617181920212223242526272829-19
01234567891011121314151617181920212223242526272829-20
01234567891011121314151617181920212223242526272829-21
01234567891011121314151617181920212223242526272829-22
01234567891011121314151617181920212223242526272829-23
01234567891011121314151617181920212223242526272829-24
01234567891011121314151617181920212223242526272829-25
01234567891011121314151617181920212223242526272829-26
01234567891011121314151617181920212223242526272829-27
01234567891011121314151617181920212223242526272829-28
01234567891011121314151617181920212223242526272829-29
As you can see on the line 11 it counts until 22 and restart the for loop for j. I don't know what is wrong, I need an 2D array of bools of size [50][50] but I don't what is wrong there.
EDIT: The problem is the compiler. I tried the same code on GCC compiler on a Linux machine and works perfectly. This code works fine, the problem is the compiler or the compiler with the CLion IDE. It compiles but I have problems with the running or the output produced. The code works fine with GCC compiler or on an Unix machine

Okay this is logically absolutely correct and i have tested your code on online compiler using 20 as well as 30. restart your compiler or try another compiler a reliable one... Here is the screenshot of your result when i executed your code online.

The line
bool world [WIDTH][HEIGHT];
Should be
bool world [HEIGHT][WIDTH];
As the i in your loop ranges from 0 to HEIGHT-1. j ranges from 0 to WIDTH-1

Related

Make floor pattern

How do i make this?
image of my homework
note: Batasan means limitaion and Contoh means example
So, my professor wants me to do make output the same size horizontal and vertically in pattern shown in the image
I dont know what to do, but the best i can make is this:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
const char * array1[4];
const char * array2[4];
array1[0] = "O", array1[1] = ">", array1[2] = "X", array1[3] = "<";
array2[0] = "v", array2[1] = "/", array2[2] = "^", array2[3] = "\\";
cin>>n;
for(int i = 1; i <= n; i++){
if (i%2 != 0){
for(int j = 0; j <=n; j++){
cout << array1[j];
}
cout<<"\n";
} else if (i%2 != 0) {
for(int j = 0; j <=n; j++){
cout << array2[j];
}
cout<<"\n";
}
return 0;
}
}
I dont know if array is necessary or not.
If you guys have any suggestion about my program feel free to give me some.
This is my first time asking in this web and im sorry if my post and english are terrible
Thanks in advance:)
We are here to help.
I will first show you the problems in your code and then make a proposal on how to make it better.
So, let us first check your code:
#include<bits/stdc++.h> is a non C++ compliant compiler extension. It should never be used. On my machine, it does not compile.
using namespace std; should not be used. It is better to always use full qualified names. This will avoid name clashes from different scopes or namespaces
Variables should have meaningful names. One character variables are in most cases not that good
All variables should be initialized during definition
C-Style arrays should not be used in C++. Always use a specialized STL container like std::vector or std::array
In C++ we use std::string for strings and not char[] or char *
Array indices in C/C++ start with 0. If you use <= in the end condition of a for loop, you will access an element one past the end. This is a severe out of bound error. You do that in you for loop with the 'j'
There is anyway a severe out of bound bug here. You access array[j] and j might be 4 or bigger. That is a bug and must be corrected. You can simply do a modulo devision % by 4. Then you do never exceed the 4. it will then always be 0,1,2,3,0,1,2,3,0,1,2,3 . . .
You should write as much as possible comments
If we correct all this findings, then we could come up with:
#include <array>
#include <iostream>
constexpr size_t NumberOfLinePatterns = 2;
constexpr size_t NumberOfElementsPerLinePattern = 4;
using Pattern = std::array<std::array<char, NumberOfElementsPerLinePattern>, NumberOfLinePatterns>;
// If you do not yet know the std::array. Then uncomment the following and
// remove on opening and closing curly brace in the initialization below
// using Pattern = char[NumberOfLinePatterns][NumberOfElementsPerLinePattern];
Pattern pattern{{
{'O','>','X','<'},
{'v','/','^','\\'}
}};
int main() {
// Get number of rows and columns to print
unsigned int numberOfElements{}; std::cin >> numberOfElements;
// Now, for all rows and columns
for (unsigned int row{}; row < numberOfElements; ++row) {
for (unsigned int column{}; column < numberOfElements; ++column) {
// Print the selected character
std::cout << pattern[row % NumberOfLinePatterns][column % NumberOfElementsPerLinePattern];
}
std::cout << '\n';
}
return 0;
}

First try on string array not working. Is there something I don't know?

I just tried to use string array for the first time, and I experienced consistent crashes. It's supposed to draw a shrinking circle. Did I forget to add some important line, or is there an error in the existing code? I'm a beginner, so please don't be too mean..
#include <iostream>
#include <string>
#include <cmath>
#include <windows.h>
using namespace std;
int main() {
for (int h = -10; h < 10; h ++)
{
int r = abs(h);
string gps[20];
for (int i = -10; i < 10; i ++)
{
for (int j = -10; j < 10; j ++)
{
if (i*i + j*j <= r*r && i*i + j*j >= (r-1)*(r-1))
gps [j+10][i+10] = char (219);
else
gps [j+10][i+10] = ' ';
}
}
for (int i = 0; i < 20; i ++)
{
for (int j = 0; j < 20; j ++)
cout << gps[i][j];
cout << '\n';
}
//system("CLS"); // I know this isn't the best method, but it's the only one i know that works
// By proffesional analysis (cout), i diagnosed the problem to occur right about here
}
return 0;
}
One major issue with your code is that you are writing to the string at an out-of-bounds index here:
//...
gps [j+10][i+10] = char (219);
//...
gps [j+10][i+10] = ' ';
This declaration:
string gps[20];
declares an array of 20 empty strings. Since the strings are empty, you cannot simply write to any position in these string. These strings must already be sized appropriately before writing to a particular location.
What you may need to do is the following:
string gps[20];
for (auto& s : gps)
s.resize(20);
This will resize each string in the array to 20 elements, thus making your loop access valid entries in any of those strings. Writing to an out-of-bounds string position is undefined behavior, where in your case, the program crashes.
Now, will this draw the circle correctly, I am not sure. But this answer focuses on the crash you are getting when running the program.

Nested for loop only runs inner loop (c++)

I am quite new to c++, and I believe the answer to my problem is very, very simple.
I've been using the Eclipse IDE, but have recently changed to a simple text editor and using the command line for compiling. (As i currently don't have my own computer, and I am not allowed to install anything on the one I am using).
However, while writing a program, I noticed that whenever I had nested loops, it would only run the inner loop.
I've tried compiling my code using different online compilers, which results in the same problem.
Because of this, I believe that the problem is related to something simple, that Eclipse was taking care of automatically.
#include <iostream>
int main() {
for (int i; i<3; i++) {
for (int j; j<3; j++) {
std::cout << j << std::endl;
}
}
return 0;
}
Above is the simplest example, I could think of, that produces the problem.
The expected output is 0, 1, 2, 0, 1, 2, 0, 1, 2, however it only outputs 0, 1, 2 when I compile and run it.
You're not initializing the i and j variables to 0, so the variables start off by having undefined values. Fix to:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << j << std::endl;
}
}
The problem is that you are using uninitialized variables, which leave them with undefined values
for (int i; i < 3; i++) {
^
Try with
for (int i = 0; i < 3; i++) {

C++ program does nothing when executed

I am on Ubuntu 18.04 using the default c++ compiler it comes with. I am trying to get the size of vector required from the keyboard and eventually fill a vector with the increasing value of i in the makeGaps function. I would then like to return a filled vector to my variable x. However, when I run the code below, after it displays the "enter gap size" it does nothing even after I supply an integer. No output, no errors and also in code blocks all the debugger icons go gray. The code also doesn't
terminate and I cannot figure out what is wrong.
#include <iostream>
#include <vector>
using namespace std;
vector<int> makeGaps (int size){
vector<int> vectorOfGaps(size);
for(int i = 0; i <= vectorOfGaps.size();i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
void printV(vector<int> collection){
for (int i = 0; i <= collection.size(); i++){
cout << collection[i]<< '\n';
}
}
int main()
{ //get the number of gaps required
int numberOfGaps;
cout << "Enter gap size";
cin >> numberOfGaps;
vector<int> x = makeGaps(numberOfGaps);
printV(x);
return 0;
}
Also if i run it in the terminal that comes with vs code it crashes my machine.
Vectors in c++ are dynamically sized.
You can create a vector without a size argument in the constructor then push size number of elements like so:
vector<int> makeGaps (int size){
vector<int> vectorOfGaps;
for(int i = 0; i < size;i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
Edit: Also, as someone already pointed out in your comments, it appears you had an off by one error in your for loop. If the for loop runs until x <= size, it will iterate size+1 number of times.

Assigning Symbols to Numbers in a 2D Array

I'm working on a program in C++ that is supposed to read in a file, store the content of the file into a 2D array, assign characters to each of the numbers in the array and store in a char array, and print both of these arrays. It's then supposed to go through the initial array and make sure that each number doesn't differ in value from it's neighboring numbers by more than 1, correct these errors by replacing these numbers with the value of the average of their neighbors, assign characters to this corrected array as it did before, and print both arrays.
The character assignments go as follows:
0=blank
1=.
2=,
3=_
4=!
5=+
6=*
7=#
8=$
9=&
I have the code written that opens the file and loads the array, but I have no idea where to go from there. To me the obvious, although probably not best, way to do the assignments is to go through the array with a for loop and use a series of if statements to check for the value of the number at each index and assign the appropriate symbol. I'm sure there's a better way to accomplish this.
Here is the code I have so far:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream prog;
prog.open("../prog1.dat");
//If file can't be opened, exit
if (!prog) {
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
else {
while (!prog.eof()) {
int size = 100, i, j;
prog >> size;
int **numArray = new int* [size];
for(i = 0; i < size; i++) {
numArray[i] = new int[size];
for(j = 0; j < size; j++) {
prog >> numArray[i][j];
}
cout << endl;
}
for(i = 0; i < size; i++) {
for(j = 0; j < size; j++) {
cout <<numArray[i][j] << " ";
}
cout << endl;
}
prog.close();
return 0;
}
}
}
I'm extremely new to this programming language, this is actually my first program I've done in C++ and I'm literally learning as I go. Any suggestions would be greatly appreciated.
In this code You have not put a check on the difference with neighbour.
Moreover their is no need for 2 nested for loops that is a very big overhead. You could have printed the numArray in the first nested for loop.
According to you it is your first programming assignment and you are already using double pointers and nested loops and also the way you checked the file is opened or not. Are you sure it's your first assignment