Search This Blog

Wednesday, 26 February 2014

setter and getter function in C++

/*
Setter means to set the values for the private member in a class.
Getter means to access them. 
*/


#include<iostream.h>
#include<conio.h>

class Student
{
  int roll;
  char *ch;

  public:
       void SetRoll(int roll)
       {
         this->roll=roll;
       }
       void SetName(char name[])
       {
         ch=name;
       }
       int GetRoll()
       {
         return roll;
       }
       char* GetName()
       {
         return ch;
       }
};

void main()
{
  Student s;
  s.SetRoll(21);
  s.SetName("sanjay kumar singh");
  cout<<"Roll no is :"<<s.GetRoll()<<" and Name is :"<<s.GetName();
  getch();
}

Output


Tuesday, 25 February 2014

counting number of vowels in a string in C++

program for checking number of vowels in a string

/*
  as we know that there is 5 vowels in our english alphabets.
  such as "a,e,i,o,u";
*/


#include<iostream.h>
#include<conio.h>
 int main()
  {
   char ch[25];
   int i,l=0;
   cout<<"Enter a string:\n";
   cin.getline(ch,25);
   for(i=0;ch[i]!='\0';i++)
   {
     //checking conditions for lower case only u can also implement for uppercase letters
     if(ch[i]=='a'||ch[i]=='e'||ch[i]=='i'||ch[i]=='o'||ch[i]=='u')
     {
       l++;
       cout<<"\nvowel is : "<<ch[i]<<" and its position is at : "<<i+1;
      }
   }
   cout<<"\n\nNumber of vowels are in the string is : "<<l;
   getch();
  }

Output


Monday, 24 February 2014

friend function in c++

/*
   friend function is a special member function which can access private members of a class.
  Syntax for such functions are : friend <return_type> <function_name>(Class_Name Object);
  Ex - friend int add(Number n);
*/


#include<iostream.h>
#include<conio.h>
class  base
{
    int val1,val2;
   public:
    void get()
    {
       cout<<"Enter two values:";
       cin>>val1>>val2;
    }
    friend float mean(base ob);
};
float mean(base ob)
{
   return float(ob.val1+ob.val2)/2;
}
void main()
{
    clrscr();
    base obj;
    obj.get();
    cout<<"\n Mean value is : "<<mean(obj);
    getch();
}

Output



types of functions in C++


Types of Member functions in C++

         1.Simple functions
         2.Static functions.
         3.Const functions.
        4.Inline Functions.
        5.Friend function.

Saturday, 22 February 2014

finding two largest numbers in an array

/*
   ar[]={1,3,2,6,3,7,8,4}
   1st largest value is : 8
   2nd largest value is:7
*/


#include<iostream.h>
#include<conio.h>

void main()
{
  int n[10],i,max1,max2;
  cout<<"Enter the array elements:";
  for(i=0;i<5;i++)
    cin>>n[i];
  cout<<"Entered array is:";
  for(i=0;i<5;i++)
    cout<<n[i]<<"\t";
  max1=n[0];
  for(i=0;i<5;i++)
  {
    if(max1<n[i])
    max1=n[i];
  }
  cout<<"\n\n1st Largest number is:"<<max1;

  for(i=0;i<5;i++)
  {
    if(max1==n[i])
    n[i]=0;
  }
  max2=n[0];
  for(i=0;i<5;i++)
  {
    if(max2<n[i])
    max2=n[i];
  }
  cout<<"\n\n2nd Largest number is:"<<max2;
  getch();
}

Output


pointer to pointer concept in C++

/*
 int a;
 int *ptr=&a  // contains the address of the variable a;
 int **ptr2=&ptr // contains the address of the pointer variable *ptr;  
*/


#include<iostream.h>
#include<conio.h>
void main()
{
    int a=2,*ptr,**dblptr;
    ptr=&a;
    dblptr=&ptr;
    cout<<"\nValue of a and address is :"<<*ptr<<"  "<<ptr;
    cout<<"\nValue of pointer to variable is and its value is:"<<dblptr<<"  "<<**dblptr;
    getch();

}

Output



Thursday, 20 February 2014

simple program of inheritance in C++

/*
  inheritance means inheriting properties from parent class by a child class .
*/


#include<iostream>
#include<conio.h>
           
class abc
{
   public: int a,b;

    void ab(int x,int y)
    {
       a=x;b=y;
       cout<<"\nvalues for a:"<<a<<" and b:"<<b;
    }

};

