You are on page 1of 8

Unit 1

Traversing of Array

#include<iostream>

using namespace std;

main()

int marks[5]={10,20,30,40,50};

for(int i=0;i<=4;i++)

cout<<"Elements are "<<marks[i];

cout<<"\n";

Inserting an element into an array

#include<iostream>

using namespace std;

main()

int marks[100],n,i,k,num;

cout<<"Enter the size of the array=\n";

cin>>n;
cout<<"Enter the elements of an array = \n";

for(i=1;i<=n;i++)

cin>>marks[i];

cout<<"Elements are = \n";

for(i=1;i<=n;i++)

cout<<marks[i]<<"\n";

cout<<"Enter the position where you want to insert an element =\n";

cin>>k;

for (i=n;i>=k;i--)

marks[i+1]=marks[i];}

cout<<"Enter the value you want to insert = \n";

cin>>num;

marks[k]=num;

cout<<"The elements are = \n";

for(i=1;i<=n+1;i++)

cout<<marks[i]<<"\n";

}}
Deleting an element from an array

#include<iostream>

using namespace std;

main()

int marks[100],n,i,k,num;

cout<<"Enter the size of the array=\n";

cin>>n;

cout<<"Enter the elements of an array = \n";

for(i=1;i<=n;i++)

cin>>marks[i];

cout<<"Elements are = \n";

for(i=1;i<=n;i++)

cout<<marks[i]<<"\n";

cout<<"Enter the position from where you want to delete an element =\n";

cin>>k;

for(i=k;i<=n-1;i++)

marks[i]=marks[i+1];
}

cout<<"The elements are=\n";

n=n-1;

for(i=1;i<=n;i++)

cout<<marks[i]<<"\n";

Linear Search

#include<iostream>

using namespace std;

main()

int num, j=0,pos,i;

int marks[5]={10,24,78,12,45};

cout<<"Array elements are = \n";

for(i=0;i<=4;i++)

cout<<marks[i]<<"\n";

cout<<"Enter element to be found = \n";

cin>>num;
for(i=0;i<=4;i++)

if(marks[i]==num)

j=1;

pos=i;

break;

if(j==0)

cout<<"Element not found";

else

cout<<"Element found at "<<pos;

Binary Search

#include<iostream>

using namespace std;


main()

int marks[100],n,i,num,beg,end,mid;

cout<<"Enter number of elements = \n";

cin>>n;

cout<<"Enter the elements = \n";

for(i=0;i<n;i++)

cin>>marks[i];

cout<<"Enter the element to be found = \n";

cin>>num;

beg=0;

end=n-1;

mid=(beg+end)/2;

while(beg<=end)

if(marks[mid]<num)

beg=mid+1;

else if(marks[mid]==num)

{
cout<<"Element found at "<<mid+1;

break;

else

end=mid-1;

mid=(beg+end)/2;

if(beg>end)

cout<<"Element not found";

Bubble Sort

#include<iostream>

using namespace std;

main()

int marks[100],n,i,j,temp;

cout<<"Enter the number of elements = \n";

cin>>n;
cout<<"Enter the elements \n";

for(i=0;i<n;i++)

cin>>marks[i];

cout<<"Arranging elements using bubble sort \n";

for(i=0;i<n-1;i++) //passes

for(j=0;j<(n-i-1);j++) //comparison

if (marks[j]>marks[j+1])

temp=marks[j];

marks[j]=marks[j+1];

marks[j+1]=temp;

cout<<"Elements in sorted manner are = \n";

for(i=0;i<n;i++)

cout<<marks[i]<<"\n";

}}

You might also like