Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include<stdio.h>
int main()
{
       float sum;
       sum=0; 
     
       for(int n=1; n<=10; ++n)
       {
          sum=sum+1/float(n);  
         printf("%f",sum);
       }

}


The program here calculates 1/1+1/2+1/3+1/4+.......+1/n
My question here is on the for loop increment . What difference is there between ++n and n++ prior to this program.
I know it's pre and post increment....But to this program how does it work??
Posted
Updated 10-Apr-13 16:37pm
v3

++n; is more efficient,n++ ; in Compilar n++ is more than ++n one step
 
Share this answer
 
Comments
CPallini 12-Apr-13 5:01am    
In such a simple case, the compiler might easily optimize.
They are equivalent, in this usage; most practitioners use post-increment, some insist that pre-increment is more efficient.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Apr-13 0:20am    
This is amazing, but I tested pre-increment with .NET, it really improves performance by clearly noticeable percentage.
My 5 anyway.
—SA
PIEBALDconsult 11-Apr-13 0:35am    
Write an article.
Sergey Alexandrovich Kryukov 11-Apr-13 0:40am    
Thank you. Nah.., there are more interesting topics; I have some line of unfinished articles...
—SA
Steve44 12-Apr-13 5:50am    
Pretty basic, the post-increment creates a temporary variable containing the value before incrementing the original variable and returns this as the value of the operation. This is most noticeable when you are overloading increment operators on a class object, there pre-increment increments the instance in-place, while post-increment creates a copy of the instance. For C the difference is minimal.
H.Brydon 12-Apr-13 12:40pm    
Differences in pre- and post- increment (also decrement) will be seen in either (1) unoptimized int code, (2) code involving a class/struct that acts like an int and (3) use of operator++()/operator--(). In all cases, the value has to be preserved for the postincrement (or postdecrement) return value. In the case of POD, the compiler can optimize this out. For a class this is a harder problem and is not always optimized out (if ever?). For the third case it can't be optimized.
You can check the difference in this code

void main()
{
int n;
int x,y;
n=1;
printf("Initial Value = %d",n);
x=n++;
printf("Assigned %d and Incremented %d",x,n);
y=++n;
printf("Assigned %d and Incremented %d",y,n);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900