Friday 30 September 2011

Function in C\C++

Functions


All languages have a construct to separate and package blocks of code. C uses the "function" to package blocks of code. This article concentrates on the syntax and peculiarities of C functions. The motivation and design for dividing a computation into separate blocks is an entire discipline in its own.

A function has a name, a list of arguments which it takes when called, and the block of code it executes when called. C functions are defined in a text file and the names of all the functions in a C program are lumped together in a single, flat namespace. The special  function called "main" is where program execution begins. Some programmers like to begin their function names with Upper case, using lower case for variables and parameters, Here is a simple C function declaration. This declares a function named  Twice which takes a single int argument named num. The body of the function computes the value which is twice the num argument and returns that value to the caller.

/*
Computes double of a number.
Works by tripling the number, and then subtracting to get back to double.
*/

static int Twice(int num)
{
   int result = num * 3;
   result = result - num;
   return(result);
}


How to use function ?


#include<stdio.h>
#include<conio.h>
int header();
int sum; /* This is a global variable */
int main( )
{
int index;
header(); /* This calls the function named header */
for (index = 1;index <= 7;index++)
square(index); /* This calls the square function */
ending();
getch(); /* This calls the ending function */
}


header() /* This is the function named header */
{
sum = 0; /* initialize the variable "sum" */
printf("This is the header for the square program\n\n");
}


square(number) /* This is the square function */
int number;
{
int numsq;
numsq = number * number; /* This produces the square */
sum += numsq;
printf("The square of %d is %d\n",number,numsq);
}
ending() /* This is the ending function */
{
printf("\nThe sum of the squares is %d\n",sum);


}

Tuesday 27 September 2011

Union in C/C++

What Is a Union?


1. Like a structure, a union is also a derived data type.
2. The members of a union share a single storage space.
3. Only ONE member of each union can be referenced at a time.
4. Amount of space allocated for storage is the amount needed for the largest
member of the union.

C/C++

In C and C++, untagged unions are expressed nearly exactly like structures (structs), except that each data member begins at the same location in memory. The data members, as in structures, need not be primitive values, and in fact may be structures or even other unions. However, C++ does not allow for a data member to be any type that has a full fledged constructor/destructor and/or copy constructor, or a non-trivial copy assignment operator. For example, it is impossible to have the standard C++ string as a member of a union.
The primary usefulness of a union is to conserve space, since it provides a way of letting many different types be stored in the same space. Unions also provide crude polymorphism. However, there is no checking of types, so it is up to the programmer to be sure that the proper fields are accessed in different contexts. The relevant field of a union variable is typically determined by the state of other variables, possibly in an enclosing struct.


Structure and union specifiers have the same form. [ . . . ] The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object (computer science) at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.One common C programming idiom uses unions to perform what C++ calls a reinterpret_cast, by assigning to one field of a union and reading from another, as is done in code which depends on the raw representation of the values. A practical example is the method of computing square roots using the IEEE representation. This is not, however, a safe use of unions in general.



Example of the Use of a Union

union temperature
{
short int surfaceOfEarthTemperature;
long int astronomicalTemperature;
float floatingPointTemperature;
};
union temperature celsiusTemperature, fahrenheitTemperature, ovenTemperature,
surfaceOfTheSunTemperature;
main()
{
celsiusTemperature.floatingPointTemperature = 87.3;
fahrenheitTemperature.floatingPointTemperature =
32.0 + (9.0 * celsiusTemperature.floatingPointTemperature/5.0);
ovenTemperature.ssurfaceOfEarthTemperature = 375;
surfaceOfTheSunTemperature.astronomicalTemperature = 4387912;
}

// anonymous_unions.cpp
#include <iostream> 
using namespace std;
int main()
{ 
      union {
              int d; char *f;
            };
             d = 4; 
             cout << d << endl; 
             f = "inside of union";
             cout << f << endl; 
}


union <name>
{ 
     <datatype> <1st variable name>; 
     <datatype> <2nd variable name>;  
     . . . 
     <datatype> <nth variable name>;
}<union variable name>;


union name1 
{
    struct name2 
    { 
       int a; 
       float b;
       char c;      
    } 
     svar; 
     int d; 
} uvar;

