Saturday, November 26, 2011

How To Set Java Path


How do I set or change the PATH system variable?


This article applies to:
  • Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 7, Vista, Windows XP
  • Browser(s): All Browsers
  • Java version(s): All JRE Versions

MORE TECHNICAL INFORMATION

The PATH is the system variable that your operating system uses to locate needed executables from the command line or Terminal window.
The PATH system variable can be set using System Utility in control panel on Windows, or in your shell's startup file on Linux and Solaris.

SOLUTION

Setting Path on Windows
For Windows XP:
  1. Start -> Control Panel -> System -> Advanced
  2. Click on Environment Variables, under System Variables, find PATH, and click on it.
  3. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  4. Close the window.
  5. Reopen Command prompt window, and run your java code.

For Windows Vista:
  1. Right click "My Computer" icon
  2. Choose "Properties" from context menu
  3. Click "Advanced" tab ("Advanced system settings" link in Vista)
  4. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  5. Reopen Command prompt window, and run your java code.

Setting Path on Solaris and Linux
To find out if the java executable is in your PATH, execute:
% java -version

This will print the version of the java executable, if it can find it. If you get error java: Command not found. Then path is not properly set.

To find out which java executable the first one found in your PATH, execute:
% which java

For bash Shell:
  1. Edit the startup file (~/ .bashrc)
  2. Modify PATH variable:
    PATH=/usr/local/jdk1.6.0/bin
  3. export PATH
  4. Save and close the file
  5. Open new Terminal window
  6. Verify the PATH is set properly
    % java -version

For C Shell (csh):
  1. Edit startup file (~/ .cshrc)
  2. Set Path
    set path=(/usr/local/jdk1.6.0/bin )
  3. Save and Close the file
  4. Open new Terminal window
  5. Verify the PATH is set properly
    % java -version

How To Install Java


How To Install Java

How do I manually download and install Java for my Windows computer?


This article applies to:
  • Platform(s): Windows 7, Vista, Windows XP, Windows 2000, Windows 2003, Windows 2008 Server
  • Java version(s): 6.0

The procedure to install Java broadly consists of:
  1. Download and Install
  2. Test Installation
» Windows System Requirements

Typical download size is 10 MB, which is the minimum download. The size may increase if additional features are selected.

Note: User needs to have an administrative rights for downloading and installing Java on their system.


 
Download and Install
It is recommended, before you proceed with online installation you may want to disable your Internet firewall. In some cases the default firewall settings are set to reject all automatic or online installations such as the Java online installation. If the firewall is not configured appropriately it may stall the download/install operation of Java under certain conditions. Refer to your specific Internet firewall manual for instructions on how to disable your Internet Firewall.

  1. Go to the Manual download page
  2. Click on Windows Online
  3. The File Download dialog box appears prompting you to run or save the download file
    • To run the installer, click Run.
    • To save the file for later installation, click Save.
      Choose the folder location and save the file to your local system.
      Tip: Save the file to a known location on your computer, for example, to your desktop.
      Double-click on the saved file to start the installation process.
  1. The installation process starts. Click the Install button to accept the license terms and to continue with the installation.



  1. Oracle has partnered with companies that offer various products. The installer may present you with option to install these programs when you install Java. After ensuring that the desired programs are selected, click the Next button to continue the installation.



  1. A few brief dialogs confirm the last steps of the installation process; click Close on the last dialog.



  1. This will complete Java installation process.


NOTE: You may need to restart (close and re-open) your browser to enable the Java installation in your browser.

Saturday, November 19, 2011

Final Keyword


The final keyword

The final keyword is used in several different contexts as a modifier meaning that what it modifies cannot be changed in some sense.

final classes

You will notice that a number of the classes in Java library are declared final, e.g.
public final class String 
This means this class will not be subclassed, and informs the compiler that it can perform certain optimizations it otherwise could not. It also provides some benefit in regard to security and thread safety.
The compiler will not let you subclass any class that is declared final. You probably won't want or need to declare your own classes final though.

final methods

You can also declare that methods are final. A method that is declared final cannot be overridden in a subclass. The syntax is simple, just put the keywordfinal after the access specifier and before the return type like this:
public final String convertCurrency()

final fields

You may also declare fields to be final. This is not the same thing as declaring a method or class to be final. When a field is declared final, it is a constant which will not and cannot change. It can be set once (for instance when the object is constructed, but it cannot be changed after that.) Attempts to change it will generate either a compile-time error or an exception (depending on how sneaky the attempt is).
Fields that are both finalstatic, and public are effectively named constants. For instance a physics program might define Physics.c, the speed of light as
public class Physics {

  public static final double c = 2.998E8;
  
  
}
In the SlowCar class, the speedLimit field is likely to be both final and static though it's private.
public class SlowCar extends Car {

  private final static double speedLimit = 112.65408; // kph == 70 mph

  public SlowCar(String licensePlate, double speed, double maxSpeed,
   String make, String model, int year, int numberOfPassengers, int numDoors) {
    super(licensePlate, 
     (speed < speedLimit) ? speed : speedLimit, 
     maxSpeed, make, model, year, numberOfPassengers, numDoors);
  }

  public void accelerate(double deltaV) {

     double speed = this.speed + deltaV;
     
     if (speed > this.maxSpeed) {
       speed = this.maxSpeed; 
     }
     
     if (speed > speedLimit) {
       speed = speedLimit;
     }
     
     if (speed < 0.0) {
       speed = 0.0; 
     } 
     
     this.speed = speed;    
     
  }
   
}

final arguments

Finally, you can declare that method arguments are final. This means that the method will not directly change them. Since all arguments are passed by value, this isn't absolutely required, but it's occasionally helpful.
What can be declared final in the Car and MotorVehicle classes?

java.lang.Math


Examples of java.lang.Math Methods
Here is an example program that exercises most of the routines in java.lang.Math. If your high school math is a little rusty, don't worry if you don't remember the exact meaning of logarithms or cosines. Just know that they're here in Java if you need them.
public class MathLibraryExample {

  public static void main(String[] args) {
   
    int i = 7;
    int j = -9;
    double x = 72.3;
    double y = 0.34;
 
    System.out.println("i is " + i);    
    System.out.println("j is " + j);
    System.out.println("x is " + x);    
    System.out.println("y is " + y);
    
    // The absolute value of a number is equal to
    // the number if the number is positive or
    // zero and equal to the negative of the number
    // if the number is negative.

    System.out.println("|" + i + "| is " + Math.abs(i));    
    System.out.println("|" + j + "| is " + Math.abs(j));
    System.out.println("|" + x + "| is " + Math.abs(x));    
    System.out.println("|" + y + "| is " + Math.abs(y));

    // Truncating and Rounding functions

    // You can round off a floating point number 
    // to the nearest integer with round()
     System.out.println(x + " is approximately " + Math.round(x));    
     System.out.println(y + " is approximately " + Math.round(y));    

    // The "ceiling" of a number is the  
    // smallest integer greater than or equal to
    // the number. Every integer is its own
    // ceiling.
     System.out.println("The ceiling of " + i + " is " + Math.ceil(i));    
     System.out.println("The ceiling of " + j + " is " + Math.ceil(j));
     System.out.println("The ceiling of " + x + " is " + Math.ceil(x));    
     System.out.println("The ceiling of " + y + " is " + Math.ceil(y));

     // The "floor" of a number is the largest 
     // integer less than or equal to the number.
     // Every integer is its own floor.
     System.out.println("The floor of " + i + " is " + Math.floor(i));    
     System.out.println("The floor of " + j + " is " + Math.floor(j));
     System.out.println("The floor of " + x + " is " + Math.floor(x));    
     System.out.println("The floor of " + y + " is " + Math.floor(y));

     // Comparison operators

     // min() returns the smaller of the two arguments you pass it
     System.out.println("min(" + i + "," + j + ") is " + Math.min(i,j));    
     System.out.println("min(" + x + "," + y + ") is " + Math.min(x,y));    
     System.out.println("min(" + i + "," + x + ") is " + Math.min(i,x));    
     System.out.println("min(" + y + "," + j + ") is " + Math.min(y,j));    

     // There's a corresponding max() method
     // that returns the larger of two numbers
     System.out.println("max(" + i + "," + j + ") is " + Math.max(i,j));    
     System.out.println("max(" + x + "," + y + ") is " + Math.max(x,y));    
     System.out.println("max(" + i + "," + x + ") is " + Math.max(i,x));    
     System.out.println("max(" + y + "," + j + ") is " + Math.max(y,j));    
     
     // The Math library defines a couple
     // of useful constants:
     System.out.println("Pi is " + Math.PI);    
     System.out.println("e is " + Math.E);      
     // Trigonometric methods
    // All arguments are given in radians

    // Convert a 45 degree angle to radians
    double angle = 45.0 * 2.0 * Math.PI/360.0;
    System.out.println("cos(" + angle + ") is " + Math.cos(angle));     
    System.out.println("sin(" + angle + ") is " + Math.sin(angle));    
   
     // Inverse Trigonometric methods
     // All values are returned as radians
  
    double value = 0.707;

    System.out.println("acos(" + value + ") is " + Math.acos(value));    
    System.out.println("asin(" + value + ") is " + Math.asin(value));    
    System.out.println("atan(" + value + ") is " + Math.atan(value));    

    // Exponential and Logarithmic Methods
 
    // exp(a) returns e (2.71828...) raised
    // to the power of a.  
    System.out.println("exp(1.0) is "  + Math.exp(1.0));
    System.out.println("exp(10.0) is " + Math.exp(10.0));
    System.out.println("exp(0.0) is "  +  Math.exp(0.0));

    // log(a) returns  the natural
    // logarithm (base e) of a.
    System.out.println("log(1.0) is "    + Math.log(1.0));
    System.out.println("log(10.0) is "   + Math.log(10.0));
    System.out.println("log(Math.E) is " + Math.log(Math.E));

    // pow(x, y) returns the x raised
    // to the yth power.
    System.out.println("pow(2.0, 2.0) is "  + Math.pow(2.0,2.0));
    System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0,3.5));
    System.out.println("pow(8, -1) is "     + Math.pow(8,-1));

    // sqrt(x) returns the square root of x.
    for (i=0; i < 10; i++) {
      System.out.println(
       "The square root of " + i + " is " + Math.sqrt(i));
    }

      
    // Finally there's one Random method
    // that returns a pseudo-random number
    // between 0.0 and 1.0;
   
    System.out.println("Here's one random number: " + Math.random());    
    System.out.println("Here's another random number: " + Math.random());

  }

}



