To break nested loop [duplicate] - c++

This question already has answers here:
Can I use break to exit multiple nested 'for' loops?
(23 answers)
Closed 4 years ago.
I want to break the inner loop and increase the value of x if I find something at Matrix[x][y] but if I break in the y for loop it will just increase the value at y loop and not in the x loop.
int matrix[5][5]; //let's assume there are values inside
for(int i = 0; i < 5; i++)
{
for(int j = 0; j<5;j++)
{
int radius = 1;
for(int x = radius - 1; x <= radius + i; x ++)
{
for(int y = radius -1; y <= radius +j; y++)
{
if((x+i) >= 0 && (y+j)>=0)
{
//for example I find the number 45 in the matrix, then the search radius should be increased by 1 and start it over again.
if(matrix[x][y] == 45)
{
radius++;
break; // but if i break here the x value wont be changed
}
}
}
}
}

Of non-local exit mechanisms C++ provides throwing:
try {
for(int x = 0; x < 10; ++x) {
for(int y = 0; y < 3; ++y) {
std::cout << x << ", " << y << std::endl;
if(y == 1 && x == 3) throw true;
}
}
}
catch(bool) {}
std::cout << std::endl;
Additionally you can modify the outer loop's variable so the final condition holds:
for(int x = 0; x < 10; ++x) {
for(int y = 0; y < 3; ++y) {
std::cout << x << ", " << y << std::endl;
if(y == 1 && x == 3) {
x = 10;
break;
}
}
}
std::cout << std::endl;
(Or, if you don't want to modify the variable itself, say, it's not local to the loop and you'll need its value afterwards, add one more flag to the loop condtion:
bool continueOuter{true};
for(int x = 0; continueOuter && x < 10; ++x) {
for(int y = 0; y < 3; ++y) {
std::cout << x << ", " << y << std::endl;
if(y == 1 && x == 3) {
continueOuter = false;
break;
}
}
}
)

Related

Move a Character in a 2d Array

I'm taking an intro to c++ class and I am quite stuck on a part to this project.
I need to have my character, 'H' move freely around the array. I have written a good amount of my code, but when I compile and run it, my hero isn't given the option to move. I don't know what is going wrong when I am calling my function in main. Any help would be gladly appreciated. I need his new position in the array to be maintained so that he can find the villain who is randomly placed in the array. I can work on the randint part later, but I am having a hard time simply getting 'H' to move.
Here is what I have so far:
Thank you.
#include <iostream>
using namespace std;
void printBoard(char board[][8])
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
cout << board[x][y];
}
cout << endl;
}
}
void move(char board[][8], char umove)
{
cout << "Please enter which direction you would like to move." << endl;
cin >> umove;
if (umove == 'x')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = x - 1;
}
}
}
else if (umove == 'd')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = y + 1;
}
}
}
else if (umove == 'a')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = y - 1;
}
}
}
else if (umove == 'w')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = x + 1;
}
}
}
}
char userinput()
{
char usermove;
cout << "Please enter the direction you want to go." << endl;
cin >> usermove;
return usermove;
}
int main()
{
char board[8][8];
int x;
int y;
while (true)
{
for (x = 0; x < 8; x++)
{
for (y = 0; y < 8; y++)
{
board[x][y] = 'e';
}
}
board[0][0] = 'H';
printBoard(board);
void move();
return 0;
}
}
you call void move() which is a method declaration and you must use move(...) instead for calling method. return 0 cause the app to finish which is not correct in this situation. you use infinite loop and you must use a condition for finish game.
depend on your description I suggest:
void printBoard(char board[][8]) {
// same as before
}
bool move(char board[][8], int &Hx, int &Hy) {
char umove;
cout << "Please enter which direction you would like to move." << endl;
cin >> umove;
if (umove == 'f') // f mean finish it
return false;
board[Hx][Hy] = 'e';
if (umove == 'a') // a mean left
Hy = Hy == 0 ? 7 : Hy - 1;
else if (umove == 'd') // d mean right
Hy = Hy == 7 ? 0 : Hy + 1;
else if (umove == 'w') // w mean up
Hx = Hx == 0 ? 7 : Hx - 1;
else if (umove == 's') // s mean down
Hx = Hx == 7 ? 0 : Hx + 1;
board[Hx][Hy] = 'H';
return true;
}
int main() {
char board[8][8];
int Hx = 0, Hy = 0;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
board[x][y] = 'e';
}
}
board[Hx][Hy] = 'H';
bool res = true;
while (res) {
printBoard(board);
res = move(board, Hx, Hy);
}
cout << "Game finished!";
return 0;
}
You can make char board[][] and Hx and Hy (which contain current position of H) global and avoid sending them to method but this is not good at all.
I hope this is what you want.

change x,y of board by user input

