Stuck in a nested do { for { if loop - c

So with this bit of code the program hangs up and won't exit the loop, the printfs were just put in for debugging and they aren't integral to the program. I am pretty new to programming so I am not sure what I am missing the logic seems like it should work. Thank you very much for taking the time to look over this and your help.
do
{
intialcollide = 0;
for(i=0; i<11; i++)
{
if(i != currentObj)
{
if(object[currentObj].new_loctX == object[i].new_loctX && object[currentObj].new_loctY == object[i].new_loctY)
{
intialcollide = 1;
}
else
{
intialcollide = 0;
}
}
printf("%d\n", intialcollide);
}
}while(intialcollide != 1 || i != 10);
printf("Collide? %d", intialcollide);
When I run it I get infinite 1's and 0's. Thanks again for the help

At the end of your for loop, i will always equal 11. Maybe you thought it would equal 10? Anyways, there is no point comparing i to anything in the while condition because you know it is always the same value.

Add a "break;" whenever you set intialcollide to 1. Your for loop is resetting the value to 0 before it hits the while loop check.

Related

How to convert nested loop construct into flow chart in C?

I'm drawing this code
if (V > 24)
{
do
{
PWM();
while (I = 0)
{
RA5 = 0;
LED();
I2C();
Delay_ms(1000);
RA5 = 1;
Delay_ms(1000);
if (I != 0)
{
break;
}
}
LED();
I2C();
} while (v < 28.7)
}
to this
I really don't know how to deal with this nested loop, is there any better idea for it?
Unrelated, but
if(I != 0){
break;
}
Is implied by the for loop, you don't need it. Also be careful:
while(I=0)
will set I to 0 and your loop will never exit! You may have found this and decided to add the break later to compensate. What you want is:
while(I==0)
Note that what you did with the do while is correct, and a while loop is the same except the check happens before entering the loop rather then when exiting the loop. Remove the break and have your arrow simply go back to before the check for I == 0.

Converting date format format from dd/mm/yyyy to yyyy/mm/dd using C

The inner while loop executes infinitely though the value of i = n which is finite.
It compiles but shows segmentation fault.
My Code
char s[]="22/02/1997",r[20],temp[20];
int i,j,k,z,n;
for(n=strlen(s)-1; n>=0; n=i)
{
i=n;
k=0;
while(s[i]!='/' || s[i]!='-')
{
temp[k++]=s[i];
i--;
}
i--;
for(z=strlen(temp)-1,j=0; z>=0; z--,j++)
{
r[j]=temp[z];
}
temp[0]='\0'; //empty the array
}
printf("%s",r);
There are multiple issues in your code.
The j = 0 will be outside of all loop. Which means it have to be placed in starting of outer for loop.
You did not handled the assign null value correctly. In any place you did not assigned the null at end of the array.
Your expected answer is yyyy/mm/dd. But you did not assigned the / or - to the output.
In while loop, you have add one more condition also, that is checking the value of the i is greater than or equal to 0. If this condition is not there, then it tries to access the -1th position in array, it is not allocated. So, only you get the segmentation fault error.
Finally I have corrected these all mistakes. Try the below code it will works fine as you expected.
#include<stdio.h>
#include<string.h>
int main()
{
char s[]="12/02/1997",r[50],temp[50];
int i,j,k,z,n;
j = 0;
for(n=strlen(s)-1; n>=0; n=i)
{
i=n;
k=0;
while(s[i]!='/' && s[i]!='-' && i >= 0)
{
temp[k++]=s[i];
i--;
}
i--;
temp[k] = '\0';
for(z=strlen(temp)-1; z>=0; z--,j++)
{
r[j]=temp[z];
}
if(i >= 1) // If the i is greater than 1, then only it have a slash or hypen
{
r[j++] = s[i + 1]; //Assigning the / or - to the output.
}
temp[0]='\0'; //empty the array
}
r[j] = '\0';
printf("%s\n",r);
}
The inner while loop executes infinitely ....
That is because you use OR (aka ||) instead of AND (aka &&). So your condition
(s[i] != '/' || s[i] != '-')
will always be true. It should at least be (see later code):
(s[i] != '/' && s[i] != '-')
.... but shows segmentation fault.
That is a consequence of the infinite loop. Since the loop keeps incrementing/decrementing k and i, you'll end up using indexes outside the array boundary which causes the crash.
Further you should check that i doesn't become -1 and, for completeness, check that k doesn't get too large.
You should also make sure to terminate the temp string as you are using strlen(temp)
Something like:
while(i>=0 && k<19 &&s[i]!='/' && s[i]!='-')
{
temp[k++]=s[i];
i--;
}
temp[k] = '\0'; // Terminate temp
Notice: There are some problems with your second loop as well but once you have solved the above, you can start looking into that part.

How to avoid 'while(true)' with 'break' and rather use a 'for' loop?

I have an application with a config file from which various settings are read. One of the settings is the cycles that the application is running.
If this variable nLoops is -1 then it's supposed to run an infinite number of times. Otherwise it shall run x times.
At the moment this is how I implemented it. However I was wondering if there's a more straight forward way without the while(true) expression (I get a warning here):
//get nLoops from config file
int i = 0;
while (true)
{
if (nLoops > -1 && i >= nLoops)
break;
i++;
// do stuff
}
Just put the if condition (inverted, since you're testing to stay in instead of break out) in the while condition:
while (nLoops == -1 || i < nLoops)
Or as a for:
for (i=0; (nLoops == -1) || (i < nLoops); i++)
You can replace while(true) with for(;;) to avoid warnings. The for loop with a missing controlling expression is explicitly defined in the standard, e.g., ISO/IEC 9899:1999 6.8.5.3/2.
This requires one more (boolean) variable, but avoid using break statement in your loop.
// Here reads from configuration file
bool isInfiniteLoop = false;
i = 0;
if(nLoops == -1)
{
isInfiniteLoop = true;
nLoops = 1;
}
while(i < nLoops)
{
// here goes your code
if(!isInfiniteLoop)
{
// If NOT infinite loop: increment counter, otherwise while condition will always be 0 < 1
i++;
}
}

Arrays in Arduino

I am trying to create an array and be able to compare the second to last and last item in an array. It needs to be constantly adding and comparing to work correctly. This is just a function I am trying to get running to help control a stepper motor function. I have a loop that is going to fast for me to be able to compare directly. I do know that some of it is wrong but as I haven't coded in C very much I can't figure out how to use an array correctly. Thank you in advance.
int P[10],V[10],i,x,y;
Serial.print("checkvalue = ");
Serial.print(checkvalue);Serial.print("\n");
Serial.print("P = "); Serial.print(P[i]); Serial.print("\n"); //attempting to print array
Serial.print("V = "); Serial.print(V[i]); Serial.print("\n"); //to see if it is collecting
//data correctly
//these variables are declared above in my code, just didn't copy in
Dgreadpb = digitalRead(13);
PBcheck = Dgreadpb;
//Serial.print("Button in = ");Serial.print(Dgreadpb); Serial.print("\n");
Dgreadvls = digitalRead(12);
VLScheck = Dgreadvls;
//Serial.print("Photo in = ");Serial.print(Dgreadvls); Serial.print("\n");
for (i = 0; i < 10; i++){
x = Dgreadpb;
y = Dgreadvls;
P[i] = x;
V[i] = y;
if (P[i-1] == P[i] && V[i-1] == V[i]){ //trying to compare second to
checkvalue == 0; //last term to the last term
return;
}
else if(P[i-1] != P[i] || V[i-1] != V[i]){
checkvalue == 1;
return;
}
}
delay (1000);
By "trying to compare second to last term to the last term", do you mean "Trying to compare second to last term with their previous"? If that's the case your indices are wrong, it should be for(i = 1; i<10; i++).
Also both conditions are opposite (Either both are equal or AT LEAST one of them is different), there is no need for else if. Even more, cause both conditions are opposite it will never complete the loop. I think that's not the intention, if you're trying to say that only one of them are different you should do:
if (P[i-1] == P[i] && V[i-1] == V[i]){ //If both are equal
checkvalue == 0;
return;
}
else if(P[i-1] == P[i] || V[i-1] == V[i]){ //If only one is equal
checkvalue == 1;
return;
}
Ok, then I'd make a different thing.
Looking at your comment, it looks like you want to do something like this: read the value of two pins, compare them to the last value you read and, if they are differernt, start the motor, otherwise stop it.
Now, a lot of info are missing (e.g. how do you check the motor? how often do you want to check the sensor? what sensor?) but IMHO you should do something like this.
In this code I suppose that
you want to check the sensor every 100 milliseconds
if the values differ, you want to turn on the motor for the next 100 ms
the motor is a DC motor turned on by setting the corresponding pin (e.g. 10)
the sensors have a binary output on pins 12 and 13, since you wrote that in the code
BTW I used the millis() function because I hate the delay, since it blocks the uC. Using my function you'll be able to perform other operations while it is idle.
const byte motorPin = 10;
const byte sensorPPin = 12;
const byte sensorVPin = 13;
#define LOOP_TIME_MS 100
unsigned long lastLoopTime;
boolean lastPval, lastVval;
void setup()
{
pinMode(motorPin, OUTPUT);
pinMode(sensorPPin, INPUT);
pinMode(sensorVPin, INPUT);
lastPval = digitalRead(sensorPPin);
lastVval = digitalRead(sensorVPin);
lastLoopTime = millis();
}
void loop()
{
if ((millis() - lastLoopTime >= LOOP_TIME_MS)
{
boolean Pval = digitalRead(sensorPPin);
boolean Vval = digitalRead(sensorVPin);
if ((Pval != lastPval) || (Vval != lastVval))
{
digitalWrite(motorPin, HIGH);
}
else
{
digitalWrite(motorPin, LOW);
}
lastLoopTime += LOOP_TIME_MS;
}
/* Here you can do something else */
}
EDIT: If, on the other side, you want to use arrays (because you want to test the last N values instead of just the previous one) please provide further info on what are the changing conditions (or better provide examples)

When conditions in a if statement are met inside a for loop, how can I print one result?

Basically I have the following code. The problem is that I only want to have "Pass" printed once if both conditions in the if statement are met. The int 'res' is an average of all 6 elements in the parts array. Therefore, all "parts" must have a value of at least 40 and the average of these parts, known as "res", must also be above 40. At the moment the code obviously outputs Pass for each of the 6 elements of the "parts" array if they are over 40. I want this to just however output Pass once if all six elements of the "parts" array and "res" are over or equil to 40.
Any help will be gratefully appreciated!
for (int i = 0; i < 6; i++)
{
if (res >= 40 && parts[i] >= 40)
{
System.out.println("Pass");
}
}
2 things:
1) You look like you're just checking for a negative case. If you find any values that are less than 40 you want to break and not print "Pass". If each element is over 40 and res is over 40 you want to continue until you either find one that isn't or finish through the list. If you get through the whole list and none failed you know you can print "Pass".
2) res isn't changing in your loop as you supplied it. If you are changing it in the loop and this is just example code that's fine. But if you're not you should really just check it once outside of the loop.
boolean print = true;
for (int i = 0; i < 6; i++)
{
if (res < 40 | parts[i] < 40)
{
print = false;
break;
}
}
if(print)
System.out.println("Pass");
If I am understanding your question correctly, you would want to put
break;
after the println
for (int i = 0; i < 6; i++)
{
if (res >= 40 && parts[i] >= 40)
{
System.out.println("Pass");
break;
}
}
You can use a break; statement for step out of your loop after you print to the console.
A break is used to step out of any kind of loop.
while(true){
//do stuff
if(condition){
break;
}
}

Resources