Here's the output from the math library example
i is 7
j is -9
x is 72.3
y is 0.34
|7| is 7
|-9| is 9
|72.3| is 72.3
|0.34| is 0.34
72.3 is approximately 72
0.34 is approximately 0
The ceiling of 7 is 7
The ceiling of -9 is -9
The ceiling of 72.3 is 73
The ceiling of 0.34 is 1
The floor of 7 is 7
The floor of -9 is -9
The floor of 72.3 is 72
The floor of 0.34 is 0
min(7,-9) is -9
min(72.3,0.34) is 0.34
min(7,72.3) is 7
min(0.34,-9) is -9
max(7,-9) is 7
max(72.3,0.34) is 72.3
max(7,72.3) is 72.3
max(0.34,-9) is 0.34
Pi is 3.14159
e is 2.71828
cos(0.785398) is 0.707107
sin(0.785398) is 0.707107
acos(0.707) is 0.785549
asin(0.707) is 0.785247
atan(0.707) is 0.615409
exp(1.0) is 2.71828
exp(10.0) is 22026.5
exp(0.0) is 1
log(1.0) is 0
log(10.0) is 2.30259
log(Math.E) is 1
pow(2.0, 2.0) is 4
pow(10.0, 3.5) is 3162.28
pow(8, -1) is 0.125
The square root of 0 is 0
The square root of 1 is 1
The square root of 2 is 1.41421
The square root of 3 is 1.73205
The square root of 4 is 2
The square root of 5 is 2.23607
The square root of 6 is 2.44949
The square root of 7 is 2.64575
The square root of 8 is 2.82843
The square root of 9 is 3
Here's one random number: 0.820582
Here's another random number: 0.866157

Wednesday, November 16, 2011

what is a Variable ?

Variable
An object stores its state in variables.




Definition: A variable is an item of data named by an identifier.




You must explicitly provide a name and a type for each variable you want to use in your program. The variable's name must be a legal identifier — an unlimited-length sequence of Unicode characters that begins with a letter. You use the variable name to refer to the data that the variable contains. The variable's type determines what values it can hold and what operations can be performed on it. To give a variable a type and a name, you write a variable declaration, which generally looks like this:

type name

In addition to the name and type that you explicitly give a variable, a variable has scope. The section of code where the variable's simple name can be used is the variable's scope. The variable's scope is determined implicitly by the location of the variable declaration, that is, where the declaration appears in relation to other code elements. You'll learn more about scope in the section Scope.

/*** Java Program For Displaying Byte values of various Datatypes */
public class MaxVariables
{
public static void main(String args[])
{

//For integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;

//For real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;

//For other primitive types
char aChar = 'S';
boolean aBoolean = true;

//Output
System.out.println("The largest byte value is "
+ largestByte);
System.out.println("The largest short value is "
+ largestShort);
System.out.println("The largest integer value is "
+ largestInteger);
System.out.println("The largest long value is "
+ largestLong);

System.out.println("The largest float value is "
+ largestFloat);
System.out.println("The largest double value is "
+ largestDouble);

if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar
+ " is upper case.");
} else {
System.out.println("The character " + aChar
+ " is lower case.");
}
System.out.println("The value of aBoolean is "
+ aBoolean);
}
}

/****** OUTPUT ******
The largest byte value is 127
The largest short value is 32767
The largest integer value is 2147483647
The largest long value is 9223372036854775807
The largest float value is 3.4028235E38
The largest double value is 1.7976931348623157E308
The character S is upper case.
The value of aBoolean is true */

Tuesday, November 15, 2011

What Is an Interface?

What Is an Interface?
In general, an interface is a device or a system that unrelated entities use to interact. According to this definition, a remote control is an interface between you and a television set, the English language is an interface between two people, and the protocol of behavior enforced in the military is the interface between people of different ranks.
Within the Java programming language, an interface is a type, just as a class is a type. Like a class, an interface defines methods. Unlike a class, an interface never implements methods; instead, classes that implement the interface implement the methods defined by the interface. A class can implement multiple interfaces.

The bicycle class and its class hierarchy define what a bicycle can and cannot do in terms of its "bicycleness." But bicycles interact with the world on other terms. For example, a bicycle in a store could be managed by an inventory program. An inventory program doesn’t care what class of items it manages, as long as each item provides certain information, such as price and tracking number. Instead of forcing class relationships on otherwise unrelated items, the inventory program sets up a protocol of communication. This protocol comes in the form of a set of method definitions contained within an interface. The inventory interface would define, but not implement, methods that set and get the retail price, assign a tracking number, and so on.

To work in the inventory program, the bicycle class must agree to this protocol by implementing the interface. When a class implements an interface, the class agrees to implement all the methods defined in the interface. Thus, the bicycle class would provide the implementations for the methods that set and get retail price, assign a tracking number, and so on.

You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:
  • Capturing similarities among unrelated classes without artificially forcing a class relationship
  • Declaring methods that one or more classes are expected to implement
  • Revealing an object's programming interface without revealing its class
  • Modelling multiple inheritance, a feature that some object-oriented languages support that allows a class to have more than one superclass

Simple Program On Java for the implementation of Multiple inheritance using interfaces to calculate the area of a rectangle and triangle

/* Area Of Rectangle and Triangle using Interface * /

interface Area
{
float compute(float x, float y);
}

class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}

class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}

class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(1,2));

area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
}
}
/** OUTPUT **

Area Of Rectangle = 2.0
Area Of Triangle = 10.0
*/

Final Keyword and Example

/* All members and variables can be

overriden by default in subclasses.

Final Keyword Is Used in Java to

prevent the subclass from overridding

the members of the superclass. Making

a method final ensures that the

functionality defiened in the mathod

will never be altered in any way.

Similarily the value of the final

variable can never be altered in any

way. */
class fe
{
double fp;
int fr;

fe(double p1,int r1)
{
fp=p1;
fr=r1;
}
}

class se extends fe
{
double sp;
int sr;

se(double p1,int r1,double p2,int r2)
{
super(p1,r1);
sp=p2;
sr=r2;
}
}

final class te extends se
{
double tp;
int tr;

te(double p1,int r1,double p2,int

r2,double p3,int r3)
{
super(p1,r1,p2,r2);
tp=p3;
tr=r3;
}

double average()
{
return (fp+sp+tp)/3;
}
}

