How do I exit a loop in C++ without using break? -
i'm writing code swap integers in array , want know how can exit loop without using break statement , keeping logic consistent. here code below:
int swapped = 0; if (arrays[0][first] % 2 == 0) { cout << arrays[0][first] << " odd " << endl; (int = 1; < arraycount; ++i) { (int j = 1; j < arrays[i][0] + 1; ++j) { if (arrays[i][j] % 2 != 0) { int temp = arrays[i][j]; cout << "array #" << 1 << " value " << arrays[0][first] << " swapped " << "array #" << << " value " << temp; arrays[i][j] = arrays[0][first]; arrays[0][first] = temp; swapped = 1; break; } } if (swapped) { break; }
using break statement not make codes logic inconsistent , breaks useful improve readability of code. in answer question can achieved utilizing while loops , logical boolean operators. modified version of code below, have tried modify little possible can still see code within example. there few logical errors in code have left in example below might want into. in particular line below print "is odd" when in fact number even. if wanting check if number arrays[0][first]
odd following if statement needed if (arrays[0][first] % 2 != 0)
instead of if (arrays[0][first] % 2 == 0)
.
logical error
if (arrays[0][first] % 2 == 0) { cout << arrays[0][first] << " odd " << endl;
this code without using breaks.
bool swapped = true; if (arrays[0][first] % 2 == 0) { cout << arrays[0][first] << " odd " << endl; int = 1; while ( (i < arraycount) && swapped) { int j = 1; bool if_odd = true; while ((j < arrays[i][0] + 1) && if_odd) { if (arrays[i][j] % 2 != 0) { int temp = arrays[i][j]; cout << "array #" << 1 << " value " << arrays[0][first] << " swapped " << "array #" << << " value " << temp; arrays[i][j] = arrays[0][first]; arrays[0][first] = temp; swapped = false; if_odd = false; } j++; } i++; } }
Comments
Post a Comment