Structures in C/C++


What Is a Structure?


1. A collection of variables that are functionally related to each other.
2. Each variable that is a member of the structure has a specific type.
3. Different members of the structure may have either the same or different
types. Cf. the elements of an array, which must all be of one type.
4. A structure is a derived data type, constructed from two or more objects of
one or more individual types.
5. The entire structure may bear a name.
6. Each member of the structure must [also] have a name.
7. The scope of the name of a structure member is limited to the structure itself
and also to any variable declared to be of the structure's type.

8. THEREFORE, different structures may contain members having the same name;
these may be of the same or of different types.
9. A self-referential structure contains a member which is a pointer to the same
structure type.
10. Declaration of the structure merely defines the new data type; space is NOT
reserved in memory as a result of the declaration.
However, declaration of the structure does define how much memory is
needed to store each variable subsequently declared to be of the type of
the defined structure.


Form of Structure Declaration: Alternative 1


(1) Complete definition including assignment of a tag name to the structure.
(2) The tag name is referred to in subsequent declarations of variables of the type
so defined.
(3) Each such declaration MUST include the keyword struct AND the name of the
user-defined structure type AND the variable name(s).
struct nameOfThisStructureType
{
typeOfFirstMember nameOfFirstMember;
typeOfSecondMember nameOfSecondMember;
typeOfThirdMember nameOfThirdMember;
. . .
};
struct nameOfThisStructureType variable1OfThisStructureType,
variable2OfThisStructureType,
. . . ;
Additional variable declarations can subsequently be made for this structure type.


Form of Structure Declaration: Alternative 2


(1) Basic named definition of the structure is effected same as for Alternative 1.
(2) In ADDITION, one or more variables can be declared within the declaration
of the structure type to be of the defined type.
(3) Other variables may also be declared subsequently to be of the same type of
this structure, using the keyword struct together with the tag name and the
variable names.
struct nameOfThisStructureType
{
typeOfFirstMember nameOfFirstMember;
typeOfSecondMember nameOfSecondMember;
typeOfThirdMember nameOfThirdMember;
. . .
} variable1OfThisStructureType, variable2OfThisStructureType, . . .;
struct nameOfThisStructureType variable3OfThisStructureType,
variable4OfThisStructureType,
. . . ;



Form of Structure Declaration: Alternative 3

(1) Tag name is not assigned to the structure when the type is declared.
(2) Variables are specified within the structure declaration to be of the defined
structure type.
(3) Because of the absence of a tag name for the structure type, there is no means
available to ever be able to declare any other variables to be of this same
type.
struct /* NO NAME ASSIGNED TO THE TYPE */
{
typeOfFirstMember nameOfFirstMember;
typeOfSecondMember nameOfSecondMember;
typeOfThirdMember nameOfThirdMember;
. . .
} variable1OfThisStructureType, variable2OfThisStructureType, . . .;


Form of Structure Declaration: Alternative 4


(1) Complete definition of the structure, including assignment to it of a tag name.
(2) Subsequently, the tag name is used in a typedef declaration to assign a second
name (i.e., an alias ) to the structure. The alias can then be used in declaring
a variable the same way as a native C type name is used, that is, without the
keyword struct, i.e., just like int, char, float, etc.
struct nameOfThisStructureType
{
typeOfFirstMember nameOfFirstMember;
typeOfSecondMember nameOfSecondMember;
typeOfThirdMember nameOfThirdMember;
. . .
};
typedef struct nameOfThisStructureType AliasForThisStructureType;
AliasForThisStructureType variable1OfThisStructureType,
variable2OfThisStructureType, . . . ;



Form of Structure Declaration: Alternative 5

(1) Complete definition of the structure without assignment of a tag name.
(2) The keyword typedef is used within the declaration of the structure to assign a
name (i.e., an alias) to the structure. The structure itself is anonymous, and
has only the alias name. The alias can be used in the same way as a native C
type name is used , that is, without the keyword struct, i.e., just like int,
char, float, etc.
typedef struct
{
typeOfFirstMember nameOfFirstMember;
typeOfSecondMember nameOfSecondMember;
typeOfThirdMember nameOfThirdMember;
. . .
} AliasForThisStructureType;
AliasForThisStructureType variable1OfThisStructureType,
variable2OfThisStructureType, . . . ;


