Monday, December 24, 2012

STAR PRINTING 6 IN C++


#include<iostream.h>
void main()
{
 int i,j,k,n;
 cout<<"\Enter the number of lines to be printed: ";
 cin>>n;
 for(i=0;i<n;i++)
 {
       for(j=n-i-1;j>0;j--)
       cout<<" ";
       cout<<"*";
       for(k=2*i-1;k>0;k--)
       cout<<" ";          
       if(i!=0)
       cout<<"*";
       cout<<endl;
  }
  for(i=n-1;i>0;i--)
  {
       for(j=0;j<n-i;j++)
       cout<<" ";
cout<<"*";
 for(k=2*i-3;k>0;k--)
      cout<<" ";
       if(i!=1)
       cout<<"*";
       cout<<"\n";
    }
}
/*
OUTPUT
*/



STAR PRINTING 5 IN C++


#include<iostream.h>
void main()
{
    int i,j,n,k;
    cout<<"\Enter the number of lines to be printed: ";
    cin>>n;
    for(i=0;i<n;i++)
    {
       for(j=0;j<n-i;j++)
       {
    cout<<"*";
       }
       for(k=0;k<(2*n-2*j);k++)
       {
      cout<<" ";     //for spaces
       }
      for(j=0;j<n-i;j++)
       {
    cout<<"*";
       }
       cout<<"\n";
    }
}

DIAMOND SHAPE STAR PRINTING IN C++


#include <iostream.h>
void main()
{
int i,j,k;
for( i = 10; i >= 1; i-- )
{
for( j = 1; j < i; j++ )
{
cout << " ";
}
for( k=10; k >= j*2; k-- )
{
cout << "*";
}
cout << "\n";
}
for( i = 2; i <= 10; i++ )
{
cout << " ";
for( j = 2; j < i; j++ )
{
cout << " ";
}
for( k = 10; k >= j * 2; k-- )
{
cout << "*";
}
cout << "\n";
}
}

Wednesday, December 19, 2012

FIND A CHARACTER POSITION AND INDEX OF A STRING IN C++


#include<iostream.h>
void main()
{
int findpos(char s[],char c);
char string[80],ch;
int y=0;
cout<<"\nENTER MAIN STRING :\n";
cin.getline(string, 80);
cout<<"\nENTER CHARACTER TO BE SEARCH FOR : ";
cin.get(ch);
y=findpos(string,ch);
if(y==-1)
cout<<"\nSORRY!! THE CHARACTER IS NOT IN STRING.";
}
int findpos(char s[], char c)
{
int flag=-1;
for(int i=0; s[i]!='\0';i++)
{
if(s[i]==c)
{
flag=0;
cout<<"\nTHE CHARACTER IN THE STRING IS AT INDEX IS  : "<<i;
cout<<"\nTHE CHARACTER IN THE STRING IS AT POSITION : "<<++i;

}
 }
return (flag);
}

CONCATENATE TWO STRINGS PROGRAMME IN C++


#include<iostream.h>
#include<string.h>
void main()
{
char str1[50], str2[50], str3[100];
int count1, count2;
cout<<"ENTER THE FIRST STRING : ";
cin.getline(str1, 25);
cout<<"ENTER THE SECOND STRING : ";
cin.getline(str2, 25);
for(count1=0; str1[count1]!='\0'; count1++)
{
str3[count1]=str1[count1];
}
str3[count1]=' ';
count1++;
for(count2=0; str2[count2]!='\0'; count2++)
{
str3[count1+count2]=str2[count2];
}
str3[count1+count2]='\0';
cout<<"\nTHE NEW CONCATENATED STRING IS : \n\n";
cout<<str3;
}

STRING C++


#include<iostream.h>
#include<string.h>
void main()
{
char  ch, str[70], flag;
int len, count;
cout<<"\nENTER THE STRING:\n\n";
cin.getline(str, 70);
len=strlen(str);
cout<<"\nENTER A CHARACTER: ";
cin.get(ch);
flag='n';
for(count=0;str[count]!=len;count++)
{
if(ch==str[count])
{
flag='Y';
break;
}
}
if(flag=='Y')
{
cout<<"\n";
cout.put(ch);
cout<<" is contained in the string : \n\n";
cout.write(str,len);
}
else
{
cout<<"\n";

cout.put(ch);
cout<<" is not contained in the string : \n\n";
cout.write(str,len);
}
}

Tuesday, December 18, 2012

CONVERT A STRING TO UPPERCASE IN C++


#include<iostream.h>
#include<ctype.h>
#include<string.h>
void main()
{
char str[50];
int flag=1;
cout<<"\nENTER A STRING : \n\n";
cin.getline(str,50);
for(int i=0; str[i]!='\0';i++)
{
if(islower(str[i]))
{
flag=1;
str[i]=toupper(str[i]);
}
}
if((flag==1)||(str[i]=='\0'))
{
cout<<"\nUPPERCASE STRING IS :\n\n";
cout<<str;
}
}

FIND THE LARGEST AND SMALEST ELEMENT IN A VECTOR IN C++


 #include<iostream.h>
void main()
{
int count, num, vec[100], large, small;
cout<<"ENTER HOW MANY ELEMENTS ARE THERE IN THE VECTOR : ";
cin>>num;
cout<<"\nENTER THE VALUES IN THE VECOR \n";
for(count=0; count<num; count++)
cin>>vec[count];
large=small=vec[1];
for(count=0; count<num;count++)
{
if(vec[count]>large)
large=vec[count];
else if(vec[count]<small)
small=vec[count];
}
cout<<"\nTHE LARGEST ELEMENT IS : "<<large<<endl;
cout<<"\nTHE SMALLEST ELEMENT IS : "<<small<<endl;
}


