Kamis, Juli 03, 2014

Introduction To Prefix And Postfix Decrement Operators On C Programming Language

Decrement operator is used to decrease variable value by substracting integer 1. There are two type of decrement operator:
  1. Prefix decrement operator, example: a = --y
  2. Postfix decrement operator, example: y--

Prefix decrement operator is used to decrease variable value before using in expression. On prefix decrement, value is first decremented and then used in expression. While postfix decrement operator is used to decrease variable value after executing expression. On postfix decrement, value is first value is defined and used in expression, then decreased.

Example of program of prefix and postfix decrement operator:

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 value of x = 10
  y=10; //define that value of y = 10
  printf("Initial value of x variable: %d", x);
  printf("\nInitial value of y variable: %d", y);

  a=--x; /*define value of a = value of x has been decreased 1,
           value of a = 9, and now value of x = 9*/
  printf("\n\na=--x, then value of a = value of x has been decreased, so that value of a: %d", a);
  printf("\nValue of x after decreased: %d", x);

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

  getch();
}


If each of decrement operator (prefix and postfix) is used thrice:

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

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

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

  getch();
}


Source/> http://www.c4learn.com

0 komentar: