Thursday, October 24, 2013

Priority of operators

 Do you remember the BODMAS rule of mathematics? Sorry… it’s VBODMAS actually.

V        :Vinculum             1st priority
B        :Bracket                2nd priority
O       :Of                        3rd priority
D       :Division               4th priority
M       :Multiplication       5th priority
A        :Addition               6th priority
S        :Subtraction          7th priority

So all time, whenever you solve mathematics expressions you have to follow this priority. Keep in mind that parentheses, and braces are used more frequently instead of vinculum now a days.

In the same way, if you deal with C’s arithmetic expressions, then also you have to follow certain rules. The rules which decides the priority of operators. 

Consider the following expression:
a*b+c
should the expression a*b+c be evaluated by performing the multiplication first or by preforming addition first?
          (a*b)+c or
          a*(b+c)

C solves this problem by assigning priorities to operators. Operators with high priority evaluates first than the operator having low priority. The following table shows the priority of C’s arithmetic operators.

Operator                                 Priority
()                                             1st
*        /        %                         2nd
+       -                                     3rd
=                                              4th     
Thus, a+b*c is evaluated as:
a+(b*c)

As the multiplication(*)  has the higher priority than addition(+). It the addition(+) was to be evaluated first then we need to use brackets as follows:
(a+b)*c

Note that the operator % is not indicates percentage. It is modulus operator.  Before proceeding any further it is necessary to know about it.

¨ Modulus operator(%) returns reminder after division.
E.g. 12%2=0
       5%2=1

 ¨ The sign of the first operand will be the sign of result.
 E.g. -5%2 =-1
       -5%-2=-1
        5%-2= 1

¨ If the value of numerator is less than that of denominator then result will be the   
   value of numerator.

E.g. 9%10=9   
       Here numerator 9 is less than denominator 10 so the result will be 9.
      1%10=1

¨ It works on integers only.
         
Examples:
Evaluate the following expressions using priority of operators.
     1)   a=100/2*1/2+5/2+99
     2)   b=9+7/2
     3)   c=-3+-3+9*2*3/9
     4)   d=3/5/4/2-3+2%9
     5)   e=-5%3+8/9%10+2


1) a=100/2*1/2+5/2+99
      =50*1/2+5/2+99
      =50/2+5/2+99
      =25+5/2+99
      =25+2+99
      =126

Note: Observe that, if the operators of same priority occur from left to right then priority is given on the first come first serve basis.

In the above expression the result of expression 5/2=2 and not 2.5. As integer and integer always yields an integer result. So the result of the expression 1/2=0 and not 0.5. If you want the result you expected then, one of the operands must be of type float.
E.g.
                  5/2.0    = 2.5
                  5.0/2   = 2.5
                  5.0/2.0 = 2.5

2) b=9+7/2+9/9%30+3
      =9+3+9/9%30+3
      =9+3+1%30+3
      =9+3+1+3
      =16

3) c=-3+ -2+9*2*3/9
      =-3+ -2+18*3/9
      =-3+ -2+54/9
      =-3+-2+6
      = -5+6
      =1

4) d=3/5/4/2-3+2%9
      =0/4/2-3+2%9 
      =0/4-3+2%9
      =0-3+2%9
      =0-3+2
      =-3+2
      =-1

5) e=-5%3+8/9%10+2
      =-2+8/9%10+2 
      =-2+0%10+2
      =-2+0+2
      =0


Associativity: Operators on the same level have the same precedence. The order of the execution of operators on the same level is controlled by associativity. Left associative operators are evaluated from left to right. Right associative operators are evaluated from right to left.
Look at the following example:

#include <stdio.h>
#include <conio.h>
main()
{
 int i=10;
 clrscr();
 printf("%d %d %d",i++,i++,i++);
 getch();

}

Output:
#-------------------------------------------------------------------------------#
12 11 10
#-------------------------------------------------------------------------------#
Note that, the associativity of ++ operator is from right to left. So first the value of last i++ gets printed i.e. 10. As ++ is post increment operator, first the value of i gets printed and then it is incremented by 1. So, the value of second last i++ i.e. 11 is printed and lastly the value of first i++ i.e. 12 gets printed. 

Wednesday, October 23, 2013

Pre increment and post increment operator


The pre increment and post increment operators work identical if they are used independently.
Look at the following code:

