I am trying to search through an array, and only check specific values (the 4th,5th and so on)- ((0+n*4) and (3+n*4).
The first one found will be checked and if it has a value of 0 will it be changed to 1 and then the program should stop. If not it will try the next value and so on..
I have the following code, but it doesn't stop ..it makes all the values 1 at once..
Any suggestions?
{
for (i=0; i<(totalnumber); i++)
{ for (n=0; n<((totalnumber)/4); n++)
{ if (i==(0+(n*4)))
{ if (array[i]==0)
{
array[i]=1;
break;
}
}
else if ((i==(3+(n*4))))
{
if (array[i]==0)
{
array[i]=1;
break;
}
}
}
}
}
Using a single break statement only breaks out of the nearest loop. It doesnt break out of the outer i loop. So, change your code to break out of the outer loop too.
One other way is to use both counter variables i,n within the same for loop. That means, you only use break once to break out of the outer for loop.
I quote from MSDN
Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control elsewhere out of the nested structure.
This is related - Can I use break to exit multiple nested for loops?
Related
What are some uses of never-ending loops? They are usually bad news in programming, but is there ever a time when you want a loop to never end?
Infinite loops are only bad news when they are not intended or their use has unintended consequences. If you use them with intent there is no difference from any other classification of loop you might consider. However you will still end up breaking things despite intentional use. It is common to use this form when you want to access the iterator or index component after the loop has been terminated, for example:
index = 0;
result = null;
for (;;)
result = foo(index);
if (bar(result))
break;
index += result;
use(index, result);
Note that mutating data outside of the loop's scope may be very undesirable depending on the context, so whether or not this is a good use case really depends on the context. For another similar example, an actual iterator may be the object desired outside of the loop, but initializing it within the loop header would not allow access outside of the loop. An infinite loop would resolve this problem.
for (foo.iterator(); foo.hasNext(); ) {
use(foo.next());
}
keep_using(foo.next()); // throws an error
Additionally, infinite loops can in some cases improve readability, especially if there are many break conditions but they might not all derive from mutually exclusive units. For example, imagine we have the following:
for (;;) {
if (condition1)
break;
else if (condition2)
do_stuff();
else if (condition3)
break;
else
do_something();
}
This can be rewritten using the three components of a loop as:
for (condition = true; condition; iteration) {
if (condition1 || condition3)
condition = false;
else if (condition2)
do_stuff();
else
do_something();
}
However if we introduce a small amount of change (at least in terms of characters on the screen) to the original code:
for (;;) {
if (condition1);
break;
if (condition2);
do_stuff();
if (condition3);
break;
else
do_something();
}
The rewrite becomes this thing that requires us to lug around this extra variable:
for (condition = true; condition; iteration) {
if (condition1)
condition = false;
if (condition2) {
do_stuff();
condition = true;
}
if (condition3)
condition = false;
else {
do_something();
condition = true;
}
}
This can quickly become difficult to read and maintain as the loop body, and especially the complexity grows, for example if condition were actually many different conditions such as a || b || c < d || (e > f) && (a > f); or, the loop contained several nested loops. Though you might apply the same logic to other the original changed version.
Another readability related example involves verbose initialization, though admittedly not a very good use case:
for (more_long = some_ridiculously_long.initialization_statement.longer_than.Long_Long_Mans_Sakeru_gummy();
more_long < lots_of && more_long < break_conditions
maybe_even_an_update_that_hangs_at_ninety_nine_percent) {
...
}
I am learning C and my question might be silly but im confused.In a function like:
int afunction(somevariables)
{
if (someconditions)
{
do some stuff
return 1;
}
raise_error("error happened")
return 0;
}
My question is,if the if statement isnt meeted(success),then it will go to the raise_error ? in other words,does the raise_errors position act like if it was in a else statement,or its because you have to return something at the end(return 0)?or would it need a proper else statement?Basically im confused on how to make a propre if condition--if this condition isnt meet--then call raise_error.
thank you!
if the if statement isn't met (success), then it will go to the raise_error?
Yes. When if condition is not met, the control is passed to else branch if it exists; otherwise, the entire if statement is skipped.
in other words, does the raise_errors position act like if it was in a else statement?
In this case, the answer is "yes", but only because your if branch is structured in a way that terminates the function due to return statement at the end.
Without that return at the end the control would go to raise_error upon completion of the if branch.
in other words,does the raise_errors position act like if it was in a else statement
Yes. Unless raise_error() does something that exits process, the return 0 will be executed aferwards.
Basically im confused on how to make a propre if condition--if this condition isnt meet--then call raise_error.
The code is fine. But if it makes it easier to understand then you can use an else clause too.
Your code is functionally equivalent to:
int afunction(somevariables)
{
if (someconditions) {
do some stuff
return 1;
}
else {
raise_error("error happened")
return 0;
}
}
The code or line that is not under some condition will always be executed unless you get out of the code before getting to that unconditional line. You don't need else in this case since you return 1 and does not execute remaining lines
I am relatively new at programming, and I'm having trouble figuring out how to loop through an array until the counter finds zero, and when it finds zero once, performs an action and exits the loop. Here is the loop I have so far:
for (int i = 0; i<13; i++)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
}
}
Currently, this loops through the array until it finds zero, calls deal(), prints the value of pHand, and then loops back through the same sequence until i=0. Please help. I am completely stumped on how to fix this.
The break statement can be used to exit an enclosing loop (e.g., a while, do-while, or for) or switch.
for (int i = 0; i<13; i++)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
break;
}
}
// code will continue executing here if the for loop condition becomes
// false (i is 13) or if the break statement is reached.
In your code, if you encountered ZERO value cell, you just call "deal" function and printf, but you don't exit the loop, your are continuing to the next iteration.
In order to exit the loop, add "break" statement in the "if" scope and you will go out the loop once you fulfill the condition.
Some consider break to be harmful. I've used it plenty, but some people have issues with it. If you wanted to avoid using break, you could do the following:
int i = 0;
char finished = 0;
while (i < 13 && !finished)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
finished = 1;
}
i++;
}
You could also rework it to use do-while. Some would say that this kind of solution is a little nicer, semantically.
I have a program similar to this:
switch(x)
{ case 1:
for(i=0; i<10; i++)
{
if ((i==3) || (i==4) || (i==5) || (i==6) || (i==7))
{
if (foobar[i])
break; // i am talking about this break
}
}
...further program
break; /not this break
if foobar[i] is true, would the program break out of the case label or the for loop?
The break follows a LIFO type nature, that is, the last break will come out of the first control structure. So, the break that you chose would break out of the for-loop, not the case.
The for loop.
Please see: break Statement (C++):
The break statement ends execution of the nearest enclosing loop or
conditional statement in which it appears. Control passes to the
statement that follows the ended statement, if any.
break will only break out of the for loop. If you have nested statements, it will only break out one level
Is the for loop. The break will bubble up until find the first for, while or a switch.
So you can just write your program like this:
switch(x){
case 1:
int loopBreaked = 0; //If you want to know if the loop has breaked
for(int i=0; i<10; i++) {
if (i <= 7 && i >= 3 && foorbar[i]) {
loopBreaked = 1;
break; //breaks the loop
}
}
break; //breaks the switch
}
How about:
for(i=3; i<=7 && !foobar[i]; i++) {}
For the sake of completeness, break will break out of the innermost statement of the type for do while, or switch. There is no need to break out of an if statement, since simply ending the code block will do the same job.
Your break will break the for loop. And the break you using later, break the switch. You can consider this code sample:
for(int i=0;i<len;i++)
{
for(int j=0;j<len;j++)
{
//statements
break;
}
//statements
break;
}
the break inside the inner loop break the inner loop and the following break statement will break the outer loop. In your code sample, the break you noticed is inside the for loop. So, the for loop will break.
if(turn==2)
{
if(forward) /*then what to do if this if comes true for coming out of outer loop*/
if(columnHead>0)
{
columnHead--;
addr[columnHead] |=1<<(rowHead-1);
}
else
{
columnHead =7;
addr[columnHead] |=1<<(rowHead-1);
}
if(rowTail!=(rowHead-1))
{
addr[columnHead+columnSize] &=~(1<<rowTail);
columnSize++;
rowTail++;
}
else
{
addr[columnTail] &=~(1<<columnTail);
if(columnTail==0)columnTail=8;
columnTail--;
}
back=1;
}
I want to come out of outer if loop if it satisfies condition if(forward)
You should create function of this code, and return from the block where the condition becomes true.
A standard idiom is to use while(true){/*your code here*/ break; } around the whole block and use break statements as appropriate which will take you to the end of the while brace. Just remember to include the final break or your program will loop.
Whatever you do, don't use a goto as they are considered very poor programming style.
Some folk, from the C days where while(true) would issue a compile warning, use for(;;) instead.
The odd thing is, thinking about this some more, you could use
do {
/*your code here, using break for premature exit*/
} while (false);
which doesn't need the final break. Only I've never seen this in production code.
I guess just putting an else in there will do what you want. Also, please put braces around big blocks - it makes the else part unambiguous.
if(turn==2)
{
if(forward) {
if(columnHead>0)
{
columnHead--;
addr[columnHead] |=1<<(rowHead-1);
}
else
{
columnHead =7;
addr[columnHead] |=1<<(rowHead-1);
}
} else {
if(rowTail!=(rowHead-1))
{
addr[columnHead+columnSize] &=~(1<<rowTail);
columnSize++;
rowTail++;
}
else
{
addr[columnTail] &=~(1<<columnTail);
if(columnTail==0)columnTail=8;
columnTail--;
}
back=1;
}
}
Version after the author's comment:
if(turn==2 && !forward) {
if(rowTail!=(rowHead-1))
{
addr[columnHead+columnSize] &=~(1<<rowTail);
columnSize++;
rowTail++;
}
else
{
addr[columnTail] &=~(1<<columnTail);
if(columnTail==0)columnTail=8;
columnTail--;
}
back=1;
}
You probably have to go the other direction, that means:
You don't want to check wether
if(forward) is true, but instead you want to do if(!forward).
Though you'd need to check what type forward is. I guess it's an integer though.
You can try giving the return 0; or return something; when you need to get out of the if, before that u may want to put the entire code in a c syntax function like-
(int)someFunction(int turn, int forward,
int columnHead, int rowHead, int rowTail, int columnTail)/*have all the arguments with proper types declaration*/{
//your code with return 0;
}.
why go into the "if" in the first place.
change the outter if to:
if(turn==2 && forward) //not sure if your logic required `forward` or `!forward` you were ambiguous
{
//...
}