class derived:public abc
{
     public :
         void input()
         {
             int sum,mult;
             cout<<"\nSum of a + b :"<<(a+b);
             cout<<"\nMultiplication of a * b :"<<(a*b);
        }
};
void main()
{
    derived d;
    d.ab(3,7);
    d.input();
    getch();
}

Ouput

Wednesday, 19 February 2014

simple program to pass pointer to a function

//  pointer to function

/*
  pointer is a variable which stores the address of the another variable.
  ex - int a = 3;
         int *ptr = &a;
         here *ptr is a pointer variable whose value is 2 and contains address of the value 2. 
*/


#include<iostream.h>
#include<conio.h>

void add(int *a)
{
  int i,sum=0;
  for(i=1;i<=*a;i++)
     sum+=i;
     *a=sum;
}

void main()
{
    int n;
    cout<<"Enter the limit :";
    cin>>n;
    int temp=n;
    add(&n);
    cout<<"Sum from 0 to "<<temp<<" is : "<<n;

    getch();
}

Output

Enter the limit :10
Sum from 0 to 10 is : 55

Tuesday, 18 February 2014

understanding calling of variables

calling variables ...

#include<iostream.h>
#include<conio.h>

int a=2;   // global variable

void main()
{
int a=5;  //  local variable
cout<<"value is:"<<a<<endl;
cout<<"value of global variable is:"<<::a;
getch();
}

Output

value is:5
value of global variable is:2

Sunday, 16 February 2014

print characters using for loop in java

/*
   ASCII values Capital letters starts from 65 to 90
   Ex - A - 65
*/

package starslayout;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;

public class starTwentyOne 
{
    public static void main(String[] args) throws Exception
     {
        int n,j,i,k;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter limit of the levels of star : ");
        n=sc.nextInt();
        k=65+n;
         for(i=65;i<=k;i++)
         {
             for(j=65;j<=i;j++)
                 System.out.print((char)j);
             System.out.println();
         }
     }
}

Output

Enter limit of the levels of star : 
6
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
 

Saturday, 15 February 2014

print numbers in decreasing order

/*
  print numbers something like this
54321
5432
543
54
5
*/


package starslayout;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;

public class starEleven 
{
    public static void main(String[] args) throws Exception
    {
        int n,j,i,k;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter limit of the levels of star : ");
        n=sc.nextInt();
         for(i=1;i<=n;i++)
         {
             for(j=n;j>=i;j--)
                 System.out.print(j);
            
             System.out.println();
         }
    }
}

Output

Enter limit of the levels of star : 
5
54321
5432
543
54
5

multiple objects of a class in c++

 Default arguments in a function

/*
    illustrate the concept of the multiple objects of a single class.
    add(int a,int b=2,int c=1)
   means a has no default value but b and c have their default values. 
*/


#include<iostream.h>
#include<conio.h>

class Base
{
   public:
       void add(int,int,int);
};

void Base::add(int a,int b=2,int c=1)
{
  cout<<"\nSum is:"<<(a+b+c);
}
void main()
{
    Base b,b1,b2;
    b.add(2);    // means a=2 ,b=2,c=1
    b1.add(1,0,0);   // means  a=1,b=0,c=0
    b2.add(2,1);      //means a=2,b=1,c=1
    getch();
}

Output

Sum is:5
Sum is:1
Sum is:4


Friday, 14 February 2014

defining the member functions outside the class in c++


//defining member functions outside any class in c++

/*
  As we know that class contains both data members and member functions .
  both data and member functions can be defined outside the class also by using scope resolution operator.
*/


#include<iostream.h>
#include<conio.h>

class MyProgram
{
   int a,b,c;

   public:
         void input();
         void output();
};

void MyProgram::input()
         {
            cout<<"Enter the integer values for the variables:";
            cin>>a>>b>>c;
         }

void MyProgram:: output()
         {
            float avg;
            int sum;
            sum=a+b+c;
            avg=sum/3;
            cout<<"sum of entered no is:"<<sum<<endl;
            cout<<"Average is:"<<avg;
         }
void main()
{
   MyProgram mp;
   mp.input();
   mp.output();
   getch();
}

Output

Enter the integer values for the variables:4  4  6
sum of entered no is:14
Average is:6.0000

program of checking armstrong number in c++

// illustrate the concept of armstrong number in c++ 

/*
  Armstrong number means a number which equals to the sum of cubes of its digits.
  Example - 153 (1*1*1 + 5*5*5 +3*3*3)
*/


#include<iostream.h>
#include<conio.h>