class Student
{
public static void main(String args[])
{
te student = new

te(75.6,40,78.6,44,70.5,48);
System.out.println("Year\tRoll

no.\tPercentage");
System.out.println("FE\t"+student.fr+"

\t\t"+student.fp);
System.out.println("SE\t"+student.sr+"

\t\t"+student.sp);
System.out.println("TE\t"+student.tr+"

\t\t"+student.tp);
System.out.println("Average

performance is " + student.average());
}
}
/* Output *

Year Roll no. Percentage
FE 40 75.6
SE 44 78.6
TE 48 70.5
Average performance is

74.89999999999999 */

Multilevel Inheritance in java

Program that makes use of Multilevel Inheritance in java
/* program To Implement Multilevel Inheritance */
class Fe
{
double fp;
int fr;

Fe(double p1,int r1)
{
fp = p1;
fr = r1;
}
}

class Se extends Fe
{
double sp;
int sr;

Se(double p1,int r1,double p2,int r2)
{
super(p1,r1);
sp = p2;
sr = r2;
}
}

class Te extends Se
{
double tp;
int tr;

Te(double p1,int r1,double p2,int r2,double p3,int r3)
{
super(p1,r1,p2,r2);
tp = p3;
tr = r3;
}

double average()
{
return (fp+sp+tp)/3;
}
}

class Student
{
public static void main(String args[])
{
Te student = new Te(78.5,41,71.73,44,79.8,48);
System.out.println("Year\tRoll no.\tPercentage");
System.out.println("FE\t"+student.fr+"\t\t"+student.fp);
System.out.println("SE\t"+student.sr+"\t\t"+student.sp);
System.out.println("TE\t"+student.tr+"\t\t"+student.tp);
System.out.println("\nAverage Performance is " + student.average());
}
}

/* Output *

Year Roll no. Percentage
FE 41 78.5
SE 44 71.73
TE 48 79.8

Average Performance is 76.67666666666668 */

program to find percentage of student in 5 subjects

/* Java program to find percentage of student in 5 subjects

class Percentage
{
public static void main(String args[])
{
float Eng, Hindi, Marathi, Science, Social, percent;
Eng=Integer.parseInt(args[0]);
Hindi=Integer.parseInt(args[1]);
Marathi=Integer.parseInt(args[2]);
Science=Integer.parseInt(args[3]);
Social=Integer.parseInt(args[4]);
percent = (Eng+Hindi+Marathi+Science+Social)/5;
System.out.println("Subjects Offered : English, Hindi, Marathi, Science, Socail Studies");
System.out.println("Percentage"+percent);
}
}

Pyramid of numbers

class pyramid1
{
public static void main(String args[])
{
int i,j;
for(i=1;i<=3;i++)
{
for(j=1;j<=i;j++)
System.out.print(j+"\t");
System.out.println();
}
}
}

/* OUTPUT

1
1 2
1 2 3

Find the Sum of digits of number

/* Simple Java Program To Find the Sum of digits of number */

class SumDigit
{
public static void main(String args[])
{
int sum, i,a,d;
a = Integer.parseInt(args[0]);
sum = 0;
for(i=1;i< =10;i++)
{
d = a%10;
a = a/10;
sum=sum + d;
}
System.out.println("Sum of Digit :"+sum);
}
}

Arrays

/********** Implementation of Matrix Operation Using Arrays *********/
// Matrix Addtion, Subtraction, Transpose, Multiplication

import matrix;

class Matrix
{
public static void main(String args[])
{
int i,j,k;
int mat1 [][]={ {1,2,3}, {4,5,6}, {7,8,9} };
int mat2 [][]={ {10,11,12}, {13,14,15}, {16,17,18} };

//Matrix A
System.out.println("\nMatrix A:");
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
System.out.print("\t"+mat1[i][j]);
System.out.println("");
}

//Matrix B
System.out.println("\nMatrix B:");
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
System.out.print("\t"+mat2[i][j]);
System.out.println("");
}
System.out.println("\nOperation ON Matrices \n1.Addition \n");
int sum [][] = new int [3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
sum[i][j] = mat1[i][j] + mat2[i][j];
System.out.print("\t" + sum[i][j]);
}

System.out.println("");
}

System.out.println("2.Subtraction\n");
int diff[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
diff [i][j] = mat1[i][j] - mat2[i][j];
System.out.print("\t"+ diff[i][j]);
}
System.out.println("");
}

System.out.println("3. Transpose Of A\n");
int trans[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
trans [i][j] = mat1[j][i];
System.out.print("\t"+ trans[i][j]);
}
System.out.println("");
}
System.out.println("4.Multiplication\n");
int prod[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
prod[i][j] = 0;
{
for(k=0;k< 3;k++)
prod[i][j] = prod[i][j]+mat1[i][k]*mat2[k][j];
}
System.out.print("\t"+ prod[i][j]);
}
System.out.println("");

}
}
}

/************* OUTPUT ***************



Matrix A:
1 2 3
4 5 6
7 8 9

Matrix B:
10 11 12
13 14 15
16 17 18

Operation ON Matrices
1.Addition

11 13 15
17 19 21
23 25 27
2.Subtraction

-9 -9 -9
-9 -9 -9
-9 -9 -9
3. Transpose Of A

1 4 7
2 5 8
3 6 9
4.Multiplication

84 90 96
201 216 231
318 342 366
*/
/******* Java Implementation of Matrix Operation Using Arrays *******/

class Matrix
{
public static void main(String args[])
{
int i,j,k;
int mat1 [][]={ {10,11,12}, {13,14,15}, {16,17,18} };
int mat2 [][]={ {1,2,3}, {4,5,6}, {7,8,9} };
System.out.println("Operation ON Matrices \n1.Addition \n");
int sum [][] = new int [3][3];
for(i=0;i <3;i++)
{
for(j=0;j< 3;j++)
{
sum[i][j] = mat1[i][j] + mat2[i][j];
System.out.print("\t" + sum[i][j]);
}
System.out.println("\t");
}

System.out.println("2.Subtraction\n");
int diff[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
diff [i][j] = mat1[i][j] - mat2[i][j];
System.out.print("\t"+ diff[i][j]);
}
System.out.println("\t");
}

System.out.println("3.Multiplication\n");
int prod[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
prod[i][j] = 0;
{
for(k=0;k< 3;k++)
prod[i][j] = prod[i][j]+mat1[i][k]*mat2[k][j];
}
System.out.print("\t"+ prod[i][j]);
}
System.out.println("\t");

}
}
}

/************* OUTPUT ***************

Operation ON Matrices
1.Addition

11 13 15
17 19 21
23 25 27
2.Subtraction

9 9 9
9 9 9
9 9 9
3.Multiplication

138 171 204
174 216 258
210 261 312 */

Employee Details and Salary

/* Simple Java Program For Displaying Emplayee Details : NAme, Id No. Designation, and depending on designation deciding the salary Of the Employee*/

class emp
{
public static int emp_no;
public static String name;
public static String designation;
public void showdata()
{
System.out.println("Employee number:--->"+emp_no);
System.out.println("Employee name:------>"+name);
System.out.println("Employee designation:--->"+designation);
}
}

class salary extends emp
{
public static float bsal,hr,da,tsal;
public void cal()
{
tsal=bsal+hr+da;
System.out.println("Total salary:---->"+tsal);
}
}

class empsal extends salary
{
public void calc()
{
if (bsal >=15000)
{
hr=0.3f*bsal;
da=0.2f*bsal;
}
else if (bsal >=10000)
{
hr=0.4f*bsal;
da=0.3f*bsal;
}
else
hr=0.3f*bsal+500;
da=0.2f*bsal+500;
}
public static void main(String args[])
{
empsal E=new empsal();
emp_no=Integer.parseInt(args[0]);
name=args[1];
designation=args[2];
bsal=Integer.parseInt(args[3]);
E.showdata();
System.out.println("Employee Salary");
E.calc();
E.cal();
}
}

Monday, November 14, 2011

Introduction to Java



Introduction to Java

Java is an object oriented and structured programming language, designed by Sun Microsystems in the year 1991. Java is a third generation programming language. It has an in built application interface which has the ability to handle the graphics and user interfaces that creates the applets or applications.
The very advantage of java is its “portability”, the programmer can write the program and compile in the same kind of environment as it is written and after that it can be run anywhere.
Java relates to both C and C++, it uses the syntax of C and the object oriented concepts from c++ and this makes Java appealing. When a source code is given as the input, the output from java compiler is the “bytecode”. Bytecode contains set of instructions which will be executed by Java Virtual machine (JVM). In a more simple way, I can say JVM interprets the bytecode and this is the reason that java can be run anywhere. Applets are the programs which are embedded in to web page and can be executed where as the applications are directly executed by JVM.
It is not always possible to compile the complete program at the same time, so java uses just-in-time compiler to compile a set of bytecodes in real time for execution and the remaining codes will just be interpreted and thus makes the execution of Java program faster. The two main building blocks of java programming are the classes and objects. Objects are the instance of class and class is a template for creating objects.
Unlike in c/c++ you need not manually allocate/de allocate dynamic memory, java itself does this and also it has garbage collection for the unused objects. Java program handles the run time errors too. Java supports multithreaded programming.

Java Programming Language : What it is ?
A high-level programming language developed by Sun Microsystems. Java was originally called OAK, and was designed for handheld devices and set-top boxes. Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning World Wide Web.
Java is an object-oriented language similar to C++, but simplified to eliminate language features that cause common programming errors. Java source code files (files with a .java extension) are compiled into a format called bytecode (files with a .class extension), which can then be executed by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines (VMs), exist for most operating systems, including UNIX, the Macintosh OS, and Windows. Bytecode can also be converted directly into machine language instructions by a just-in-time compiler (JIT).
Java is a general purpose programming language with a number of features that make the language well suited for use on the World Wide Web. Small Java applications are called Java applets and can be downloaded from a Web server and run on your computer by a Java-compatible Web browser, such as Netscape Navigator or Microsoft Internet Explorer.

Java Programmers : Why They Are Highly In Demand

Java is a complex object-oriented computer programming language which is a result of some concepts taken from other computer languages such as C and C++. Although there are abound negative feedbacks, Java is generally considered to be the most admired multi-facets computing language that is utilized in today’s generation.
There are quite a number of reasons why Java is on the top spot when it comes to computer language. First off is the fact that composite dynamic website processes are achievable in Java programming. With Java being a multithreaded language, its use in superb and fast applications is increasing. An evidence of this is its presence in most gadget applications up to the fastest computers found today. As Java applets are platform-independent, the program can straightforwardly be accessed by a software developer and it can be run in various platforms. One of Java’s best features is the truth that even it is a very powerful and vigorous, this programming languages comes out free. It is an open source programming language which has a mechanical garbage collection. With regards to the database, Java can adapt to any database may it be paid or free. And the last but not the least is the reality that Java language is a collection of well planned and APIs which aids Java coders to do improved outputs without any annoyance.
The IT world has a number of platforms nowadays. This gift of numerous choices provides advantage and disadvantages. On one hand it provide more options to the developers or consumers; on the other hand making a software that is working on all platforms is becoming very scarce. To address this concern, there is now Java Platform which is intended for running extremely interactive, lively, and safe applets and computer applications on a set of connections of different computers.
Software developers can make applications on a single platform to deliver to that same platform — the Java Platform, which is accessible on a wide array of operating systems. This greatly minimizes the developing cost of the software. For support workforce, version management and advancement are much easier for the reason that Java-enabled software application can be found in a central storage area and work from that location for each individual handling.
The bottom line is, if you wish to study Java and become a professional on this field, you will certainly be ahead of the game. To start off, since Java is a popular language, you can turn on to basic Java tutorials found online or find a Java book with positive reviews. Deciding to be in this field is an action you shall never regret.

