The difference between n++ and ++n at the end of a while loop? (ANSI C)

this is probably a dumb question but I just can't figure it out. It has to do with the differences between n++ and ++n (which I thought I understood but apparently not).

#include <stdio.h>
#include <math.h>
long algorithmA(int n);
long algorithmB(int n);
int main(){ long A, B; A = B = 0; int n = 1; while(A >= B){ A = algorithmA(n); B = algorithmB(n); n++; } printf("At n = %d, Algorithm A performs in %ld seconds & " "Algorithm B performs in %ld seconds.", n, A, B);
}
long algorithmA(int n){ return pow(n,4) * 86400 * 4;
}
long algorithmB(int n){ return pow(3,n);
}

Here you can probably tell I'm trying to see at what point Algorithm A outperforms Algorithm B. The functions and units of time were given to me in a homework problem.

Anyways, I always thought that the order of "++" would not matter at the end of a while loop. But if I put ++n instead of n++, I get the wrong answer. Can somebody explain why?

Edit: Well it WAS showing 24 with ++n and 25 with n++, but it must have been for another reason. Because I just checked now and there is no difference. Thanks for your patience and time guys, I just wish I knew what I did!

7

3 Answers

If you increment without assignment, no difference. However, in the following circumstances, there is:

int n = 1;
int x = n++; // x will be 1 and n will be 2

In this example, the statement gets executed prior to the increment.

int n = 1;
int x = ++n; // both x and n will be 2

However, in this example, increment occurs prior to the execution of the statement.

Operator precedence can help you out.

The only difference between n++ and ++n is that n++ yields the original value of n, and ++n yields the value of n after it's been incremented. Both have the side effect of modifying the value of n by incrementing it.

If the result is discarded, as it is in your code, there is no effective difference.

If your program is behaving differently depending on whether you write

n++;

or

++n;

it must be for some other reason.

In fact, when I compile and execute your program on my system, I get exactly the same output in both cases. Adding newlines to the output format, I get:

At n = 25, Algorithm A performs in 114661785600 seconds &
Algorithm B performs in 282429536481 seconds.

You haven't told us what output you're getting. Please update your question to show the output in both cases.

The prefix versions (++n) alter the variable and then pass along its value. The postfix version (n++) pass along the current value and then alter the variable.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like