THE FACTORS OF THE NUMBER IN C++


#include<iostream.h>
void main ()
{
int num, fact, gfact;
cout<<"ENTER A NUMBER : ";
cin >> num;
gfact=num/2;
cout<<"THE FACTORS OF " << num << " ARE : " << endl;
for ( fact=1; fact<=gfact; fact=fact+1)
{
if (num%fact==0)
cout << fact << endl;
}
}

FIBONACCI SERIES 3 PROGRAMME IN C++


#include<iostream.h>
void main()
{
int a=0,b=1,c=0,n;
cout<<"Enter the number of element required: ";
cin>>n;
cout<<a<<" "<<b<<" ";
for(int i=1;i<=n-2;i++)
{
c=a+b;
a=b;
b=c;
cout<<c<<" ";
}
}

FIBONACCI NUMBER SERIES PROGRAMME 2 IN C++


#include <iostream.h>
int fib(int n)
{
  if(1 == n || 2 == n)
  {
      return 1;
  }
  else
  {
      return fib(n-1) + fib(n-2);
  }
 }
void main()
{
    for(int i=1; i<=10; i++)
    {
        cout << fib(i) << endl;
    }
}

FIBONACCI NUMBER PROGRAMME IN C++


#include<iostream.h>
void main()
{
char choice;
do
{
long double num, a=1, b=0, count;
cout<<"ENTER THE NUMBER OF ELEMENTS REQUIRED : ";
cin>>num;
cout<<"\n\n";
for(count=1; count<=num/2;count++)
{
a+=b;
cout<<b << "\t";
b+=a;
cout<<a << "\t";
}
cin>>choice;
}while(choice=='x'||choice=='x');
}

Monday, December 17, 2012

PRIME NUMBER PROGRAMME IN C++


#include<iostream.h>
void main ()
{
long num, fact; int count;
cout << "ENTER A NUMBER : ";
cin >> num;
for ( fact=1, count=0; fact<=num/2; fact=fact+1)
{
if (num%fact==0)
count=count+1;
}
if (count==1)
cout << "\nYES! IT IS A PRIME NUMBER." << endl;
else
cout << "\nNO! IT IS NOT A PRIME NUMBER." << endl;
}

PERFECT NUMBER PROGRAMME IN C++


#include<iostream.h>
void main ()
{
int num, fact, gfact, fsum=0;
cout << "ENTER A NUMBER : ";
cin >> num;
gfact=(num/2)+1;
for (fact=1; fact<=gfact; fact=fact+1)
{
if (num%fact==0)
fsum+=fact;
}
if (fsum==num)
cout << "\nIT IS A PERFECT NUMBER. " << endl;
else
cout << "\nIT IS NOT A PERFECT NUMBER. " << endl;
}

STAR PRINTING 4 IN C++


#include<iostream.h>
void main()
{
int count,i, n=10;
for(count=0;count<=n;count++)
{
for(i=0; i<count;i++)
{
cout<<" ";
}
for(int j=10; j>count;j--)
{
cout<<"*";
}
cout<<endl;
}
}

/*
OUTPUT
*/

STAR PRINTING 3 IN C++


#include<iostream.h>
void main()
{
int count,i, n=10;
for(count=0;count<=n;count++)
{
for(int j=10; j>count;j--)
{
cout<<" ";
}
for(i=0; i<count;i++)
{
cout<<"*";
}
cout<<endl;
}
}
/*
output
*/

STAR PRINTING 2 IN C++


#include<iostream.h>
void main()
{
int count,i;
for(count=10;count>=0;count--)
{
for(i=count;i>=0;i--)
cout<<'*';
cout<<endl;
}
}
 /*OUTPUT
*/







STAR PRINTING 1 IN C++


#include<iostream.h>
void main()
{
int count,i;

for(count=0;count<=10;count++)
{
for(i=0;i<=count;i++)
cout<<'*';
cout<<endl;
}
}

/*
OUTPUT
*/

EXAMPLE CODING OF INCREMENT AND DECREMENT OPERATORS IN C++


#include<iostream.h>
void main()
{
int num, a,b,c,d;
cout<<"ENTER A NUMBER : ";
cin>>num;
a=num;
b=num;
c=num;
d=num;
cout<<"\n"<<num<<" is assigned to a,b,c and d : "<<endl;
cout<<"++a = " << ++a<<"\n--b = "<< --b<<"\nc++ = " << c++<<endl;
cout<<"d-- = " << d--<<endl;
cout<<"a = "<<a<<"\nb = "<<b<<"\nc = "<<c<<"\nd = "<<d<<endl;
}

GREATER OF THREE NUMBERS IN C++


#include<iostream.h>
void main()
{
int a, b, c;
cout<<"ENTER THE FIRST NUMBER : ";
cin>>a;
cout<<"ENTER THE SECOND NUMBER : ";
cin>>b;
cout<<"ENTER THE THIRD NUMBER : ";
cin>>c;
if(a>b && a>c && b>c)
{
cout<<a<<" IS GREATEST."<<endl;
cout<<b<<" IS SECOND GREATEST."<<endl;
cout<<c<<" IS LEAST.";
}
else if(a>b && a>c && c>b)
{
cout<<a<<" IS GREATEST."<<endl;
cout<<c<<" IS SECOND GREATEST."<<endl;
cout<<b<<" IS LEAST.";
}
else if(b>a && b>c && a>c)
{
cout<<b<<" IS GREATEST."<<endl;
cout<<a<<" IS SECOND GREATEST."<<endl;
cout<<c<<" IS LEAST.";
}
else if(a>b && a>c && c>a)
{
cout<<b<<" IS GREATEST."<<endl;
cout<<c<<" IS SECOND GREATEST."<<endl;
cout<<a<<" IS LEAST.";
}
else if(c>a && c>b && b>a)
{
cout<<c<<" IS GREATEST."<<endl;
cout<<b<<" IS SECOND GREATEST."<<endl;
cout<<a<<" IS LEAST.";
}
else if(c>a && c>b && a>b)
{
cout<<c<<" IS GREATEST."<<endl;
cout<<a<<" IS SECOND GREATEST."<<endl;
cout<<b<<" IS LEAST.";
}
else
cout<<"INVALID INPUT.";
}

