My teacher asked to write a program that prints the power of each array element using recursive function.
My code:
#include <stdio.h>
#include <conio.h>
void pow(int a[10],int i);
main()
{
int a[10],i,c=0;
printf("Enter 10 numbers:\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("Power of elements in array:\n");
pow(a,c);
getch();
}
void pow(int a[10],int i)
{
if(i!=10)
{
printf("%d\n",a[i]*a[i]);
pow(a,i+1);
}
}
Up to here, I had no problems.But when I changed the third last line pow(a,i+1) to pow(a,i++)
the output was an infinite number of ones.
Can anyone please explain me why it ended up like this?
What exactly happened when I changed i+1 to i++?
Thank you in advance!
There are two increment operators in C: one of which is postfix or postincrement operator as for example
i++
and other is unary operator or preincrement operator as for example
++i
The value of an expression of postincrement operator is the value of the operand before its increment. Thus this call
pow(a,i++);
is equivalent to
pow(a,i), i = i + 1;
Instead of the postincrement operator you could use the preincrement operator
pow(a, ++i);
and you will get the expected result because the value of the operator is the value of its operand after its increment.
Take into account that main shall have return type int.
Also in general case your function is wrong. It can not be applied to any array because it uses magic number 10.
I would write the function the following way
void pow( int a[], int n )
{
if ( n > 0 )
{
printf( "%d\n", a[0] * a[0] );
pow( a + 1, n - 1 );
}
}
and call it like
pow( a, 10 );
In this case it can be used with arrays that have different sizes.
i++ is called a post-increment, which returns i and increments it afterwards.
i + 1 is a temporary which returns what it says, i + 1, but does not change the value of i itsself.
You change the value of i, which is only local to the function. Therefore, the value of i recursively passed to pow() is always the same.
pow(a, i+1) is passing to the next recursive call the incremented value of i. pow(a, i++), is using the post-increment notation, which is FIRST returning the value of i (non-incremented) and thus performing the recursive call with the same value of i, and only then incrementing it, but the incremented value is lost. So your recursion turns to be infinite, since every call is receiving the same value of i.
In your code you can regard pow(a,i++) as pow(a,i); i=i+1;
x+1
is an expression equal to one plus the value of x. x is not modifed
x++
changes the value of after it is evaluated
Related
This question already has answers here:
What is the difference between prefix and postfix operators?
(13 answers)
Closed 11 months ago.
When I was doing the practice questions today, I found that the outputs of printf("%d\n",x--); and printf("%d\n",x); are the same.
I changed it to printf("%d\n",x++); and found to be the same. I want to know why.
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x);
if (x++ > 5)
printf("%d",x);
else
printf("%d\n",x--);
return 0;
}
You used the post-decrement/-increment operators.
x-- decrements x and returns the original value of x.
x++ increments x and returns the original value of x.
To get the desired behaviour, use the pre-decrement/-increment operators.
--x decrements x and returns the modified x.
++x increments x and returns the modified x.
That's simple and you can understand as well if you know the usage of these 2 kind of operators.
Post Increment/Decrement Operator e.g. a++, a-- etc.
So when we use it in the statement, the current value of the variable will be used and post that its value is incremented by 1.
Just take a look into my comments at end of statements (shows the o/p).
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x); // 10
printf("%d", x++); // 10
printf("%d", x); // 11
return 0;
}
Pre Increment/Decrement Operator, e.g. ++a, --a etc.
So when we use it in the statement, first its value of variable is incremented by 1 & then the incremented value will be used.
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x); // 10
printf("%d", ++x); // 11
printf("%d", x); // 11
return 0;
}
I think, now it's clear to you. For info on usages, just take a look into Usage of Pre/Post Increment & Decrement operators in C.
According to the C Standard (6.5.2.4 Postfix increment and decrement operators)
2 The result of the postfix ++ operator is the value of the
operand. As a side effect, the value of the operand object is
incremented (that is, the value 1 of the appropriate type is added to
it)
and
3 The postfix -- operator is analogous to the postfix ++ operator,
except that the value of the operand is decremented (that is, the
value 1 of the appropriate type is subtracted from it).
Consider this pair of calls of printf
int x = 10;
printf( "%d\n", x++ );
printf( "%d\n", x );
The output is
10
11
That is the value of the expression of x++ is the value of its operand that is equal to 10. As a side effect the variable x is increased and in the second call of printf the new value of x after applying the side effect is outputted.
You can imagine this call
printf( "%d\n", x++ );
like
printf( "%d\n", x ), x += 1;
Opposite to postfix increment and decrement operators the values of unary increment (++x) and decrement (--x) operators are values after incrementing and decrementing their operands.
From the C Standard (6.5.3.1 Prefix increment and decrement operators)
2 The value of the operand of the prefix ++ operator is incremented.
The result is the new value of the operand after incrementation.
and
3 The prefix -- operator is analogous to the prefix ++ operator,
except that the value of the operand is decremented.
I'm new to C language and I'm not entirely sure why on Line 4 when post-increment is done the value of x isn't change what I mean is that
x = printf("%d",x++);
The value for x was 12 so the printf would print 12 and then x should be assigned 2 and while ++ was there x should be later changed with 2+1 and on line 6 pre-increment is done so output shouldn't be 124.
Why x on line 4 isn't added?
Please help.
#include <stdio.h>
int main(){
int x = 12;
x = printf("%d", x++);
printf("%d", ++x);
return 0;
}
Make yourself aware of sequence point. From this [emphasis mine]:
There is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call.
From this [emphasis mine]:
Increment operators initiate the side-effect of adding the value 1 of appropriate type to the operand. Decrement operators initiate the side-effect of subtracting the value 1 of appropriate type from the operand. As with any other side-effects, these operations complete at or before the next sequence point.
Looks at this statement:
x = printf("%d", x++);
The post increment operator increase the value of operand by 1 but the value of the expression is the operand's original value prior to the increment operation.
So, the value of x passed to printf() will be its original value which is 12 and due to sequence point, before calling printf() the value of x will be incremented by 1. The return value of printf() will be assigned to x which overwrites the last value of x which is the incremented value due to post ++ operator. Hence, after this statement the value of x is 2.
The value for x was 12 so the printf would print 12 and then x should be assigned 2 and while ++ was there x should be later changed with 2+1 and on line 6 pre-increment is done so output shouldn't be 124.
no, the assignment is done after all concerning printf("%d", ++x);, your code is equivalent to that :
#include <stdio.h>
int main(){
int x = 12;
int y = printf("%d", x++);
x = y;
printf("%d", ++x);
return 0;
}
so x = printf("%d", ++x); does :
printf writes 12
then x is incremented to value 13
then x is assigned to the result of printf valuing 2
then you execute printf("%d", ++x); while x values 2 before, so x is incremented before to be given in argument, so 3 is written
and the final print result is 123
PS. As said by #H.S. in an other remark :There is a sequence point after the evaluation of all function arguments (x++ is an argument to printf()) and the pre/post increment/decrement operation complete at or before the next sequence point.
This will work for you:
++x is prefix increment and the x++ is postfix increment, and here is the difference on both of them:
The prefix increment returns the value of a variable after it has been incremented.
On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.
#include <stdio.h>
int main()
{
int x = 12;
x = printf("%d", ++x);
printf("%d", ++x);
return 0;
}
Is the increment in case of an expression involving x++ always made after the variable to be copy to a function ?
The call :
foo(x++, y);
The function :
int foo(int x, int y)
{
return x*y;
}
Is that a undefined behavior for all compilers?
Let's see the official descriptions here to get a deeper understanding.
For the postfix operator, quoting C11, chapter §6.5.2.3
The result of the postfix ++ operator is the value of the operand. As a side effect, the
value of the operand object is incremented (that is, the value 1 of the appropriate type is
added to it). [...] The value computation of the result is sequenced before the side effect of
updating the stored value of the operand.
and, regarding the function call, chapter §6.5.2.3
There is a sequence point after the evaluations of the function designator and the actual
arguments but before the actual call. Every evaluation in the calling function (including
other function calls) that is not otherwise specifically sequenced before or after the
execution of the body of the called function is indeterminately sequenced with respect to
the execution of the called function.
So, as per above description, there's nothing problematic in your code as shown above.
The old value of x is passed and then, the value is increased.
However, please note the last part of the second quote, you need to maintain the sanity of the code. For example, you need to make sure, there's no change in value without having a sequence point in between. Something like
foo(x++, x++, y);
will be a problem as, you're trying to changing the same variable (x) more than once.
Consider the following program
#include <stdio.h>
int x;
void foo(int x1 )
{
extern int x;
printf( "x1 = %d\n", x1 );
printf( "x = %d\n", x );
}
int main(void)
{
foo( x++ );
return 0;
}
Its output is
x1 = 0
x = 1
Thus as it is seen the value of the expression x++ is the value of the operand before incrementing
x1 = 0
However the side effect was applied before the function gets the control
x = 1
The program is well-formed and there is no undefined behavior.
Whenever post increment is used, the original value of the variable will be sent to the function. And after that, the value of x will be incremented.
I have been trying to run a code for fibonacci series through recursion and used to pass fib(x, y, i--) which resulted in an infinite recursion while the same code worked well by using fib(x, y, i-1).
Is there any significant reason for this?
i-- passes i to the function then decrements i value in the caller scope.
i-1 passes i-1 to the function and does not change i value in the caller scope.
So yes they're totally different. If fib calls itself, the same number is passed over and over again, resulting in infinite recursion
First of all consider that using i-1 your result will be the value of i minus 1, but the variable i will retain its initial value (there is no assignment). Conversely the use of increment or decrement operators modify the variable (in this case there is assignment. I.e. i++ is equivalent to i=i+1).
Said that, the operators --, decrement, and ++, increment, come in two flavours: prefix (i.e. ++i) and postfix (i.e. i++), the operation of increment or decrement is actuated respectively before or after the use of the expression value depending on where you put it.
While the expression i-1 always execute the operation before to use the result (it behaves as a prefixed decrement operator), using increment or decrement operators as prefix the action, increment or decrement, is performed first then the result is used. On the other hand if the operator follow the expression, postfix, the value will be used, or passed, before the operator is applied.
In your case you are using postdecrement in something like:
void fib(int x, int y, int i)
{
...
if (i = 0)
return;
fib(x, y, i--);
...
}
int main(void)
{
...
fib(10, 20, 30);
...
}
Each time you call fib you pass the initial value of i, then locally decrement its value. It will never become 0 in recursed calls, and your loop will never end.
If you use the predecrement, prefixing the operator to the expression (in this case the variable i), the behavior changes, the decrement is executed before to pass the value, and your program will work (the behavior is the same of i-1):
void fib(int x, int y, int i)
{
...
if (i = 0)
return;
fib(x, y, --i); //Note the prefix
...
}
Question 1
int x;
if (x++)
{
printf ("\nASCII value of X is smaller than that of x");
}
Is x assigned here with a garbage value ??
Question 2:
main ()
{
int i;
for (i = 0; i++ < 10;)
{
printf ("%d\n", i);
}
}
Can anyone explain how i++ < 10 works?I mean it should end at 9 why 10
The value of x is indeterminate, and is possibly a trap representation, in which case the behavior of x++ is undefined.
The expression i++ evaluates to the current value of i; as a side effect, the value in i is incremented. So if i == 1, the expression i++ will evaluate to 1, and as a side effect i will be set to 2.
Chapter and verse:
6.5.2.4 Postfix increment and decrement operators
...
2 The result of the postfix ++ operator is the value of the operand. After the result is
obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate
type is added to it.) See the discussions of additive operators and compound assignment
for information on constraints, types, and conversions and the effects of operations on
pointers. The side effect of updating the stored value of the operand shall occur between
the previous and the next sequence point.
Emphasis mine.
In the first question, you declare x
int x;
but you do not assign it, this reserves some memory to hold the value of x, but doesn't initialize it to a known value. That's a really bad thing. Then you read it, increment it, and possibly do something.
if ( x++ ) {
printf ( "\nascii value of X is smaller than that of x" ) ;
}
Since you don't know what it's value was before you read it, it is impossible to make an educated guess as to whether your if statement will print anything.
In your second question (please one question per question), you read the value of i, then increment it, and then do the comparison on the read value. Post increment basically means, "increment the value after I read it" and so the new value will be stored, then the comparison made on the old value, and the printf statement below will print the "current, new" value.
Question 1: Yes
Question 2: Yes. i is incremented by one then compared if it's lesser than 10.