#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n,*a,item,loc=-1;
cout<<"\nenter the no. of elements :";
cin>>n;
a=new int[n]; //dynamically initialize array
cout<<"\nenter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"\nenter the element you want to search: ";
cin>>item;
int mid,end=n,beg=0;
while(beg<=end&&loc==-1)
{
mid=(beg+end)/2;
if(a[mid]==item)
loc=mid;
else if(a[mid]<item)
beg=mid+1;
else
end=mid-1;
}
if(loc!=-1)
cout<<"\nlocation of "<<item<<" is:"<<loc+1;
else
cout<<"\n"<<item<<" not found!!!";
getch();
}
By Gurpreet Singh, Department of Computer Science & Engineering, Amritsar College of Engineering & Technology
Showing posts with label C&Cpp. Show all posts
Showing posts with label C&Cpp. Show all posts
Saturday, 1 August 2015
Binary Search Program
Linear Search Program
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int *a,n,loc=-1,item;
cout<<"\nenter the no. of elements (max. 10):";
cin>>n;
a=new int[n]; //dynamically initialize array
cout<<"\nenter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"\nenter the element to be searched: ";
cin>>item;
for(i=0;i<n;i++)
if(a[i]==item)
{ loc=i;
break;
}
if(loc==-1)
cout<<"\n"<<item<<" not found!!!";
else
cout<<"location of "<<item<<" is: "<<loc+1;
getch();
}
Selection Sort Program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n,temp,min;
cout<<"\nEnter the no. of elements you want:";
cin>>n;
int *a=new int[n]; //dynamically initialize array
cout<<"\nEnter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
{
min=i;
for(int j=i+1;j<n;j++)
{
If(a[min]>a[j])
min=j;
}
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
cout<<"\nSorted list of given integers is(in ascending order) :\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
getch();
}
Bubble Sort Program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n,temp;
cout<<"\nEnter the no. of elements you want:";
cin>>n;
int *a=new int[n]; //dynamically initialize array
cout<<"\nEnter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"\nSorted list of given integers is(in ascending order) :\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
getch();
}
Merge Sort Program
#include<iostream.h>
#include<conio.h>
#include<values.h>
void merge(int a[],int p,int q,int r)
{
int n1=q-p+1,n2=r-q;
int *l=new int[n1+1];
int *rt=new int[n2+1];
for(int i=0;i<n1;i++)
l[i]=a[p+i];
for(int j=0;j<n2;j++)
rt[j]=a[q+j+1];
l[n1]=MAXINT; //SENTINEL
rt[n2]=MAXINT; //SENTINEL
i=j=0;
for(int k=p;k<=r;k++)
{
if(l[i]<=rt[j])
{
a[k]=l[i];
i+=1;
}
else
{
a[k]=rt[j];
j+=1;
}
}
}
void mergesort(int a[],int p,int r)
{
int q;
if(p<r)
{
q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
}
void main()
{
clrscr();
int n;
cout<<"\nEnter the no. of elements you want:";
cin>>n;
int *a=new int[n]; //dynamically initialize array
cout<<"\nEnter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
mergesort(a,0,n-1);
cout<<"\n\nSORTED ARRAY IS:\n";
for( i=0;i<n;i++)
cout<<a[i]<<" ";
getch();
}
Quick Sort Program
#include<iostream.h>
#include<conio.h>
int partition(int a[],int p,int r)
{
int x,i,temp;
x=a[r];
i=p-1;
for(int j=p;j<r;j++)
{
if(a[j]<=x)
{
i=i+1;
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
temp=a[i+1];
a[i+1]=a[j];
a[j]=temp;
return i+1;
}
void quicksort(int a[],int p,int r)
{
int q;
if(p<r)
{
q=partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
}
void main()
{
clrscr();
int *a,n;
cout<<"\nEnter the no. of element you want:";
cin>>n;
a=new int[n]; //dynamically initialize array
cout<<"\nEnter the elements:\n";
for(int i=0;i<n;i++)
cin>>a[i];
quicksort(a,0,n-1);
cout<<"\nSorted Array is:\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
getch();
}
Heap Sort Program
#include<iostream .h>
#include<conio .h>
int heapsize,length;
void exchange(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void maxheapify(int a[],int i)
{
int l,r,largest,temp;
l=2*i; //left[i]
r=2*i+1; //right[i]
if(l<=heapsize&&a[l]>a[i])
largest=l;
else
largest=i;
if(r<=heapsize&&a[r]>a[largest] )
largest=r;
if(largest!=i)
{
exchange(a[i],a[largest]);
maxheapify(a,largest);
}
}
void buildmaxheap(int a[])
{
heapsize=length;
for(int i=length/2;i>=1;i--)
maxheapify(a,i);
}
void heapsort(int a[])
{
buildmaxheap(a);
for(int i=length;i>=2;i--)
{
exchange(a[1],a[i]) ;
heapsize-=1;
maxheapify(a,1);
}
}
void main()
{
clrscr();
int *a,n;
cout<<"\nEnter the no of element you want(max 20):";
cin>>n;
length=n;
a=new int[n+1]; //DYNAMICALLY INITIALISE ARRAY,AS ARRAY MUST START FROM INDEX 1 SO SIZE IS (N+1)
cout<<"\nEnter the elements:\n";
for(int i=1;i<=n;i++)
cin>>a[i];
heapsort(a);
cout<<"\nSorted Array is:\n";
for(i=1;i<=n;i++)
cout<<a[i]<<" ";
getch();
}
Thursday, 14 May 2015
Program to print rhombus in C
#include<stdio.h>
int main( )
{
int n = 5, inc = 1, i, j,k; //n is number of stars to be printed in middle row
for (i = 1; i <= n && i >= 1; i = i + inc)
{
for (j = 1; j <= n - i; j++)
printf(" "); //prints a space
for (k = 1; k <= i;k++ )
printf("* "); //prints star and space
printf("\n"); //prints a new line
if (i == n)
inc = -1;
}
return 0;
}
Program to find missing elements in an array in C
#include<stdio.h>
int main( )
{
int a[ ]={2,4,7}; //array to be tested
int n=sizeof(a)/sizeof(a[0]); //length of array
int i,j,match;
for(i=1;i<=9;i++) //here we are testing the missing elements from 1 to 9
{
match=0;
for(j=0; j<n | | (match==0);j++) //it will loop until the array ends or we found a match
if(a[j] = = i)
match=1;
if(match==0) //no match found
printf("%d ",i);
}
return 0;
}
How to find length of an array in C or C++?
To find the length of an array in C or C++, you can use the following:
int n=sizeof(a)/sizeof(a[0]);
Here, a is array
What is Object slicing? Give an example.
When a Derived Class object is assigned to Base class, the base class' contents in the derived object are copied to the base class leaving behind the derived class specific contents. This is referred as Object Slicing. That is, the base class object can access only the base class members. This also implies the separation of base class members from derived class members has happened.
class base
{
public:
int i, j;
};
class derived : public base
{
public:
int k;
};
int main()
{
base b;
derived d;
b=d;
return 0;
}
here b contains i and j where as d contains i, j& k. On assignment only i and j of the d get copied into i and j of b. k does not get copied. on the effect object d got sliced.
Pointer to member of class
We can assign the address of a member of a class to a pointer by applying operator & to a "fully qualified" class member name. Pointer to class member can be declared using the operator ::*. For example:
class abc
{
int x;
public :
void show( );
};
Now we can define a pointer to the member x as follows:
int abc::* p=&abc :: x;
The p pointer created thus act like a class member in that it must be invoked with a class object. In the statement above, the phrase abc::* means "pointer-to-member of abc class". The phrase &abc::x means the "address of the x member of abc class".
abc a;
cout<<a.*p;
cout<<a.x;
Above two statements are identical
class abc
{
int x;
public :
void show( );
};
Now we can define a pointer to the member x as follows:
int abc::* p=&abc :: x;
The p pointer created thus act like a class member in that it must be invoked with a class object. In the statement above, the phrase abc::* means "pointer-to-member of abc class". The phrase &abc::x means the "address of the x member of abc class".
abc a;
cout<<a.*p;
cout<<a.x;
Above two statements are identical
How to declare const member functions?
If a member function does not alter any data in the class, then we may declare it as a const member function as follows:
void func(int , int) const;
float sum(float , float) const;
The qualifier const is appended to the function prototypes (in both declaration and definition). The compiler will generate an error message if such functions try to alter the data values of the data members of that class.
void func(int , int) const;
float sum(float , float) const;
The qualifier const is appended to the function prototypes (in both declaration and definition). The compiler will generate an error message if such functions try to alter the data values of the data members of that class.
Some facts about static member functions in C++
Like static member variable, we can also have static member functions. A member function that is declared static has the following properties:
- A static function can have access to only other static members (functions or variables) declared in the same class.
- A static member function can be called using the class name (instead of its objects) as follows:
Situations where inline expansion may not work
The inline keyword merely sends a request, not a command, to the compiler. The compiler may ignore this request if the function definition is too large or too complicated and compile the function as a normal function.
Some of the situation where inline expansion may not work are:
1. For functions returning value, if a loop, a switch, or a goto exists.
2. For functions not returning values, if a return statement exist.
3. If functions contain static variables.
4. If inline functions are recursive.
Some of the situation where inline expansion may not work are:
1. For functions returning value, if a loop, a switch, or a goto exists.
2. For functions not returning values, if a return statement exist.
3. If functions contain static variables.
4. If inline functions are recursive.
Some facts on C/C++
- Functions defined in a class are by default inline.
- Memory space for the members of a class is allocated when an object of that class is created, not before that(at declaration of the class).
- Compiler provides a zero argument constructor only when there is no other constructor defined in the class.
- Realloc can be used to reallocate the memory allocated using new operator.
- Size of the pointer does not depend on where it is pointing to, it is always the same.
- Copy constructor and assignment operators are provided by default by the compiler.
- When an object is passed or returned to/from a function by value the copy constructor gets called automatically.
- For a template function to work it is mandatory that its definition should always be present in the same file from where it is called.
- All static data members are initialized to zero.
- For every static data member of a class it should also be defined outside the class to allocate the storage location.
Some facts about comma operator
Consider the following C programs.
// PROGRAM 1
#include<stdio.h>
int main(void)
{
int a = 1, 2, 3;
printf("%d", a);
return 0;
}
The above program fails in compilation, but the following program compiles fine and prints 1.
// PROGRAM 2
#include<stdio.h>
int main(void)
{
int a;
a = 1, 2, 3;
printf("%d", a);
return 0;
}
And the following program prints 3
// PROGRAM 3
#include<stdio.h>
int main(void)
{
int a;
a = (1, 2, 3);
printf("%d", a);
return 0;
}
In a C/C++ program, comma is used in two contexts: (1) A separator (2) An Operator.
Comma works just as a separator in PROGRAM 1 and we get compilation error in this program.
Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3″ becomes equivalent to “(a = 1), 2, 3″. That is why we get output as 1 in the second program.
// PROGRAM 1
#include<stdio.h>
int main(void)
{
int a = 1, 2, 3;
printf("%d", a);
return 0;
}
The above program fails in compilation, but the following program compiles fine and prints 1.
// PROGRAM 2
#include<stdio.h>
int main(void)
{
int a;
a = 1, 2, 3;
printf("%d", a);
return 0;
}
And the following program prints 3
// PROGRAM 3
#include<stdio.h>
int main(void)
{
int a;
a = (1, 2, 3);
printf("%d", a);
return 0;
}
In a C/C++ program, comma is used in two contexts: (1) A separator (2) An Operator.
Comma works just as a separator in PROGRAM 1 and we get compilation error in this program.
Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3″ becomes equivalent to “(a = 1), 2, 3″. That is why we get output as 1 in the second program.
Some facts about static variable
IN C STATIC VARIABLE CAN BE INITIALIZED USING ONLY CONSTANT LITERALS.........
FOR EXAMPLE :
static int i=20;
IF WE DO NOT INITIALIZE ANY VALUE THEN......
FOR EXAMPLE :
static int i;
then by default value of i will be ZERO.......
MEANS i will be 0 ......
FOR EXAMPLE :
BELLOW PROGRAM WILL GIVE COMPILE TIME ERROR...
#include<stdio.h>
int a( )
{
return 6;
}
main( )
{
static int i=a( ); /* Compile Time Error*/
printf("%d",i);
return 0;
}
Explanation: All objects with static storage duration must be initialized before execution of main() starts......
FOR EXAMPLE :
static int i=20;
IF WE DO NOT INITIALIZE ANY VALUE THEN......
FOR EXAMPLE :
static int i;
then by default value of i will be ZERO.......
MEANS i will be 0 ......
Note: All objects with static storage duration must be initialized before execution of main() starts......
FOR EXAMPLE :
BELLOW PROGRAM WILL GIVE COMPILE TIME ERROR...
#include<stdio.h>
int a( )
{
return 6;
}
main( )
{
static int i=a( ); /* Compile Time Error*/
printf("%d",i);
return 0;
}
Explanation: All objects with static storage duration must be initialized before execution of main() starts......
Disadvantages of C
The most common disadvantages of C are:
- No Run Time Checking mechanism.
- Does not support Object Oriented Programming (OOP) features.
- No Strict Type Checking.
- Does not support Exception Handling.
Subscribe to:
Posts (Atom)