SQUARE OF A NUMBER IN C++


#include<iostream.h>
void main ()
{
int num, sqr;
cout << "ENTER THE NUMBER : ";
cin >> num;
sqr= num*num;
cout << "\nTHE SQUARE OF " << num << " is " << sqr;
}

Sunday, December 16, 2012

FIND THE BIG NUMBER OF TWO NUMBERS IN C++


#include<iostream.h>
void main()
{
int num1, num2;
cout << "PLEASE ENTER THE FIRST NUMBER : ";
cin >> num1;
cout << "PLEASE ENTER THE SECOND NUMBER : ";
cin >> num2;
if (num1>num2)
{
cout << "1st NUMBER IS GREATER THAN 2nd NUMBER.";
}
else
{
cout << "2nd NUMBER IS GREATER THAN 1st NUMBER.";
}
}

SWAPPING NUMBERS IN C++


#include<iostream.h>
void main()
{
int a, b, c;
cout<<"\nENTER FIRST NUMBER : ";
cin>>a;
cout<<"\nENTER SECOND NUMBER : ";
cin>>b;
c=a;
a=b;
b=c;
cout<<"\nNEW FIRST NUMBER= "<<a;
cout<<"\nNEW SECOND NUMBER= "<<b;
}

MULTIPLICATION OF TWO NUMBERS IN C++


#include<iostream.h>
void main()
{
int no1,no2,m;
cout<<"ENTER THE FIRST NUMBER : ";
cin>> no1;
cout<<"\nENTER THE SECOND NUMBER : ";
cin>>no2;
m=no1*no2;
cout<<"\nTHE DIFFERENCE OF TWO NUMBERS IS : "<<m;
}

FIND THE DIFFERENCE BETWEEN TWO NUMBERS IN C++


#include<iostream.h>
void main()
{
int no1,no2,d;
cout<<"ENTER THE FIRST NUMBER : ";
cin>> no1;
cout<<"\nENTER THE SECOND NUMBER : ";
cin>>no2;
d=no1-no2;
cout<<"\nTHE DIFFERENCE OF TWO NUMBERS IS : "<<d;
}

FIND THE SUM OF THE TWO NUMBERS IN C++


#include<iostream.h>
void main ()
{
int no1,no2,sum;
cout<<"ENTER FIRST NUMBER : ";
cin>>no1;
cout<<"ENTER SECOND NUMBER :";
cin>>no2;
sum=no1+no2;
cout<<"THE SUM OF TWO NUMBER : "<<sum;
}








Friday, December 7, 2012

Data Structures and Algorithms with Java - 1 PAST PAPER 2008


1.

(a.) Specify the most suitable data type to declare followings? [3 Marks]
       i.) No of subjects in the course
      ii.) Name of the lecturer
     iii.) Average mark for a subject in a class

(b.) List all primitive data types [4 Marks]

(c.) Explain the purpose of following escape sequence characters? [3 Marks]
                 i.) \n
                ii.) \t
               iii.) \”
(d.) What will be the output of following program fragment? [2 Marks]
            byte num=0;
                 num++;
                 ++num;
             System.out.println(num++);

(e.) Fill in the blanks of the following sentences with suitable terms. [4 Marks]
    i.) The file produced by the java compiler contains………………..that are executed by the Java Virtual                               Machine.
   ii.) Three parts in the method definition form …………………………...
  iii.) A variable declared and initiated within a loop is known as …………
  iv.) A class variable should be declared with a…………keyword before the type of variable.

(f.) Write a java program to compare two integer variables and display the largest
using with input and message dialog boxes. [4 Marks]

2.

(a.) State whether each of the following is true or false. [4 Marks]
   i.) By convention, method names begin with an uppercase first letter and all subsequent words in the name   begin with a capital first letter
  ii.) Empty parentheses following a method name in a method declaration indicate that the method does not require any parameter to perform its task.
  iii.) The number of argument in the method call must match the number of parameters in the method declaration’s parameter list.
 iv.) An import declaration is not required when one class in a package uses another in the same package.

(b.) What is the different between local variable and a field? [2 Marks]

(c.) Explain the purpose of a method parameter. What is the difference between a
parameter and an argument? [2 Marks]

(d.) Write a complete Java application to prompt the user for the double radius of a
sphere, and call method sphereVolume to calculate and display the volume of the sphere. Use the Math.pow( radius) method and Math.PI constant of Math class. [4 Marks]

(e.) Write what would be the output of the following program if it is executed. [8 Marks]
    class ResultPrint
      {
          public static void main(String[] args)
             {
              int x1 = 5, x2 = 6, x3 = 4, x4 = 7;
              System.out.println((x1^2+3*x3)/2);
              System.out.println( x1 == 5);
              System.out.println( x2!=6 );
               System.out.println( x3!= 5 && x4 < 8);
              System.out.println( x1<= 3 & x2 > x3);
             System.out.println( x2 >= x3|| x1 != x4);
             System.out.println( x1 + x2 - x3> x4 | 4*x1>= (x3^2));
              System.out.println( x4 != x3+x2 );
            }
  }

3.

(a.) After compilation of program files, following error messages were shown on
command prompt. Identify the causes for those specific errors. [4 Marks]
                    i.) Testing.java:8:package system does not exist.
                          system.out.println(“No of items:”+totalItem);
                                   ^
                                 1 error

                    ii.) Testing.java:10: cannot find symbol
                                   Location: class Testing
                                    Symbol: variable count
                                        ++count;
                                         ^
                                2 errors