Example 1

enum genders {MALE, FEMALE};
enum studentStatus {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR, POSTBAC};
struct student
{
char firstName[20];
char lastName[20];
char middleName[20];
long int studentNumber;
short int entranceYear;
genders studentGender;
studentStatus status;
char major[6];
struct student *nextStudent; /* Useful for making a linked list. */
struct student *priorStudent; /* Useful for a doubly linked list. */
};
struct student undergraduateStudent, graduateStudent;
struct student specialStudent;


Example 2


enum genders {MALE, FEMALE};
enum studentStatus {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR, POSTBAC};
struct student
{
char firstName[20];
char lastName[20];
char middleName[20];
long int studentNumber;
short int entranceYear;
genders studentGender;
studentStatus status;
char major[6];
struct student *nextStudent;
struct student *priorStudent;
} undergraduateStudent, graduateStudent;
struct student specialStudent;



Example 3

enum genders {MALE, FEMALE};
enum studentStatus {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR, POSTBAC};
struct
{
char firstName[20];
char lastName[20];
char middleName[20];
long int studentNumber;
short int entranceYear;
genders studentGender;
studentStatus status;
char major[6];
struct student *nextStudent;
struct student *priorStudent;
} undergraduateStudent, graduateStudent, specialStudent;


Example 4


enum genders {MALE, FEMALE};
enum studentStatus {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR, POSTBAC};
struct student
{
char firstName[20];
char lastName[20];
char middleName[20];
long int studentNumber;
short int entranceYear;
genders studentGender;
studentStatus status;
char major[6];
struct student *nextStudent;
struct student *priorStudent;
} undergraduateStudent, graduateStudent;
typedef struct student StudentType;
StudentType specialStudent;



Example 5

enum genders {MALE, FEMALE};
enum studentStatus {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR, POSTBAC};
typedef struct
{
char firstName[20];
char lastName[20];
char middleName[20];
long int studentNumber;
short int entranceYear;
genders studentGender;
studentStatus status;
char major[6];
struct student *nextStudent;
struct student *priorStudent;
} StudentType;
StudentType undergraduateStudent, graduateStudent, specialStudent;



Which Alternative(s) Should YOU Use?


1. Alternative 3 is useful (example 3) because it forces all variables to be
declared at structure definition time.
2. Alternative 5 is useful (example 5) because it enables variable declarations
to be made to the structure type withOUT use of the keyword struct.
3. NONE of the other alternatives should ever be used; they are principally of
historical interest.



Accessing Members of a Variable of a Structure Type

1. Structure Member operator ≡ Dot operator
StudentType undergraduateStudent;
char lastNameOfStudent[20];
lastNameOfStudent = undergraduateStudent.lastName;
1. Structure Pointer operator ≡ Member operator
StudentType *pointerToGraduateStudent;
short int yearOfStudentEntrance;
yearOfStudentEntrance = pointerToGraduateStudent—>entranceYear;
OR
StudentType *pointerToGraduateStudent
short int yearOfStudentEntrance;
yearOfStudentEntrance = (*pointerToGraduateStudent).entranceYear;
/* NOTE: The parentheses are NECESSARY in this example. */

Monday 26 September 2011

Java program for addition and multiplication of two number in AWT view


The java.awt Package

The java.awt package is the main package of the AWT, or Abstract Windowing Toolkit. It contains classes for graphics, including the Java 2D graphics capabilities introduced in the Java 2 platform, and also defines the basic graphical user interface (GUI) framework for Java. java.awt also includes a number of heavyweight GUI objects, many of which have been superseded by the javax.swing package. java.awt also has a number of important subpackages.
The most important graphics classes in java.awt are Graphics and its Java 2D extension, Graphics2D. These classes represent a drawing surface, maintain a set of drawing attributes, and define methods for drawing and filling lines, shapes, and text. Classes that represent graphics attributes include ColorFontPaintStroke, and Composite. The Image class and Shape interface represent things that you can draw using a Graphics object and the various graphics attributes. Figure shows the graphics classes of this package.


