Introduction To Programming

Why programs ? Programming is nothing but making the computers think the same way a human thinks. Programs are made for obtaining a specific solution which can even be solved by humans which when solved by us may consume time..

Monday, January 25, 2010

#define Macroprocessor

One of macroprocessor #define used to define value for variable. The value will be constant for that variable. Can't change in run time.
eg:
#define a 10
'a' value is constant has always 10.

#define can be used before all functions or inside functions like usual variable declaration.


#include< stdio.h >
#define a 1
main( )
{
#define b 2
printf("%d %d", a,b);
}

not only used for define values but also define function.
#define f(a,b) a+b
this function will get two arguments a and b and return addition of them.


#include< stdio.h >
#define fn(a,b,c) a+(b*c)
main()
{
printf("%d",fn(1,2,3));
}


output:
7

Left shift - Right Shift

#include< stdio.h >
int powerof2(int a)
{
int p=0;
for(int i=0;i p+=2;
return p;
}
main()
{
int n,shift,ln,rn;
printf("enter number and shifting number");
scanf("%d %d",&n,&shift);
ln=n*powerof2(shift);
rn=n/powerof2(shift);
printf("Left shift: %d", ln);
printf("Right shift: %d", rn);
}

Lpart5

There are two type of bit shifting.
  • Left shift: shifting bits in left side. < < left shift operator. Use left shift like this number< < shift.
    For Eg:
    4<<1
    This will shift one bit left side of number 4. I.e., 4 is 0100. If we shift one bit of 4 in left side, 1000 will be the answer i.e 8.
    Simply we can calculate the value after left shifting by formula i.e., "number*2^shift". 4*2=8.

  • Right shift: > > this will shift bits in right direction. 4 > > 2. The value after shifting is 0001. Simply we can calculate right shift by this formula "number/2^shift".
    4/2^2 =4/4=1.
  • Lpart4

    #include< stdio.h >
    main()
    {
    int a=1,b;
    b=++a*2*++a;
    printf("%d %d", a,b);
    }
    Output
    3 18


    in this program there's two preincrement for 'a'. So 'a' will be incremented two times before multiplication. So now a= 3. so b=3*2*3=18.

    Lparts

    #include< stdio.h >
    main()
    {
    int a=1,b;
    b=a++*2*++a;
    printf("%d %d",a,b);
    }

    output:
    3 8

    as a explained in last post , this program also works.