(b.) Find the error in each of the following code segment and explain how to
correct it. [4 Marks]
           i.) For(index =0.1;index!=1.0;index+=0.1)
                   System.out.println(“Index =” + index);
           ii.) Switch(x)
                      {
                             case 1:
                             System.out.println(“The number is 1”);
                            Break;
                            case 2:
                           System.out.println(“The number is 2”);
                              Default:
                           System.out.println(“The number is not 1 or 2”);
                           Break;
                    }

(c.) Compare and contrast the while and for loop repetition statement [2 Marks]

(d.) Write the output if the following code is executed. [4 Marks]
                        class LabelTest
                                {
                                        public static void main (String arg[])
                                              {
                                                      xyz:
                                                     for (int i = 1; i <= 4; i++)
                                                          for (int j = 1; j <= 2; j++) {
                                                    System.out.println("i is " + i + ", j is " + j);
                                                    if (( i + j) > 3)
                                                      break xyz;
                                                     }
                                                 System.out.println("End of loops");
                                               }
                                     }
         (e.) What would be the output if the following code is executed ? [6 Marks]
class PatPrint
{
public static void main(String[] args)
{
for(int i=0;i<2;i++)
{
for(int j=0; j<1;j++)
System.out.print("*");
System.out.print("\n");
for(int j=0; j<2;j++)
System.out.print("*");
System.out.print("\n");
for(int j=0; j<3;j++)
System.out.print("*");
System.out.print("\n");
for(int j=0; j<4;j++)
System.out.print("*");
System.out.print("\n");
for(int j=0; j<5;j++)
System.out.print("*");
System.out.print("\n");
}
}

}      



4


(a.) Fill in the blanks in each of the following statements. [4 Marks]
                                i.) The ………………..statement in a called method can be used to pass the value of an expression back to the calling method.
ii.) An array that uses two indices is referred to as a(n)…………array.
iii.) The name of the element in row 3 and column 5 of array d is ………..
iv.) Command-line arguments are stored in …………………………..

(b.) Determine whether each of the following is true or false. [4 Marks]
i.) An array can store many different types of values.
ii.) An array index should normally be of type double.
iii.) Command-line arguments are separated by white space.
                                iv.) Expression array.length is used to access the number of arguments of a variable-length argument called array.

(c.) Perform the following tasks for an array called table: [3 Marks]
                           i.) Declare and create the array as an integer array has three rows and three columns. Assume that the constant ARRAY_SIZE has been declared to be 3.

ii.) How many elements does the array contain?
                                  iii.) Use a for statements to initialize each element of the array to the sum of its indices. Assume that the integer variable x and y are declared as control variable.

(d.) Write the output of the following program if it is executed. [4 Marks]
class FamilyList
{
String[] personNames = {"Mendis", "Ravi", "Nihar", "James"};
String[] personWifeNames = new String[personNames.length];
void printPersonNames()
{
for(int i = 0; i< personNames.length; i++)
{
System.out.println(personNames[i]);
}
}
void printPersonWifeNames()
{
for(int i = 0; i< personWifeNames.length; i++)
{
System.out.println(personWifeNames[i]+" "+ personNames[i]);
}
}
public static void main (String args[])
{
FamilyList familyList = new FamilyList();
System.out.println("List of Male");
System.out.println("-------------");
familyList.printPersonNames();
familyList.personWifeNames[0]= "Malathy";
familyList.personWifeNames[1]= "Priya";
familyList.personWifeNames[2]= "Susmina";
familyList.personWifeNames[3]= "Rosemary";
System.out.println();
System.out.println("List of Female");
System.out.println("---------------");
familyList.printPersonWifeNames();
}
}


(e.) Write method distance to calculate the distance between two points
(x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points. [5 Marks]

5.

(a.) Complete the following statements with suitable terms. [5 Marks]
                        i.) The ………… method is called by the garbage collector just before it reclaims an object’s memory.
ii.) Keyword …………specifies that a variable is not modifiable.
                    iii.) A(n)……………….consists of a data representation and the operations that can be performed on the data.
                   iv.) ……………………is a form of software reusability in which new classes acquire the member of existing classes and embellish those classes with new capabilities
                v.) A superclass’s …………members are accessible anywhere that the program has a reference to an object of that superclass or to an object of one of its subclass.
(b.) Define what the following terms means: [6 Marks]
i.) abstract class
ii.) concrete class
iii.) Interface
(c.) What will be the output if the following code is executed? [6 Marks]
class VariableScopeTest
{
static int num1 = 10;
int num2 = 15;
void printNumGroup1()
{
System.out.println("Number2 = " + num2);
}
public static void main (String args[])
{
System.out.println("Number1 = " + num1);
VariableScopeTest vST = new VariableScopeTest();
vST.printNumGroup1();
vST.printNumGroup2();
System.out.println("Number2 = " + vST.num2);
}
void printNumGroup2()
{
int num2 = 20;
7
System.out.println("Number2 = " + num2);
System.out.println("Number2 = " + this.num2);
}
}
(d.) Define class variable, instance variable and local variable. Give an example
from the source code given (c.). [3 Marks]

6.

(a.) What will be the output if the following code is executed? [5 Marks]
public class TestMathFun
{
public static void main(String [] args)
{
double val1 = 9.2;
double val2 = -23.3;
double val3 = -9.8;
System.out.printf("%s\t%s\t%s\t%s\t\n","value","abs","ceil","floor");
System.out.printf( "%.1f\t%.1f\t%.1f\t%.1f\t\n", val1,Math.abs(val1),Math.ceil(val1),Math.floor(val1));
System.out.printf( "%.1f\t%.1f\t%.1f\t%.1f\t\n", val2,Math.abs(val2),Math.ceil(val2),Math.floor(val2));
System.out.printf( "%.1f\t%.1f\t%.1f\t%.1f\t\n", val3,Math.abs(val3),Math.ceil(val3),Math.floor(val3));
}
}

