Java program to demonstrate UrlClass

This program demonstrate URL class in Java. A URL class is used to fetch information about a given URL. This program demonstrates all the functions of a URL class. The program declares an object, url of the of the URL class. Then the program applies various functions of the URL class to this object. The URL class id defined in java.net package. Below is a list of functions in the URL class an its description.

  • toString: This function is used to retrieve the whole url.
  • getProtocol: Every url starts with a protocol. This function retrieves the protocol from the url. Here the protocol is http.
  • getAuthority: Retrieves the authority of the url. 
  • getFile: Retrieves the file name of the url.
  • getHost: Retrieves the host of the url.
  • getPath: Retrieves the path of the url.
  • getPort: Retrieves the port number of the url.
  • getDefaultPort: Retrieves the default port of the url.
  • getQuery: Retrieves the query part in the url.
  • getRef: Retrieves the reference part of the url.


Program



//Url Class Java Program

import java.net.*;

class UrlClass

{

public static void main(String s[]) throws MalformedURLException

{

URL url=new URL("http://www.kerala.gov.in:85/index.html");

System.out.println("URL is:"+url.toString());

System.out.println("Protocol is:"+url.getProtocol());

System.out.println("Authority is:"+url.getAuthority());

System.out.println("File is:"+url.getFile());

System.out.println("Host is:"+url.getHost());

System.out.println("Path is:"+url.getPath());

System.out.println("Port is:"+url.getPort());

System.out.println("Default port is:"+url.getDefaultPort());

System.out.println("Query is:"+url.getQuery());

System.out.println("Ref is:"+url.getRef());

}

}


Output


Java program for URL class
URL class program in Java


Applet program to play audio/sound

This applet program plays an audio. The program declares objects sf1 and sf2 of AudoClip class. The program uses two audio clips. The getAudioClip() function is used to fetch the audio file from the disk, it will be stored in the objects sf1 and sf2.  The play() function is used to play the audio clip. When the program first loads the function sf1.play(); will be invoked and the first audio clip will be played. When the user clicks somewhere on the window, the first audio clip will be stopped and the second audio clip will be played. Also both the audio files must be stored in the same directory where the source file if stored. 


Program


//Applet program in java to add sound/Audio

//<Applet code=SoundApplet height=400 width=400></Applet>

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class SoundApplet extends Applet implements MouseListener

{

AudioClip sf1,sf2;

public void start()

{

System.out.println("Applet Started");

}

public void init()

{

sf1=getAudioClip(getCodeBase(),"doorbell.wav");

sf2=getAudioClip(getCodeBase(),"doorbell.wav");

addMouseListener(this);

setBackground(Color.BLUE);

sf1.play();

}

public void paint(Graphics g)

{

g.drawString("Sound",100,200);

}

public void mouseClicked(MouseEvent e)

{

sf2.play();

}

public void mouseReleased(MouseEvent e)

{

System.out.println("Mouse Released");

}

public void mousePressed(MouseEvent e)

{

System.out.println("Mouse Pressed");

}

public void mouseEntered(MouseEvent e)

{

System.out.println("Mouse Entered");

}

public void mouseExited(MouseEvent e)

{

System.out.println("Mouse Exited");

}

}


Java applet program to display image

This applet program displays an image on the applet viewer. The program declares an object of the Image class. Then the program calls the getImage() function to specify the image and drawImage() function to draw the image to the output screen. The image to be displayed must be stored in the same directory where the source code is stored. 


Program



//Applet program to display image

//<Applet code=ImageApplet height=400 width=400></Applet>

import java.awt.*;

import java.applet.*;

public class ImageApplet extends Applet

{

Image img;

public void paint(Graphics g)

{

img=getImage(getCodeBase(),"lotus.jpg");

g.drawImage(img,100,100,this);

}

}


Output


image applet in java
Applet program to display image

Java program to divide two numbers

This program divides two numbers in Java, using command line arguments. The dividend and divisor are read as input from the command line. The program uses a try catch statement to read the inputs and perform the division. The statement a=Integer.parseInt(s[0]); stores the first argument to the variable a and the statement b=Integer.parseInt(s[1]); stores the second argument to the variable b. If the divisor is 0 the program will throw an ArithmeticException also if there is any problem in reading the arguments the program throws an ArrayIndexOutOfBoundsException. Otherwise the program prints the result of the division to the output screen. 

Program


 

 // command line arguments in java

// Java program to find the quotient 

// Use command line arguments find the quotient of two numbers

// Demonstrate divide by zero exception

class Quotient
{ public static void main(String s[]) throws Exception { int a,b,c; try { a=Integer.parseInt(s[0]); // getting data b=Integer.parseInt(s[1]); // from command line try { c=a/b; System.out.println("Quotient is "+c); } catch(ArithmeticException ex) { System.out.println("Error in division !"); } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array out of bound!"); } finally { System.out.println("End of the progarm!!!"); } } }


Output


java program to divide two numbers, command line

Java program to find the average of n numbers

This Java program finds the average on n numbers using command line arguments. The program uses a try catch statement to read the arguments form the command line. Each arguments are stored to the array a[] using a while loop. Then the program uses another while loop to calculate the sum of all the elements in the array a[] and it will be stored in the variable sum. The statement avg=sum/n; outside the while loop calculates the average and it will be displayed in the output screen.

Program



 //Java program to calculate the average of n numbers using  //command line arguments

import java.io.*; public class Average { public static void main(String s[]) throws Exception { int a[]=new int[10]; int i=0,n,sum=0,avg; n=s.length; try { while(i<n) { a[i]=Integer.parseInt(s[i]); //taking values from command line i++; } } catch(Exception e) { System.out.println("Error"); } n=i; i=0; while(i<n) { sum=sum+a[i]; i++; } avg=sum/n; System.out.println("Average is: "+avg); } }


Output


average command line n numbers java


Applet program to draw national flag

This applet program draws Indian national flag. The program uses four fillRect() function. The first one is used to draw the stand and the other three are used to draw the red, white and the green parts of the flag. The program uses a g.drawOval(); function to definer the border of the Ashoka Chakra. Then a for loop is used to draw the 24 spokes. The setColor(); function is used to specify the color to be used in the objects.

Program


// Draw national flag using Java applet program

//<applet code=Flag.class height=400 width=400></applet>

import java.applet.*;

import java.awt.*;

public class Flag extends Applet

{

public void paint(Graphics g)

{

Color c;

c=Color.black;

g.setColor(c);

g.fillRect(237,114,10,500);

c=Color.red;

g.setColor(c);

g.fillRect(248,125,200,25);

c=Color.white;

g.setColor(c);

g.fillRect(248,150,200,25);

c=Color.green;

g.setColor(c);

g.fillRect(248,175,200,25);

c=Color.blue;

g.setColor(c);

g.drawOval(342,149,25,25);
int l=0;
int x=355,y=162;
double x1,y1;
double d;

c=Color.black;

g.setColor(c);
for(int i=1;i<=24;i++)
{
d=(double)l*3.14/180.0;
x1=x+(double)10*Math.cos(d);
y1=y+(double)10*Math.sin(d);
g.drawLine(x,y,(int)x1,(int)y1);
l=l+(360/24);
}

}

}


Output


National flag drawing in applet
Applet program to draw national flag

C++ program to find the sum of elements in a matrix

This C++ program finds the sum of all elements in a matrix using pointer. The row and column values of the matrix are read into the variables m and n. Then the program uses for loop to read the elements to the matrix and at the same time the address of the first element of each row is read into the pointer array p[]. Then the program uses nested for loop to calculate the sum of elements row by row and stores it in the variable s. Then the sum is printed to the output screen.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
          int a[10][10],*p[10],m,n,i,j,s=0;
          cout<<"Enter the order of matrics: ";
          cin>>m>>n;
          cout<<"\nEnter the elements\n\n";
          for(i=0;i<m;i++)
          {
                   p[i]=&a[i][0];
                   for(j=0;j<n;j++)
                   {
                             cin>>a[i][j];
                   }
          }
          for(i=0;i<m;i++)
          {
                   for(j=0;j<n;j++)
                   {
                             s=s+*(p[i]+j);
                   }
          }
          cout<<"\nSum of elements: ";
          cout<<s;   

          getch();
}

C++ program to sort n strings

 This C++ program sorts n strings using pointer. The value for n is read as input and the strings are read into the 2D character array a[][]. A pointer array p[] is declared to store the address of each element in the array a[][]. Then the program uses nested for loop to sort the strings. Here strcmp() function is used to compare each strings and strcpy() function is used to copy the strings from one location to another.After sorting is completed, the program displays the sorted strings to the output screen.

Program


#include<iostream.h>

#include<conio.h>

#include<string.h>

void main()

{

          char a[10][20],*p[10],temp[20];

          int n,i,j;

          cout<<"Enter the value for n: ";

          cin>>n;

          cout<<"\nEnter the strings:\n\n";

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

          {

                   cin>>a[i];

                   p[i]=a[i];

          }

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

                   {

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



                             {

                                      if(strcmp(p[j],p[j+1])>0)

                                                {

                                                          strcpy(temp,p[j]);

                                                          strcpy(p[j],p[j+1]);

                                                          strcpy(p[j+1],temp);

                                                }

                             }

                    }

                   cout<<"Strings after sorting: \n";

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

                   {

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

                   }

          getch();

}

C++ program to sort an array using bubble sort

This program implements bubble sort in C++.  Bubble sort iterates through the array by considering each pair of elements and swapping them if it is not in the sorted order. This procedure repeats until the entire array is sorted. The program reads the limit of the array into the variable n. The elements are read one by one into the array a[]. Then the program uses a nested for loop to perform bubble sort. After sorting is completed the new array is displayed to the output screen.


Program


// bubble sorting in c
#include<iostream.h>
#include<conio.h>
void main()
{
          int a[10],i,n,j,temp,*p;
          clrscr();
          cout<<"Enter the limit: ";
          cin>>n;
          cout<<"\nEnter the "<<n<<" array elements\n\n";
          for(i=0;i<n;i++)
          {
                   cin>>a[i];
          }
          p=a;
          for(i=0;i<n;i++)
          {
                   for(j=0;j<n-1-i;j++)
                   {
                             if(*(p+j)>*(p+j+1))
                             {
                                      temp=*(p+j);
                                      *(p+j)=*(p+j+1);
                                      *(p+j+1)=temp;
                             }
                   }
          }
          cout<<"\nsorted array is as follows\n\n";
          for(i=0;i<n;i++)
          {
                   cout<<a[i]<<" ";
          }
          getch();
}



bubble sort in c++
C++ program for bubble sort












Related post: Bubble sort in c

C++ program to demonstrate binary search

This program implements binary search in C++.  Binary search requires that the array be sorted in either ascending or descending order. The algorithm then compares the middle element in the array with the item to be searched, if a match is found its position is returned. Otherwise if the item to be searched is less than the middle element, the algorithm proceeds with the elements which are on the left side of the middle element, or if the item to be searched is greater than the middle element, the algorithm proceeds with the elements which comes after the middle element.  



Program



#include<iostream.h>
#include<conio.h>
void main()
{
          clrscr();
          int a[50],*p,n,ele,i,beg=0,end,mid;
          cout<<"Enter the no.of elements:";
          cin>>n;
          cout<<"\nEnter the elements in ascending order:";
          for(i=0;i<n;i++)
          {
                   cin>>a[i];
          }
          cout<<"\nEnter the element to be searched:";
          cin>>ele;
          beg=0,end=n-1;
          while(beg<=end)
          {
                   mid=(beg+end)/2;
                   p=&a[mid];
                   if(*p==ele)break;
                   else if(ele>*p) beg=mid+1;
                   else end=mid-1;
          }
          if(beg<=end)
          cout<<"\nThe element "<<ele<<" found at position "<<mid+1;
          else
          cout<<"\nnot found";
          getch();
}



Binary search program in C++
Binary Search in C++

C++ program to find the even and odd elements from a matrix

 This C++ program finds the even and odd elements in a matrix. The program uses two arrays even[] and odd[] to store the even and odd elements respectively.  The row and column values of the matrix are read into the variables m and n.  Then the program uses a nested for loop to read the elements one by one into the array a[][], at the same time the address of the first element of each row is stored in the pointer array p[]. Next the program uses modulo operator in the for loop to check each element and stores the even elements in the array even[] and odd elements in the array odd[].


Program


// Matrix even and odd elements c++ program
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],*p[10],m,n,i,j,k=0,l=0,even[20],odd[20];
cout<<"Enter the order of matrics: ";
cin>>m>>n;
cout<<"\n\nEnter the elements\n\n";
for(i=0;i<m;i++)
{
p[i]=&a[i][0];
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(*(p[i]+j)%2==0)
{
even[k]=*(p[i]+j);
k++;
}
else
{
odd[l]=*(p[i]+j);
l++;
}
}
}      
cout<<"\nEven elements\n\n";
for(i=0;i<k;i++)
cout<<even[i]<<" ";
cout<<"\n\nOdd elements\n\n";
for(i=0;i<l;i++)
cout<<odd[i]<<" ";getch();
}


C++ program to find the transpose of a matrix and check whether it is symmetric or not

This C++ program finds the transpose of a matrix and checks whether it is symmetric or not. A matrix is symmetric if  both the matrix and its transpose are equal. The program reads the row and column values of the matrix into the variable m and n. Then the elements are read one by one into the 2D array a[][] using a nested for loop and at the same time the address of the first element of each row is stored to the pointer array p[]. Then the transpose of the matrix a[][] is found and stored in the array b[][]. Next the elements of the arrays a[][] and b[][] are compared to find any dissimilarity. If there is any dissimilarity, the matrix is not symmetric, otherwise the matrix is symmetric.  

Program


#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[10][10],b[10][10],f=0,*p1[10],*p2[10],m,n,r,c,i,j;
cout<<"Enter the order of matrics: ";
cin>>m>>n;
cout<<"\n\nEnter the elements\n\n";
for(i=0;i<m;i++)
{
p1[i]=&a[i][0];
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
r=m;r
c=n;
for(i=0;i<c;i++)
{
p2[i]=&b[i][0];
for(j=0;j<r;j++)
{
b[i][j]=*(p1[j]+i);
}
}
cout<<"\n\nTranspose Matrics\n\n";
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
cout<<b[i][j]<<"\t";
}
cout<<"\n";        
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if((*(*(a+i)+j))!=(*(*(b+i)+j)))
{
f=1;
break;
}
}
}
if(f==0)
{
cout<<"\n\nThe matrix is symmetric";
}
else
cout<<"\n\nThe matrix is not symmetric";
getch();
}