Java Application Programming


Java is a very popular programming language which involves various syn-taxes from C++ and C language. But it has a simpler model then these two other complex programming languages. It has object model and low-level facilities for the users which makes it easier and simpler to use and understand.
Java Application Programming was developed by a person named James Gosling in 1995, at a present date subsidiary of Oracle Corporations, which was then called as sun Micro-systems. JVM or Java Virtual Machines are needed to run these java applications which are compiled to class file format. Irrespective of the computer architecture JVM is always required to run this type of files. Java Application Programming is specifically designed to have the least amount of implementation bottlenecks. It works on the principle of “write once, run anywhere” pattern.
It means once your write the coding of the program, you can use it on other destination too. You don’t need to write it again and gain every time. Java is not only a programming language but also a software platform, which lets the application developers to use this simpler, class based and object-oriented programming language instead of the complicated high level languages like C and C++.
But the major disadvantage of using Java Application Programming is that, the programs written in Java are slower and need more memory space to get stored then the programs written in C language.
For that concern, the sun Micro-systems have been working upon java technologies under the specifications of the Java community process. And have achieved remarkable success in the context of introducing Just in time compilation model to run these applications in the year 1997-98. Some new language features have been added to the language like inner classes, optional assertions and String-buffer class etc.
Java has compilers in it, which conduct the basic functions whenever an application developer writes a code with syn-taxes and characters to run a particular Java Application Programming code.
For faster speed a company names Systronix has developed a micro-controller called jStik based on a line of java processors. A standard edition for Java Application Programming language has various components. It uses multi-tier architecture for database connectivity. It uses XMl files to store data and writing codes. JDOM is used for outputting XML data from Java code.
All the components of java work together to perform a given task, and such components are listed below:
1. Development tools and APIs as Java complier, Java debugger, Javadoc and JPDA
2. Deployment technologies could have sub-parts like Java web-start and Java plug-in
3. User interface tool kits are swing, AWT, sound, input methods, java 2D and accessibility.
4. Integration APIs are RMI, JDBC, JNDI, and CORBA.
5. Core APIs are like XML, logging, beans, Locale support, Preferences, Collections, JNI, Security, Lang, Util, New I/O and Networking
6. Java virtual machines are of three types as, Java hotspot client compiler, Java hotspot server complier ad Java hotspot VM runtime.
The various Java platforms are:
• Solaris
• Linux
• Windows
• And others.

Friday, November 11, 2011

Slide Show Applet

