continue statement inside for loop and if condition [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have following code snippet and the output i am getting is 4. Please explain me if it takes i=2 or 0. I am confused. And How output was 4?
int main() {
int i=2;
for(i=0;i<2;i++) {
i=i%3;
if(i==2) {
i++;
continue; }
else
++i;
}
printf("%d",i);
}

The loop starts with i = 0. Both the if and the else to exactly the same thing. Increment i and continue.
If you use a bit of logic, the whole block can be reduced to i++ (i = i % 3 has no effect since i < 2).
It's not possible to get 4 with the code you posted.

The output cannot be 4 for the program you posted, because by the time the loop breaks, the value of i would be 2, not 4 and the loop will run exactly once.
Also, your code never enters the if block, because the condition is i==2 which can never be true inside the for loop, as by that time the loop would be exited.
So your code is equivalent to this:
int main() {
int i=2;
for(i=0;i<2;i++) {
i++;
}
printf("%d",i);
}

Related

while exercise with return in c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I've just started coding in c++ and now I have an exercise that I can't do because the code seems to not work.
I've to find the max and the min with a sequence of n numbers (in this case i already know that they are 4). I've to use while.
I've just started so I don't know how return properly works...
there aren't syntactical errors but when I run it ask me the number but then it says that the algorithm ends with 0 value.
Here's the code, if you can help me thank you!
#include <iostream>
using namespace std;
main ()
{ float mag,min,i,a;
mag=0;
min=0;
i=0;
while (1)
{
if (i<5)
{ cout<<"insert a number"<<endl;
cin>>a;
if (i = 0)
{ mag=a;
min=a;
}
else
{ if (a<min)
{ min=a;
}
else
{ if (a>mag)
{ mag=a;
}
}
}
i=i+1;
}
else
{ cout<<"maggiore= "<<mag<<endl<<"min= "<<min<<endl;
}
return 0;
}
system ("pause");
}
I see at minimum one problem:
if (i = 0)
This is assignment of i to 0 and compare the result of assignment, which is always false if you assign a 0.
I believe you want only compare and not assign, so you have to use:
if ( i == 0 )
The next problem is
return 0;
This will always end the current function, if the function is main(), it will terminate your program. In your case, you can simply remove the return statement, as in main it will return 0 by default if the function ends.
But if you use
while (1)
without any return, your program runs endless. I don't know what is the expected behavior.
Rest looks fine.
Hint: Your indentation is a bit special. :-)
1st it should be i==0 not i=0 in the if
2nd you should place that return 0 after that cout maggiore or it will close after the first loop
3rd you don't need that system pause there. It does literally nothing. You should either remove it or place it exactly before the return.

Project Euler #5 - Why won't this while loop finish? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
If I change the code line "num++" to "num+=2520", the code runs fine and returns the correct answer, but I'd like to know why it doesn't run as is, primarily because I didn't think of the fact that the number must be a multiple at 2520 before looking the answer up, and I don't see why my own code isn't correctly giving the answer without that change. To me, it seems correct. Unfortunately, the while loop never ends.
My guess is it has something to do with how long the correct number is (232792560), because if I lower the requirements even a little bit (from 9 to 8, per se), the while loop manages to finish.
long long int num = 1;
int div_counter = 1;
bool check = false;
while(!check)
{
for(int i = 2; i < 21; i++)
{
if(num % i == 0)
{
div_counter++;
}
}
if(div_counter == 20)
{
check = true;
}
else
{
num++;
div_counter = 0;
}
}
return num;
You have to reset div_counter to 1 instead of 0.
Your for loop only runs from 2 to 20 inclusive, so if div_counter starts at 0 the max value it can reach is 19.

