Kamis, Juli 03, 2014

Introduction To Prefix And Postfix Increment Operators On C Programming Language

Increment operator is used to increase variable value by adding integer 1. There are two typed of increment operator:
  1. Prefix increment operator, example: a = ++y
  2. Postfix increment operator, example: a = y++
Prefix increment operator is used to increment the value of variable before using in the expression. In the Pre-Increment value is first incremented and then used inside the expression. Postfix increment operator is used to increment the value of variable as soon as after executing expression completely in which post increment is used. In the Post-Increment value is first used in a expression and then incremented.

Example of program of prefix and postfix increment:

main()
{
  int x,y,a,m;
  x=10;
  y=10;
  printf("%d", x);
  printf("\n%d", y);

  a=++x;
  printf("\n\n%d", a);
  printf("\n%d", x);

  m=y++;
  printf("\n\n%d", m);
  printf("\n%d", y);

  getch();
}


if added explanation:

main()
{
  int x,y,a,m;
  x=10; //define that x value = 10
  y=10; //define that y value = 10
  printf("Initial value of x variable: %d", x);
  printf("\nInitial value of x variable: %d", y);

  a=++x; /*define that value of a = value of x has been added 1,
           value of a = 11, and now value of x = 11*/
  printf("\n\na=++x, then value of a = value of x has been added, so that value of a:%d", a);
  printf("\nValue of x has been increased: %d", x);

  m=y++; /*define that value of m = value of y, value of m = 10,
           and then value of y is increased, and now value of y = 11*/
  printf("\n\nm=y++, then value of m = value of y, so that value of m: %d, then value of y is increased", m);
  printf("\nValue of y after increased: %d", y);

  getch();
}


if each increment operator (prefix dan postfix) is used 3 times:

main()
{
  int x,y,a,b,c,m,n,o;
  x=10;
  y=10;
  printf("Initial value of x variable: %d", x);
  printf("\nInitial value of y variable: %d", y);

  a=++x;
  printf("\n\na=++x, mthen value of a: %d", a);
  printf("\nValue of x after increased once: %d", x);
  b=++x;
  printf("\nb=++x, then value of b: %d", b);
  printf("\nValue of x after increased twice: %d", x);
  c=++x;
  printf("\nc=++x, then value of c: %d", c);
  printf("\nValue of x after increased thrice: %d", x);

  m=y++;
  printf("\n\nm=y++, then value of m: %d", m);
  printf("\nValue of y after increased once: %d", y);
  n=y++;
  printf("\nn=y++, then value of n: %d", n);
  printf("\nValue of y after increased twice: %d", y);
  o=y++;
  printf("\no=y++, then value of o: %d", o);
  printf("\nValue of o after increased thrice: %d", y);

  getch();
}


Source:
http://www.c4learn.com

0 komentar: