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++)
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.
What makes this an infinite loop? Shouldn't n reach 5 and terminate the loop?
int main()
{
int n = 1;
while (n <= 5)
cout << n ;
n++;
}
There are no curly braces after the while condition.
That's why only cout << n; is executed over and over again. When you write while (something) doThis(); doThat(); or if (something) doThis(); doThat();, only doThis() gets executed while (or if) something is true.
If it was written like this
int n=1;
while (n<=5) {
cout << n;
++n;
}
Then it wouldn't be infinite
Because your code is equivalent to
int main()
{
int n = 1;
while (n <= 5)
{
cout << n ;
}
n++;
}
n++ will not be executed.
In your code, the value of n wouldn't get incremented (unless control is out of loop). This is because the n++; is not a part of the loop. This is the reason why it becomes an infinite loop.
Use { } to indicate block of code when there is more than one statement.
Make the following change:
while (n <= 5) {
cout << n;
n++;
}
In the above code, n++; is a part of the loop and the value of n increments with every iteration and finally the control moves out of the loop when n is 6.
Note: The loop does not terminate when n is 5. It terminates when n is 6 since you are asking the loop to run when n<=5. So it will run even when n is 5.
Can somebody explain to me why the output will be as follows?
Why the loop runs a second time after (int i) gets as value 9, which is not less than 5?
It seems that even if (int i) is greater than 5 it still adds another 3 but the body won't run a second time. Why?
#include <iostream>
using namespace std;
int i=0;
int main()
{
for(;i<5;i+=3){
i=i*i;
}
cout << i << endl;
//Output: 12(i)
it works that way, more or less:
i = 0
i < 5 ? yes, keep on
i*i = 0
i+=3 => i ==3 now
i < 5 ? yes, keep on
i*i = 9
i+=3 => i is 12 now
i < 5 ? no, exit loop
You write a for(initialization; condition; excuteAtTheEndOfCycle):
initialization is executed only once at the beginning, condition is evaluated before each cycle, excuteAtTheEndOfCycle (i+=3, in your case), it's executed at the end of each cycle, before a further evaluation of condition
it is not running because you are giving condition of the loop to be less than five,
What are you want ,that output will be?
The code that I did was for solving the following problem. However, the logic of the code is wrong and I as a good newbie cannot figure what is wrong.
After I compile the result of 'sum' is always 0, if I change the initialization of 'sum' for a whatever number, that whatever number is what appear as answer of 'sum'.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
long sum = 0;
for( long i; i < 1000; ++i )
{
if (( i % 3 == 0 ) || ( i % 5 == 0 ))
{
sum = sum + i;
}
}
cout << "The sum is: " << sum << endl;
return 0;
}
You need to initialize i in your loop:
for (long i = 0; i < 1000; ++i )
As it is, i is probably some random number greater than 0 at the top of the loop, and the result is that the loop is never executed.
You need to initialize i to zero otherwise i's value will be whatever happens to be in memory. In this case it's > 1000.
for (long i = 0; i < 1000; ++i)
Also, a nice trick I learned. Use ii as your index variable. It's much easier to find ii than just i in your code.
You forgot to set i=O in your loop so the loop won't iterate.
All answers above are correct - you need to set your i to 0. What you might be interested in is that accessing uninitialized variable is an "undefined behaviour" (UB) and modern compilers are actually pretty good in finding the UBs and using them to optimize the code. For example, GCC 5.2 with -O2 (optimizations enabled) will generate same assembly for your code and for one without the loop at all regardless of what might happen to be in the memory at the address of i.
Try putting this code to (which is your code with additional #if for convenience) this online disassembler
#include <iostream>
using std::cout;
using std::endl;
int main()
{
long sum = 0;
#if 1
for (long i; i < 1000; ++i)
{
if ((i % 3 == 0) || (i % 5 == 0))
{
sum = sum + i;
}
}
#endif
cout << "The sum is: " << sum << endl;
return 0;
}
add the -O2 flag to compiler options on top right and try changing #if 1 to #if 0 and observe that the disassembly is the same meaning that the compiler cut out the loop completely.
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.