Google Add

Search

Pre-increment Vs Post-increment Operators - Difference Between Pre-increment and Post-increment Operators

What's the difference between pre-increment (++i) and post-increment (i++) operators. How pre-increment and post-increment works in programming.

In programming, pre-increment and post-increment operator is very important.  Let's see and understand, what's the difference between these two operators.

Pre-increment and Post-increment MCQ for practice



Pre-increment Vs Post-increment Operator


Pre-increment (++i) Operator


When we use Pre-increment operator in our program, value is first incremented and then incremented value is used in an expression.

For example - Let's take a very basic example.

    /* Declared a variable num */

    int num = 5;

    /* Assign pre-increment value */

    result  = ++num;

    /* 6 will be printed when i print result */

    printf("%d", result);
       


Let's write a complete program.

#include <stdio.h>

void main()
{
   
   int result, num;

   num = 5;

   result = ++num;
   
   printf("%d", result);
}


Post-increment Operator


When we use post-Increment operator in our program, then original value is first used in an expression and after that it's incremented.

Let's understand through example.
    

    /* Declared a variable num */

    int num = 5;

    /* Assign pre-increment value */

    result  = num++;

    /* 5 will be printed when i print result */

    printf("%d", result);
       


#include <stdio.h>

void main()
{
   
   int p, num=5;
   
   p = num++;
   
   printf("%d", p);
}


Some questions based on pre-increment and post-increment operator for practice.

Print even numbers from 1 to n.

Count number of vowels and consonants in a string

Program to count number of digits in a number

Find length of a string without using strlen

No comments:

Post a Comment