figure


import java.awt.*;
import java.awt.event.*;
class GuiApp extends MouseAdapter
{
static Frame f; //because the frame is used in outside of method.
public void mouseEntered(MouseEvent m) //we can enter in the frame then Color is change
{
f.setBackground(Color.red);
}
public void mouseExited(MouseEvent m) //when we can exit then color same.
{
f.setBackground(Color.yellow);
}
public static void main(String g[])
{
Label l1=new Label("Enter first no:");
Label l2=new Label("Enter second no:");  //lable object is defind.
Label l3=new Label("result:");
TextField tf1 =new TextField(10); //textfeild object is defind.
tf1.setBackground(Color.pink); //set the color of textfeild.
MyKeyListener mkl=new MyKeyListener(); //object of mykeylistener.
tf1.addKeyListener(mkl);//and call then it is type for one.
    TextField tf2 =new TextField(10); //textfeild object is defind.
tf2.setBackground(Color.pink); //set the color of textfeild.
TextField tf3 =new TextField(10); //textfeild object is defind.
tf3.setBackground(Color.pink); //set the color of textfeild.
LogicListener ll=new LogicListener();//logic class ka object.
ll.getData(tf1,tf2,tf3);//data get and pass.
Button b1=new Button("Add"); //create an object of class of button.
b1.setForeground(Color.red); //set color of button.
b1.addActionListener(ll);//registered with button.
Button b2=new Button("multiply"); //create an object of class of button.
b2.setForeground(Color.red); //set color of button.
b2.addActionListener(ll);//registered with button.
f=new Frame("MyGuiApp"); //create an object of frame.
f.setBackground(Color.yellow); //set color of frame.
ClosingListener cl=new ClosingListener(); //object of close class.
f.addWindowListener(cl);//call and pass cl to the source.
GuiApp ga=new GuiApp(); //object of GuiApp.
f.addMouseListener(ga);// call and pass ga in mouse.
FlowLayout f1=new FlowLayout(); //Layout of frame is created.
f.setLayout(f1);//pass it method frame.
Panel p1=new Panel(); //create object of panel class.
p1.setBackground(Color.green); //set color of panel.
p1.add(l1);//add in panel lable L1.
p1.add(tf1);//add Textfeild.
Panel p2=new Panel(); //create object of panel class.
p2.setBackground(Color.green); //set color of panel.
p2.add(l2);//add in panel lable L2.
p2.add(tf2);//add Textfeild.
Panel p3=new Panel(); //create object of panel class.
p3.setBackground(Color.green); //set color of panel.
p3.add(b1);//add in panel button.
p3.add(b2);//add in panel button.
f.add(p1);// add in frame all.
f.add(p2);
f.add(p3);
f.add(l3);
f.add(tf3);
f.setSize(200,200);//set size of frame and we can change at run time.
f.setVisible(true);//visible is true or not.
}
}
class ClosingListener extends WindowAdapter
{ ////extends the class Adapter where all method declear.
public void windowClosing(WindowEvent w) //first create an object of this then call.
{
System.exit(0); //this method is clos the window of GuiAPP.
}
}
class MyKeyListener extends KeyAdapter
{
public void keyTyped(KeyEvent ke)
{
System.out.println("Key is type ...");//this work on text feild then create object and call
}
}
class LogicListener implements ActionListener
{ //logic of class is.
int res;
TextField tf1,tf2,tf3; //varabile defiend and pass it textfield.
public void getData(TextField tf1,TextField tf2,TextField tf3) //return the textfield
{
this.tf1=tf1;//current variable
this.tf2=tf2;
this.tf3=tf3;
}
public void actionPerformed(ActionEvent ae)//this is Action of the method.
{
int a=Integer.parseInt(tf1.getText());//this is the covert the String to integer.
int b=Integer.parseInt(tf2.getText());
if(ae.getActionCommand().equals("Add"))//return the Caption source and eqality with add
{
res=a+b;
}else
{
res=a*b;
}
tf3.setText(String.valueOf(res));//this is return in string result.
}
}

