Thursday 21 February 2013

a program to set nth bit of an integer to 0


#include<stdio.h>
#include<conio.h>
void main()
{
int n=2;
int f=12;
clrscr();
f&=~(1L<<n);
printf("%d",f);
getch();
}


Explanation:
f &=~(1L<<n)
=> f = f & ~ (1L<<n)
in binary; f : 0000 1100
             1L: 0000 0001
   (1L<<2) : 0000 0100  ; bits are shifted to left 2 times.
  ~(1L<<2) : 1111 1011 ; complement the bits.
  &  is a bitwise AND operator, it will perform AND operation and result will be stored to f  so;
                f : 0000 1000
output will be 8.



A program to set nth bit of an integer to 1


#include<stdio.h>
#include<conio.h>
void main()
{
int n=2;
 int f=8;
clrscr();
f |= (1L<<n);
printf("%d",f);
getch();
}

Explanation:
f |= (1L<<n)
=> f = f | (1L<<n)
in binary; f : 0000 1000
             1L: 0000 0001
   (1L<<2) : 0000 0100  ; bits are shifted to left 2 times.
   | is a bitwise or operator, it will perform or operation and result will be stored to f  so;
                f : 0000 1100
output will be 12.


Wednesday 20 February 2013

array of pointer


#include<iostream.h>
#include<conio.h>
void sort(char *name[],const int size);
void main()
{
char *name[]={"saurabh","amit","sushant","rohan"};
sort(name,4);
getch();
}
void sort(char *name[],const int size)
{ clrscr() ;
for(int i=0;i<size;i++)

cout<<name[i]<<"\t";
}

accessing elements of array of any dimention with single loop with pointer


#include<stdio.h>
#include<conio.h>
int sum(int *ptr,const int row,const int col);
void main()
{
int a[][3]={1,2,3,4,5,6,7,8,9};
int *ptr;
clrscr();
ptr=&a[0][0];
printf("%d",sum(ptr,3,3));
getch();
}
int sum(int *ptr,const int row,const int col)
{
int s=0;
for(int i=0;i<row*col;i++)
{
s=s+*(ptr+i);
}
return s;
}
NOTE: program will sum all the elements of array.

pointer to array


#include<stdio.h>
#include<conio.h>
int highest(int *ptr,const int row,const int col);
void main()
{
int *ptr;
int temp[3][4]={3,4,2,6,5,8,9,12,0,4,7,10};
ptr=&temp[0][0];
printf("%d",highest(ptr,3,4));
getch();
}
int highest( int *ptr,const int row,const int col)
{
int h=0;
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
if(*(ptr+i*col+j)> h)
h=*(ptr+i*col+j);
return h;
}

NOTE: here *(ptr+i*col+j)=temp[i][j].
program finds the highest value element of 3x4 array. 

passing array to function



#include<stdio.h>
#include<conio.h>
const int row=3,col=4;
int high(int temp[3][4])
{
int i,j,h=0;
for( i=0;i<row;i++)
{
for( j=0;j<col;j++)
{
if(h<temp[i][j])
h=temp[i][j];
}
}
return h;
}

void main()
{
int temp[][4]={12,23,45,10,13,24,24,56,30,45,28,90};
printf("%d",high(temp));
getch();
}