void main()
{
 int n,rem,sum=0,temp;
 cout<<"Enter a number:";
 cin>>n;
 temp=n;
 while(n>0)
 {
   rem=n%10;
   sum=sum+rem*rem*rem;
   n=n/10;
 }
 if(temp==sum)
   cout<<"Entered number is a armstrong";
 else
 cout<<"Entered number is not armstrong";

 getch();
}

Output

Enter a number : 153
Entered number is a armstrong


Enter a number : 165
Entered number is not armstrong



Thursday, 13 February 2014

simple program of thread in java

Simple thread program 1

/* programming for thread  using Runnable Interface*/


package threads;

class SimpleThread implements Runnable
{
    public void run()
    {
        System.out.println("Thread implementing by  runnable interface... ");
    }
}
class Main
{
    public static void main(String[] args)
    {
        SimpleThread st=new SimpleThread();
        Thread t=new Thread(st);
        t.start();
       // t.start(); generates exception becuse previous thread is in runing state.
    }
}

Output

Thread implementing runnable interface... 

Simple thread program 2
/* programming for thread  using Thread Class*/


package threads;

class ThreadClass extends Thread
{
    public void run()
    {
        System.out.println("Thread inheriting process runs...");
    }
}
class Code
{
    public static void main(String[] args)
    {
        ThreadClass tc=new ThreadClass();
        tc.start();
    }
}

Output

Thread inheriting process runs...

Wednesday, 12 February 2014

get absolute path of file in java

/* using java.io package for finding the absolute path of any path  */


import java.io.*;

class getPathOfFile
{
    public static void main(String[] args)
    {
        try
        {
            File f=new File("NewFileCreate.txt");
            if(!f.exists())
            {
                f.createNewFile();
                System.out.println("New File created...");
                System.out.println("Its absolute path is : "+f.getAbsolutePath());
            }
            else
            {
                System.out.println("File already exists...");
            }
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Output


New File created...
Its absolute path is : E:\Java_NetBeans\PROGRAMMING\JavaIO\NewFileCreate.txt

Sunday, 9 February 2014

linear searching of data in an array in java

/* linear searching of data in an array  */


import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *
 * @author sanjay kumar singh
 */
public class Linear_Searching
{
     public static void main(String[] args)
     {
         try
         {
             int n,val,pos=0,i,flag=0;
             int []ar=new int[10];
             InputStreamReader ins=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(ins);
        System.out.println("Enter the total no of elements :");
        n=Integer.parseInt(br.readLine());
        System.out.println("Enter elements : ");
        for(i=0;i<n;i++)
        {
            ar[i]=Integer.parseInt(br.readLine());
        }
        System.out.println("Elements are :" );
        for(i=0;i<n;i++)
        {
            System.out.print(ar[i]+" ");
        }
        System.out.println("\n");
        System.out.println("Enter the element u want to search:");
        val=Integer.parseInt(br.readLine());
        for(i=0;i<n;i++)
        {
            if(ar[i]==val)
            {
                pos=i;
                flag=1;
                break;
            }
        }
        if(flag==1)
        {
            System.out.println("Element is found and its location is : "+(pos+1));
        }
        else
            System.out.println("Element not found");
            
         }
         catch(Exception e)
         {
             System.out.println(e.getMessage()); 
         }
     }
}

Output


Enter the total no of elements :
5
Enter elements : 
2
4
1
7
8
Elements are :
2 4 1 7 8 

Enter the element u want to search:
4
Element is found and its location is : 2

matrix multiplication in java

/* multiplication of two matrix is as follows :
 
    c[i][j] = a[i][k] * b[k][j] 

  */



import java.util.*;

class ArrayMulti
{
   public static void main(String[] args)
   {
       Scanner sc=new Scanner(System.in);
        int [][]ar1=new int[2][2];
        int [][]ar2=new int[2][2];
        int [][]ar3=new int[2][2];
       int i,j,k;
    
    //////first matrix
    
        System.out.println("Enter the elements of the matrix :");
        for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                 ar1[i][j]=sc.nextInt();
            }
        }
         System.out.println(" the elements of the matrix First are :");
         for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                 System.out.print(ar1[i][j]+" ");
            }
            System.out.println();
        }
         
        ///////////// 2nd matrix  
         