Transpose of a sparse matrix and check whether it is symmetric in c++
Transpose of a matrix in c++















C++ program to find the sum of diagonal elements of a matrix

This C++ program finds the sum of the diagonal elements of a matrix. The row and column values of the matrix are read into the variables m and n. Then the elements are read one by one into the 2D array a[][] using a nested for loop, at the same time the address of the first element in each row is stored to the pointer array p[]. Then the program uses for loop to find the sum of the first and second diagonal elements and the result is displayed to the output screen. 

Program


//matrix diagonal elements sum c++
#include<iostream.h>
#include<conio.h>
void main()
{
          int a[10][10],*p[10];
          int m,n,i,j,s1=0,s2=0,t;
          cout<<"Enter the order of matrics: ";
          cin>>m>>n;
          cout<<"Enter the elements\n\n";
          for(i=0;i<m;i++)
          {
                   p[i]=&a[i][0];
                   for(j=0;j<n;j++)
                   {
                             cin>>a[i][j];
                   }
          }
          cout<<"\n\nFirst diagonal elements are\n\n";
          for(i=0;i<n;i++)
          {
                   cout<<*(p[i]+i)<<"\t";
                   s1=s1+*(p[i]+i);
          }
          cout<<"\n\nSecond diagonal elements are\n\n";
          t=n;
          for(i=0;i<n;i++)
          {
                   cout<<*(p[t-1]+i)<<"\t";
                   s2=s2+*(p[t-1]+i);
                   t--;
          }
          cout<<"\n\nSum of first diagonal elements is: ";
          cout<<s1;
          cout<<"\n\nSum of second diagonal elements is: ";
          cout<<s2;
          getch();

}


 

