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 6 years ago.
Improve this question
My code is meant to print an array in reverse but for some reason the decrement operator isn't working as expected. According to my understanding --var decrements the variable var before anything is done to it while var-- decrements the variable var after an operation has been completed such as a for loop.
Here is my code:
#include <iostream>
int main() {
int arrLen;
int arr[4];
scanf("%d\n %d %d %d %d", &arrLen, &arr[0], &arr[1], &arr[2], &arr[3]);
for (; arrLen >= 0; --arrLen)
printf("%d %d\n", arr[arrLen], arrLen);
return 0;
}
And here are my results (the right value in the output is the decremented variable, I added it to check):
0 4
2 3
3 2
4 1
1 0
Without the decremented variable being printed it should be:
0 2 3 4 1
Here are my expected results:
2 3 4 1
The reason this is not behaving as you expect is because of how for loops work.
for (statement_1; condition; statement_2) {
body;
}
statement_1 is called only once before the loop begins.
condition is evaluated at the beginning of each pass in the loop. If it is true, body is evaluated. If not the loop exits.
statement_2 is evaluated after the body at the end of each pass in the loop, just before re-evaluating the condition.
So while --var does decrement and return the decremented value, it is only actually called after the body of your for loop each time it is run.
This means that --var and var-- will have the same effect on the behaviour of a for loop when part of statement_2.
To produce your desired behaviour you could change your for loop to this:
while (--arrLen >= 0)
printf("%d %d\n", arr[arrLen], arrLen);
Try with the following line. I think your for loop was not proper.
for (; arrLen > 0; --arrLen) printf("%d %d\n", arr[arrLen - 1], arrLen);
It will now have the following output
2 4
3 3
4 2
1 1
Related
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 2 years ago.
Improve this question
I have to find all prime numbers between two given numbers(given in ascending order i.e small, large) I made logic such that my program starts from the given least number till the given most numbers and find factors for each number in between, if factors count are 2 i.e 1 and itself(which is a condition for a prime number), hence it is printed as prime. However I am unable to print my desired output.. can't track why(P.S I am 19 years old newbie in Programming)
#include <iostream>
using namespace std;
int main(){
int start,end;
cin>>start,end;
for(int i=start+1;i<end;++i){
int count;
for(int j=1;j<=i;++j){
if(i%j==0 || i/2==0)count++;
}
if(count==2) cout<<i<<endl;
}
return 0;
}
Input: 1 10
Expected Output:
2
3
5
7
9
Output: (nothing)
Your program has several issues.
cin>>start,end; is not going to read in 2 numbers. You need cin >> start >> end;
You are not initializing count to anything, so you invoke undefined behavior when you do count++. You need to do int count = 0;
Also, when checking if n is prime, you don't need to check for divisibility by 1 or n since this is always true.
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 4 years ago.
Improve this question
When running the following code, the output is 2 4 6. I expected it to be 2 5 and so on...
Why the difference?
#include <iostream>
using namespace std;
int main() {
static int i;
for (i++; ++i; i++) {
printf("%d ", i);
if (i == 6)
break;
}
return 0;
}
I did the same thing here, without the for loop, from 2nd iteration. The result is 5.
Why is that?
#include <iostream>
using namespace std;
int main() {
static int i=2;
i++;
i++;
cout<<++i;
return 0;
}
Each time the loop is traversed you increase i by two, not three (I guess you expected the latter to happen).
In a general case
for ( init_statement ; condition ; iteration_expression ) {
loop_statements
}
is equivalent to
init_statement
for ( ; condition ; ) {
loop_statements
iteration_expression
}
and
init_statement
while ( condition ) {
loop_statements
iteration_expression
}
See, e.g., this.
In your case,
for (i++; ++i; i++) {
...
}
is equivalent to
i++
for ( ; ++i; ) {
...
i++
}
and
i++
while ( ++i ) {
...
i++ ;
}
As for your second piece of code, you mention that "The result is 5". It appears you expect otherwise, perhaps 4. If so, try replacing
cout<<++i;
with
cout<<i++;
(incrementing prior vs. after other operations in the sentence).
When you see the syntax of for loop which is
for(initialize;condition;inc/decrement)
the statement in initialize block only executes once at the starting of for loop that's why it is increamenting i by 2.
Hopefully that help
In a for loop you've got 4 parts. I forget the "official" name for the individual pieces but I typically refer to them as:
Initialization
Anchor Statement
Body
Follow-up
effectively:
for(Initialization (1); Anchor Statement (2); Follow-up (4))
{
Body (3)
}
It's going to hit in the following order:
1, 2, 3, 4, [2, 3, 4]... until step 2 evaluates to false or a break statement is hit. Then it exits.
So i starts as 0.
You hit step 1 and 2, making i evaluate to 2 in step 3 (the body).
Then you hit step 4 and 2, making i evaluate to 4 in step 3.
Then you hit step 4 and 2, making i evaluate to 6 in step 3.
Then you have a break statement that will exit the loop.
The important part that seems to be the confusion, is that the initialization step only runs once.
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 6 years ago.
Improve this question
I have a task to make a code which will write 100 first numbers of an equation (or a function, I don't know what this is)
A(n) = (A(n-1))^2 -n*A(n-2) where A(1) = 1 and A(2) = 1
It has to be solved recursively. I have written this code so far
#include <iostream>
using namespace std;
int rekurzija(int n){
if(n=1){
return 1;
}
if(n=2){
return 1;
}
if(n>2){
return rekurzija(n-1)*rekurzija(n-1)-n*rekurzija(n-2);
}
}
int main(){
for(int n=1;n<101;n=n+1){
cout << rekurzija(n) << endl;
}
}
The problem is that the program returns 1 hundred times instead of 1,1,-2,0,...(instead of actually solving this function). What is wrong in this code?
You are using simple assignment operator = instead of Is equals to relational operator == in your rekurzija() function for if conditions
if(n = 1) //here `n = 1`is an assignment statement
{
//something...
}
What happens if you use = instead of ==?
The if condition will always evaluate to be true if the assigned value in the assignment statement is non-zero number.
Note: An assignment to zero evaluates to be false i.e, for if(n = 0), the if block will not be entered. You don't have any such if blocks in your code.
So your first if is always evaluated to be true because you are assigning a non-zero value i.e, 1 and thus your function always returns 1. that's the reason why you get 100 1's as your answer.
So, instead try changing all the if conditions to something like:
if(n == 1)
{
//something...
}
This would check if n is equals to 1 or not. If n is equal to 1 then the if block is entered, else it would not enter the if block and the next if condition is checked.
Note: Just remember this while using the = and == operators
= is for assignment
== is for comparison
When you compare things in C++ you need to do it like:
if (a == b)
and not
if (a = b)
The latter will assign b to a and return the value of a.
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 6 years ago.
Improve this question
#include<iostream>
using namespace std;
int factorial(int x)
{
if(x == 1)
{
return 1;
}
else
{
return x*factorial(x-1);
}
}
int main()
{
cout<<factorial(5)<<endl;
}
I don’t get the part when the value reaches 1. Why doesn't the program print 1 as the output, because when 1 is reached it returns 1. Consider the below steps.
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*factorial(1)
So now, when the x value becomes 1 and goes into if , condition becomes true and 1 is returned. So why doesn't it output 1? Is it that the value of the 5*4*3*2*factorial(1) is stored somewhere and the returned value of just gets multiplied with 5*4*3*2*1 and outputs 120?
Also please explain, what happens when we pass 0 instead of 5,how will it output 1? (0!=1)
it is exactly like you said:
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*factorial(1)
So if it reaches 1 then this will be replaced by
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*1
so the result of the last step goes into the second last step.... where 2*1 will be calculated... After that the 3rd last step gets the value of 2*1 = 2 and multiplies 3 on in and so on.
If you insert smaller or equal 0 into your function, you will get an endless recursion because if(0 == 1). But if you replace this code with
int factorial(int x)
{
if(x <= 1)
{
return 1;
}
else
{
return x*factorial(x-1);
}
}
Then also 0 and -numbers will work
The stack stores in some sense all pending operations. As soon as fact(2) gets 1 from the call, it multiplies it by 2 and returns 2. fact(3) receives that 2, multiplies it by 3 and returns 6. fact(4) receives that 6, multiplies it by 4 and returns 24. And so on...
Passing a 0 was not thought of in the current form of the program and will actually cause the program to crash (most likely). Changing the if(x==1) line to if(x==0) will fix this.
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 6 years ago.
Improve this question
can anybody clear my doubt .. why this program is giving 10 as output.
can you please explain the mechanism .. for loop is also having ; before the statements also
#include <iostream>
using namespace std;
int main() {
int i ;
for ( i =0 ; i<10 ; i++);
{
cout<<i ;
}
return 0;
}
for ( i =0 ; i<10 ; i++);
This is a complete loop, the semicolon at the end indicates an empty body. Hence it simply increments i eventually to 10. The reason it's 10 (rather than 9) is because that is when the continuation condition i < 10 becomes false.
Which means that this little snippet:
{
cout<<i ;
}
is a once-executed statement outputting the contents of i (left at 10 by the loop).
The braces in this case simply put the statement into an enclosed scope, they are not related to the loop at all.
So, if you want to output i each time through the loop, simply get rid of the semicolon so that the braces and their contents become the body of that loop.
for ( i =0 ; i<10 ; i++); // This means loop till i = 10 at which point loop breaks. This is because of ending the for loop with ';'
{ // start of scope
cout<<i ; // Print the value of i which is 10 now
} // end of scope
Consider that the loop has reached a point where i = 9, so, 'i < 10' condition is true.
Therefore, for the next iteration 'i++' will increment it to 10.
Now again the test 'i < 10' is checked. At this point '10 < 10' test returns false and the for loop breaks and the value of i is 10.