/* Java applet to display sildeshow to images from a given folder in thumbnail form, images can be selected one by one and can be enable/disable slideshow of images. The thumbnail images are placed in slides folder, the download button(rectangle) downloads the images from the web server, hence a webserver is required eg : any webserver even tomcat webserver with download folder with images*/
/* Requirements
1. Name of java file : Sildeshow.java
2. Name of images folder : slides
3. Names of images 1.jpg, 2.jpg and so on upto 8.jpg.
3. Name of download folder in webserver : download
4. Download images given below and paste them in slides folder :
1.jpg │2.jpg │3.jpg │4.jpg │5.jpg │6.jpg │7.jpg │8.jpg
5. Download images given below and paste them in download folder in webserver :
1.jpg │ 2.jpg │ 3.jpg │4.jpg │5.jpg │6.jpg │7.jpg │8.jpg

Java Code for Sildeshow

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class Slideshow extends Applet implements Runnable
{
// Variable Declaration
Thread runner;
boolean left,right,click,auto;
boolean but0,but1;
boolean b0,b1;
boolean waitMessage = true;
String str_desc[] = { // Display Messages
" This is an Abstract piece.Painted on:20/11/86.",
" This picture is an Abstract work.Painted on:10/1/89.",
" This picture is a Canvas oil painting (15/8/92).",
" This is a Pastel painting (2/10/99).",
" This picture is an Abstract piece.Painted on:6/5/03.",
" This is a Brush painting (2/6/05).",
" This a painted collage (30/1/83).",
" This is my Graphical art piece.Painted on:20/12/08."};
int number=1;
static final int MAX=8;
Image Picture[]=new Image[MAX]; // Image variable
Image Buffer;
Graphics gBuffer; // Graphics Variable
Font a = new Font("Helvetica", Font.PLAIN,12);
Font b = new Font("Dialog", Font.PLAIN,10);
Font c = new Font("Helvetica", Font.BOLD,13);
Rectangle r0=new Rectangle(400,70,50,20); // ON / OFF
Rectangle r1=new Rectangle(400,195,120,20); // Click Here
void loadGraphics()
{ //
Track the status of a number of media objects
MediaTracker t=new MediaTracker(this);
for(int i=0;i< MAX;i++)
{
// Load an image in an applet
Picture[i]=getImage(getCodeBase(),"slides/"+(i+1)+".jpg");
t.addImage(Picture[i],0);
try{
t.waitForAll(0);
}
catch(InterruptedException e)
{
}
waitMessage=false;
}
}

public void init()
{
// Creates an image
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();
// Creates a graphics context for this component
}
public void start()
{
if (runner == null)
{
runner = new Thread (this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}
public void run()
{
while(true)
{
try
{
runner.sleep(2500);
}
catch (Exception e)
{ }
if(auto)
{
if(number< MAX)
number++;
else
number=1;
}
repaint();
}
}
public void update(Graphics g)
{ paint(g); }
public void drawArrow(int w,int h,int x,int y,boolean left,boolean over,boolean click)
{
if(click&&over) // set color to yellow on click or mouse over
gBuffer.setColor(Color.yellow);
else
if(over) // set color to orange on mouse over
gBuffer.setColor(Color.orange);
else
// set color to red on click
gBuffer.setColor(Color.red);
if(left)
{
int al[] = {x,x+w,x+w};
int bl[] = {y+h/2,y,y+h};
gBuffer.fillPolygon(al, bl, 3);
}
else {
int ar[] = {x,x,x+w};
int br[] = {y,y+h,y+h/2};
gBuffer.fillPolygon(ar, br, 3);
}
}
public void drawPanel()
{
gBuffer.setColor(Color.white);
gBuffer.fillRect(0,0,size().width,size().height);
// Display Text
drawArrow(40,40,330+70,120,true,left,click);
// Display Left Arrow
drawArrow(40,40,380+70,120,false,right,click);
// Display Right Arrow
gBuffer.setColor(Color.lightGray);
gBuffer.setFont(b);
gBuffer.setColor(auto?Color.orange:Color.lightGray);
gBuffer.fill3DRect(400,70,50,20,!but0);
// Rectangle for ON rectangle
gBuffer.setColor(b0?Color.red:Color.black);
// Color For ON rectangle
String s=auto?"OFF":"ON";
gBuffer.drawString(s,410,85);
gBuffer.setColor(Color.lightGray);
// Download
s="Click Here";
gBuffer.fill3DRect(400,190,120,20,!but1);
gBuffer.setFont(a);
gBuffer.setColor(b1?Color.red:Color.black);
gBuffer.drawString(s,430,205);
// Display Image
gBuffer.drawImage(Picture[number-1],20,20,this);
gBuffer.setColor(Color.black);
gBuffer.setFont(c);
gBuffer.drawString("Slideshow:",300,80);
gBuffer.drawString("Scroll:",300,140);
gBuffer.drawString("Download it!",300,200);
gBuffer.drawString("Description:",300,35);
gBuffer.setFont(a);
gBuffer.drawString(str_desc[number-1],300,50);
}
public boolean mouseDown(Event evt,int x,int y)
{
if(r0.inside(x,y))
{
but0=true; auto^=true;
}
if(r1.inside(x,y))
{
but1=true;
auto=false;
}
if(but1)
{
String link ="http://localhost:8080/download/"+number+".jpg";
try {
// corresponds to an applet's environment
AppletContext a = getAppletContext();
URL url = new URL(link);
// url of the image to be downloaded
a.showDocument(url,"_blank");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
if(left)
{
auto=false;
if(number>1)
number--;
else number=8;
}
if(right)
{
auto=false;

if(number< MAX)
number++;
else
number=1;
}
click=true;
repaint();
return true;
}
public boolean mouseUp(Event evt,int x,int y)
{
but0=but1=click=false;
repaint();
return true;
}
public boolean mouseMove(Event evt,int x,int y)
{
Rectangle rl=new Rectangle(330+70,120,40,40);
Rectangle rr=new Rectangle(380+70,120,40,40);
if(rl.inside(x,y))
left=true;
else
left=false;
if(rr.inside(x,y))
right=true;
else
right=false;
if(r0.inside(x,y))
b0=true;
else
b0=false;
if(r1.inside(x,y))
b1=true;
else
b1=false;
repaint();
return true;
}
public void paint(Graphics g)
{
if(waitMessage)
{ g.setColor(Color.blue);
g.drawString("Loading images, please wait...",200,100);
loadGraphics();
}
else
{
drawPanel();
g.drawImage (Buffer,0,0, this);
}
}
}
//< code ="Slideshow" height ="500" width="500">
//< /applet>

C++ Notes


 

Introduction


          The main pitfall with standard C has been identified as the lack of facilities for data abstraction. With the emergence of more abstract and modular languages like Modula-2 and Ada and Object-oriented languages like Small-Talk, BJARNE STROUSRUP at Bells Lab was motivated to develop C++ by upgrading C with appropriate mechanisms to create object like abstract data structures. The introduction of the class mechanism in C++ mainly provides the base for implementing abstract data types to suit object-oriented programming. The C++ language is thus considered as the superset of the standard C.

IDENTIFIERS AND KEYWORDS

Identifiers can be defined as the name of the variables and some other program elements using the combination of the following characters.

Alphabets   : a…z, A…Z
Numerals    : 0…9
Underscore : _

Eg.,
          NAME, A23C, CODE, EMP_NAME


Special characters :

 All characters other than listed as alphabets, numerals and underscore, are special characters.


Keywords

Keywords are also identifiers but cannot be user defined since they are reserved words.

Keywords in C++

Auto  break          case char  const          continue   default do  double else  enum extern float for  goto  if  long  register  return  short signed  sizeof 
static  struct  switch  union  unsigned   void  volatile  while

Constants

·      String constants
·      Numeric constants
·      Character constants

String constants

A string constant is a sequence of alphanumeric characters enclosed in double quotation marks whose maximum length is 255 Characters.

Eg. “The man”
       “A343”



Numeric Constants

These are positive or negative numbers.
Types of Numeric constants are :


Integer
·      Integer
·      Short Integer(short)
·      Long Integer(long)

Float
·      Single precision(float)
·      Double precision(double)
·      Long double

Unsigned
·      Unsigned char
·      Unsigned integer
·      Unsigned short integer
·      Unsigned long integer

Hex
·      Short hexadecimal
·      Long Hexadecimal

Octal
·      Short octal
·      Long octal


Operators

·      Arithmetic operators (+, -, *, /, %)
·      Assignment operators (=, +=, -=, *=, /=, %=)
·      Comparison and Logical operators (<, >, <=, >=, ==,!=, &&, ||, !)
·      Relational operators (<, >, <=, >=)
·      Equality operators (==, !=)
·      Logical operators(&&, ||, !)
·      Unary operators(*, &, -, !, ++, --, type, sizeof)
·      Ternary operator (?)
·      Scope operator(::)
·      New and delete operators

Skeleton of typical C++ program

          Program heading
          Begin
                   Type or variable declaration
                   Statements of operation
                   Results
          End

Sample C++ program

#include<iostream.h>
void main()
{
          cout << “God is Great”;
}

iostream

The “iostream” supports both input/output stream of functions to read a stream of characters from the keyboard and to display a stream of objects onto the video screen.

Input and Output statements
Output Statement

The syntax…

  • cout << “Message”
  • cout << variable_name
  • cout << “Message” << variable_name

The ‘<<’ is called as “insertion” operator.

Eg.
                        Cout << “god is great”
                        Cout << age
                        Cout << “name is …” << name

Input Statement


The syntax…..
            Cin >> var1 >> var2 >> var3…..varn;
The ‘>>’ is called as “extraction” operator.

Eg.
                        Cout << “Enter a number”
                        Cin << a


Sample program to add, subtract, multiply and divide of the given two numbers


#include<iostream.h>
void main()
{
            int a,b,sum,sub,mul,div;
            cout << “Enter any two numbers “ << endln;
            cin >> a >> b;
            sum=a+b;
            sub=a-b;
            mul=a*b;
            div=a/b;
            cout << “Addition of two numbers is…” << sum;           
            cout << “Mulitiplication of two numbers is…” << mul;  
            cout << “Subtraction of two numbers is…” << sub;      
            cout << “Division of two numbers is…” << div;  
}


CONTROL STATEMENTS

Conditional Statements
The conditional expressions are mainly used for decision making. The following statements are used to perform the task of the conditional operations.

  • if statement
  • if-else statement
  • switch-case statement



if Statement

The if statement is used to express conditional expressions. If the given condition is true then it will execute the statements; otherwise it will execute the optional statements.

If (expression)
{
Statement;
Statement;
;;
;;
}

if-else statement
Syntax
if (expression)
                        statement;

else
                        statement;

Syntax
if (expression)
{
                        block-of-statements;
}
else
{
                        block-of-statements;
}

Nested if
If (expression) {
                        If (expression) {
                                    **********
                                    **********
                                    }
                        else {
                                    *********
                                    **********
                                    }
else {
                        if (expression) {
                                    *******
                                    ****
                        }
                        else {
                                    *********
                                    *********
                                    }
}

A program to read any two numbers from the keyboard and to display the largest value of them.
#include<iostream.h>
void main()
{
float x,y;
cout << “Enter any two numbers \n”;
cin >> x >> y;

if (x>y)
            cout << “Biggest number is…” << x << endl;
else
            cout << “Biggest number is…” << y << endl;
}

switch statement

The switch statement is a special multiway decision maker that tests whether an expression matches one of the number of constant values, and braces accordingly.

Syntax
            switch (expression) {
                        case contant_1 :
                                    Statements;
                        case contant_2 :
                                    Statements;

                                    ;;
                                    ;;         
                                    ;;
                        case contant_n :
                                    Statements;
                        default :
                                    Statement;
            }


A program to find out whether the given character is vowel or not
#include<iostream.h>
void main(){
char ch;
cout << “Enter the character :”
cin >> ch;
switch(ch){
                        case ‘A’ :
                        case ‘a’ :
                                    cout << “The given character is vowel “;
                                    break;
                        case ‘E’ :
                        case ‘e’ :
                                    cout << “The given character is vowel “;
                                    break;
                        case ‘I’ :
                        case ‘i’ :
                                    cout << “The given character is vowel “;
                                    break;
                        case ‘O’ :
                        case ‘o’ :
                                    cout << “The given character is vowel “;
                                    break;
                        case ‘U’ :
                        case ‘u’ :
                                    cout << “The given character is vowel “;
                                    break;
                        default :
                                    cout << “The given character is not vowel”;
                                    break;
                        }



Loop Statements

A set of statements are to be executed continuously until certain condition is satisfied. There are various loop statements available in C++.

  • for loop
  • while loop
  • do-while loop



for loop

This loop consists of three expressions. The first expression is used to initialize the index value, the second to check whether or not the loop is to be continued again and the third to change the index value for further iteration.

Syntax

for (initial_condition; test_condition; increment or decrement value)
{
statement_1;
statement_2;
;;
;;
}


A Program to find the sum and average of given numbers
#include<iostream.h>
void main(){

            int n;
            cout << “Enter the no. of terms…”;
            cin >> n;
            float sum = 0;
            float a;
            for (int i=0; i<=n-1;++i) {
                        cout << “Enter a number  :\n”;
                        cin >> a;
                        sum = sum+a;
            }
float av;
av = sum/n;
cout << “sum= “ << sum << endl’
cout << “Averave = << av << endl;
}

Nested For-Loops

for(i=0;i<=n; ++i){     
            for(j=0; j<=m ; ++j)
                        statements;
                        statements;
                        statements;
            }



while loop

This loop is used when we are not certain that the loop will be executed. After checking whether the initial condition is true or false and finding it to be true, only then the while loop will enter into the loop operations.

Syntax
            While (Condition)
                        Statement;

For a block of statements,

            while(condition) {
                        Statement_1;
                        Statement_2;
                        ----
                        ----
            }

Example

            while ((character = cin.get()) != EOF )
                        cout.put (character);

do-while loop

Whenever one is certain about a test condition, then the do-while loop can be used, as it enters into the loop at least once and then checks whether the given condition is true or false.
Syntax
do{
                        Statement_1;
                        Statement_2;
                        ------
                        ------
                        } while (expression);

Example

Sum=0;
do
{
            sum=sum+I;
            i++;
            }
while (i<n);

break statement

The “break” statement is used to terminate the control from the loop statements of the “case-switch” structure. This statement is normally used in the switch-case loop and in each case condition, the break statement must be used. If not, the control will be transferred to the subsequent case condition also.

Syntax
                        break;

Continue statement

This statement is used to repeat the same operations once again even if it checks the error.

Syntax
                        continue;

go to statement

This statement I used to alter the program execution sequence by transferring the control to some other part of the program.

Syntax
            goto label;

There are two types of goto statements, which are conditional and unconditional goto statement.

Unconditional goto


This goto statement is used to transfer the control from one part of the program to other part without checking any condition.

Example

#include<iostream.h>
void main(){
                        start:
            cout << “God is Great”;
                        goto start;
            }

Conditional goto


This will transfer the control of the execution from one part of the program to the other in certain cases.

Example

            If (a>b)
                        goto big1;

 

            big1:


Functions


            A function definition has a name, a parentheses pair containing zero or more parameters and a body. For each parameter, there should be a corresponding declaration that occurs before the body. Any parameter not declared is taken to be an int by default.

Syntax

            Function_type functionname(datatype arg1, datatype arg2,….)
            {
                        body of function;
                        ------
                        ------
                        return value;
            }


return keyword

          This keyword is used to terminate function and return a value to its caller. This can be also used to exit a function without returning a value;

Syntax
          return;
          return(expression);

Types of Functions

The user defined functions may be classified in the following three ways based on the formal arguments passed and the usage of the “return” statement, and based on that, there are three types of user-defined functions.

a)  A function is invoked without passing any formal argument from the calling portion of a program and also the function does not return back any value to the called function.
b)  A function is invoked with formal arguments from the calling portion of a program but the function does not return back any value to the calling portion.
c)   A function is invoked with formal arguments from the calling portion of a program which returns back a value to the calling environment.

Type 1
Example
          #include<iostream.h>
          void main(){
                   void message() // function declaration
                   message(); // function calling
          }
          void message(){
                   ----------
                   ---------- // body of the function
                   ----------
          }
Type 2
Example
          #include<iostream.h>
          void main(){
                   void square(int ) // function declaration
                   int a;
                   -------
                   -------
                   square(a); // function calling
          }
          void square(int x){
                   ----------
                   ---------- // body of the function
                   ----------
          }
Type 3
Example
          #include<iostream.h>
          void main(){
                   int check(int,int,char) // function declaration
                   int x,y,temp;
                   char ch;
                   ----------
                   ----------
                   temp=check(x,y,ch); // function calling
          }
           int check(int a, int b, char c){
                   int value;
                   ----------
                   ---------- // body of the function
                   ----------
                   return(value);
          }

A program to find the square of its number using a function declaration without using the return statement

#include<iostream.h>
Void main()
{
void square(int);
int max;
cout << “Enter a value for n ?\n”;
cin >> max;
for (int i=0;i<=max-1;++i)
            square(i);
}
void square(int n)
{
float v;
v=n*n;
cout << “ I = “<< n << “square = “ << value <<endl;
}

A program to find the factorial of a given number using function declaration with the return statement

#include<iostream.h>
void main(){
long int fact(int);
int x,n;
cout << “Enter the no. to find factorial “ << endl;
cin >> n;
x=fact(n);
cout << “value = “ << n << “and its factorial = “;
cout << x << endl;
}
long int fact(int n)
{
int value=1;
if (n == 1)
            return (value);
else
            {
                        for (int i=1;i<=n;++i)
                                    value = value * I;
                                    return(value);
                        }
}

Local and Global variables

Local variables

Identifiers declared as label, const, type variables and functions in a block are said to belong to a particular block or function and these identifiers are known as the local parameters or variables. Local variables are defined inside a function block or a compound statement.

Eg.

Void funct(int I, int j)
{
            int a,b; // local variables
            ::
            :;
            // body of the function
}


Global variables

Global variables are variables defined outside the main function block.

Eg.
            int a,b=10; // global variable declaration
            Void main()
            {
                        void func1();
                        a=20;
                        ::
                        :;
                        func1();
            }
            func1()
            {
                        int sum;
                        sum=a+b;
                        ::
                        :;
            }





Storage Class Specifiers

The storage class specifier refers to how widely it is known among a set of functions in a program. In other words, how the memory reference is carried out for a variable.

·         Automatic variable
·         Register Variable
·         Static variable
·         External variable


Automatic variable

Internal or local variables are the variables which are declared inside a function.

Eg.
            #include <iostream.h>
            void main()
            {
                        auto int a,b,c;
                        ::
                        ::
            }

Register Variable

These variables are used for fast processing. Whenever some variables are to be read or repeatedly used, they can be assigned as register variables.

Eg.
            function ( register int n)
                        {
                        register char temp;
                        ::
                        ::
                        }
Static Variable

Static variables are defined within a function and they have the same scope rules of the automatic variables but in the case of static variables, the contents of the variables will be retained throughout the program.

Eg.
            Static int x,y;
External variable

Variables which are declared outside the main are called external variables and these variables will have the same data type throughout the program, both in main and in the functions.

Eg.

            extern int x,y;
            extern float a,b;


A program to display the no and its square from 0 to 10  using REGISTER variables.

#include<iostream.h>
void main()
{
int funt(registerint x, register int y);
register int x,y,z;
x=0;
y=0;
cout<<”x           y”<<endl;
do
{
z=funt(x,y);
cout<<x<<’\t’<<z<<endl;
++x;
++y;
}
while(x<=10);
}
int funt(register int x, register int y);
{
register int temp;
temp=x*y;
return(temp);
}

Program to display 1 to 10 with addition of 100 using the automatic             variable and the static variable.

#include<iostream.h>
void main()
{
int func(int x);
int fun(int x1);
int k,s,v;
for (k=1;k<=10;k++)
{
v=func(k);
s=fun(k);
cout<<k<<’\t’<<v<<s<<endl;
}
}
func(int x)
{
int sum=100; // Automatic variable
sum+=x;
return(sum);
}
fun(int x1)
{
static int sum=100; // Static variable
sum+=x1;
return(sum);
}

Recursive Function

A function which calls itself directly or indirectly again and again is known as the recursive function.


Program to find the factorial of the given no using the recursive function

#include<iostream.h>
void main()
{
long int fact(long int);
int x,n;
cin>>n;
x=fact(n);
cout<<n<<x<<endl;
}

long int fact(long int n);
{
long int fact(long int n);
int v=1;
if(n==1) return(v);
else
{
v=n*fact(n-1);
return(v);
}
}

Arrays

An array is a collection of identical data objects which are stored in consecutive memory locations under a common heading or a variable name.

Syntax

            Storage_class data_type array_name[expression];

Example

            int value[10];
            char line[50];
            static char page[20];


Array initialization

            int values[5] = {44,65,77,77,55};
            char sex[] = { ‘M’, ‘F’};
            float bpay[] = {423.0,43.5,656.4};

A program to initialize a set of numbers in the array and to display it in a standard output device

#include <iostream.h>
void main()
{
int a[5]={44,67,77,88,34,55};
int I;
cout << “Contents of the array \n”;
for (i=0;i<5;++i)
{
          cout << a[i] << ‘\t’;
          }
}

Multidimensional Array

These are defined in the same manner as one dimensional arrays, except that a separate pair of square brackets are required for each subscript.

Syntax
          Storage_class data_type arrayname[expr1][expr2]…..[exprn];

Example
          float coordinate x[4][4];
          int value[10][5][5];

POINTERS

A pointer is a variable which holds the memory address of another variable.

Pointer operator
A pointer operator can be represented by a combination of *(asterisk) with a variable.

For eg.
                   int *ptr;
                   float *fp;

The general format of pointer declaration is…

                   data_type *pointer_variable;



Address operator
An address operator can be represented by a combination of & (ambersand) with a pointer variable.

For eg.

                   K = &ptr;

Pointer Expressions

Pointer assignment : A pointer is a variable data type and hence the general rule to assign its value to the pointer is same as that of any other variable data type.

Eg.
                   int x,y;
                   int *ptr1, *ptr2;
                   ptr1 = &x;
The memory address of variable x is assigned to the pointer variable ptr1.

                   y = *ptr1;

The contents of the pointer variable ptr1 is assigned to the variable y, not the memory address.

                   ptr1 = &x;
                   ptr2 = ptr1;

The address of the ptr1 is assigned to the pointer variable ptr2. The contents of both prt1 and ptr2 will be the same as these two pointer variables hold the same address.

A program to assign a character variable to the pointer and to display the contents of the pointer.

#include <iostream.h>
void main()
{
char x,y;
char *pt;
x = ‘k’; // assign character
pt = &x;
y = *pt;
cout << “Value of x = “ << x << endl;
cout << “Pointer value = “ << y << endl;
}

Structure

A structure is an aggregate of several data items that can be of different types, and it is defined using the keyword struct. The items are called members of the structure and are logically grouped. They convey information about the same object.

Eg.

          struct student {
                   int rollno;
                   char name[20];
                   };


typedef

The typedef is used to define new data items that are equivalent to the existing data types.

Syntax

          typedef datatype newtype;
Eg.

          typedef int integer;
          typedef float real;
          Integer a,b;
          real x,y;

Features of C++

Class 

A group of objects that share common properties and  relationship. In C++, a class is a new data type that contains member variables and member functions that operates on the variables. A class is defined with the keyword class.

Class Object
          A variable whose data type is a class.

Structure of C++ Program

A C++ program is similar to an ANSI C program except with some newly added types of declarations. Since CLASS types encapsulate all the functions, a C++ program may not have any subordinate function apart from the main function. A general structure of a program may look like

< include standard header files>
<include user-defined header files>
<declaration of class type>
<declaration of objects>
void main()
{
   declaration of local objects and variables
   statements
}

C++ class definition

 Syntax:  <classkey> <classname> [<:baselist>] { <member list> }
Classes are specific to C++.
   <classkey> is one of the keywords "class", "struct", or "union".
  <classname> can be any name unique within its scope.
   <baselist> lists the base class(es) that this class derives from.
    <baselist> is optional.
   <member list> declares the class's data members and member functions.
Within a class,
  the data are called "data members"
  the functions are called "member functions"

 Example:
  class students {
    int rollno;
    int calculate(void);
  };


Access Specifiers

public, private, and protected

Members of a class can acquire access attributes in one of two ways:
by default, or through the use of the access specifiers  public, private, and protected.

Syntax:

   public: <declarations>
   private: <declarations>
   protected <declarations>

Public
If a member is public, it can be used by any function. In C++, members of a struct or union are public by default.

Private
If a member is private, it can only be used by member functions and friends of the class in which it is declared. Members of a class are private by default.

Protected
If a member is protected, its access is the same as for private. In addition, the member can be used by member functions and friends of classes derived from the declared class, but only in objects of the derived type.

Scope Resolution Operator(::)

This operator can be used to refer to any member in the class explicitly.


Sample c++ program

#include<iostream.h> // include files
class student   // class declarations
{
        char name[30];
        int age;
   public:
       void getdata(void);
      void display(void);
 }
void student:: getdata(void) // member functions definitions
    {
       cout << "Enter name ";
       cin >> name;
      cout << "enter age"
       cin >> age;
 }
void student::display(void) // member function definitions
{
  cout << " name à " << name;
  cout << " age à " <<, age;
}
void main()   // main function program
 {
  student s1;  // s1 is an object for the class student
  s1.getdata();
  s1.display();
}

Constructor

          C++ provides a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it construct the values of data members of the class.

Firing of Constructor.
            A Constructor fires at the time of creation of objects.
Types of Constructor
There are 4 types of constructors.

1.    Default Constructor
2.    Argument or Parametric Constructor
3.    Copy Constructor
4.    Dynamic Constructor

  1. Default Constructor : Default Constructor fires automatically at the time of creation of the objects.
  2. Argumental Constructor : It fires only if the argument is passed to the constructor.
  3. Copy Constructor : If the value of one constructor is given to an another constructor, then it is called as copy constructor.
  4. Dynamic Construtor : It is used for allocation of memory to a variable at run time.

Example :
# include <iostream.h>
class date
  {
    private :
            int dd;
            int mm;
            int yy;
    public :
            date ()             // ex. for default constructor
            {
            dd=01;
            mm=01;
            yy=2002;
            }
date (int d,int m, int y)          // ex. for argumental constructor
            {
            dd=d;
            mm=m;
            yy=y;
            }
            date(date x)
            {  
                dd = x.dd;
                mm = x.mm;
                yy=x.yy;
}
            void showdate();
            void displaydate();
};
void date ::showdate()
{
cin >> dd>>mm>>yy;
}
void date ::displaydate()
{
cout << dd<<mm<<yy;
}
void main()
{
date  d1,d2(3,3,2002);
d1.showdate();
d1.displaydate();
d2.showdate();
d2.displaydate();
date (d2);                   // ex for copy constructor
}

Parameterized Constructors

          Parameterized constructor is used to initialize the various data elements of different objects with different values when they are created. C++ permits us to achieve this objective by passing arguments to constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors.

Destructor

          A destructor, as the name implies, is used to destroy the objects that have been created by a constructor. The destructor is a member function whose name is the same as the class name but is preceded by tilde. A destructor never takes any argument not does it return any value. It will be invoked implicitly by the compiler upon exit from the program to clean up the storage that is no longer accessible.

Example for Destructor :
class word {
            private :
            char *str_word;
            public :
            word (char *s)
            {
            str_word=new char(strlen(s));
            strcpy=(str_word,s);
            }
            int getlen()
            {
            return strlen(str_word);
            }
            char *getword()
            {
            return str_word:
            }
       ~word()
        {
delete str_word;
}
};
void main()
{
word *word1;
word1->word::~word;
}

Inheritance

Inheritance is the process of creating new classes called derived classes, from existing or base classes. The derived class inherits all the capabilities of the base classes. The derived class inherits all the capabilities of the base class but can add embellishments and refinements of its own. The base class is unchanged by this process.

Inheritance has important advantages, most importantly it permits code reusability. Once a base class is written and debugged, if need not be touched again but can nevertheless be adapted to work in different situations. Reusing existing code saves times and money and increases program’s reusability.

            1. Inheritance is the concept by which the properties of one entity are available to another.
            2. It allocates new class to be built from older and less specialized classes instead of being rewritten from scratch.
            3. The class that inherits properties and functions is called the sub class or the derived class and the class from which they are inherited is called super class (or) the base class.
            4. The derived class inherits all the properties of the base class and can add properties and refinements of its own. The base class remains unchanged.

# include <iostream.h>
class Base
{
public :
            void show()
            {
            cout << “\n Base”;
            }};
class Der1 :public Base
{
public :
            void show()
            {
            cout <<”\nDer1”;
            }
};
class Der2:public Base
{
            public :
            void show()
            {
            cout <<”\nDer2”;
            }
};
void main()
{
Der1 d1;
Der2 d2;
Base *ptr;
Ptr=&d1;
Ptr->show();
Ptr=&d2;
Ptr->show();
}



Function overloading

This is a logical method of calling several functions with different arguments and data types that perform basically identical things by the same name.

A program to demonstrate how function overloading is carried out for swapping of two variables of the various data types.

#include <iostream.h>
void swap(int &x, int &y);
void swap(float a,float b);
void main()
{
int x,y;
float a,b;
cout << “Enter any two integers..” << endl;
cin >> x>>y;
cout << “Enter any two Float numbers..” << endl;
cin >> a>>b;
// swapping integer numbers
swap(x,y)
cout << “After swapping integer numbers..”<<endl;
cout <<x<<y;
// swapping float numbers
swap(a,b)
cout << “After swapping float numbers..”<<endl;
cout <<x<<y;
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void swap(float &a, float &b)
{
float temp;
temp=a;
a=b;
b=temp;
}

Static Data Members

Static member variables are similar to C static variable. A static member variable has special characteristics. It is initialized to zero when the first object of its class is created. No other initialization is permitted. Only one copy of that member is created for the entire class and is shared by all objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Static variables are normally used to maintain values common to entire class.

Polymorphism

          A property by which we can send the same message to objects of several different classes, and each respond in a different way depending on its class. We can send such message without knowing to which of the classes the objects belongs.

# include <iostream.h>
class date
{
     private :
            int dd;
            int mm;
            int yy;
    public :
            void showdate();
            void displaydate();
};
void date ::showdate()
{
cin >> dd>>mm>>yy;
}
void date ::displaydate()
{
cout << dd<<mm<<yy;
}
void main()
{
date  d;
d.showdate();
d.displaydate();
}

Virtual functions

Virtual functions let derived classes provide different versions of a base class function. You can declare a virtual function in a base class, then redefine it in any derived class, even if the number and type of arguments are the same. The redefined function overrides the base class function of the same name. Virtual functions can only be member functions.

You can also declare the functions

  int Base::Fun(int)
and
  int Derived::Fun(int)
even when they are not virtual.

The base class version is available to derived class objects via scope override. If they are virtual, only the function associated with the actual type of the object is available. With virtual functions, you can't change just the function type. It is illegal, therefore, to redefine a virtual function so that it differs only in the return type. If two functions with the same name have different arguments, C++ considers them different, and the virtual function mechanism is ignored.

A function qualified by the virtual keyword. When a virtual function is called via a pointer, the class of the objects pointed to determine which function definition will be used. Virtual functions implement polymorphism, whereby objects belonging to different classes can respond to the same message in different ways.

# include <iostream.h>
# include <string.h>
class Base
{
public :
virtual void show_message(void)
{
cout <<”Base class message”<<,endl:};
};
virtual void show_reverse(void)=0;
};
class Derived :public Base
{
public :
            virtual void show_message(void)
            {
            cout <<”Derived class message”<<endl;
            };
            virtual void show_reverse(void)
            {
            cout <<strrev(“Derived class message”)<<endl;
}
};
void main(void)
{
Base *poly=new Derived;
Poly->show_message();
Poly->show_reverse();
}

Operator Overloading

C++ enables use of system defined (or standard) operators, such as +, -, *, == etc., to act on the user-defined data structures(or objects) in a way relevant to that data structure( or object). An operator thus may have the same LABEL OR SYMBOL as a structure operator, but associating with different parameters and resulting to different action.

We may use the plus(+) operator on different objects.

str=str1 + str2 // concatenate two strings
arr=arr1 + arr2 // add two arrays
c =  c1 + c2 // add two complex numbers
r = r1 + r2 // add two rational numbers
s = s1 + s2 // union of sets s1,s2


C++ allows two variables of user-defined type with the same syntax that is applied to the basic types. C++ has the ability to provide the operators with a special meaning for a data type. The mechanism of giving such special meaning to an operator is known as Operator Overloading.

The following program segment illustrates the overloading of an assignment operator in a class.

#include <iostream.h>
class sample {
          private :
                   int x;
                   float y;
          public :
                   sample(int, float);
                   void operator = (sample abc);
                   void display();
          };
void sample :: operator = (sample abc)
{
          x = abc.x;
          y = abc.y;
}
void main()
{
          sample obj1;
          sample obj2;
          ;;;;;
          ;;;;;
          obj1 = obj2;
          obj2.display();
}

new (operator) and delete (operator)

Operators that create and destroy an object

 Syntax:
 <pointer_to_name> = new <name> [ <name_initializer> ];
  delete <pointer_to_name>;

The "new" operator tries to create an object <name> by allocating sizeof(<name>) bytes in the heap. The "delete" operator destroys the object <name> by deallocating sizeof(<name>) bytes (pointed to by <pointer_to_name>).

The storage duration of the new object is from the point of creation until the operator "delete" deallocates its memory, or until the end of the program.

 Example:
  name *nameptr;  // name is any non-function type
   ...
  if (!(nameptr = new name)) {
    errmsg("Insufficient memory for name");
    exit (1);
  }
  // Use *nameptr to initialize new name object
   ...
  delete nameptr; //destroy name; deallocate sizeof(name) bytes

friend (keyword)

A friend of a class X is a function or class that, although not a member of that class, has full access rights to the private and protected members of class X.

 Syntax:
                     friend <identifier>;

In all other respects, the friend is a normal function in terms of scope, declarations, and definitions.

Example:

  class students {
    friend department;
    int rollno;
    int calculate(void);
  };
  class department {
     char ugcourse[25];
     void performance(students*);
  };


Example 2 for Friend function
# include <iostream.h>
class Sample
{
int a,b;
public :
friend int sum(sample object);
void set_ab(int i, int j);
};
void sample ::set_ab(int I,int j)
{
            a=i;
            b=j;
}
int sum(sample object)
// because it is friend of a samples
return object a + object b;
}
void main (void)
{
sample integer;
integer.set_ab(3,4);
cout <<sum(integer);
}

inline (keyword)

          Declares/defines C++ inline functions

 Syntax:
  <datatype> <function>(<parameters>) { <statements>; }
  inline <datatype> <class>::<function> (<parameters>) { <statements>; }

In C++, you can both declare and define a member function within its class.
Such functions are called inline.

The first syntax example declares an inline function by default. The syntax
must occur within a class definition.

The second syntax example declares an inline function explicitly. Such
definitions do not have to fall within the class definition.

Inline functions are best reserved for small, frequently used functions.

 Example:
  /* First example: Implicit inline statement */

  int num;     // global num
  class cat {
  public:
    char* func(void) { return num; }
    char* num;
  }


  /* Second example: Explicit inline statement */
  inline char* cat::func(void) { return num; }