i have a board of 10x10 and here his code:
for(int x = 0; x < 10; x++) // X
{
cout << 0;
for(int y = 0; y < 10; y++) // Y
{
cout << " " << 0;
}
cout << endl;
}
now I want to change 0 to 1 in the x,y location by user input.
how can I do that?
here is simply what I want to do ( in pictures ):
the user input is x = 2, y = 2 and the table changing from Table 1 Example to Table 2 Example ( as a new table ):
TABLE 1 Example | TABLE 2 Example
its just a curiosity question that I've been trying to make.
Get x0 and y0 before the loop using cin>> x0 and cin>> y0.
Inside the loop
if(x == x0 && y==y0)
cout << " " << 1;
else
cout << " " << 0;
The best way would be to keep all values in a two dimensional array. Then, play around with the
values of that array. After than, write the whole array once to the screen.
See the example below :
int matrix[10][10];
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++) matrix[i][j]=0;
matrix[2][3]=1;
matrix[3][4]=1;
matrix[4][5]=1;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
cout<<matrix[i][j];
}
cout << endl;
}
you can print again the whole matrix and check the x,y pair before writing the 0 or the 1
for(int x = 0; x < 10; x++) // X
{
cout << 0;
for(int y = 0; y < 10; y++) // Y
{
//here verify the x,y against the user input
if(x == xUser && y == yUser)
{
cout << " " << 1;
} else{
cout << " " << 0;
}
}
cout << endl;
}

how to set boxes in array with at least 1 neighbor equal to 1

