Blog Moved

This website completely moved to new domain. For latest content, visit www.programmingposts.com

Search This Blog

22 Jul 2012

C Program to Show the Operations of Arithmetic Operators


c program to understand the Arithmetic Operators And their Precedences..

PROGRAM: 

#include<stdio.h>
void main()
{

    int a=25,b=5,c=10,d=4;
    int result;
    result=a+b;  /*adding a and b*/
    printf("\n Addition Result: %d",result);
    result=a-b;  /* subtracting b from a*/
    printf("\n Subtraction Result is: %d",result);
    result=a*b; /* multiplying a and b*/
    printf("\n Multiplication result is:%d",result);
    result=a/b; /* dividing a by b to get quotient*/
    printf("\n Division Result is: %d",result);
    result=a%b; /* dividing a by b to get ramainder*/
    printf("\n Division Result Remainder is: %d",result);
    result=a+b*c/d; /*refer precedence 1 explanation below*/
    printf("\n The Result of (a+b*c/d): %d",result);
    result=a+b-c*d; /*refer precedence 2 explanation below*/
    printf("\n The result of (a+b-c*d): %d",result);
    result=++a + b++ /d; /*refer precedence 3 explanation below*/
    printf("\n The Result of (++a + b++ / d): %d",result);
}

Output: (using GNU GCC Compiler with Code Blocks IDE)


Addition Result: 30
Subtraction Result is: 20
Multiplication Result is : 125
Division Result is: 5
Division Result Remainder is: 0
The Result of (a+b*c/d): 37
The Result of (a+b-c*d): -10
The Result of (++a + b++ /d): 27


EXPLANATION:
Every time the variable result is overritten with a new value and printing

Precedence1:  a+b*c/d;
              i)   c*d = 50
             ii) (c*d)/d i.e.,50/4=12.5 
(here float value is not considered because result is declared as int)
            iii) 12 is added to a (25+12=37)

precedence2: a+b-c/d;
             i) c/d is evaluated 
            ii) b-(c/d) evaluated
           iii) a+(b-(c/d)) evaluated

precedence3:  ++a+b++/d;
              i)a value incremented
             ii)b value incremented
            iii)b++/d evaluated
             iv)++a + (b++/d) is evaluated

Link: for more about precedence and order of evaluation

No comments:

Post a Comment