(b.) List five common examples of exceptions. [2.5 Marks]

(c.) Give reasons why exception-handling techniques should not be used for
conventional program control. [2 Marks]

(d.) If no exceptions are thrown in try block, where does control proceed to when the
try block completes execution? [1.5 Marks]

(e.) What would be the output of the following source code if an integer numerator is
divided by a zero denominator? [5 Marks]
import java.util.Scanner;
public class TryCatchTest
{
public static int quotient( int numerator, int denominator )
8
{
return numerator / denominator;
}
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
boolean continueLoop = true;
do
{
try
{
System.out.print( "Enter an integer for numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Enter an integer for denominator: " );
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result );
continueLoop = false;
}
catch ( ArithmeticException arithmeticException )
{
System.err.printf( "\nException: %s\n", arithmeticException );
System.out.println( "Zero is an invalid denominator. Please try again.\n" );
}
}while(continueLoop);
}
}

(f.) Define each of the following terms. [4 Marks]
i.) thread
ii.) multithreading
iii.) runnable state
iv.) timed waiting state

Saturday, December 1, 2012

JAVA Fundamental

Fundamentals


Java Terminology 

* Java Virtual Machine(JVM) –set of computer software programs and data structures that use a virtual machine model for the execution of other computer programs and scripts.
* Java Runtime Environment(JRE) –A runtime environment which implements Java Virtual Machine, and provides all class libraries and other facilities necessary to execute Java programs. This is the software on your computer that actually runs Java programs
* Java Development Kit(JDK) –The basic tools necessary to compile, document, and package Java programs (javac, javadoc, and jar, respectively). The JDK includes a complete JRE.
* Application Programming Interface (API) –Contains predefined classes and interfaces for developing Java programs

Comments 

Comment-The contents of a comment are ignored by the compiler.  Three type of comment in java.
1. Single line comments(Slash-Slash) //text // This comment extends to the end of the line.
2. Multiple line comments  /* This comment, a "slash-star" comment, includes multiple lines.*/ 
3. Documentation Comments /** documentation */  The last type of comment is the
Javadocument. This comment type has some guidelines that allows a Javadocreader to display information about a Java method or class by using special tags 

Excercise
# Exercise:Write a simple Java program which displays following two lines on the screen.
I like Java programming.
So I do practical .

Operators 

* An operator is a symbol that tells the compiler to perform a specific mathematical or logical manipulation.
* Java has four general classes of operators: arithmetic, bitwise, relational, and logical
* Examples of expressions that include Java operators :
 1. n = 2
 2. n += 3
 3. ++n
 4. n / 3
5.  n % 3




Arithmetic Operators












Example
x = y / 2;
* in the above expression, x and y are variables, 2 is a literal and = and / are operators. 
* This expression states that the y variable is divided by 2 using the division operator (/), and the *result is stored in x using the assignment operator (=).Notice the expression was described from right to left. 
*It is how the compiler itself analyzes expressions to generate code.








It is also possible to use the shortcuts for arithmetic operators as given below.










class Arithmetic {

public static void main (String args[]) 
{

intx=17, y=5;

System.out.println(“x=“+x);

System.out.println(“y=“+y);

System.out.println(“x+y=“+(x+y));

System.out.println(“x-y=“+(x-y));

System.out.println(“x*y=“+(x*y));

System.out.println(“x/y=“+(x/y));

System.out.println(“x%y=“+(x%y));

}

}
Output
 










 Bitwise Operators







Friday, November 30, 2012

INTRODUCTION TO JAVA

JAVA programming Language

* Developed at Sun Microsystems in 1991
*  James Gosling, initially named “OAK”
* Formally announced java in 1995
* Object oriented and cant write procedural programs
* Functions are called methods
* Unit of a program is the class from which objects are created
* Automatic garbage collection
* Single inheritance only
* Each class contains data and methods which are used to manipulate the data
* Programs are small and portable
* Multithreaded which allows several operations to be executed concurrently
* A rich set of classes and methods are available in java class libraries
* Platform Independent
* Case sensitive

Java program development

