Friday 26 December 2014

Functions

02:19 Posted by Hindustan News , No comments
A function is a module or block of program code which deals with a particular task. Making functions is a way of isolating one block of code from other independent blocks of code. Functions serve two purposes. They allow a programmer to say:"this piece of code does a specific job which stands by itself and should not be mixed up with anything else", and they make a block of code reusable since a function can be reused in many different contexts without repeating parts of the program text. In previous modules, main( ) itself is a pre-defined function.

Functions help us to organize a program in a simple way

Each function has a name or identifier by which is used to refer to it in a program. A function can accept a number of parameters or values which pass information from outside, and consists of a number of statements and declarations, enclosed by curly braces { }, which make up the doing part of the object. The declarations and `type of parameter' statements are formalities which will be described in good time.

Some Rules for writing functions:
The name of a function in C can be anything from a single letter to a long word. The name of a function must begin with an alphabetic letter or the underscore _ character but the other characters in the name can be chosen from the following groups:

a .. z       (any letter from a to z)
A .. Z     (any letter from A to Z)
0 .. 9       (any digit from 0 to 9)
_             (the underscore character)

Uses of C functions:
  • C functions are used to avoid rewriting same logic/code again and again in a program.
  • There is no limit in calling C functions to make use of same functionality wherever required.
  • We can call functions any number of times in a program and from any place in a program.
  • A large C program can easily be tracked when it is divided into functions.
  • The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.

C function declaration, function call and function definition:
There are 3 aspects in each C function. They are,
  • Function declaration or prototype  - This informs compiler about the function name, function parameters and  return value’s data type.
                       Syntax: return_type function_name ( argument list );
  • Function call – This calls the actual function
                        Syntax: function_name ( arguments list );
  • Function definition – This contains all the statements to be executed.
                        Syntax:  return_type function_name ( arguments list )
                                      { Body of function; }
Example:
#include
// function prototype, also called function declaration
float square ( float x );                              
 
// main function, program starts from here
int main( )              
{
 
        float m, n ;
        printf ( "\nEnter some number for finding square \n");
        scanf ( "%f", &m ) ;
        // function call
        n = square ( m ) ;                      
        printf ( "\nSquare of the given number %f is %f",m,n );
 
}
 
float square ( float x )   // function definition
{
        float p ;
        p = x * x ;
        return ( p ) ;
}

Output:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000

C - ARRAY

C Array is a collection of homogeneous value i.e. belongings to the same data type. You can store group of data of same data type in an array.
  • Array might be belonging to any of the data types.
  • Array size must be a constant value.
  • Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
  • It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array. 
For example: If the user want to store marks of 100 students. This can be done by creating 100 variable individually but, this process is rather tedious and impracticable. These type of problem can be handled in C programming using arrays.

There are 3 types of C arrays. They are,
  1. One dimensional array
  2. Two dimensional array
  3.  Multidimensional array
One Dimensional Array:

Example:
#include
int main()
{
    int i;
    int arr[5] = {10,20,30,40,50};  
    // declaring and Initializing array in C
    //To initialize all array elements to 0, use int arr[5]={0};
    /* Above array can be initialized as below also
       arr[0] = 10;
       arr[1] = 20;
       arr[2] = 30;
       arr[3] = 40;
       arr[4] = 50;
    */
    for (i=0; i<5; i++)
    {
        //Accessing each variable
        printf("value of arr[%d] is %d \n", i, arr[i]);
    }
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

Notes:
1.If number of values in list is less than the number of elements or size of array then only that many element will be initialized.The remaining elements will be set to zero automatically. If array is character type then remaining element will be NULL.
Ex:
        int a[5]={3,4,5};
        value of arr[0] is 3
        value of arr[1] is 4
        value of arr[2] is 5
        value of arr[3] is 0
        value of arr[4] is 0
2.The size may be omitted. In such case, the compiler allocates enough space for all initialized elements.
Ex:
        int counter[]= {1,1,1,1};
        It will works fine.

Two Dimensional Array: 

Example:
#include
int main()
{
    int i,j;
    // declaring and Initializing array
    int arr[2][2] = {10,20,30,40};
    /* Above array can be initialized as below also
       arr[0][0] = 10;   // Initializing array
       arr[0][1] = 20;
       arr[1][0] = 30;
       arr[1][1] = 40;
    */
    for (j=0;j<2;j++)
       {
          // Accessing variables
          printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
       }
    }
}

Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

Note:
1.Some different types initialization:
int table[2][3] = {0,0,0,1,1,1};
             It simply initialized first row with 0 and second row with 1.
int table[2][3] = {{0,0,0},{1,1,1}};
             In this only we specify curly braces to distinguish the rows.So it gives same result.
int table[2][3] ={
                            {0,0,0},
                             {1,1,1}
                           };
             It also same as above.Commas are required after each braces that closes off a row, except in the case of the last row.
int table[][3] = {{0,0,0},{1,1,1}};
            When the array is completely initialized with all values, explicitly, we need not specify the  size of the first dimension.
int table[2][3] = {{1,1},{2}};
            If values are missing in an initializer, they are automatically set to zero. In above example,it initialize first two element of the first row to 1, the first element of the second row to two, and all other elements to zero.
int table[2][3] ={{0},{0}};
            In above statement, all elements are to be initialized to zero.

Note: We discussed later about Multidimensional array after discussing about Pointer.

Sunday 26 October 2014

Constructor in java

Java constructors are the methods which are used to initialize objects. Constructor has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. 

Example of Constructor:

public class A
{
 public A()  // constructor method
 {
 
 }
}

Types of Constructor 

1. Default Constructor.
2. Parameterized Constructor.

1. Default Constructor.

If Constructor method has no argument then its known as the "default constructor".If we do not create constructor then compiler automatically crate "default constructor"

class A
{
 public A()  
 {
     System.out.println("Default Constructor called");
 }
}

public MainClass
{
 public static void main(String[] args)
 {
  A a=new A(); 
 }
}


OUTPUT
Default Constructor called

2. Parameterized Constructor.

If we pass arguments in constructors' method then it called as "parameterized constructor."
class A
{
 public A()  
 {
     System.out.println("Default Constructor called");
 }
 
 public A(int i)  
 {
     System.out.println("The value of i="+i);
 }
}

public MainClass
{
 public static void main(String[] args)
 {
  A a=new A(10); 
 }
}

OUTPUT
The value of i=10


Note :
Constructor never return a value.

Constructor Overloading:

Like other methods in java constructor can be overloaded we can create as many constructors in our class as desired. When we create object and pass the arguments appropriate constructor is called.

class A
{
 public A()  
 {
     System.out.println("Default Constructor called");
 }
 
 public A(int i)  
 {
     System.out.println("The value of i="+i);
 }
 public A(String arg)  
 {
     System.out.println("String Argument is="+arg);
 }
}

public MainClass
{
 public static void main(String[] args)
 {
  A a1=new A();
  A a2=new A(10);
  A a3=new A("Hello");
 }
}

OUTPUT
Default Constructor called
The value of i=10
String Argument is=Hello

Constructor chaining:

constructor can not inherited into subclass.But we can call super class constructor from subclass by "super() key word".when subclass object created subclass constructor invoked and by super keyword we can invoke super class constructor this is called "constructor chaining".

class A
{
 public A()  
 {
     System.out.println("A Constructor called");
 }
 
 public A(String arg)  
 {
     System.out.println("String Argument is="+arg);
 }
}
class B extends Argument
{
 public B()
 {
  super("Hello");
   System.out.println("B Constructor called");
 }
 public B(int i)
 {
  super();
  System.out.println("Argument is="+i);
 }
}
public MainClass
{
 public static void main(String[] args)
 {
  A a1=new A();
  B b1=new B();
  B b2=new B(20);
 }
}

OUTPUT
A Constructor called
String Argument is=Hello
B Constructor called
A Constructor called
Argument is=20

Inheritance in java

00:11 Posted by Unknown No comments

Inheritance :

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
Using inheritance you can create general class that defines common set of related items.This class can be inherited by other classes.
In the terminology of java  , a class that is inherited is called "superclass" and the class that does inheriting called as "subclass".

Note : - 

In Java, only si.ngle inheritance is allowed and thus, every class can have at most one direct superclass. A class can be derived from another class that is derived from another class and so on. Finally, we must mention that each class in Java is implicitly a subclass of the Object class.

By "extends" keyword we can implement inheritance in java.

Example of inheritanc

class A
{
          //members of class A
}
class B extends A
{
          //members of class A inherited into B
           // members of class B
}

The private members of the superclass that cannot be accessed directly from the subclass. Also, constructors are not members, thus they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Simple example of inheritance

class Animal
{
     public Animal()
    {
               System.out.println("Animal created........");
    }
    public void sleep()
   {
         System.out.println("Animal sleep........");
    }
}
class Horse extends Animal
{
     public Horse()
    {
               System.out.println("Horse created........");
     }
      //Horse class inherits sleep() method from Animal class
}
public class MainClass
{
                 public static void main(String[] args)
                {
                    Animal animal=new Animal();   //Animal class Object created
                    Horse horse=new Horse();       // Horse class Object created
                   animal.sleep();
                    horse.sleep();   
                }
}

OUTPUT

Animal created........
Animal created........
Horse created........
Animal sleep........ Animal sleep........

The inheritance in Java provides the following features:

1.You can declare new fields in the subclass that are not in the superclass.
2.You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
3.You can declare new methods in the subclass that are not in the superclass.

Saturday 28 June 2014

Oops Concept in Java

1. Data Hiding :

Hiding of the data , so that outside class can not access that data.By using the private modifier we can implement the data hiding.
The main advantage of data hiding is we can achieve the security.

Example of data hiding:
public class Account
{
 private double balance=20000; //Can not available outside the class
}

2. Abstraction :

By abstraction we can hide internal implementation details and just highlight the set of services what are offering is known as the abstraction.
For example At ATM machine , bank people will highlight the set of services what they are offering without highlighting the internal implementation details this is simply known as the abstraction.
By using interface and abstract class we can achieve the abstraction.

3. Encapsulation :

Wrapping data and corresponding method into a single module is known as "Encapsulation". 
E.g. A capsule , it wrapped with different medicines.
Encapsulated class follows both Data Hiding and Abstraction.
The main advantage of the encapsulation are:
1. We can achieve security.
2. Improve modularity  of the application,

4. Inheritance :

It is also known as the IS-A relationship.The main advantage of the inheritance is re-usability.
In inheritance one class acquired the properties of the other class.Using inheritance , you can create general class that defines the set of related items.This class can be inherited by the other class.The class that is inherited is known as "super" class and the class that does inheriting known as the "subclass" .Subclass inherits all of the instance variables and methods defined by the super class and adds its own members.
By extends keyword we can implement the inheritance concept.

A simple example of inheritance :
class Parent
{

   public void test()
   {
 System.out.println("Parent class");
   }
}

class Child extends Parent
{
    public void test()    //Reuse the method of parent class
    {
 System.out.println("Child class"); 
    }
 
    public void test1()   //Additional method of child class
    {
 System.out.println("Additional method of child class");
    }
}


5.HAS-A-RELATIONSHIP :

Has-a-relationship also known as the "aggregation or composition".When a class depend on the other class known as the Has-a-relationship.The main advantage of the has-a-relationship is reuseability.
But the main dis-advantage of Has-a -relationship is it increases the dependency between the class. so it is the difficult to maintain the relationship between them.

Simple program of Has-a-relationship:
public class Address 
{
     int houseNo;
     String city;
     String state;
}
 
public class Person 
{
     String name;
     long mobNo;
     Address address;  //Has-a-relationship

}

Composition:

  • In the case of composition whenever the container object is destroyed all the contained objects will be destroyed automatically.
  • Without existing of container there is no chance of existing of contained object.
  • In composition there will be strong association .

Aggregation:

  • In the case of aggregation whenever the container object is destroyed there is no guarantee of destruction of contained object.
  • Without existing the container object there may be chance of existence of the contained object .
  • Container object just maintain the reference of the contained objects .
  • This type of  relationship also known as the "weak association" .   



6.  Polymorphism :

  • Poly means many and morphs means form , So polymorphism means many forms.
  • We can use same name to represent multiple forms in polymorphism . 
  • For example addition operation between  to integer gives the integer number while addition of two strings gives the concatenation . This is nothing but the polymorphic form of addition operation .
  • In java there are two types of the polymorphism .
  1. Compile time polymorphism.
  2. Run time polymorphism. 

Tuesday 24 June 2014

Difference Between Array and Collection

Difference Between Array and Collection



Array

Collection
 1. Size of arrays are fixed.  1. Size of collection are growable in nature we can increase or decrease the size as our requirement.
2. Memory point of view array concept not recommended to use.2. Memory point of view collection concept highly recommended to use.
3. Arrays can hold only homogeneous elements. 3. Collection can hold both homogeneous and heterogeneous objects.
4. Arrays can hold both primitives and objects type elements. 4. Collection can hold only objects.


Sunday 22 June 2014

Difference Between Method Overloading and Overriding

Difference Between Method Overloading and Overriding


Method Overloading

Method Overriding
1. Method name must be same. 1. Method name must be same.
2. Method argument must be different. 2. Method arguments must be same.
3. Method signature must be different. 3. Method signature must be same.
4. Return type can be changed. 4. Return type must be same until 1.4v but after 1.5v co-variant type allowed.
5. Private , static and final method can be overloaded. 5. Private , static and final method can not be override.
6. Any type of access modifier is allowed(public ,  protected , private). 6. We can not decrease the scope modifier.
e.g. public method can not override as  protected.
7. There is no restriction in exception handling. 7. Child class should be handle exception same as the parent class or the child exception.

e.g. P: Exception
C: Exception or IOException
8. Method resolution takes by the compiler. 8. Method resolution takes by the JVM based on the object reference.
9. Method overloading also known as static polymorphism, compile-time polymorphism or early binding 9. Method overriding also known as dynamic polymorphism, run-time polymorphism or late binding




Saturday 21 June 2014

Difference Between Abstract class and Interface

Difference Between Abstract class and Interface.

Abstract Class Interface
1. If we are talking about implementation but not completely (partially implementation) then go for abstract class. 1. If we does know anything about the implementation then we should go for the interface.
2. Every method present in abstract class need not be abstract ,it can be not abstract also. 2. Every method present inside interface is by default abstract.
3. Every method present in abstract class need not be public. 3. Every method present inside interface is by default public.
4. We can use any modifier for the method. 4. The following modifiers are not allowed for the interface methods:
Strictfp , protected , final , native , static , private , synchronized .
5. No restriction for abstract class variables. 5. Every attribute present inside the interface is by default public , static and final.
6. No restriction for the abstract class variables. 6. Following modifiers cannot declares for the interface variables
Private , protected , transient , volatile .
7. No restriction for the initialization of abstract class variables. 7. Compulsory initialize the variables whenever declaration.
8. Inside abstract class we can take instance and static block. 8. Inside interface we cannot take instance and static block.
9. Inside abstract class we can create constructor. 9. Inside interface we can not create constructor.


Difference Between C++ and Java

Difference Between C++ and Java

C++ Java
1. C++ is an extension of C with Object oriented behavior , C++ is not complete object oriented language as Java. 1. Java is complete object oriented language.
2. C++ supports pointer concept. 2. Java does not support pointer.
3. At compilation stage C++ source code converted into machine level code. 3. At compilation stage Java source code converted into byte code.
4. C++ is platform dependent , you have to compile and run program for different platform. 4. Java is platform independent language so you can compile once and run any where.
5. C++ uses only compiler. 5. Java uses both compiler and interpreter.
6. C++ supports operator overloading. 6. Java does not supports operator overloading.
7. C++ supports multiple inheritance. 7. Java does not supports multiple inheritance.
8. Goto statements available in C++. 8. There no goto statements concept in Java.
9. C++ supports :: scope resolution operator. 9. No :: scope resolution operator.
10. C++ does not have garbage collector concept. 10. Garbage collector is most useful feature of Java
11. C++ does not support final keyword. 11. Java supports final keyword.
12. C++ supports constant keyword. 12. Java does not supports constant keyword.
13. C++ uses #include to include different files. 13. Java uses import keyword to include different classes.




Difference Betwee C and C++

Difference Between C and C++


C

C++
1. C is Procedural Language. 1. C++ is non Procedural i.e Object oriented Language.
2. In C, Polymorphism is not possible. 2. The concept of polymorphism is used in C++.Polymorphism is the most Important Feature of OOPS.
3. Inheritance is not possible in C. 3. Inheritance is possible in C++.
4. Virtual Functions are not present in C. 4. The concept of virtual Functions are used in C++.
5. Operator overloading is not possible in C. 5. Operator overloading is one of the greatest Feature of C++.
6. Top-down approach is used in Program Design. 6. Bottom-up approach adopted in Program Design.
7. Multiple Declaration of global variables are allowed. 7. Multiple Declaration of global varioables are not allowed.
8. scanf() Function used for Input.
printf() Function used for output.
8. Cin>> Function used for Input.
Cout<< Function used for output.
9. Namespace Feature is not present in C. 9. Namespace Feature is present in C++ for avoiding Name collision.
10. In C, we can call main() Function through other Functions 10. In C++, we cannot call main() Function through other functions.
11. C requires all the variables to be defined at the starting of a scope. 11. C++ allows the declaration of variable anywhere in the scope i.e at time of its First use.
12. In C, malloc() and calloc() Functions are used for Memory Allocation and free() function for memory Deallocating. 12. In C++, new and delete operators are used for Memory Allocating and Deallocating.
13. C supports built-in and primitive data types. 13. C++ support both built-in and user define data types.
14. Mapping between Data and Function is difficult and complicated. 14. Mapping between Data and Function can be used using Objects
15. In C, Exception Handling is not present. 15. In C++, Exception Handling feature us available.