C++ program to find the largest and smallest element in a matrix

This C++ program finds the largest and smallest element in a matrix using pointers. The row and column values of the matrix are read into the variables m and n. Then the program uses nested for loop to read the values to the 2D array a[][] and also the address of the first element of each row is stored in the pointer array p[]. The variables l and s is initially set with the value at a[0][0], these variables are used to store the largest and smallest element. Then the program uses another nested for loop to check in each row for the largest and smallest element and stores it in the variables l and s. Then the value of l and s is displayed to the output screen.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
          int a[10][10],*p[10],m,n,i,j,s,l;
          cout<<"Enter the order of matrics: ";
          cin>>m>>n;
          cout<<"Enter the elements\n\n";
          for(i=0;i<m;i++)
          {
                   p[i]=&a[i][0];
                   for(j=0;j<n;j++)
                   {
                             cin>>a[i][j];
                   }
          }
          l=a[0][0];
          s=a[0][0];
          for(i=0;i<m;i++)
          {
                   for(j=0;j<n;j++)
                   {
                             if(*(p[i]+j)>l)
                             l=*(p[i]+j);
                             if(*(p[i]+j)<s)
                             s=*(p[i]+j);
                   }
          }
          cout<<"\nLargest element is: ";
          cout<<l;
          cout<<"\nSmallest element is: ";
          cout<<s;
          getch();
}

C++ program to sort elements in a matrix

This C++ program sorts the elements of a 2D matrix row by row using pointer. The row and column values of the matrix are read into the variables m and n. Then the program uses nested for loop to read the elements to the matrix a[][] using pointers, also each elements are stored into the pointer array p[]. The elements in the pointer array is sorted and the new array is written to the original 2D array a[][] overwriting the existing elements. Then the sorted 2D array is displayed to the output screen.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
          int a[20][20],i,j,m,n,*p[10],temp,b[20],s,*p1;
          p1=b;
          clrscr();
          cout<<"\n\nEnter the order of the matrix: ";
          cin>>m>>n;
          s=0;
          cout<<"\nEnter the elements:";
          for(i=0;i<m;i++)
          {
                   for(j=0;j<n;j++)
                   {
                             cin>>*(*(a+i)+j);
                             p[i]=(*(a+i)+j);
                             p1[s]=*(*(a+i)+j);
                             s++;
                   }
          }
          for(i=0;i<s;i++)
          {
                   for(j=i+1;j<s;j++)
                   {
                             if(p1[i]>p1[j])
                             {
                                      temp=p1[i];
                                      p1[i]=p1[j];
                                      p1[j]=temp;
                             }
                   }
          }
          s=0;
          for(i=0;i<m;i++)
          {
                   for(j=0;j<n;j++)
                   {
                             *(*(a+i)+j)=p1[s];
                             s++;
                   }
          }
          cout<<"\nMatrics after sorting:";
          for(i=0;i<m;i++)
          {
                   cout<<"\n\n";
                   for(j=0;j<n;j++)
                   {
                             cout<<*(*(a+i)+j)<<"\t";
                   }
          }
          getch();
}

Void and NULL pointer C progarm

This program demonstrates void pointer and null pointer in C. A pointer is a variable which stores the address of another variable. A null pointer does not point to anything and a void pointer can be used to point to a variable of any data type. In the program p is the null pointer and p1 is the void pointer, p is assigned with the value NULL and p1 is assigned with the address of the variable a, which is of integer data type. The statement (int *)p1; is to indicate that p1 refers to an integer data type.
 

Program


//C program to show the working of Void pointer and NULL pointer

#include<iostream.h> #include<conio.h> void main() { int *p=NULL,a; void *p1; cout<<"Enter the value for a"; cin>>a; p=&a; cout<<"Value of null pointer= "<<p; cout<<"Value of void pointer="<<(int *)p1; getch(); }

C++ program to implement linear search

This C++ program implements linear search. In this method all the elements in the list will be checked in a sequential order, to check for a match with the element to be searched. If a match is found the iteration will be stopped and the element will be returned with its position. The program reads the size of the array in the variable n, then the elements are read into the array a[] by using a for loop. Next the element to be searched is read into the variable elem. Then the program uses a for loop to check all the elements in the array with the value of elem to find a match. 

 

Program


#include<iostream.h>
#include<conio.h>
void main()
{
          int a[50],f=0,elem,*p,i,n;
          cout<<"Enter the size of the array: ";
          cin>>n;
          p=a;
          cout<<"Enter the elements: ";
          for(i=0;i<n;i++)
          {
                   cin>>a[i];
          }
          cout<<"Enter the element to be searched: ";
          cin>>elem;
          for(i=0;i<n;i++)
          {
                   if(*p==elem)
                             {
                             cout<<"\nItem Found at position "<<i+1;
                             f=1;
                             break;
                             }
                   p++;
          }
          if(f==0)
          cout<<"\nItem not found";
          getch();
}


C++ program for linear search
Linear search in C++

C++ program to delete an element from an array

This C++ program deletes an element from an array. The size of the array is read as input into the variable n. Then the elements are read into the array a[] using a for loop.  Then the position of the element to be deleted is read into the variable pos. The elements which lies after the element to be deleted is shifted one position backward, overwriting the element to be deleted. Then the new array is displayed to the output screen.


Program


//Delete element from array c++ program

