I am having trouble with the while loop in my code. The instructions say to "Set a loop-control variable to a value that automatically enters the loop for the first time". Any suggestions on how I can do this? Any input will be appreciated. Thank you!
}//end main
I will assume you don't know what most of these terms mean.
A while loop assumes the following syntax (I'll do it in C# since I'm not sure what language you're coding in; update your original post and I'll change my samples):
while (/* loop control/condition here */)
{
// Code here
}
This evaluates like this in english (pseudocode):
while the loop control is true
do this
when it equals false leave the while
So what you want to do is initialize a variable (I'm using type bool here for clarity's sake) and put it in between the parenthesis as the "loop control."
Here's a small sample:
bool daytime = true; // This is the loop control.
int i = 0;
while (daytime == true) // We are seeing if it's day out.
{
System.out.println("It is daytime.");
if (i == 6) {daytime = false;} // If our counter hits 6:00 it's nighttime.
i = i + 1; // Increment our counter.
}
Anyway hope that helps you. Good luck!
Edit: Do-While
I may have misunderstood your original question a bit, this is what a do-while loop looks like:
Syntax:
do
{
// Code here
} while (/* loop control/condition here */);
Pseudocode:
do this code
keep repeating code until the condition is false
Sample:
bool daytime = true; // This is the loop control.
int i = 0;
do
{
System.out.println("It is daytime.");
if (i == 6) {daytime = false;} // If our counter hits 6:00 it's nighttime.
i = i + 1; // Increment our counter.
} while (daytime == true) // We are seeing if it's day out.
Related
I have a recursive function which I call acc. If a specific condition is fulfilled I call the function again. If not, I want do add a number to the variable a.
In my opinion it does not what it should. Can someone have a look on this:
double acc(v)
{
double a = 0;
for(int q=0; q<v; q++)
{
if(bf(q) < 1)
{
if(ef() == 0)
{
a += cf();
}
else
{
a += df();
}
}
else
{
return a += acc(v);
}
}
return a;
}
I tried to simplify it as good as I can. vis a variable. bf(), cf(), ef() and df() are functions which return an integer value. Now I want that a gets incremented every time a specific condition is fulfilled during the whole recursive process. Does my code what I want? I don't see it at the moment.
Your problem is that a is defined inside the recursive function. If you want to count events inside the recursion, declare a outside of acc().
The code below shows the rowtotal[0], which is the return value I'm getting from an infinite loop for every iteration. I'm trying to break the loop when all three returned values from the costcheck array are the same. This is my code:
do
{
.
.
.
/*do loop body*/
.
.
costcheck[counter3]=rowtotal[0];
if(costcheck[counter3-2]==costcheck[counter3] &&
costcheck[counter3-1]==costcheck[counter3] )
{
response=1;
}
counter3++;
printf("\t\t\t Number of iterations: %d \r", stop++);
}
while(response!=1);
Just get rid of all strange, superfluous variables. You only need to save the result of the previous iteration, together with a counter which you increase each time you find a match, rather than every time in the loop.
int counter=0;
const int COUNT_N = 3;
data_t prev=FORBIDDEN; // a value that rowdata[0] can never have
while(counter != COUNT_N)
{
...
if(prev == rowdata[0])
{
counter++;
}
else
{
counter=0;
}
prev = rowdata[0];
}
just to elaborate on Lundins Answer wich is the way to go in my opinion (would have posted as a comment, but lacking reputation...)
Only thing missing is the actual loop advancement counter (counter3 in your example):
int quitCounter=0; // Counter for quiting the loop on 3 consecutive identical values
int loopCounter=0; // Your normal rowdata index
const int QUIT_COUNT_N = 3;
#define FORBIDDEN 0xffffff // or some other value that rowdata[0] can never have
data_t prev=FORBIDDEN; // a value
do
{
...
/* do loop body, provide new value for rowtotal[0] on each iteration */
/* if you need to store the consecutive values returned in rowtotal[0] in costcheck array,
make sure that it will be big enough - if you only need to break on 3 identical values,
you can skip the entire costcheck array as Lundin proposes. */
...
costcheck[counter3]=rowtotal[0];
if(prev == costcheck[counter3])
{
quitCounter++;
}
else
{
quitCounter=0;
}
prev = costcheck[counter3];
counter3++;
} while(quitCounter!= QUIT_COUNT_N )
If you really want an infinite loop, a if(costcheck[counter-1] == costcheck[counter-2] && costcheck[counter-2] == costcheck[counter-3]) will lead to failure of program, if costcheck array has less than 3 elements. You have to be sure that it does have at least 3 elemets in this array.
BUT!!!! counter does not need to be more than 3 because as far as i get it, you want to check 3 most reciently read elements. Which means for comparison, you only need to remember 3 last values that were read.
The exapmple below stores up to 3 rowtotal[0] values, and checks if they are equal. If they are, progarm exits, if not, program gets new rowtotal[0] to the "end" of costcheck array, also the oldest value: here it's costcheck[0] is lost.
I can post the code to the example which i made, to show how the logic should work.
NOTE!!! I strongly think Lundin's and Morphine's solutions are by far better than mine.
do
{
.............
if(counter < 3)
{
costcheck[counter] = rowtotal[0];
counter++;
continue;
}
else
{
if(costcheck[counter-1] == costcheck[counter-2] && costcheck[counter-2] == costcheck[counter-3])
{
response=1;
}
else
{
costcheck[counter-3] = costcheck[counter-2];
costcheck[counter-2] = costcheck[counter-1];
costcheck[counter-1] = rowtotal[0];
}
}
}
while(response!=1);
}
I have a piece of code wrapped in try-catch in order to catch an exception, but I want to re-try that piece of code until it is successful. I have added a loop based on this post. This works as far as looping the code, however it is an infinite loop. Once the code is successful and moves to the next page, the code is still looping and ends up failing because it is searching for a locator that is no longer available because the page has advanced to the next. My question is this: how do I break out of the loop once the code is successful?
int count = 0;
int maxTries = 1;
while (true)
{
try{
driver.FindElement(By.id("textbox").sendKeys("123");
driver.FindElement(By.id("submit").click();
driver.FindElement(By.id("catalog").click();
if(driver.getTitle().equals("Correct Page"))
{break;
}
}
catch(NoSuchElementException e)
{
if (++count == maxTries) throw e;
}
}
}
driver.FindElement(By.id("part1").click();
Maybe using an exception for this purpose is not the right route.
Instead of while (true), try while (!driver.getTitle().equals("Correct Page"))
Then within the loop, increment the count, check it against maxTries and break when it is exceeded
Context : I'm searching for all the words contained in a 2d array (horizontally,vertically and diagonaly).
So what I do is I get all the possible words, check if they're in the given dictionary and if they are store them in an array. The thing is, I don't want it to have duplicates.
Here's a snippet of the code:
for (i=l-1;i>=0;i--){
palavra[aux]=mat[i][caux];
for (j=i;j>=0;j--){
palavra[aux]=mat[j][caux];
palavra[aux+1]='\0';
for (it=0;encontradas[it]!=NULL;it++){
if (strcmp(palavra,encontradas[it])==0)flag=1;
else flag=0;
}
if (flag==0) {
r = palavra_existe(dic,palavra);
if (r!=0) {
found[auxenc]=mystrdup(palavra);
auxenc++;
}
}
flag=0;
aux++;
}
aux=0;
}
The
if (strcmp(palavra, found[it])==0)flag=1
line is there to check if the formed worded has been found already, to avoid creating a duplicate. The problem is it doesn't work, duplicates appear anyway (as the flag variable never takes the value 1).
What could I be missing here?
The flag variable does get the value 1, but then it turns back to 0 again in the next iteration.
Set flag to zero before the loop, and when you find a match you set it to 1 and exit the loop:
flag = 0;
for (it = 0; encontradas[it] != NULL; it++) {
if (strcmp(palavra,encontradas[it]) == 0) {
flag=1;
break;
}
}
(Exiting the loop isn't needed for the logic to work, but there is no point in looping through the rest of the items once you have found a match.)
i have a problem in c like this:
I have a problem in the code below. The problem is this that i doing some addition part after both if conditions break.And that addiion is repeatative while loop until count>0 The problem is if i put braces in for loop then it repeats the the part inside the braces until it's condition is not false. Buti have to do addition which is like this:
We have an array data[i].freq={0,1,2,3,4,5} and data[i].next represents the next member to be added.Suppose i add 0 and 1 first i got"1" as a result and i put the result in last index of my array , like this ({0 1 2 3 4 5 1})now 0 and 1 cann not be added because they are already added(i don't have to repeat the addition on same elements), so next time the addition will be between the last index element and smallest element before the last element (but not those elements who are already added). so here the addition will be between the "1" in last index+ smallest element in right to it which is "2" Note here we have not taken in acount 0 and 1 because they are already added, the same way this 2 will not be added next time because it is being added this time and their addition wil be {0 1 2 3 4 5 1 3} we have to repeat the same until there left & element at last.
data[data_size].freq=data[i].freq+data[p].freq; // here i add the first 2 elements "0" and "1" in the example i given below.
int count=5;
do
{
for(i=0;data[i].next!=-1;i=data[i].next)//the problem is here if i put bracesit dont't do the ask which i expect it to do.
if(data[data[i].next].freq>data[data_size].freq && data[data[i].next].flag==0)
break;
data[data_size+1].freq= data[data_size].freq+ data[data[i].next].freq;
data[data_size].next=data[i].next;
data[i].next=data_size;
data_size++;
if(data[data[i].next].freq<data[data_size].freq && data[data[i].next].flag==0)
break;
data[data_size+1].freq= data[data_size].freq + data[i].freq
data[data_size].next=data[i].next;
data[i].next=data_size;
data_size++;
count--;
} while(count>0)
could any one please help me in desiging the code for what i want to achieve.
If you write
for(i=0 ..any condition)
if(condition1)
break;
if(condition2)
break;
you don't only have an unreadable mess, but you also have only the first if clause in the for loop.
If you want the for loop to extend over both, you must put them into {}:
for(...) {
if(condition1) break;
if(condition2) break;
}
My personal preference is to always use braces when the statements are in the next line. S don't write
if(condition1)
break;
as someone could be tempted to insert an andditional statement and be surprised that it doesn't work as it should, but either do
if(condition1) break;
in one line or
if(condition1) {
break;
}
add braces which are not needed for functionality, but for readability.
This is how the compiler sees your code:
int count=5;
do
{
for (i = 0; data[i].next != -1; i = data[i].next)
{
if (data[data[i].next].freq > data[data_size].freq && data[data[i].next].flag == 0)
break; // break out of the enclosing 'for' loop (goes to point A)
}
// Point A
data[data_size].next = data[i].next;
data[i].next = data_size;
data_size++;
if (data[data[i].next].freq < data[data_size].freq && data[data[i].next].flag == 0)
{
break; // break out of the outer 'do' loop (goes to point B)
}
data[data_size].next = data[i].next;
data[i].next = data_size;
data_size++;
count--;
} while (count > 0);
// Point B
Based on your code comments, I think your problem is that your 'break' statements are not taking you where you think they're taking you.