Java program to play an audio clip in Applet


/*<APPLET CODE="PlaySoundApplet" WIDTH="200" HEIGHT="300"></APPLET>*/

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class PlaySoundApplet extends Applet implements ActionListener{
  Button play,stop;
  AudioClip audioClip;

  public void init(){
  this.setBackground(Color.blue);
  play = new Button("  Play in Loop  ");
  add(play);
  play.addActionListener(this);
  stop = new Button("  Stop  ");
  add(stop);
  stop.addActionListener(this);
  audioClip = getAudioClip(getCodeBase(), "mausam03(www.songs.pk).mp3");
  }

  public void actionPerformed(ActionEvent ae){
  Button source = (Button)ae.getSource();
  if (source.getLabel() == "  Play in Loop  "){
  audioClip.play();
  }
  else if(source.getLabel() == "  Stop  "){
  audioClip.stop();
  }
  }
}

Download this mp3 sound for play the above code:
Ik Tu Hi Tu Hi -Mausam

Calculator program codes using Java Swing package.

This is a basic calculator using java Swing package. In output you will see a pop up calculator window. You can use this like a simple calculator with greater pleasure.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Calculator
{
   public static void main(String[] args)
   {  
      CalculatorFrame frame = new CalculatorFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}




//   A frame with a calculator panel.


class CalculatorFrame extends JFrame
{
   public CalculatorFrame()
   {
      setTitle("Calculator");
      CalculatorPanel panel = new CalculatorPanel();
      add(panel);
      pack();
   }
}


//   A panel with calculator buttons and a result display.


class CalculatorPanel extends JPanel
{  
   public CalculatorPanel()
   {  
      setLayout(new BorderLayout());


      result = 0;
      lastCommand = "=";
      start = true;
      
      // add the display


      display = new JButton("0");
      display.setEnabled(false);
      add(display, BorderLayout.NORTH);
      
      ActionListener insert = new InsertAction();
      ActionListener command = new CommandAction();


      // add the buttons in a 4 x 4 grid


      panel = new JPanel();
      panel.setLayout(new GridLayout(4, 4));


      addButton("7", insert);
      addButton("8", insert);
      addButton("9", insert);
      addButton("/", command);


      addButton("4", insert);
      addButton("5", insert);
      addButton("6", insert);
      addButton("*", command);


      addButton("1", insert);
      addButton("2", insert);
      addButton("3", insert);
      addButton("-", command);


      addButton("0", insert);
      addButton(".", insert);
      addButton("=", command);
      addButton("+", command);


      add(panel, BorderLayout.CENTER);
   }


   /*
      Adds a button to the center panel.
      @param label the button label
      @param listener the button listener
   */


   private void addButton(String label, ActionListener listener)
   {  
      JButton button = new JButton(label);
      button.addActionListener(listener);
      panel.add(button);
   }


   /*
      This action inserts the button action string to the
      end of the display text.
   */
   private class InsertAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String input = event.getActionCommand();
         if (start) 
         {
            display.setText("");
            start = false;
         }
         display.setText(display.getText() + input);
      }
   }


   /*
      This action executes the command that the button
      action string denotes.
   */
   private class CommandAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {  
         String command = event.getActionCommand();


         if (start)
         {  
            if (command.equals("-")) 
            { 
               display.setText(command); 
               start = false; 
            }
            else 
               lastCommand = command;
         }
         else
         {  
            calculate(Double.parseDouble(display.getText()));
            lastCommand = command;
            start = true;
         }
      }
   }


   /*
      Carries out the pending calculation. 
      @param x the value to be accumulated with the prior result.
   */
   public void calculate(double x)
   {
      if (lastCommand.equals("+")) result += x;
      else if (lastCommand.equals("-")) result -= x;
      else if (lastCommand.equals("*")) result *= x;
      else if (lastCommand.equals("/")) result /= x;
      else if (lastCommand.equals("=")) result = x;
      display.setText("" + result);
   }
   
   private JButton display;
   private JPanel panel;
   private double result;
   private String lastCommand;
   private boolean start;
}


Here is the popup window of calculator as an output.