#include<iostream.h>
#include<conio.h>
void main()
{
          int a[50],n,i,*p,pos;
          cout<<"Enter the value for n: ";
          cin>>n;
          cout<<"\nEnter the elements\n";
          for(i=0;i<n;i++)
          {
                   cin>>a[i];
          }
          cout<<"\nEnter the position of element to delete: ";
          cin>>pos;
          p=&a[pos];

          for(i=pos;i<n;i++)
          {
                   *(p)=*(p+1);
                   p++;
          }
          p=a;
          cout<<"\nArray after deletion\n\n";
          for(i=0;i<n-1;i++)
          {
                   cout<<*(p+i)<<"\t";
          }
          getch();
}



Delete an element from an array C++ progarm
C++ - delete an element from an array

C++ program to insert an element to an array

This c++ program inserts an element into an array in a given position. The variable n reads the limit of the array. Then the numbers are read one by one into the array a[]. Next the element to be inserted and the position of insertion is read to the variables elem and pos. Then the program uses a for loop to make space of the new element in the array and the new element is inserted into the given position and the new array is displayed to the output screen.   


Program


#include<iostream.h>
#include<conio.h>
void main()
{
          int a[50],n,i,*p,pos,elem;
          cout<<"Enter the value for n: ";
          cin>>n;
          cout<<"\nEnter the elements\n";
          for(i=0;i<n;i++)
          {
                   cin>>a[i];
          }
          cout<<"\nEnter the element and position to insert: ";
          cin>>elem>>pos;
          p=&a[n];
          for(i=n;i>pos;i--)
          {
                   *(p)=*(p-1);
                   p--;
          }
          a[pos]=elem;
          p=a;
          cout<<"\nArray after insertion\n\n";
          for(i=0;i<=n;i++)
          {
                   cout<<*(p+i)<<"\t";
          }
          getch();
}


Insert an element to an array in c++
C++: Insert an element into an array

C++ program to swap 2 arrays

This C++ program swaps two integer arrays using pointers. Two arrays a[] and b[] are declared which stores the two input arrays. The pointers p1 and p2 is initially set to point to the first index of both the arrays a[] and b[]. Then the program uses a for loop to swap values in the two arrays. After swapping is complected the new arrays are displayed to the output screen.


Program



//program to swap array's using c++

#include<iostream.h>
#include<conio.h>
void main()
{
int *p1,*p2,a[50],b[50],n1,n2,i=0,t;
cout<<"Enter the size of first array: ";
cin>>n1;
p1=a;
cout<<"Enter the elements:\n";
for(i=0;i<n1;i++)
{

cin>>a[i];
}
cout<<"Enter the size of second array: ";
cin>>n2;
p2=b;
cout<<"Enter the elements:\n";
for(i=0;i<n2;i++)
{
cin>>b[i];
}
for(i=0;i<n1|i<n2;i++)
{
t=*p1;
*p1=*p2;
*p2=t;
p1++;
p2++;
}
p1=a;
p2=b;
cout<<"Arrays after swapping\n";
cout<<"Array A\n";
for(i=0;i<n2;i++)
{
cout<<*p1<<" ";
p1++;
}
cout<<"Array B\n";
for(i=0;i<n1;i++)
{
cout<<*p2<<" ";
p2++;
}
getch();
}

Output



program in c++ to swap arrays
C++ program to swap two arrays

C++ Program to find the cube of a number using void pointer

This program finds the cube of a number in C++. The number is read as input and is stored is the variable n. The program uses a void pointer which points to n.  The statement int *pint= (int *)p; stores the value at p to the pointer variable pint. Then the program repeatedly multiples pint 3 times which gives the cube of the given number.



Program



#include<iostream.h>



#include<conio.h>



void main()



{



          int n;



          void *p;



          p=&n;



          cout<<"Enter the number";



          cin>>n;



          int *pint= (int *)p;



          n=(*pint)*(*pint)*(*pint);



          cout<<"Cube of the number is\n";



          cout<<n;



          getch();



}


C program to sort using quick sort

This program implements quick sort in C.  Quick sort is also known as partition exchange sort. In the best case quick sort makes O(n log n) comparisons and in the worst case it makes O(n2) comparisons. This algorithm selects a random number from the list as a pivot element, all the elements which are smaller than the pivot element will be shifted to the left of the pivot element and all the elements which are greater than the pivot element will be shifted to the right of the pivot element. Now the pivot element is in its final position, the algorithm repeatedly applies the above technique to the left part and the right part until the list is sorted.

 Program