Program 10:  
#include <stdio.h>
#include <conio.h>
void main()
{
    int i=2,j=2;
    clrscr();
    ++j;
    i++;
    printf("The value of i=%d”,i);
    printf("\nThe value of j=%d”,j);
   getch();
}
Output:
#-------------------------------------------------------------------------------#
The value of i=3
The value of j=3
#-------------------------------------------------------------------------------#

Here, in the statement ++j the ++ before the variable j is called the pre increment operator whereas the ++ after the variable I is called post increment operator. Their real behavior can be studied when they are used in expressions. The following program demonstrates the difference between these two.

Program 11:  
#include <stdio.h>
#include <conio.h>
void main()
{
    int i=2,j=2,a,b;
    clrscr();
    a=++j;
    b=i++;
    printf("a=%d  and b=%d”,a,b);
    printf("\ni=%d j=%d”,I,j);
   getch();
}
Output:
#-------------------------------------------------------------------------------#
a=3 and b=2
i=3 j=3
#-------------------------------------------------------------------------------#

Here, the value of a is 3 whereas the value of b is 2 because pre increment operator first increments the value of the operand it precedes and then assigns the value of the operand to the variable on the left hand side. So, in the statement a=++j, first the value of the variable j is incremented by 1 and then the value (i.e. 3) is assigned on the variable on the left hand side i.e. a. In the statement b=t++, first the value of i is assigned to the variable on the left hand side i.e. b and then incremented the value of i i.e. 2. So, the statement
          b=i++; is same as
         b=i;
         i++;
Whereas the statement a=++j is similar to
          j++;
         a=j;

Pre decrement and post decrement operator:

The working principal of the pre decrement and the post decrement operator is similar as that of pre increment and post increment operators except that they decrement the value of the variable.

Tuesday, October 22, 2013

Identifiers, Integer and float conversions

Identifiers:
In computer programming language, the names of variables, functions, arrays and other objects are of prime importance. The names of variables, functions, arrays and other objects are called as identifiers.

Rules for constructiong identifiers:
All rules applied to the variables are applied to the identifiers as well.

Integer and float conversions
The following rules are used for implicit conversion of floating point and integer values in C.

♦ If both the operands are of type int then the result is of type int (considering the resultant variable is of type int).

♦ If either operand or both, is of type float then the result is of type float (considering the resultant variable is of type float).

♦ If the expression evaluates of type int and the resultant variable of type float then the int will be converted to an equivalent float before assignment to the resultant variable.

♦ If the expression evaluates of type float and the resultant variable of type int then the float will be converted to an int, usually by rounding towards zero, before assignment to the resultant variable.
It is quite to loose accuracy in an assignment statement.
E.g.
          i=3.5;

♦ If the variable i is declared as an int then the compiler will convert the value 3.5 to an integer value before carrying out the assignment. hence the value 3 will be assigned to the variable i. The compiler will normally truncate the float value to the integer value, which is nearer to zero. Rounding to the nearest integer is not carried out.

♦ The result of the division operator between two int operand is of type int. It gives the result truncated towards zero if the result is positive and the language does not define what should happen if the result is negative.
E.g. 2/5=0 and

      -2/5=0 also.

Monday, October 21, 2013

Using constants


In C any literal; number, single character or character string is known as constant. Constant is the quantity, which does not change during program execution. Consider the following statement:

          z=x+100;

Here, 100 is a constant, and the value 100 cannot be modified during program execution.

Using symbolic constants:
C provides following three ways to define symbolic constants:
    1)   #define preprocessor directive
    2)   enumerated data type
    3)   const keyword
Now, we are going to discuss these constants one by one.

#define preprocessor directive: The C preprocessor is the program, that preprocesses our program before it is passed to the compiler. The preprocessor directive begins with a #symbol. The directive can be placed anywhere in the program, but before using it. The syntax to declare #define constants is as follows:

#define symbolic_name expression

Where,
symbolic_name is the name given to the constant. The rules you applied to naming symbolic constants are same as that for naming variables.
expression can be arithmetic expression, string expression or it may be a character expression.

Examples:
#define MAX 100
#define PI 3.14159
#define MSG “The road to a friend’s house is never long.”

The first example defines the symbolic constant MAX and assigns a value 100 to it. The second example defines the symbolic constant name PI and assigns a value 3.14159 to it. The third example define the symbolic constant MSG and assigns the string “The road to a friend’s house is never long.” to it.

Note: It is not necessary to declare the type of symbolic constant (i.e. int, float or char). It is automatically assigned by the compiler when we define it.
Generally the symbolic constants are written in uppercase letter to distinguish them from the ordinary constants, but this is convention not a rule. If you desire, you can declare them in lower case also. But, it is good practice to make a habit of defining the symbolic constant in upper case letters.
To understand this concept thoroughly, now we are going to write some programs using symbolic constants. Study them keenly.

Program 12: Write a program to find the net salary if the basic salary is input through the keyboard.
#include <stdio.h>
#include <conio.h>
void main()
{
    float bas_sal,net_salary;
    clrscr();
    printf(“\nEnter basic salary:”);
    scanf(“%f”,&bas_sal);
    #define DA 2500
    #define HRA 1500
    #define PF 2500
    net_salary=bas_sal+DA+HRA-PF;
    printf("\nThe net salary is=%f”,net_salary); 
    getch();
}

Output:
#-------------------------------------------------------------------------------#
Enter basic salary:2300
The net salary is=3800.000000
#-------------------------------------------------------------------------------#
Here, we define three symbolic constant namely DA,HRA and PF. Note that we define these constants inside main() but before using them.

Program 13: WAP to find the area of circle without using preprocessor directives.
#include <stdio.h>
#include <conio.h>
void main()
{
    float radius,area;
    clrscr();
    printf(“\nEnter the radius of circle:”);
    scanf(“%f”,&radius);
    area=3.14159*radius*radius;
    printf("\nArea of circle=%f”,area);
    getch();
}
Output:
#-------------------------------------------------------------------------------#
Enter the radius of circle:4.5
Area of circle=63.617199
#-------------------------------------------------------------------------------#

Now, we are going to write same program using preprocessor directives.
#include <stdio.h>
#include <conio.h>
#include <math.h>

#define BEGIN main(){
#define END getch();}
#define CLS clrscr();
#define  DISPLAY printf(
#define  ENDDISPLAY );
#define INPUT(K) scanf(“%f”,&K);

BEGIN
    float radius,area;
    CLS
    DISPLAY “\nEnter the radius of circle:” ENDDISPLAY
    INPUT(radius)
    area=M_PI*radius*radius;
    DISPLAY “\nArea of circle=” ENDDISPLAY
    DISPLAY “%f”,area ENDDISPLAY
END
Output:
#-------------------------------------------------------------------------------#
Enter the radius of circle:4.5
Area of circle=63.617252
#-------------------------------------------------------------------------------#

The constant M_PI used in the above program is inbuilt symbolic constant defined in the header file “math.h”. There are various PI, logarithms and other constants are declared in “math.h”. You can use the following PI constants in your program.

Common PI constants   
M_PI            :p
M_PI_2        : p/2
M_PI_4        : p/4
M_1_PI        : 1/p
M_2_PI        : 2/p
M_1_SQRTPI: 1/Öp
M_2_SQRTPI: 2/Öp

Tip: For other constants please refer to “constant data types and global variables” section of “math.h”. To do this type math.h in an empty area of your program window, press CTRL+F1 by placing the cursor at the first character i.e. m.

How preprocessor works?
The preprocessor replaces all the macro symbols used in the program by their corresponding values before the compilation operation.
For example, the statement,
          area=PI*radius*radius;
is transferred as
          area=3.14159*radius*radius;

Note: The content of the quoted strings are never changed by the preprocessor.

For example, in the statement
          printf(“PI=%f”,PI);
only the second PI in printf will be changed by the above #define directives to the preprocessor. And so, the statement output will be:
          PI=3.14159

Redefining symbolic constants
The definition of the symbolic constant can be changed by the new definition. For instance the symbolic constant PI can be redefined as:
#define PI (22.0/7)   

Look at the following code which demonstrates this:
#include <stdio.h>
#include <conio.h>
#define FLOWER “LOTUS”
void main()
{
    clrscr();
    printf(FLOWER);
    printf(“  is a national flower.”);
    printf("\n");
    #define FLOWER “ROSE -”
    printf(FLOWER);
    printf(“ I am king of flowers.”);
    getch();
}
Output:
#-------------------------------------------------------------------------------#
LOTUS is a national flower.
ROSE – I am king of flowers.

#-------------------------------------------------------------------------------#

Sunday, October 20, 2013

Enumerated data types:


enum is the abbreviation for enumerate, and we can use this keyword to declare and initialize the sequence of integer constants. An enumerated data type is the data type with user specified values. to declare the enumerated data type, we write the keyword enum followed by the optional identifier of the enumerated type called tag, followed by the list of names that are permissible values for the data type. The values are enclosed in braces and separated by commas. Here’s an example:

          enum colors{RED,YELLOW,GREEN,BLUE};

I’ve made the constant names in uppercase, but you can name them whichever way you want to. Here, colors is the name given to the set of constants (remember that this name is optional). Now, if you don’t assign a value to the constant, the default value for the first one in the list (i.e. RED in our case) is 0. The rest of the undefined constants have a value 1 more than the one before. So, YELLOW is 1, GREEN is 2 and BLUE is 3. But, you are free to assign any value.

E.g.    enum colors{ RED=1,YELLOW,GREEN=6,BLUE }

Now, RED=1, YELLOW=2,GREEN=6 and BLUE=7.
The main advantage of enum is that if you don’t initialize your constants each one would have a unique value. The first will be 0 and the rest would be then counted upwards.

You can name your constants in usual order if you really wanted.

enum marital_status{SINGLE,LEARNING,DIVORCED,WIDOWED};

After enum declaration you can declare the enum variables to access the enum members.

The following lines declares two enum variables chap1, and chap2 of type enum marital_status.

enum marital_status chap1,chap2;

Now, we can assign values to these variables.
          chap1=LEARNING;
          chap2=LICENCED;

But, we can’t use values which are not use in the original declaration. Thus the following expression is wrong.
 chap1=NOVICE;

Remember that without declaring enum variables, you can access the enum members directly.Look at this tiny code:

Program 15:  
#include <stdio.h>
#include <conio.h>
void main()
{
    enum BOOL{FALSE,TRUE};
    clrscr();
    printf("%d”,TRUE);
   getch();
}
Output:
#-------------------------------------------------------------------------------#
  1
#-------------------------------------------------------------------------------#

Warning: enum is used to initialize the sequence of integer constants only. So, the following declaration would be wrong.
enum price{ITEM1=50.60,ITEM2=99.33,ITEM3};

By mistake, if you made this declaration in this program then compile generate “constant expression required” error.

The following program demonstrates the use of enum. So, do study them carefully.
Program 16:  
#include <stdio.h>
#include <conio.h>
void main()
{
    /* Anonymous enum (enum having no tag or name.) */
    enum {VOILET=1,INDIGO,BLUE,GREEN,YELLOW,ORANGE,RED};
    clrscr();
    printf("\nDear,");
    printf("\n*** Make your life colourful with me ***");
    printf("\n                                      Yours");
    printf("\n                                    Rainbow");
    printf("\n----------------------------------------------");
    printf("\n Violet is my %dst color.",VOILET);
    printf("\n Indigo is my %dnd color.",INDIGO);
    printf("\n Blue is my %drd color.",BLUE);
    printf("\n Green is my %dth color.",GREEN);
    printf("\n Yellow is my %dth color.",YELLOW);
    printf("\n Orange is my %dth color.",ORANGE);
    printf("\n Red is my %dth color.",RED);
    getch();
}
Output:
#-------------------------------------------------------------------------------#
  Dear,
  *** Make your life colorful with me ***
                                                  Yours
                                              Rainbow
 ----------------------------------------------
Violet is my 1st color.
Indigo is my 2nd color.
Blue is my 3rd color.
Green is my 4th color.
Yellow is my 5th color.
Orange is my 6th color.
Red is my 7th color.

#-------------------------------------------------------------------------------#

The following program demonstrates the wonderful usage of enum in your program.

#include <stdio.h>
#include <conio.h>
void main()
{
    int education, attitude, knowledge, hardwork;
    enum ATT {A=1,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z};
    clrscr();
    printf("\nHow important the attitude is ?\n");
    printf("\nIf");
    printf("\n A B C D E F G H I J K L M N \nO P Q R S T U V W X Y Z is\n”);                                                 
    printf("\n”);
    printf("\n1 2 3 4 5 6 7 8 9 10 11 12 13 \n14 15 16 17 18 19 20 21 22 23 24 25 
    26 %");
    printf("\nthen\n”);
    education=E+D+U+C+A+T+I+O+N;
    knowledge=K+N+O+W+L+E+D+G+E;
    hardwork=H+A+R+D+W+O+R+K;
    attitude=A+T+T+I+T+U+D+E;
    printf(“\nEducation got %d%%”,education);
    printf(“\nKnowledge got %d%%”,knowledge);
    printf(“\nHardwork got %d%%”,hardwork);
    printf(“\nAttitude got %d%%”,attitude);
    getch();
}

Output:
#-------------------------------------------------------------------------------#
  How important the attitude is ?
  If
  A B C D E F J H I J K L M N
  O P Q R S T U V W X Y Z is
 
  1 2 3 4 5 6 7 8 9 10 11 12 13
  14 15 16 17 18 19 20 21 22 23 24 25 26
  then
 
  Education got 92%
  Knowledge got 96%
  Hardwork got 98%
  Attitude got 100%

 #-------------------------------------------------------------------------------#