About increment operation in cpp - c++

are following code samples equivalent?
This:
while (true)
if (!a[counter] || !b[counter++]) break;
and this:
while (true){
if (!a[counter] || !b[counter]) break;
counter++;
}
i mean, would increment be performed after all conditions' checking done?
Here:
int _strCmp(char* s1,char*s2)
{
int counter = 0;
while (s1[counter]==s2[counter])
if (!s1[counter] || !s2[counter++]) return 0;
if (s1[counter] > s2[counter])
return 1;
if (s1[counter] < s2[counter])
return-1;
return 0;
}
Are there some cases, when this function doesnt work correctly?

No they are not.
Here if !a[counter] returns true the OR'ed condition will not be evaluated.
The second condition in OR is only evaluated if the first condition is false. This is because anything OR'ed with true will be true.
Look at the following image :
As in the image you can see that case 2 is not equivalent

Since the it is incremented post-evaluation (rather than ++counter), the value that will be returned is the value before it is incremented. So, those are equivalent statements.
If counter = 6, then !b[counter++] will return b[6], and then increment 6 to 7.

You could try it yourself changing your code to this:
run = 5;
while (run > 0) {
run--;
if (!a[counterA] || !b[counterA++]) break;
}
run = 5;
while (run > 0){
run--;
if (!a[counterB] || !b[counterB]) break;
counter++;
}
// compare counterA and counterB
EDIT:
Regarding "i mean, would increment be performed after all conditions' checking done?"
No. There are post and preincrement operations. Since you are doing a postincrementation your value would be incremented after it's value was used to evaluate the expression.

Related

The for loop isn't entered even if the initial requirement is true

I have the following function with a for loop inside it. The code is run on an Arduino and the Serial.print function shows that the function is entered correctly with the correct input value. But the for loop isn't entered. Does anyone have an idea why?
void openvalveCold(int steps){
Serial.println(steps);
// Steps is confimed to be 200.
digitalWrite(sleep1,HIGH);
for (antalsteg = 0; antalsteg == steps; antalsteg++)
{
Serial.println("2");
//digitalWrite(dir1,HIGH);
digitalWrite(stepp1,HIGH);
delay(25);
digitalWrite(stepp1,LOW);
delay(25);
Serial.println(antalsteg);
nr_of_steps_cold++;
}
}
void loop{
// calling on function
openvalveCold(200);
}
A for loop is usually constructed like this:
for(init counter; condition; increase counter)
You have made the (false) assumption that it loops until the condition is true. That's wrong. It loops while it is true. Change to:
for (antalsteg = 0; antalsteg < steps; antalsteg++)
The loop isn't entered because the condition is false when the loop starts:
for (antalsteg = 0; antalsteg == steps; antalsteg++)
When the conditional of the loop is first evaluated, antalsteg is 0 and steps is 200. So antalsteg == steps evaluated to 0 == 200 which is false. So the loop is never entered.

Index of the condition that was satisfied inside if-statement

if(command[i]=='H' or command[i]=='h' or command[i]=='C' or command[i]=='c'){
do something;
}
Once the logic flow goes inside this if-statement, I want to know what exactly command[i] was. Surely I can make individual comparisons again in the inside block and find out, but is there a more elegant way of knowing, say, the index of the condition that was satisfied?
If you use
if((myC=command[i]) =='H' ||
(myC=command[i]) =='h' ||
(myC=command[i]) =='C' ||
(myC=command[i]) =='c')
then the value of the successful expression will end up in myC, because evaluation in a chain of "or"s stops at the first true subexpression.
If you go one step further you can get a number value identifying the subexpression by index.
if(((myC=1), command[i]) =='H' ||
((myC=2), command[i]) =='h' ||
((myC=3), command[i]) =='C' ||
((myC=4), command[i]) =='c')
Same concept, the first successful subexpüression is the last to be evaluated and the , operator ensures that only the second part gets used for the comparison.
Another option is to assign a value. You could use switch, an if..else tower, or a function with return statements. Here is a version with function:
int classify( char command )
{
switch( command )
{
case 'H': return 1;
case 'h': return 2;
case 'C': return 3;
case 'c': return 4;
default : return 0;
}
}
void func(void)
{
int result = classify( command[i] );
if ( result )
{
// use result value here as appropriate
}
}
It would also be possible, in fact preferable, to use an enumerator instead of magic numbers.
Just do this -
if(command[i]=='H' or command[i]=='h' or command[i]=='C' or command[i]=='c'){
print command[i]; //use whatever command is appropriate for printing
do something;
}

what is the use of if else statements?