How to count negatives? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wrote this code and the output is not coming as expected. The function returns the negatives recursively. But it is not doing returning what it should be.
size_t recursive_x(stack<int> mystack){
int count=0;
if(!mystack.empty()){
if(mystack.top()<0){
count+=1;
}
mystack.pop();
count+=recursive_x(mystack);
}cout<<count<<endl;
return count;
}
int main(){
stack<int> mystack;
mystack.push(9);
mystack.push(-2);
mystack.push(-2);
mystack.push(1);
mystack.push(-3);
mystack.push(-1);
mystack.push(99);
mystack.push(-1);
mystack.push(1);
mystack.push(1);
recursive_x(mystack);
}
The output should be 5 but it is coming like this:
Output:
0
0
1
2
2
3
4
4
5
5
5
Assuming you do call the function, the output is exactly what I would expect.
The display shows the number of negative numbers on the stack at the point where
cout<<count<<endl;
is invoked.
It is invoked first for the innermost recursion, because you make your recursive call before doing any output for the current recursion.
count+=recursive_x(mystack);
}cout<<count<<endl;
If you just want the output 5, you could print the result returned from your initial call
int finalCount = recursive_x(mystack);
cout<<finalCount<<endl;
and remove the output in recursive_x().
Each recursive call will print the result.
You just need to move the print command to the main:
size_t recursive_x(stack<int> mystack){
int count=0;
if(!mystack.empty()){
if(mystack.top()<0){
count+=1;
}
mystack.pop();
count+=recursive_x(mystack);
}
return count;
}
int main(){
stack<int> mystack;
mystack.push(9);
mystack.push(-2);
mystack.push(-2);
mystack.push(1);
mystack.push(-3);
mystack.push(-1);
mystack.push(99);
mystack.push(-1);
mystack.push(1);
mystack.push(1);
cout<<recursive_x(mystack)<<endl;
}
Output:
5

Unexpected changing of C++ constant integer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The variable steady_counter is intialized as a constant integer.
cout << steady_counter;
So long as i have the above statement anywhere before the following code, the function runs as expected and checks if an integer input is or is not a runaround number.
The problem is that when the cout line is not present, the constant integer changes within the below if statements. I tested this by printing steady_counter before entering the if-else, and then after the if-else.
Without the cout line, steady_counter changes to a 4 digit number.
for (int i = 0; i < 10; i++)
{
if (CheckArr[i])
{
num_of_unique++;
}
}
if ((steady_counter == num_of_unique) & (final == NumArr[0]) )
{
return true;
}
else
{
return false;
}
}
Any idea what's going on? Why do I require a cout line to maintain the constant integer steady_counter?
One obvious problem:
for (int i = counter; i > 0; i --)
NumArr[i] = -1;
This covers values from 1 to counter inclusive; while valid indexes for NumArr are from 0 to counter-1 inclusive. So you write outside the array, corrupting something else; possibly another local variable.
Either correct the off-by-one error in the index
NumArr[i-1] = -1;
or use a more canonical loop
for (int i = 0; i < counter; ++i)
or, for more of a C++ flavour,
std::fill(NumArr, NumArr+counter, -1);
There are likely to be further errors, which are better found by using your debugger than by asking people to read through all your code.

For loop variable going to hell for seemingly no reason? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have run into what seems to be a very obscure bug. My program involves looping some code for a long time, and eventually running some functions in the loop. Weirdly, after I run a specific function, my for loop variable, 'z', jumps from 3200 to somewhere around 1059760811 (it changes every time). The function does not naturally use the loop variable, so I honestly have no idea what is happening here.
The entire code is too long to paste here, so I will try to paste only the important parts, with the relevant functions first and the for loop after:
void enterdata(float dpoint,int num){
autodata[num] += dpoint;
}
float autocorr(){
float autocorrelation = 0;
for(int a = 0; a<SIZEX; a++)
{
for(int b = 0; b<SIZEY; b++)
{
if(grid[a][b] == reference[a][b]){autocorrelation++;}
}
}
autocorrelation /= SIZEX*SIZEY;
autocorrelation -= 0.333333333333;
return autocorrelation;
}
for (long z = 0.0; z<MAXTIME; z++)
{
for (long k=0; k<TIMESTEP; k++)
{
grid.pairswap();
}
if (z == autostart_time)
{
grid.getreference();
signal = 1; // signal is used in the next if statement to verify that the autocorrelation has a reference.
}
if ((z*10)%dataint == 0)
{
if (signal == 1) {
//!!! this is the important segment!!!
cout << z << " before\n";
grid.enterdata(grid.autocorr(),count);
cout << z << " after\n";
cout << grid.autocorr() << " (number returned by function)\n";
count++;
}
}
if (z%(dataint*10) == 0) { dataint *= 10; }
}
From the "important segment" marked in the code, this is my output:
3200 before,
1059760811 after,
0.666667 (number returned by function)
Clearly, something weird is happening to the 'z' variable during the function. I have also become convinced that it is the enterdata function and not the autocorrelation function from tests running each separately.
I have no idea how to fix this, or what is going on. Help?!?!?
Thanks!
Looks like you may have a Stack Overflow issue in your enterdata function.
Writing to before the array starts or past the end of the array result in undefined behavior, including writing over variables already on the stack.
#WhozCraig is right, a stack overwrite by a called function seems the most likely explanation.
You should be able to find out in your debugger how to break on any change to the memory at address of z, this will quickly provide an exact diagnosis.
For Visual Studio (for example), see here.