* Edit – use any editor
* Compile – use command „javac‟   if your program compiles correctly, will create a file with extension .class
* Execute – use the command „java‟
Java language keywords 
* Keywords are special reserved words in java that you cannot use as identifiers for classes, methods or variables. They have meaning to the compiler, it uses them to understand what your source code is trying to do.

   First java Program

 class FirstPro  
                 {    
                            public static void main(String args[])    
                                     {   
                                         System.out.println("Hello World!“);    
                                       }  
                   } 

Java Source files

* All java source files must end with the extension „.java‟ 
* Generally contain at most one top level public class definition 
* If a public class is present, the class name should match the file name 

 Top level elements appears in a file 

* If these are present then they must appear in the following order.
* Package declarations 
* Import statements 
* Class definitions 

 Identifiers 

* An identifier is a word used by a programmer to name a variable, method class or label.
* Keywords may not be used as an identifier 
* Must begin with a letter, a dollar sign($) or an underscore( _ ). 
* Subsequent character may be letters, digits, _ or $. 
* Cannot include white spaces.   ref: Note

Declaring Variables


* Type identifier;

Type identifier=initial value;

Primitive Data Types

Type                           Bits                                          Range 
boolean                         1                                          true, false
char                              16                                        0 to 65,535 
byte                               8                                        -128 to +127 
short                             16                                       -32,768 to +32,767 
int                                 32                                           -232 to +232-1 
long                              64                                         -264 to +264-1 
float                               32                                      -3.4E+38 to +3.4E+38 (approx) 
double                           64                                      -1.8E+308 to +1.8E+308 (approx) 
* int grade; // an integer to hold a grade, no initial value 
*  int grade = 0; // an integer to hold a grade with initial value 0
* char answer; // an answer to something – one character 
* String name; // a string to hold a name
* String name = "Gumboot"; // as above, with an initial value
* boolean finished; // to hold "true" if finished
* boolean finished = false; // as above, but with an initial value

Declarations and Assignments

Declarations   

int grade;
char answer; 
String name; 

Assignments 

grade = 70; 
answer = 'a'; 
name = "alan turing";


Default Values

Data Type                                                            Default Value (for fields) 
byte                                                                              0 
short                                                                             0 
int                                                                                 0 
long                                                                              0L 
float                                                                              0.0f 
double                                                                          0.0d 
char                                                                             '\u0000' 
String (or any object)                                                  null 
boolean                                                                        false

Comments

* Single line comments begin with //  
* Multiline comments begin with /* and end with */ 

Sunday, November 25, 2012

COMPUTER PROGRAMMING C++ BASIC

Computer Programming

 It means to develop or write computer programs to perform different types of activities in a computer system using computer languages.
 Programming can be classified into two types: systems programming and   (application) programming. 
 System programming is handled by computer engineers or system programmers to develop system programs such as operating systems, language translators, etc. 
(Application) programming is handled by ordinary computer programmers to develop application software such as payroll system, stock control system, etc. 
Computability
 The possibility of programming a task by a machine is called computability. 
Complexity
 Complexity is the measuring term of quantity of resources used for many alternative algorithms.  Knowledge of complexity helps to find the best algorithm.   Average cases and worst cases can also be identified.
Correctness
 A program should produce the required result for all possible inputs and it is called correctness.
Structured programming 
Programming that produces programs with clean flow, clear design, and a degree of modularity (or hierarchical structure) is called structured programming. 
 The three basic constructs in structured programming are sequence (ordered set of statements), selection (conditional branch), and iteration (repetition).
  There is no GOTO statement to jump to any place in the program.
Modular programming
 An approach to programming in which the program is broken into several independently compiled modules is called modular programming.  
It facilitates group programming efforts.
 Modular programming is a precursor (ancestor) of object oriented programming.
Object-oriented programming (OOP)
 It is a programming paradigm in which a program is viewed as a collection of discrete objects that are self contained collection of data structures and routines that interacts with other objects.
Top-down programming
 An approach to programming that implements a program in top-down fashion is referred to as top- down programming. 
Typically this is done by writing a main body which calls to several major routines (implemented as stubs).
 Each routine is then coded, calling other, lower-level routines (also done initially as stubs).
  Here, stub is a placeholder for a routine to be written later.
Bottom-up programming
 It is a programming technique in which lower-level functions are developed and tested first.
  higher-level functions are then built using the lower- level functions.
Programming Language 
It is any artificial language that can be used to define a sequence of instructions that can ultimately be processed and executed by the computer.  
 A program called, language translator, translates statements written in one programming language into their machine language.
Levels/Generations of Languages
 Languages are generally divided into five levels/generations.
1. Machine language 
2. Assembly language 
3. High-level languages 
4. Very high-level languages 
5. And Natural languages 
Machine language
 * Programs that are written in 1’s and 0’s are in the actual machine language.
 * Machine code consists of binary coded instructions and data intermixed.
 * All programs in other languages must be translated into machine language before  their execution.
* Each type of computer has its own unique machine language.
 * Machine language is very difficult to write programs and to detect and correct program errors.
* A thorough knowledge of computer hardware is required for machine language programming.
 * Here, programmers cannot concentrate on data processing problems, because more attention should be paid for the architecture of the computer system.  
* Machine language programs are not portable among different types of computers.
* However, machine language programs can be executed much faster and maximum usage of resources (e.g. memory) can be obtained.
Assembly language
* It is the direct symbolic representation of a machine language.
* Assembly languages include IBM BAL(Basic Assembly Language for IBM) and VAX Macro (For Digital Equipment Corporation, Macro 11,  Macro 32,  Macro 64 ).
* Assembly languages use English-like mnemonic codes to represent the operations:  A for add, C for compare, MP for multiply,  STO for storing information in memory, and so on.
* Assembly language specifies registers with meaningful codes, such as AX, BX, etc., instead of binary numbers. 
* Furthermore, it permits the use of names,  perhaps RATE or TOTAL for memory locations, instead of the actual binary memory address.
* As with machine language, each type of computer has its own unique assembly language.
 * Therefore, both machine and assembly languages are considered as machine oriented or low-level computer languages. 
*Assembly language is easy to write programs and to detect and correct program errors compared to machine language programs. 
* As source program should be translated into machine language, more time is required for execution.
* The part of the machine language or assembly language instructions that specifies the operation or function to be carried out is called opcode.

High-level languages
* To overcome problems of low-level languages, high- level languages were developed. 
* As standard words of those languages are closer to human language (English).
 * It is much easier to write programs and to detect and correct errors. 
* As high-level languages are machine independent, programs are portable, less hardware knowledge is required, and more attention can be paid for data processing requirements.
 *Here, a lesser number of instructions are required.
* Due to the compilation process more time is needed to execute the program.
 *Here, computer resources cannot be used fully.
  * FORTRAN (Formula translator), ALGOL (Algorithmic Language), COBOL (Common business oriented language), RPG (Report program generator), BASIC (Beginners all purpose symbolic instruction code), Pascal, C, C++, Java, and Visual Basic, are some of the examples for high-level language. 
*For any given high-level language, there are usually a number of translators available, each of which translates a program in that language to the machine language for a specific type of computer
Very high-level languages
* Very high-level languages are often known as 4GLs (fourth-generation languages).
 * Languages belonging to the first three generations are procedural languages, consisting of instructions that describe the step-by-step procedure to solve the problem.
 *4GLs are non procedural languages, in which the programmer specifies the desired results, and the language develops the solution.
* Query languages, such as SQL (Structured query language), are variations on 4GLs and are used to retrieve information from databases.
Natural language
*The natural language (sometimes considered to be 5GLs) translates human instructions into codes the computer can execute.
 * If it does not understand the user’s request, it politely asks for further explanation.
* For example, INTELLECT, a natural language, would use a statement like, “What are the average exam scores in C++?”.
Comparison among different levels of programming languages
Language Translators
*All the source programs should be converted into their machine language before the execution process.
* Language translators are used for this process. 
*There are three types of language translators: Assemblers, Compilers, and Interpreters. 
Assembler
* It is a language translator which translates source programs written in assembly language into their object programs. 
Compiler
* It translates/compiles the entire program written in a high-level language into its object program considering the program as a single unit.
* After the compilation process the source program is no more required as the object program is available.
 *A compiler is able to look at the whole of a program and to work out the best way of translating.
 * This is some times called optimization and is one of the reasons why a compiler can produce efficient code.
 * Once all errors have been corrected, the program will run faster.
 * However errors are more difficult to find during compilation because they are not reported until the end of the process and a single error can generate additional error messages making it harder to locate the error. 
* When the program is in testing mode, there is no benefit to have a stored executable program since this will have to be rebuilt each time.
Interpreter
* It is a language translator which converts high-level language statements into equivalent machine language statements one at a time as the program is executed.
 *It does not generate an object program as a separate unit.
* Here, each statement is checked for syntax,  then converted into machine code, and then executed.
* The presence of the source program is required for the execution of the program and it should be interpreted each time.
  * Here, In the case of repetition, some program statements may be translated many times.
 * Executing an interpreted program is slower than executing a compiled program since each statement has to be converted to binary each time even if it has been converted previously. 
* With an interpreted language there is always the danger that a syntax error may exist in a section of code that has not been tested. 
* However, there is no lengthy compile and link cycle.
* If the program encounters an error, the interpretations stops and an error message is displayed so the user can correct it.
 * Therefore, interpreters are comfortable for beginners because small programs can be written and tested very quickly. 
Integrated development environment (IDE)
* Most current languages come in a comprehensive package called an integrated development environment (IDE) that includes language aware editor, project build capability (compiler and linker), debugger, and other programming tools. 
* Other programming tools include diagramming packages, code generators,  libraries of reusable objects and program code, and prototyping tools. 
Some Commonly Used High-Level Languages
*FORTRAN (Formula translator) was developed by IBM and introduced in 1954. It was the first high-level language. It is very good at representing complex mathematical formulas.  
*ALGOL (Algorithmic Language) was the first structured procedural programming language developed in late 1950s.  
* COBOL (Common business oriented language) is a verbose (wordy), English-like compiled programming language developed between 1959 and 1961 and still in widespread use, especially in business applications typically run on mainframes. It is very good for processing large, complex data files and for producing well-formatted business reports.  
* RPG (Report program generator) was developed by IBM in 1965 to allow rapid creation of reports from data stored in the computer files.  
* BASIC (Beginners all purpose symbolic instruction code) was originally developed by Dartmouth College professors John Kemeny and Thomas Kurtz in 1965 to teach programming to their students.
* Pascal was designed between 1967 and 1971 by Niklaus Wirth. It is a compiled, structured language built upon ALGOL, simplifies syntax while adding data types and structures such as sub ranges, enumerated data types, files, records, and sets.  
* C was created in 1972. One of the C’s primary advantages is its portability. There are C compilers for almost every combination of computer and operating system available today. 
* C++ is an object-oriented version of C, developed in the early 1980s.
* Java is a network-friendly object-oriented programming language derived from C++ that permits a piece of software to run directly on many different platforms.
 * Java programs are not compiled directly into machine language, but into an intermediate language called bytecode.
* This bytecode is then executed by a universal platform, called the JVM (Java Virtual Machine), which sits atop a computers regular platform. 
* The JVM interprets (translates) compiled Java code into instructions that the platform underneath can understand.
* Java provides high level of security to the user and the network.
* Java uses Unicode coding system, which allows displaying all character sets in a uniform manner.
* Web pages can include Java mini programs, called applets, which run on a Java platform included in the user’s Web browser. 
* Visual Basic (VB) was introduced by Microsoft in 1987 as its first visual development tool. 
*It allows the programmer to easily create complex user interfaces containing standard Windows features, such as buttons, dialog boxes, scroll bars, and menus.
 * VB enables the user to control program execution.
 * This type of program is referred to as being event-driven. 
*The ability to create user-friendly event-driven programs with attractive Windows-like interfaces quickly has resulted in VB becoming one of the most popular programming languages.
  * VB can also be thoroughly integrated with Microsoft Office to customize programs.
* Perl (Practical Extraction and Report Language) is an interpreted language, based on C and several UNIX utilities.
 * Perl has powerful string handling features for extracting information from text files. 
* Perl can assemble a string and send it to the shell as a command; hence, it is often used for system administration tasks. 
* A program in Perl is known as a script.
Classification of Currently Available Languages according to The Programming Style 
1 Procedural/Imperative Languages:   These consist of explicit instructions that describe the step-by-step procedure to solve the problem.   These are formed from collection of basic commands (assignments, input, output, etc) and control structures (selection, iteration, etc.).   E.g.: C, Pascal, FORTRAN, Assembly, etc.
 2 Non procedural languages:   These are a programming languages that do not follow the procedural paradigm (pattern) of executing statements, subroutine calls, and control structures sequentially but instead describes a set of facts and relationships and then is queried for specific results.
 3 Functional Languages:   These are based on lambda-calculus, which concerns the application of functions to their arguments.   Functional Language programs consist of collections of function definitions and their applications.   E.g.: LISP (LISt Processing), etc.
4 Logic Programming Languages:   Here, programs consists of collections of statements within a particular logic, such as predicate logic.   E.g.: Prolog (Programming logic), etc.
 5 Object Oriented Language:   Here, programs consist of objects that interact with each other.   E.g.: SIMULA (Simulation Language), Smalltalk, Eiffel, etc..   The object-oriented language that currently dominates the market is C++.   It supports both object-oriented programming and non-object-oriented programming. 
Java, the language threatening C++ dominance, is a pure object-oriented language; that is, it is impossible to write a non-object-oriented program.   The latest version of Java is J2EE (Java2 Enterprise Edition).   A relatively new language, C# (“cee-sharp”) is Microsoft’s answer to Java.   It has most of the same advantages over C++ as does Java, but it is designed to work within Microsoft’s .NET environment. 
The .NET environment is designed for building, deploying (organizing), and running Web-based applications.   Many people referred to prior versions of Visual Basic as ‘object-oriented’, because VB programs used ‘objects’ such as command buttons, scroll bars, and others. However, it wasn’t until the current version, VB.NET, that Visual Basic supported the concepts of inheritance and polymorphism, thus meeting the criteria for a true object-oriented language.
6 Declarative Language:   These are collections of declarations.   Many functional and Logic languages are also declarative.   Here, you describe a pattern to be matched without writing the code to match the pattern.  
 7 Scripting Languages:   Scripting languages are designed to perform special or limited tasks, sometimes associated with a particular application or function.   E.g.: Perl (Practical extraction report language), etc. 
 8 Parallel Languages:   These are collections of processes that communicate with each other.   E.g.: C*, Ada, etc.. 

Stages of Computer Programming 
1         Analyzing and defining the problem
 *In some organizations, programmers receive asset of specifications from system analysts. 
* In others, the programmers meet directly with users to analyze the problem and determine the user’s needs.
* In either case, the task of problem definition involves determining the input and output.  
             *  Finally, you produce a written agreement that specifies, in detail, the input data, the required output, and the processing required converting the input into the output.  
  2  Program design  (or planning the solution)
 * The next step is to design an algorithm, a detailed, step-by-step solution to the problem.
* An algorithm must have some characteristics:
* must be precise (unambiguous); 
*must be effective;
* must have a finite number of instructions; 
* execution must always terminate. 
* There are number of design tools that a programmer can use to develop the algorithm: 
*flowchart
* pseudo code
* decision trees
 *decision tables
 *structure diagrams  .   
* After completing the algorithm design, the programmer should perform a process, called desk- checking or dry-run, to verify that it produces the desired result.
 *This involves sitting down with a pencil and paper and ‘playing computer’ by carrying out each step of the algorithm in the indicated sequence.  
   Program coding 
* Program coding means conversion of the algorithm into a set of instructions written in a computer programming language. 
* This program is keyed into the computer by using a text editor, a program that is similar to a word processor. 
Program testing and debugging
 * The following diagram illustrates the steps in preparing a program for execution.
*During these steps computer programs should be checked for program errors.
*The original program written in a computer programming language is called as source program.
 * Initially, this source program is translated into its machine language form (called object program) by the language translator (compiler).
 *If the source program violates the grammatical rules of that programming language, it cannot be converted into its machine language and these types of errors can be described as syntax errors, compile time errors, or diagnostic errors.
* As data cannot be processed without some utility programs, object programs should be linked with them to produce an executable program (load module).
 * This job is done by another system program called a linkage editor (linker).
* When required utility programs are not available or when utility programs cannot be linked with the object program properly, an executable program cannot be produced. These errors are described as link errors
* When the executable program cannot be executed, such errors can be described as run-time errors or execution-time errors.
* When an executable program is executed and if it produces undesirable results it is due to some errors in the program logic or algorithm.
 * Such errors are described as logical errors. 
* Programmers call these errors  to as bugs, and the process of locating and correcting them is referred to as debugging the program.
* If syntax, link or run-time errors are available computer can detect those errors, but the logical error should be detected by computer programmers.
  * During program testing, different types of test data (both valid and invalid) should be used as input data.


 Program implementation
* If program testing provides satisfactory results, the executable program can be used to handle data processing activities of the organization in the real environment.
* This is called program implementation.
  Program maintenance and update
* Program maintenance means to make simple corrective actions in order to run the computer program to meet data processing requirements of the organization. 
* Generally software maintenance agreements can be signed  with outsourcing or in-house maintenance personnel can be used for program maintenance.
 *Program updating means making structured changes to the existing programs or introducing a new set of programs to meet new data processing requirements of the organization.
Program documentation
* Program documentation means to keep or record information related to all the activities of the computer programming. 
*Although documentation appears as the last step in the programming process, it is actually performed throughout the entire process.
 * Documentation consists of materials generated during each step.
*E.g.: problem analysis report, algorithm, program listing, test reports, maintenance and update information, user manuals and training materials.
The Characteristics of a Good Computer Program
1. Reliability: The program should provide correct results at all times and should be free from errors.  
2. Maintainability: The existing program should be able to change or modify to meet new requirements.  
3. Portability: The program should be able to transfer to a different computer system.  
4. Readability: The program must be readable and understandable with the help of documentation.  
5. Performance: The program should handle the task more quickly and efficiently.  
6. Storage saving: The program should be written with the least number of instructions.