#include <iostream>
using namespace std;
int main()
{
int j=20;
int i=0;
for ( int k=0; i<10 && j>10; i++ && j--)
cout<< "i is " <<i<< " and j is " <<j<<endl;
}
So, this is how I see it, first i is 0 and j is 20, both follows the condition, hence the output is "0 20", then i is incremented and j is decremented, thus the output should be "1 19" but the next output is "1 20", as if the j hasn't been decremented!. Why?
When i==0, i++ && j-- short-circuits the first time it is called, so you end up with i==1 and j==20.
You can fix this by using the comma operator: i++, j--.
Remember, in C/C++, 0 is considered false, so 0 && x will never evaluate x since it knows the expression is false. See the above link for more detail.
The expression (i++ && j++) short circuits, and J is never incremented, because (i) holds a (false) initial value. I think you want it to look more like this:
for (int k=0; i<10 && j > 10; i++, j--)
The && operator checks the left side first for truth, and if it's false, (when i is 0, this is false) it doesn't even evaluate the right side. If the left side IS true, then and ONLY then will it check the right side of the &&.
The incremental part of the for-loop shouldn't be evaluating a boolean condition.
Related
In my opinion, it should output 1 as the first number as variable i is initialized first, then the condition is checked and then it's incremented. When incremented, it should output 1 but it outputs 0 instead. Why?
int i = 0; i < 10; ++i;
cout << i;
// Outputs 1
for (int i = 0; i < 10; ++i)
cout << i;
// Outputs 0123456789 while having 0 as first number
int i = 0; i < 10; ++i;
cout << i;
This is not a loop. It executes the following things in order:
int i = 0; // sets it to 0
i < 10; // true (result is not stored)
++i; // increments to 1
cout << i;
In the first example, the statements are executed separately.
int i = 0; i < 10; ++i; // declare variable i, do comparision and discard the result, increment i
cout << i; // print i
In the second example, you have to know how for works.
for loop - cppreference.com
formal syntax:
attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement
iteration_expression - any expression, which is executed after every iteration of the loop and before re-evaluating condition. Typically, this is the expression that increments the loop counter
The above syntax produces code equivalent to:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
As you see, the iteration_expression ++i is executed after the execution of the loop body, in which i is printed. Therefore, the initial value of i, which is 0, is printed in the first iteration.
I do not understand why the two codes below lead to the same result. Shouldn't the latter print from 6 to 10 since n is incremented first?
Edit: I used both Visual Studio 2019 and repl.it.
#include <iostream>
using namespace std;
int main() {
int n=5;
for (n; n<10; n++)
cout << n << endl;
return 0;
}
>>> 5
6
7
8
9
#include <iostream>
using namespace std;
int main() {
int n=5;
for (n; n<10; ++n)
cout << n << endl;
return 0;
}
>>> 5
6
7
8
9
From https://en.cppreference.com/w/cpp/language/for
attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement
The above syntax produces code equivalent to:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
Your two for loops are therefore equivalent to
{
n;
while (n < 10) {
cout << n << endl;
n++;
}
}
and
{
n;
while (n < 10) {
cout << n << endl;
++n;
}
}
In a for loop:
The first statement is executed exactly once
The conditional is checked, and if true
The body is executed
Then the iteration expression is executed
Goto (2.)
If you want your loop to start at 6, you need to explicitly tell it to start at 6.
There's Nothing wrong here, its just how its supposed to work
Firstly, you should know a for loop works
for loop, without loss of generality can be written as:
for(exp1; exp2; exp3)
{
//body
}
here exp1 will be executed only when entering the loop first time, then exp2 will be evaluated, if true loop will continue, otherwise not.
exp3 is evaluated only after each iteration is complete.
also the only difference between i++ and ++i, is when you assign it to something.
say i is 5, then after statement
i++;
i will be 6
which is also true for this statement:
++i;
but say i=5,
but you try something like this:
a=i++;
after this statement, a will be 5, and i will be 6.
but after this statement, with same initial condition(i = 5):
a=++i;
both a and i will be 6.
The only difference is this:
for (n; n<10; n++)
vs. this:
for (n; n<10; ++n)
The first and third expressions in a for statement are evaluated only for their side effects, with any result discarded. (The second is evaluated and its result used to determine whether to continue the loop.) The only difference between n++ and ++n is their results; their side effects are identical. So in this context n++ and ++n are effectively identical.
I'll also mention that the first expression n has no side effects, so it might well be omitted:
for (; n<10; n++)
Or, better yet, you could incorporate the declaration and initialization into the loop, replacing the existing declaration int n=5;:
for (int n = 5; n < 10; n++)
I wrote some code I wrote to print the powers of 2 up to like 39 or 40 idk but it dm. Anyway, I wrote it and rather than run the code and it not working because of a logic error, i ran the code and found that it works, and then spotted some logic errors showing that the code shouldn't work. Here is the code:
#include <iostream>
using namespace std;
int main()
{
int i = 1;
int j = 1;
int k = 1;
while (i < 40)
{
while (k < i)
{
j = j * 2;
cout << j <<"\n";
k++;
}
i++;
}
}
The output of this code is the powers of 2 up to about 2^40.
Why it shouldn't work: the second while loop shouldn't run because k = 1 and i = 1 so (k < i) is false. Also after each time the second while loop is completed, j and k should be reset to 1 in order for the logic to work however I don't resent them.
Can someone please explain why although all these logic errors, the code still works?
Also I tried this in python and got the same result.
Initial values:
i=1, k=1, j=1
Then we check i < 40. True. Then we check k < i. False. Then we increment i. Now:
i=2, k=1, j=1
Check i < 40. True. Check k < i. True. j=j*2 sets j=2. Print 2. Increment k. Check if k < i. False. Increment i. Now:
i=3, k=2, j=2
Following this, the inner loop executes at most once for every iteration of the outer loop. k < i is true until the k++ line, and then becomes true again at the i++ line.
I'm not sure whether I understand why there are nested loops here in the first place. It could be replaced with
while (i < 40) {
j = j * 2;
count << j << "\n";
i++
}
What was the intention of k?
I am using this following code to find 10001th prime number but it is not running.
I am using devc++, but when I run this code, a blank screen comes up.
This is my Code:
#include<iostream>
#include<conio.h>
using namespace std;
int prime(int a)
{
int p=0;
for(int j=2;j<=a/2,p<=0;j++)
{
if(a%j==0)
{
p++;
}
}
if(p==0)
{
return 1;
}
else
return 0;
}
int main()
{
int i,c=0;
for(i=2;c<=10001;i++)
{
if(prime(1))
{
c++;
}
}
cout<<i;
return 0;
}
point 1:
you are passing if(prime(1)) argument 1 every time change this line to
if(prime(i))
point 2:
Change this line
for(int j=2;j<=a/2,p<=0;j++)
To
for(int j=2;(j<=a/2 && p<=0);j++)
Point 3:
Change this line
cout<<i;
To
cout<<i-1; // as at the end of `for` loop it will increment to `1` so print `i-1`.
First of all , I think you meant
if(prime(i))
instead of
if(prime(1))
Secondly, there are many gaps in this code .. First, you can verify if the number a divides by j with j taking a maximum value of sqrt(a) (using math.h library) , it would be faster when working with higher values.
Another thing, you said this is a code for finding the 10001th prime number not the number of prime numbers until 10001 and cout<<i; in the end doesn't make any sense, I think you meant cout<<c;
Let's look at each problem.
First, you need to use
if( prime(i) )
instead of
if( prime(1) )
I believe that was a typo on your part.
Second, as i is incremented after the for loop, you need to change
cout << i;
to
cout << i-1;
Third, the comma operator only executes the expression at the end. What you need here is &&. So change
for(int j = 2 ; j <= a/2 , p <= 0 ; j++)
to
for(int j = 2 ; j <= a/2 && p <= 0 ; j++ )
For more info on the comma operator, see Uses of C comma operator
Lastly, change
for( i = 2 ; c <= 10001 ; i++ )
to
for( i = 2 ; c < 10001 ; i++ )
Otherwise, you will get the 10002th prime number.
These should fix your problem.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please explain the output:
#include<iostream.h>
int main()
{
int i= -3, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
OUTPUT :
-2 2 0 1
Here's what I thought:
(++i || ++j) && (++k) //Considering the precedence order
++i becomes -2 so first part of OR true, so it won't check 2nd part.
(Thanks Joachim Pileborg for telling me the short circuit evaluation)
So overall, first part of AND is true.
But that is not enough for statement to be true, 2nd part must be true to.
So ++k makes k = 1
Here's where I get it wrong. Why is k not increasing?
whereas, in this case:
#include<iostream.h>
int main()
{
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
OUTPUT:
0 3 1 1
I got this one too considering short circuit evaluation.
Let's start with this code snippet
#include<iostream.h>
int main()
{
int i= -3, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
It is obvious that m will be have a boolean value converted to int. As ++i is equal to -2 that is unequal to zero then all other expressions will not be evaluated because it is already known that the whole expression is equal to true. So after statement
m = ++i || ++j && ++k;
m is equal to 1 and i is equal to -2 All other variables were not changed.
In this code snippet
#include<iostream.h>
int main()
{
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
++i will be equal to 0. So the right operand of operator || will be evaluated. This operand is
++j && ++k
As ++j will be equal to 3 and is not equal to 0 then ++k also will be evaluated and will be equal to 1. As the both operands of operator && is not equal to zero then the result is equal to true
Thus you will get i == 0, j == 3, k == 1, m == 1.
From the C++ Standard
5.14 Logical AND operator
1 The && operator groups left-to-right. The operands are both
contextually converted to bool (Clause 4). The result is true if both
operands are true and false otherwise. Unlike &, && guarantees
left-to-right evaluation: the second operand is not evaluated if the
first operand is false.
5.15 Logical OR operator
1 The || operator groups left-to-right. The operands are both
contextually converted to bool (Clause 4). It returns true if either
of its operands is true, and false otherwise. Unlike |, ||
guarantees left-to-right evaluation; moreover, the second operand is
not evaluated if the first operand evaluates to true.
In logical expressions, such as: ... || ... && ... C++ can omit executing statements that would not change the output value of expression. For example: if it computes first value and it's output is not equal to 0, then expression: true || ... && ... is always true, therefore execution of further expressions is not necessary
Below is your second case:-
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
In
( cond1 || cond2)
expression if cond1 is true then compiler does not go on to check for cond2. It will evaluate cond2 only if cond1 returns false.
So, in second ++i makes first expression to be false and forces compiler to go on to evaluate further whereas in first case first expression returns true.