operator (keyword)
Defines a new action
 Syntax:
  operator <operator symbol>( <parameters> )
  {
     <statements>;
  }

The keyword "operator", followed by an operator symbol, defines a new (overloaded) action of the given operator.

Example:

  complex operator +(complex c1, complex c2)
  {
     return complex(c1.real + c2.real, c1.imag + c2.imag);
  }

this (C++ keyword)

Non-static member functions operate on the class type object with which they are called. For example, if x is an object of class X and func is a member function of X, the function call x.func() operates on x. Similarly, if xptr is a pointer to an X object, the function call xptr->func() operates on *xptr. But how does func know which x it is operating on? C++ provides func with a pointer to x called "this". "this" is passed as a hidden argument in all calls to non-static member functions.

The keyword "this" is a local variable available in the body of any nonstatic member function. The keyword "this" does not need to be declared and is rarely referred to explicitly in a function definition. However, it is used implicitly within the function for member references. For example, if x.func(y) is called, where y is a member of X, the keyword "this" is set to &x and y is set to this->y, which is equivalent to x.y.

Virtual Classes

You might want to make a class virtual if it is a base class that has been passed to more than one derived class, as might happen with multiple inheritance.

A base class can't be specified more than once in a derived class:
  class B { ...};
  class D : B, B { ... };  // ILLEGAL