         System.out.println("Enter the elements of the second matrix :");
        for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                 ar2[i][j]=sc.nextInt();
            }
        }
         System.out.println(" the elements of the matrix second are :");
         for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                 System.out.print(ar2[i][j]+" ");
            }
            System.out.println();
        }
         
         ///// multiplication
         
       for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                ar3[i][j]=0;
                for(k=0;k<2;k++)
                 ar3[i][j]+=ar1[i][k]*ar2[k][j];
            }
        }
       
       /// display
       
       System.out.println("Multiplication of the matrix is : ");
        for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                 System.out.print(ar3[i][j]+"     ");
            }
            System.out.println();
        }
       
 }
}

Output


Enter the elements of the matrix :
4
1
2
4
 the elements of the matrix First are :
4 1 
2 4 
Enter the elements of the second matrix :
3
2
5
7
 the elements of the matrix second are :
3 2 
5 7 
Multiplication of the matrix is : 
17     15     
26     32 

Saturday, 8 February 2014

sum of n natural numbers using recursion in java

// program to illustrate recursion

/* Sum of N natural numbers 
    limit of  N numbers entered by the user.
    int sum=0; 
    for(i=1;i<=n;i++)
    sum = sum+i;
    cout<<sum;
*/


import java.io.*;

public class Recursion 
{

    public static int Sum(int n)
    {
        if(n==1)
            return 1;
        return n+Sum(n-1);
    }
    
    public static void main(String[] args) throws Exception
    {
        int n;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the limit of the natural no : ");
        n=Integer.parseInt(br.readLine());
        int total=Sum(n);
        System.out.println("Sum is : "+total);
    }
}

Output


Enter the limit of the natural no : 
10
Sum is : 55

Monday, 3 February 2014

addition of two matrix in java

/* program to illustrate the concept of addition of two user entered matrix */

/* c[i][j] = a[i][j] + b[i][j]  */


import java.util.*;

class ArrayAdditon
{
   public static void main(String[] args)
   {
       Scanner sc=new Scanner(System.in);
        int [][]ar1=new int[2][3];
        int [][]ar2=new int[2][3];
        int [][]ar3=new int[2][3];
       int i,j;
    
    //////first matrix
    
        System.out.println("Enter the elements of the matrix :");
        for(i=0;i<2;i++)
        {
            for(j=0;j<3;j++)
            {
                 ar1[i][j]=sc.nextInt();
            }
        }
         System.out.println(" the elements of the matrix First are :");
         for(i=0;i<2;i++)
        {
            for(j=0;j<3;j++)
            {
                 System.out.print(ar1[i][j]+" ");
            }
            System.out.println();
        }
         
        ///////////// 2nd matrix  
         
         System.out.println("Enter the elements of the second matrix :");
        for(i=0;i<2;i++)
        {
            for(j=0;j<3;j++)
            {
                 ar2[i][j]=sc.nextInt();
            }
        }
         System.out.println(" the elements of the matrix second are :");
         for(i=0;i<2;i++)
        {
            for(j=0;j<3;j++)
            {
                 System.out.print(ar2[i][j]+" ");
            }
            System.out.println();
        }
         
         ///// Additon
         
       for(i=0;i<2;i++)
        {
            for(j=0;j<3;j++)
            {
                 ar3[i][j]=ar1[i][j]+ar2[i][j];
            }
        }
       
       /// display
       
       System.out.println("Additon of the matrix is : ");
        for(i=0;i<2;i++)
        {
            for(j=0;j<3;j++)
            {
                 System.out.print(ar3[i][j]+"     ");
            }
            System.out.println();
        }
       
 }
}

Output


Enter the elements of the matrix :
2
3
4
5
4
5
 the elements of the matrix First are :
2 3 4 
5 4 5 
Enter the elements of the second matrix :
1
2
3
4
5
6
 the elements of the matrix second are :
1 2 3 
4 5 6 
Additon of the matrix is : 
3     5     7     
9     9     11    

clone method in java

/* illustrate the concept of clone() in java */

/*
    Cloneable is an interface .
*/


package clonemethod;
class Student implements Cloneable
{
    int roll;
    String name;
    Student(int roll,String name)
    {
        this.roll=roll;
        this.name=name;
        System.out.println("details are : "+roll+" "+name);
    }
public Object clone()throws CloneNotSupportedException{  
return super.clone();  
}  

public static void main(String args[]){  
try{  
Student s1=new Student(21,"sanjay");  
  
Student s2=(Student)s1.clone();  
  
System.out.println(s1.roll+" "+s1.name);  
System.out.println(s2.roll+" "+s2.name);  
  
}catch(CloneNotSupportedException c){}  
  
}  
}  


Output

details are : 21 sanjay
21 sanjay
21 sanjay

user defined exception in java

/* illustrate the concept of making UserDefinedException in java */