I'm attempting to go through an array and figure out which ones have at least 1 immediate neighbor..
the answer I'm getting is
display
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
display
11111
10001
11111
11111
11111
box :1 :1
box :1 :3
which is perfect. I am able to see from the output which ones have exactly 1 neighbor array[1][1] and array[1][3].
Now how do I set those 2 only (array[1][1] and array[1][3]) = 1?
Since you use the nested 'display' loop multiple times, it'd be ideal to factorise that into its own function:
void Draw(int array[5][5]) {
for (int x = 0; x < 5; ++x) {
for (int y = 0; y < 5; ++y)
std::cout << array[x][y] << ' ';
std::cout << '\n';
}
}
Likewise, your 'finding neighbours' checks can be shortened drastically with an additional nested loop.
This will also make solving your problem much easier:
#include <iostream>
using namespace std;
void Draw(int array[5][5]) {
cout << endl;
for (unsigned x = 0; x < 5; ++x) {
for (unsigned y = 0; y < 5; ++y)
cout << array[x][y] << ' ';
cout << '\n';
}
cout << endl;
}
int main() {
int num = 0;
cout << "How many neighbours?: "; //Asks user for the number of neighbours they'd like to check for.
cin >> num; //Saves the number of neighbours to look for in 'num'
int array[5][5];
int dummyarray[5][5]; //A spare array we'll use to keep track of which boxes have the specified number of neighbours.
for (unsigned x = 0; x < 5; ++x) {
for (unsigned y = 0; y < 5; ++y)
array[x][y] = 1; //Here we fill our original array with 1's
}
for (unsigned x = 0; x < 5; ++x) {
for (unsigned y = 0; y < 5; ++y)
dummyarray[x][y] = 1; //Now we fill our dummy array with 1's so it's the same as our original array
}
Draw(array); //Here we call the Draw function, which prints our array for us.
array[1][1] = 0;
array[1][2] = 0; //Set some values of our original array to 0
array[1][3] = 0;
for (unsigned x = 0; x < 5; ++x) { //Here's where the checking starts
for (unsigned y = 0; y < 5; ++y) {
if (array[x][y] == 0) { //If we find a 0, start checking for neighbours of that 0 that are also 0's
int count = -1; //Because this method counts the original box (array[x][y]) when searching for 0's, we anticipate this by removing one from the count, so that we get the correct number of neighbours
for (int vertical = -1; vertical < 2; ++vertical) { //This loop checks boxes above and below our original box
for (int horizontal = -1; horizontal < 2; ++horizontal) { //This loop checks boxes side to side of our original box
if (vertical + y >= 0 && vertical + y < 5 && horizontal + x >= 0 && horizontal + x < 5) { //If we're inside the array bounds (ie, if we're not trying to access array[-1][-2] or something similar which would undefined behaviour), continue
if (array[x + horizontal][y + vertical] == 0) //If the box we're checking is a 0, add 1 to the number of neighbours our original box has
++count;
}
}
}
cout << "(" << x << ", " << y << "): " << count << endl;
if (count == num) dummyarray[x][y] = 0; //If the box we just checked has the number of neighbours we're looking for, mark it in the dummy array.
}
}
}
for (unsigned x = 0; x < 5; ++x) {
for (unsigned y = 0; y < 5; ++y)
array[x][y] = dummyarray[x][y]; //Here we copy all of dummyarray's data to our original array.
}
Draw(array); //Finally, we draw our array again with Draw()
return 0;
}
I'm really confused why you're trying to match the full neighborhood if all you need is "at least one neighbor is 1". Is there a reason you can't just do:
// going through the loop to figure out which ones have at least 1 neighbor
for (int x = 0; x <5 ; x++)
{
for (int y = 0; y <5 ; y++)
{
if ( (array[x][y] == 0 )
&&
(array [x-1][y] == 1 || array [x+1][y] == 1 ||
array [x][y-1] == 1 || array [x][y+1] ==1 ||
array [x+1][y+1]==1 || array [x-1][y-1]==1 ||
array [x-1][y+1]==1 || array [x+1][y-1] == 1)
)
{
cout << endl;
cout << "box :" << x << " :" << y << endl;
}
}
Oh and you should probably handle the cases at the borders.
int clamp04(int coord){return coord<0?0:(coord>4)?4:coord;}
and then use it like
// going through the loop to figure out which ones have at least 1 neighbor
for (int x = 0; x <5 ; x++)
{
for (int y = 0; y <5 ; y++)
{
if ( (array[x][y] == 0 )
&&
(array [clamp04(x-1)][y] == 1 || array [clamp04(x+1)][y] == 1 ||
array [x][clamp04(y-1)] == 1 || array [x][clamp04(y+1)] ==1 ||
array [clamp04(x+1)][clamp04(y+1)]==1 || array [clamp04(x-1)][clamp04(y-1)]==1 ||
array [clamp04(x-1)][clamp04(y+1)]==1 || array [clamp04(x+1)][clamp04(y-1)] == 1)
)
{
cout << endl;
cout << "box :" << x << " :" << y << endl;
}
}
Also, as a side-note, if you're then setting those values to 1 the operation you're executing is a morphological filter operation known as "dilation"

expected expression in C++?

#include <iostream>
using namespace std;
void num7()
{
int numRows;
cin >> numRows;
for (int x = 0; x < numRows/2; x++) {
for (int y = 0; y <= x; y++) {
cout << "*";
}
cout << "\n";
}
float numRowsfloat = numRows;
double cos = numRowsfloat / 2;
int tan = numRowsfloat / 2;
double sin = tan;
if (cos == sin)
cout << "\n";
for (int x = 0; x < numRows/2; x++) {
for (int y = numRows/2; y >0; y--) {
cout << "*";
}
}
else
for (int x = 0; x < numRows/2+1; x++) {
for (int y = x; y >0; y--) {
cout << "*";
}
cout << "\n";
}
}
In the else column, it says expected expression.
This is trying to make a triangular shape. like
*
**
***
***
**
*
for inputed 6
or
*
**
***
**
*
for inputed 5
You problem is this:
if (cos == sin)
cout << "\n";
for (int x = 0; x < numRows/2; x++) {
for (int y = numRows/2; y >0; y--) {
cout << "*";
}
}
Here only the cout is part of the if statement. The loop is not. You need to add braces around the whole block.
You forgot the braces for the if statement. try this:
if (cos == sin) {
cout << "\n";
for (int x = 0; x < numRows/2; x++) {
for (int y = numRows/2; y >0; y--) {
cout << "*";
}
}
} else
for (int x = 0; x < numRows/2+1; x++) {
for (int y = x; y >0; y--) {
cout << "*";
}
cout << "\n";
}

Is it possible to dynamically increment in a for-loop in C++?

I was wondering if it is possible to dynamically increment in a for-loop in C++. For example, I have the following code:
for (int x = 0; x < maxX-1; x ++){
for (int y = 0; y < maxY-1; y ++){
for (int z = 0; z < maxZ-1; z++){
cout << "z = " << z << endl;
}
}
}
Which prints out
z = 0
z = 1
z = 2
...
However, if I were to change the loop to:
amount = 2;
for (int x = 0; x < maxX-1; x ++){
for (int y = 0; y < maxY-1; y ++){
for (int z = 0; z < maxZ-amount; z+= amount){
cout << "z = " << z << endl;
}
}
}
Then I get an infinite loop of
z = 0
z = 0
z = 0
z = 0
Is it not possible to do this?
It's perfectly possible. What's more likely is that you have an integer overflow/underflow bug.
I don't see any reason why the above code doesn't work.As Rhuidean said may be the z loop is iterating and also it depends upon the values of maxX,maxY and maxZ.
it's perfectly possible.
The code you submitted doesn't create an ininite loop.
#include <iostream>
int main () {
int amount = 2;
int maxX = 4;
int maxY = 5;
int maxZ = 12;
for (int x = 0; x < maxX-1; x ++){
for (int y = 0; y < maxY-1; y ++){
for (int z = 0; z < maxZ-amount; z+= amount){
cout << "z = " << z << endl;
}
}
}
}
http://codepad.org/TZtTFdnD
You can, but you are creating a maintenance headache as the code gets very difficult to follow.
I think you should rethink your strategy.