//c program for sorting using quick sort
#include<stdio.h>
#include<conio.h>
int partition(int a[],int l,int r);
void quicksort(int a[],int l,int r);
void main()
{
int a[10],n,i,j,l,r,pivot;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
a[n]=1000;
l=0;
r=n;
quicksort(a,l,r);
printf("Array after sorting\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
void quicksort(int a[10],int l,int r)
{
int pivot1;
if(l<r)
{
pivot1=partition(a,l,(r+1));
quicksort(a,l,pivot1-1);
quicksort(a,pivot1+1,r);
}
}
int partition(int a[10],int l,int r)
{
int i,j;
int pivot,t;
i=l+1;
j=r-1;
pivot=a[l];
do
{
while((a[i]<=pivot)&&(i<=r))
i++;
while((a[j]>pivot)&&(j>l))
j--;
if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}}
while(i<=j);
t=a[l];
a[l]=a[j];
a[j]=t;
return j;
}

Output


Quick sort program in c
Quick Sort

C program to sort using merge sort

This program demonstrates merge sort in C.  Merge sort is based on divide and conquer algorithm. In the best case merge sort makes O(n log n) or O(n) comparisons and in the worst case is makes O(n log n) comparisons. The first step in merge sort is to divide the input list into sub lists which contains only one element. Then the algorithm repeatedly merges the sub lists into sorted list until there is only one list. Merge sort can be either bottom up or top down implementation.


Program



//Merge Sort c progarm 

#include<stdio.h>

#include<conio.h>

#include<math.h>

void mergesort(int a[],int p,int q);

void merge(int a[],int p,int q,int r);

void main()

{

int n,a[10],i;

printf("Enter the size of the array: ");

scanf("%d",&n);

printf("Enter the elements\n");

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

scanf("%d",&a[i]);

mergesort(a,0,n-1);

printf("Array after sorting\n");

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

printf("%d ",a[i]);

getch();

}

void mergesort(int a[10],int p,int r)

{

int mid;

if(p<r)

{

mid=(floor(p+r))/2;

mergesort(a,p,mid);

mergesort(a,mid+1,r);

merge(a,p,mid,r);

}

}

void merge(int a[10],int p,int q,int r)

{

int i=p,j=q+1,k=p,b[10];

while((i<=q)&&(j<=r))

{

if(a[i]<=a[j])

b[k++]=a[i++];

else

b[k++]=a[j++];

}

while(i<=q)

b[k++]=a[i++];

while(j<=r)

b[k++]=a[j++];

for(k=p;k<=r;k++)

a[k]=b[k];

}


Output


c program for merge sort
Merge Sort

C Program to sort using insertion sort

This program demonstrates insertion sort in C. Insertion sort  proceeds by considering each item in the list and placing it in the position it belongs to in the sorted list. Other elements will be shifted either to the left or to the right in order to make space for the current element. Insertion sort is only efficient for smaller lists and cannot be used in larger lists since the complexity will be high. In the best case insertion sort has a time complexity of O(n) and in the worst case, the time complexity is O(n2).

Program


#include<stdio.h>

#include<conio.h>

void main()

{

int a[10],small,n,i,j;

printf("Enter the size of the array: ");

scanf("%d",&n);

printf("Enter the elements: \n");

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

scanf("%d",&a[i]);

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

{

small=a[i];

j=i-1;

while(j>=0&a[j]>small)

{

a[j+1]=a[j];

j--;

}

a[j+1]=small;

}

printf("\nArray after sorting\n");

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

printf(" %d",a[i]);

getch();

}


Output


Insertion sort program in c
Insertion Sort











Related post:-  C++ program to implement insertion sort

C program to sort using selection sort

This program demonstrates selection sort in C. The time complexity of selection sort is O(n2). The advantage of selection sort is its simplicity and the disadvantage is that it is more time consuming when sorting large arrays. Selection sort finds smallest element in a list and replaces it with the left most element. This procedure will be repeated till the whole list is sorted.

Program


//Implementation of selection sort program in c

#include<stdio.h>

#include<conio.h>

void main()

{

int a[25],i,j,n,small,t;

printf("Enter the size of the array\n");

scanf("%d",&n);

printf("Enter the elements\n");

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

scanf("%d",&a[i]);

for(i=0;i<n;i++)                   //Selection sort starts here.

{

    small=a[i];

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

    {

        if(a[j]<small)

        {

            small=a[j];

            t=a[i];

            a[i]=small;

            a[j]=t;

        }

    }

}

printf("Array after selection sort\n");

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

{

printf("%d ",a[i]);

}

getch();

}


Output

C program for selection sort
Selection sort

c program to find the length of a string without using strlen

This program finds the length of a string without using strlen() function. strlen() is a built in function available in c, which returns the length of a string. The program reads a string and stores it in the character array a[]. By default a character array stores a '/0' at the end, which marks the end of string. The while loop uses loop variable i, which is initially set to 0. At each iteration in the while loop the value of count is incremented. The loop continues until, the value of a[i] equals '/0'.

Program



#include<stdio.h>

#include<conio.h>

void main()

{

clrscr();

int count=0,i=0;

char a[10];

printf("Enter the string");

scanf("%s",&a);

while(a[i]!='\0')

{

count++;i++;

}

printf("%d",i);

getch();

}


Output

Length of a string without using strlen
c program to find the length of a string without using strlen


C++ program to swap 2d character array

This program swaps two 2d character arrays.  The limit of the two arrays are read to the variables n1 and n2. Then the program reads the strings one by one to both arrays. After reading the strings the program swaps the two arrays using a for loop and a while loop. The program uses strcpy() function to copy the string from one location to other.

Program



// Program to swap two dimensional character arrays
#include<iostream.h> #include<conio.h> #include<string.h> void main() { char a[5][10],b[5][10],t[10]; int i,j,n1,n2; cout<<"Enter the value for n1: "; cin>>n1; cout<<"Enter the value for n2: " ; cin>>n2; cout<<"Enter the strings to first array"; for(i=0;i<n1;i++) cin>>a[i]; cout<<"Enter the strings to second array"; for(i=0;i<n2;i++) cin>>b[i]; for(i=0;i<n1&&n2;i++) { strcpy(t,a[i]); strcpy(a[i],b[i]); strcpy(b[i],t); } if(i==n1) { while(i<n2) { strcpy(a[i],b[i]); i++; } } else { while(i<n1) { strcpy(b[i],a[i]); i++; } } cout<<"\nArrays after swapping\n"; cout<<"\nArray 1\n"; for(i=0;i<n2;i++) cout<<"\n"<<a[i]; cout<<"\nArray 2\n"; for(i=0;i<n1;i++) cout<<"\n"<<b[i]; getch(); }

C++ Program to demonstrate virtual function working

This program demonstrates virtual function in c++. When there exist two functions with same function name in both base and derived class the compiler identifies which function to use at run time based on the type of object pointed to by base pointer. The run time polymorphism in c++ is achieved through virtual functions.

Program


 //Run time polymorphism

#include<iostream.h>

#include<conio.h>

class base

{

public:

void display()

{

cout<<"\nDisplay Base";

}

virtual void show()

{

cout<<"\nShow Base";

}

};

class derived:public base

{

public:

void display()

{

cout<<"\nDisplay Derived";

}

void show()

{

cout<<"\nShow Derived";

}

};

void main()

{

base *bptr;

base b;

bptr=&b;

bptr->display();

bptr->show();

derived d;

bptr=&d;

bptr->display();

bptr->show();

getch();

}


Output



Display Base
Show Base
Display Base
Show Derived

C program to find the transpose of a sparse matrix

This program finds the transpose of a sparse matrix in c. A sparse matrix is a matrix where majority of its elements are 0. A sparse matrix can be represented by using 3 tuple method to avoid memory wastage. This program reads a matrix as input and finds its 3  tuple representation. Then the program finds the transpose of this sparse matrix.

Program


//program to find the transpose of a sparse matrix

#include<stdio.h>

#include<conio.h>

void main()

{

int m,p,n,i,j,k,t=0,l,a[10][10],s[10][10],st[10][10];

printf("Enter the size of the orginal array");

scanf("%d%d",&m,&n);

printf("\nEnter the array elements\n");

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

{

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

{

scanf("%d",&a[i][j]);

}

}

k=1;

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

{

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

{

if(a[i][j]!=0)

{

s[k][0]=i;

s[k][1]=j;

s[k][2]=a[i][j];

k++;

if(j>t)

t=j;

}

}

}

s[0][0]=m;

s[0][1]=n;

s[0][2]=k-1;

printf("3 tuple representation of the given matrix is\n");

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

{

printf("\n");

for(j=0;j<3;j++)

{

printf(" %d",s[i][j]);

}

}

p=1;

l=k-1;

printf("\nt= %d, l= %d",t,l);

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

{

k=1;

for(j=0;j<l;j++)

{

if(s[k][1]==i)

{

st[p][1]=s[k][0];

st[p][0]=s[k][1];

st[p][2]=s[k][2];

p++;

k++;

}

else

k++;

}

}

st[0][0]=s[0][1];

st[0][1]=s[0][0];

st[0][2]=s[0][2];

printf("\nTranspose of the sparse matrix is\n");

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

{

printf("\n");

for(j=0;j<3;j++)

{

printf(" %d",st[i][j]);

}

}

getch();

}



C++ program to demonstrate unary operator overloading

This program demonstrate unary minus overloading in c. The value of x is read as input in the function getdata() and the putdata() function is used to display the value of x. The function void operator -() performs the overloading, which changes the sign of x to negative. In the main function, the statement a.getdata(); calls the function getdata() and the statement a.putdata(); calls the function putdata(). The statement -a; calls the function void operator -(), which overloads the unary minus operator. The statement a.putdata(); after the statement cout<<"\nAfter Overloading value of x="; prints the negative value of x.

Program

//program to overload unary operator -

#include<iostream.h>

#include<conio.h>

class overld

{

int x;

public:

void getdata()

{

cout<<"Enter the value for x";

cin>>x;

}

void putdata()

{

cout<<x;

}

void operator -()

{

x=-x;

}

};

void main()

{

overld a;

a.getdata();

cout<<"\nBefore Overloading value of x=";

a.putdata();

-a;

cout<<"\nAfter Overloading value of x=";

a.putdata();

getch();

}

C++ program to demonstrate file operations

This program demonstrates file operations in c++. The program reads as input five names and stores it in a file named sample.txt using the out statement, then the file is closed. Next the program reads a new name to be searched in the file and stores it in the variable name. Then the program program compares each name in the file with the value stored in the variable name, if there is a match the string is found in the file. Otherwise the string is not present in the file.


Program


//c++ program to check whether a particular word is present in the file

#include<iostream.h>

#include<conio.h>

#include<fstream.h>

#include<string.h>

#include<process.h>

void main()

{

int i;

char name[20],t[20];

ofstream out;

out.open("sample1.txt");

cout<<"Enter five names\n\n";

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

{

cin>>name;

out<<name<<"\n";

}

out.close();

cout<<"Enter the name to be searched for";

cin>>name;

ifstream in;

in.open("sample1.txt");

while(in)

{

in.seekg(2,ios::beg);

in>>t;

cout<<"\n"<<t;

}

in.close();

in.open("sample1.txt");

while(in)

{

in>>t;

if(strcmp(name,t)==0)

{

cout<<"\nString found!!!";

getch();

in.close();

exit(0);

}

}

cout<<"\nString not found!!!";

in.close();

getch();

}





C program to implement interpolation search

This program implements interpolation search in c. Interpolation search makes log(log(n)) comparisons on average and O(n) comparisons in the worst case.Where  'n' is the number of elements to be searched. Interpolation search is used to search for a key value in an indexed array ordered by the values of the key.

Program


#include<stdio.h>

#include<conio.h>

void main()

{

int a[25],n,mid,low,high,f=0,item,i;

printf("Enter the size of the array");

scanf("%d",&n);

printf("Enter the elements in sorted order");

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

{

scanf("%d",&a[i]);

}

printf("Enter the item to be searched for");

scanf("%d",&item);

low=0;

high=n-1;

while(low<=high)

{

mid=(low+(high-low)*((item-a[low])/(a[high]-a[low])));

if(a[mid]==item)

{

printf("\n\nItem found at position %d",mid);

f=1;

break;

}

else if(a[mid]>item)

{

high=mid-1;

}

else

{

low=mid+1;

}}

if(f==0)

printf("\n\nItem not found in the array");

getch();

}

C Program to implement linked queue

This program implements linked queue in c. A linked queue uses linked list to insert and delete elements. A queue is a data structure where new items are entered on the rear and are removed form from the front. The advantage of linked queue is that the items need no be in contiguous memory locations. This program implements enqueue, dequeue and display operations of a linked queue. The terms enqueue and dequeue represents insertion and deletion operations respectively.


Program


//Demonstration of linked queue

#include<stdio.h>

#include<conio.h>

struct node

{

int data;

struct node *next;

}*f=NULL,*r=NULL,*p;

void main()

{

int ch,item;

printf("\n1.Enqueue\n2.Dequeue\n3.Display\n4.Exit ");

scanf("%d",&ch);

while(ch!=4)

{

switch(ch)

{

case 1:

printf("\nEnter the data to be inseted ");

scanf("%d",&item);

p=(struct node *)malloc(sizeof(struct node));

if(r==NULL)

{

f=p;

r=p;

p->data=item;

p->next=NULL;

break;

}

p->data=item;

p->next=NULL;

r->next=p;

r=p;

break;

case 2:

if(r==NULL&&f==NULL)

{

printf("\nQueue is empty\n");

break;

}

if(f->next==NULL&&r->next==NULL)

{

free(f);

f=NULL;

r=NULL;

}

p=f;

f=f->next;

free(p);

break;

case 3:

if(f==NULL&&r==NULL)

{

printf("\nQueue is Empty\n");

break;

}

p=f;

while(p!=NULL)

{

printf("%d->",p->data);

p=p->next;

}

break;

}

printf("\n1.Enqueue\n2.Dequeue\n3.Display\n4.Exit ");

scanf("%d",&ch);

}

}


C Program to implement linked stack

This program implements linked stack in c. A linked stack uses linked list to insert and delete elements in Last In First Out (LIFO) order. The items are entered and deleted form the top of the stack. The advantage of linked stack is that the items need not be entered in contiguous memory locations. This program implements push, pop and display operations in a linked stack. The stack uses the terms push and pop to denote insertion and deletion operation respectively.


Program


//Linked Stack
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
}*top=NULL,*p;
void main()
{
int ch,item;
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
scanf("%d",&ch);
while(ch!=4)
{
switch(ch)
{
case 1:
printf("\nEnter the data to be inserted ");
scanf("%d",&item);
p=(struct node *)malloc(sizeof(struct node));
p->data=item;
p->next=top;
top=p;
break;
case 2:
if(top==NULL)
{
printf("\nStack is empty!!!\n");
}
else
{
p=top;
top=top->next;
free(p);
}
break;
case 3:
p=top;
if(p==NULL)
{
printf("Stack is empty!!!");
break;
}
printf("Stack Now is..\n\n");
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
break;
}
printf("\n\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
scanf("%d",&ch);
}
}

C Program to implement singly linked list

This program implements linked list in c.  A linked list is a collection of nodes. Each node contains a data part and a pointer to the next node.The advantage of linked list is that the data items need not be stored in contiguous locations in the memory. This program implements insertion, deletion and display of a linked list.

Program


#include<stdio.h>

#include<conio.h>

struct node

{

    int data;

    struct node *next;

}*start=NULL,*p,*traverse,*temp;

void main()

{

    int ch,item;

    printf("1.Insert Begin\n2.Insert after\n3.Delete Begin");

    printf("\n4.Delete after\n5.Display\n6.Exit\nEnter Your Choice");

    scanf("%d",&ch);

    while(ch!=6)

    {

    switch(ch)

    {

        case 1:

        p=(struct node*)malloc(sizeof(struct node));

        printf("Enter the data\n");

        scanf("%d",&item);

        p->data=item;

        p->next=start;

        start=p;

        break;

        case 2:

        printf("Insert after which item\n");

        scanf("%d",&item);

        traverse=start;

        while(traverse->data!=item)

        traverse=traverse->next;

        temp=traverse->next;

        p=(struct node*)malloc(sizeof(struct node));

        printf("Enter the data\n");

        scanf("%d",&item);

        p->data=item;

        traverse->next=p;

        p->next=temp;

        break;

        case 3:

        temp=start->next;

        free(start);

        start=temp;

        break;

        case 4:

        printf("Delete after which item");

        scanf("%d",&item);

        traverse=start;

        while(traverse->data!=item)

        traverse=traverse->next;

        p=traverse->next;

        temp=p->next;

        traverse->next=temp;

        free(p);

        break;

        case 5:

        traverse=start;

        printf("\nCurrent List is\n");

        while(traverse!=NULL)

        {

            printf("%d -> ",traverse->data);

            traverse=traverse->next;

        }

        break;

    }

    printf("\n\n1.Insert Begin\n2.Insert after\n3.Delete Begin");

    printf("\n4.Delete after\n5.Display\n6.Exit\nEnter Your Choice");

    scanf("%d",&ch);

    }

}