package userdefinedexceptiondemo;

class MyException extends Exception
{
    public String toString()
    {
        return "Exception occured ...";
    }
}

class MyClass 
{
    int a=2,b,c;
    public void Number(int b) throws MyException
    {
        this.b=b;
        if(b<=0)
            throw new MyException();
        else
        {
            c=a/b;
            System.out.println("Answer is : "+c);
        }
    }
}
class MainMethod
{
    public static void main(String[] args)
     {
         try
         {
            MyClass mc=new MyClass();
            // mc.Number(2);  Ouput is : Answer is : 1
            mc.Number(0);
         }
         catch(MyException n)
         {
             System.out.println(n);
         }
         
      }
}

Output

Exception occured ...

Saturday, 1 February 2014

fibacnocci series in java

/* program to generate a series called fibanocci series  */


class Fibanocci
{
    public static void main(String[] args)
    {
        int a=0,b=1,c,i,n;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the limit of the series : ");
        n=sc.nextInt();
        for(i=1;i<=n;i++)
        {
            c=a+b;
            System.out.print(c+" ");
            a=b;
            b=c;
        }
    }
}

Output


Enter the limit of the series : 
8
1 2 3 5 8 13 21 34 

multiple inheritance in java

/* illustrating the concept of multiple inheritance in java */


interface Name
{
    void StudentName();
}
interface Branch 
{
    void StudentBranch();
}
interface RollNo
{
    void roll();
}

/*
 * Shows the concept of multiple inheritance in java.
 */

public class multipleInherit implements Name,Branch,RollNo
{
    public void StudentName()
    {
        System.out.println("Student Name is : Sanjay kumar singh ");
    }
    public void StudentBranch()
    {
        System.out.println("Student Branch is : Computer Science ");
    }
    public void roll()
    {
        System.out.println("Student roll number is : 21 / 2000263");
    }
    
    public static void main(String[] args)
    {
        multipleInherit mi=new multipleInherit();
        mi.StudentName();
        mi.StudentBranch();
        mi.roll();
    }
            
}

Output


Student Name is : Sanjay kumar singh 
Student Branch is : Computer Science 
Student roll number is : 21 / 2000263

interface in java

/* program to illustrate the concept of interface in java */



interface FirstLetter
{
   public char First(char c);
}
interface SecondLetter
{
    public char Second(char c);
}
interface ThirdLetter
{
    public char Third(char c);
}
class Name implements FirstLetter,SecondLetter,ThirdLetter
{
    public char First(char c)
    {
        return c;
    }
     public char Second(char c)
    {
        return c;
    }
      public char Third(char c)
    {
        return c;
    }
}

class MainClass
{
    public static void main(String args[])
    {
        Name nm=new Name();
        nm.First('j');
        nm.Second('a');
        nm.Third('y');
        System.out.println("Name is :"+nm.First('j')+nm.Second('a')+nm.Third('y'));
    }
}

Output

Name is :jay

get the total number of lines in a text file

/* count total number of lines in a file  */


import java.io.*;;

public class get_length
{
    public static void main(String[] args)
    {
        File f=new File("E://NewFile.txt");
        try
        {
           FileReader fr=new FileReader(f);
           LineNumberReader lr=new LineNumberReader(fr);
           int count=0;
           while(lr.readLine()!=null)
           {
               count++;
           }
           System.out.println("Total lines are : "+count);
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Output

Total lines are : 6

File E://NewFile.txt  is


read from a file

/*  program to read text from a file */


import java.io.*;
import java.io.FileWriter;

class FileReader
{
    public static void main(String[] args)
    {
        try
        {
           File f=new File("E://NewFile.txt");
           FileInputStream fs=new FileInputStream(f);
           DataInputStream ds=new DataInputStream(fs);
           String str;
           while((str=ds.readLine())!=null)
           {
               System.out.println(str);
           }
           
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Output

sanjay kumar singh 

File is present in the E:// Drive and the content is 


get AbsolutePath of a file in java

/* program for finding the absolute path of the file  */


import java.io.*;

class getPathOfFile
{
    public static void main(String[] args)
    {
        try
        {
            File f=new File("NewFile.txt");
            if(!f.exists())
            {
                f.createNewFile();
                System.out.println("New File created...");
                System.out.println("Its absolute path is : "+f.getAbsolutePath());
            }
            else
            {
                System.out.println("File already exists...");
            }
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Output

New File created...
Its absolute path is : E:\Java_NetBeans\PROGRAMMING\JavaIO\NewFile.txt

Popular Posts