However, a base class can be indirectly passed to the derived class more than once:
  class X : public B { ... }
  class Y : public B { ... }
  class Z : public X, public Y { ... }  // OK

In this case, each object of class Z will have two sub-objects of class B.
If this causes problems, you can add the keyword "virtual" to a base class
specifier.

For example,

  class X : virtual public B { ... }
  class Y : virtual public B { ... }
  class Z : public X, public Y { ... }

B is now a virtual base class, and class Z has only one sub-object of class B.




Constructors for Virtual Base Classes

Constructors for virtual base classes are invoked before any non-virtual base classes. If the hierarchy contains multiple virtual base classes, the virtual base class constructors are invoked in the order in which they were declared.

Any non-virtual bases are then constructed before the derived class constructor is called. If a virtual class is derived from a non-virtual base, that non-virtual base will be first, so that the virtual base class can be properly constructed. For example, this code

  class X : public Y, virtual public Z
     X one;

produces this order:

  Z();   // virtual base class initialization
  Y();   // non-virtual base class
  X();   // derived class

Function Definition and Prototyping

The compiler must be informed of the return types and parameter types of the functions so that it will be able to check for the correct usage of the calls to those functions during compilation. To satisfy the compiler either of the following conventions may be adapted:

1.   A complete function definition
#include< iostream.h>
int triple(int); // function prototype
void main()
{
   cout<<”\n The tripled value of f is “<<triple(25);
  }