I don't quite understand the meaning of else if statements.
why not just to continue with the if statements in case one is false?
it works the same.
example with if only that will work the same with else if:
function testSize(num) {
if (num < 5){
return "Tiny";
}
if (num < 10){
return "small";
}
return "Change Me";
}
testSize(7);
In your actual code you specify a return statement in the code associated to the if statement.
Suppose you don't specify a return statement or suppose today you specify a return statement but tomorrow you remove it to do a common return at the end of the method.
This code will test each condition even if the first one is true :
if (num < 5){
// do something
}
if (num < 10){
// do something
}
This code will not test the next condition if the first one is true :
if (num < 5){
// do something
}
else if (num < 10){
// do something
}
These two ways of doing have two distinct meanings.
When you have a series of if statements, you expect that more than one condition may be true.
When you have a series of if-else-if statements, you expect to have not more than one condition true.
Using the first form (a series of if) while functionally you expect to have not more than one condition true is misleading.
Besides, if the code is modified and you add a condition that is both true for two if statements while you don't want have this case, it would create an issue.
Your code is only showing your belief. What would happen in the example below?
function testSize(num) {
if (num < 5){
x = 1;
}
if (num < 10){
x = 2;
}
result = complex calculations;
}
function testSize2(num) {
if (num < 5){
x = 1;
} else if (num < 10){
x = 2;
}
return x * 2;
}
testSize(4); // result is 4
testSize2(4); // result is 2
x may also be involved in more calculations
if(condition) {...}
if(condition) {...}
if(condition) {...}
In above code, even if the first or second condition is true, third condition have to be checked.
if(condition) {}
else if(condition){}
else if(condition){}
Here if first condition is true, next two will not be checked. So, it saves time and is more readable logically.
A one way if statement takes an action if the specified condition is true.If the condition is false, nothing is done. But what if you want to take alternative actions when the conditions is false ? You can use a two-way if-else statement. The action that a two-way if-else statements specifies differ based on whether the condition is true or false.
Well, there is a bit different from this two statement.Consider the follow samples
if(a > 0) {
...
}
if( a == 0) {
...
}
if(a < 0) {
...
}
and
if(a > 0) {
...
}
else if( a == 0) {
...
}
else if(a < 0) {
...
}
when a is zero the last else if statement will not be execute while if need to compare third time.If a equals to 10, else if could be execute once while if is third.From this else if statement could be execute less and let your program a bit fast.
else if should be used when there are multiple conditions and you want only one of them to be executed, for instance:
if(num<3){ console.log('less than 3') }
else if(num<2){ console.log('less than 2')
If you use multiple if statements instead of using else if, it will be true for both the conditions if num = 1, and therefore it will print both the statements.
Multiple if statements are used when you want to run the code inside all those if statements whose conditions are true.
In your case it doesn't make a difference because the function will stop and return at the very first return statement it encounters. But let's say, the blocks' orders are interchanged, then your function will never return 'tiny' even if num = (anything less than 5).
I hope that helps!
If all your if branches terminate the function (e.g., but returning a value of throwing an exception), you're right, and you really don't need an else statement (although some coding standards might recommend it).
However, if the if branches don't terminate the function, you'd have to use an else or else if clause to prevent multiple blocks from being executed. Assume, e.g., you want to log a message to the console instead of returning it:
if (num < 5) {
console.log("Tiny");
} else if (num < 10) {
console.log("small");
} else {
console.log("Change Me");
}

Simple recursive function to determine if two elements are transitively true

newbie here. Even newer to recursion. I'm writing a function for my C++ program, and as you'll be able to tell, I'm a bit clueless when it comes to recursive algorithms. I'd appreciate it greatly if someone could fix my function so I can get it working and perhaps have a better idea how to handle recursion afterward.
My function takes a two-dimensional square array of booleans, and integer i, and an integer array_size as parameters. The function returns a boolean value.
The array is an adjacency matrix that I use to represent a set of conditionals. For example, if the value at [0][3] is true, then 0 -> 3 (if 0, then 3). If [3][7] is true, then 3 -> 7 (if 3, then 7). By the transitive property, 0 -> 7 (if 0, then 7).
The integer i is a particular element in the set of conditionals. The function will return true if this element is transitively connected to the last element in the array. The last element in the array is the integer (array_size - 1),
The integer array_size is the size of each dimension of the square array. If array_size is 20, then the array is 20x20.
The idea of this function is to determine if there is any logical "path" from the first integer element to the last integer element by the transitive property. When the path exists, the function returns true, otherwise, it returns false. The recursive call should allow it to traverse all possible paths, returning true once it finally reaches the last element and false if all paths fail.
For example, if i = 0 and array_size = 10, then the function will return whether or not 0 -> 9 is valid according to the conditionals provided by the matrix and the transitive property.
This is my code so far:
bool checkTransitivity(bool **relations, int i, int array_size){
bool isTransitive = false;
if (i == array_size - 1)
{
isTransitive = true;
}
else
{
for (int j = i; j < array_size; j++){
if (relations[i][j])
{
isTransitive = checkTransitivity(relations, j, array_size);
}
}
}
return isTransitive;
Currently, the function returns true for all input.
Any help at all is appreciated. Thanks in advance!
EDIT: This first part is unnecessary because of your if-else statement. Move on to END OF EDIT.
Let's start with what a base case in a recursive function is:
if (i == array_size - 1)
{
isTransitive = true;
}
Well you do have a base case, but nothing is being returned. You are just setting a flag to true. What you want to do is:
if (i == array_size - 1) {
return true;
}
Now the function will work its way up the recursive stack to return true. END OF EDIT.
But we still need to fix the recursive case:
else {
for (int j = i; j < array_size; j++) {
if (relations[i][j]) {
isTransitive = isTransitive || checkTransitivity(relations, j, array_size);
}
}
}
return isTransitive;
The || means binary OR. So you have the logic right. You want to check each possible path to see if it can get there, but by setting isTransitive to the result of each check, isTransitive is only going to be set to the last call. By doing isTransitive = isTransitive || recursive call, isTransitive will be true as long as one of the calls results in a true value.
The last thing I want to say is a caution: if relations[i][j] == true and relations[j][i] == true, your code will still be in an infinite loop. You must find a way to eliminate the potential backtracking. One way to do this is to create another array that stores which paths you have already checked so you do not infinitely loop.
More information can be found here: Depth First Search
I think all you need is a break condition to stop continuing the loop when you encounter a non-transitive item. See below (haven't tested)
bool checkTransitivity(bool **relations, int i, int array_size){
bool isTransitive = false;
if (i == array_size - 1)
{
isTransitive = true;
}
else
{
for (int j = i; j < array_size; j++){
isTransitive = relations[i][j] && checkTransitivity(relations, j, array_size);
if (!isTransitive)
break;
}
}
return isTransitive;
}

I want to increment a counter by one in a while loop c++

I am trying to increment a lap counter in my game by one but because I have to put this code in the game loop my counter goes over every time by about 500 instead or moving up one. Here is my code. The checkpointPassed variable is only true when a checkpoint is passed through. I know this works and the checkpoint number is the current checkpoint and they start at 0.
if(checkpointNumber == 0 && checkpointPassed == true)
{
lapNumber += 1;
}
I can't post the game loop because it is quite large.
Any Help is appreciated.
EDIT
Here is some more of the code so you can see what I am trying to do.
if(distance > carRadius && markerCounter < 5000)
{
if(checkpointPassed == true)
{
markerCounter++;
}
}
if(checkpointNumber == 0 && checkpointPassed == true)
{
lapNumber += 1;
}
if(distance < carRadius)
{
markerCounter++;
cross->SetX(checkpointX);
cross->SetY(checkpointY);
cross->SetZ(checkpointZ);
checkpointNumber += 1;
checkpointPassed = true;
}
if(markerCounter > 4999)
{
checkpointPassed = false;
cross->SetPosition(0,-50,0);
markerCounter = 0;
}
Add another two variable called inCheckpoint, which stores whether the user is currently "inside" the checkpoint or not. This allows you to detect when the user enters a checkpoint and only increment the lapNumber then. The code would look as follows:
if(checkpointNumber == 0 && checkpointPassed == true)
{
if (inCheckpoint == false) /* previously not inside a checkpoint */
lapNumber += 1;
inCheckpoint = true;
}
else
{
inCheckpoint = false;
}
UPDATE: Don't rely on checkpointPassed:
if(distance < carRadius)
{
if (inCheckpoint == false) /* previously not inside a checkpoint */
lapNumber += 1;
inCheckpoint = true;
}
else
{
inCheckpoint = false;
}
You could set/pass a gueard value that indicates how many iterations in the game loop you are (or whether this is the first iteration). If it is the first iteration (within the current lap), increment the variable as you do now, otherwise don't
You will need to reset this guard value for each lap -- e.g. right after you increment lapNumber.
You might need to cancel the 'checkpointPassed` state.
if (checkpointNumber == 0 && checkpointPassed == true)
{
lapNumber += 1;
checkpointPassed = false;
}
This means that you won't be counting the lap again until the next time a checkpoint is passed, which is presumably when you need it counted.
However, if you need checkpointPassed true later in the loop, then you'll need to think whether you need yet another variable, such as lapCounted, which is set to false when checkpointPassed is set to true, and reset to true by the code above (instead of setting checkpointPassed, not as well as setting it).
If I understand correctly what you said, your 'if' statement is inside the main loop and when you pass a checkpoint, 'checkpointPassed' becomes true. For how long?
If it stays 'true' for a few iterations, then each time your game loop does an iteration,your lap counter is incremented. In this case, you should either set checkPointPassed to false at the end of the iteration, or use a different variable, that you set to true at the same time that checkPointPassed becomes true and false after incrementing.
If this does not answer your question, can you give a little more context as with only this part of the code, it is hard to figure out what you want to do.