int triple(int f)
{
    return (f * f * f);
}

2.   A declaration of the function prototype before the function call.

Float square(float); or float square(float x);

Int main(void)
{
          printf(“%f\n”,square(5.0));
}

/* A simple C++ program to demonstrate the use of function prototype */

#include<iostream.h>
float square(float);
void print(float);
          int main(void)
          {
                   float x;
                   x=square(25.0);
                   print(x);
          }

          /* Actual definition of the function */
                   float square(float x)
          {
                   return(x*x);
          }
          void print(float x)
          {
                   cout<<x;
          }

Some conventions in specifying default initializers

1.   Multiple default initializers and their order:

Multiple parameters may be given default values, but these must be assigned from the rightmost parameter to the left.

2.   Default initializers and prototype definitions:

By convention, default initializes can occur only in the prototype definitions, not in the actual function definitions.

Eg. int power(int exponent, int base=2);// This prototype definition is                                                    correct//
int power(int exponent, int base=2); // Not correct//
{ /* function code */ }

3.   No repetition of default intializer:

A default intializer can occur only once. Assume that myfunc.h contains the following prototype definition:
Int power(int exponent, int base=2);
Then,
          #include “myfunc.h”// myfunc.h has original definition
          int power(int exponent, int base=2) // Illegal, base is given with                                                             a default value//

4.   Successive default initialization :
Applications can use this convention to customize the default initialization according to their requirement. The following cases show legal and illegal successive declarations.

Case 1:
          int power(int exponent, base); // Original declaration
int power(int exponent, base=2); // legal(successive)
                                                redeclaration//
 int power(int exponent=0, base); // legal(successive)
                                                redeclaration//
         
Case 2:

          int power(int exponent, base); // Original declaration
int power(int exponent=0, base); // Illegal, start from
                                                rightmost redeclaration //

 int power(int exponent=0, base=2); // Illegal, exponent already
                                                          initialized //
                  
                   Case 3:

          int power(int exponent, base=2); // Original declaration
int power(int exponent, base); // Legal redeclaration
 int power(int exponent=0, base); // Legal redeclaration
TEMPLATE

A Template provides the formats of functions and type placeholder. It eliminates duplication of functions and data’s. The following shows the general forms of a function template, where T is a type that the compiler will later replace.

Template<class T> T function_name(T param_1, T param_b)
{
// statements
}
for example
template<class T> T compare_values(T a,T b)
{
return(a+b);
}

The complier can replace the letter T with either the type float or int.

Function Template

The function template acts as model and it can be replaced by any type of function data types.

Simple Example:

#include <iostream.h>
template<class T > T add(T a, T b)
{
T c;
c=a+b;
return(c);
}
void main()
{
int a,b;
float c,d;
cin>>a>>b;
cout<<add(a,b);
cout<<add(c,d);
}


Generic Template:

A generic function defines a general set of operations that the function will apply to various data type. A generic function receives the type of data on which the function will operate as a parameter. Creating generic functions within our program can be useful because many algrorithms are fundamentally the same in their processing yet independent of the data type on which the algorithm operates. The word template is a key and T type is place holder of the data type.
template <class T type> return type function name(parameter list)
{
//statement
}
#include <iostream.h>
template<class T, class T1 > T avg(T a, T b)
{
T1 c;
c=(a+b)/2;
return(c);
}
void main()
{
int a,b;
float c;
cin>>a>>b;
c=avg(a,b);
cout<<c;
}

Class Template:

If a class acts a placeholder for nay data type then the class must be defined in the form of template.
template <class T> class someclass
{
//statement ;
}
Here  the template not only specifies a type placeholder , it also specifies a parameter that the program can use within the template. When the program later uses the template, it can pass a parameter value to the template as shown here
Someclass<int 1029> this_instance
template <class T> class add
{
T a;
T b;
public:
void  sum();
void getdata();  };

template <class T>void  add<T>::sum()
{
T c;
c=a+b;
cout<<c;
}
template <class T>void  add<T>::getdata()
{
cin>>a>>b;
}
void main()
{
add a;
a.getdata();
a.sum()
}


















LAB CYCLE

1. Write a C++ program to generate a pyramid using a set of integer numbers.
2. Write a C++ program to solve a Quadratic equation.
3. Write a C++ program to generate a Fibonacci series of ‘N’ numbers.
4. Write a function in C++ program to find the sum of the following series.
          a) sum=1+3+5+……+n
          b) sum =x+x2/2!+x4/4!....+xn/n!
5. Write a C++ program to read a line and find out the number of vowels(a,e,I,o,u).
6. Write a C++ program to find the largest and smallest number in the given set of ‘N’ numbers.
7. Write a program to read any four characters and print out all the possible combinations.
8. Write a program in C++ to read a set of characters using a pointer and to print in the reverse order.
9. Write an object oriented program in C++ to read an integer number and find out the sum of all the digits until it comes to a single digit.
10. Write an oop in C++ that prints whether a given number is prime or not.

11. Write an OOP in C++ to read a number n and print it digit by digit in words using inline member function.
12. Write an OOP in C++ to read two dimensional array; find the sum of the elements row-wise and column-wise separately, and display the sums using ‘new’ and ‘delete’ operators.
13. Develop an OOP in C++ to create a data base of the following items of the derived class.
          Name of the patient
          Sex
          Age
          Ward number
          Bed number
          Nature of illness
          Date of admission
Design a base class consisting of the data members, viz, name of the patient,sex, and age and another base class consisting of ward number,bed number and nature of the illness. The derived class consists of the data member, date of admission. Develop the program for the following facilities.

·      build a master table
·      list a table
·      insert a new entry
·      delete old entry
·      search a record that is to be printed

14. Write a function overloading program to read a set of coordinates of a rectrangle.
15. Write a program in C++ to perform the following using operator overloading:
          a) Area of a circle          b) Area of a rectangle   c) Area of triangle
16.Write an OOP in C++ using polymorphic technique that prints either the number and its square  or the number and its cube from 0 to 100.

17.Write a program in C++ to perform the following using the function template concepts:
          i) to read a set of integers
          ii) to read a set of floating point numbers
          iii) to read a set of double numbers individually.
Find out the average of the non-negative integers and also calculate the deviation of the numbers.

18.Write a program in C++ to read student’s record such as name,sex,roll number, height, and weight from the specified file and to display in a sorted order.(name is the key sorting)
19. Write a program in C++ to merge two files into one file heading.
20. Write an OOP in C++ to add, subtract of any two given complex numbers using friend function.