Académique Documents
Professionnel Documents
Culture Documents
Manual
August 2010
Computer Programming Lab
Contents
Preliminaries
0.1 Introduction 7
0.1.1 Understand the needs 7
0.1.2 Define the solution 7
0.1.3 Map the solution 7
0.3 Pseudocode
0.5 C Language 8
0.7 Java 9
0.7.1 Java Language Principles 9
0.7.2 Java Platform 9
0.7.3 Java Applets 10
0.7.3 Embedding Applet into web page 10
0.7.4 Serialization 10
Java Programming
2.0 Simple Java Programs 53
2.1 Inheritance 60
2.2 Polymorphism 62
2.3 Serialization – Reading & Writing Object 65
2.4 Sine Wave Applet 66
References
R.1 ASCII Chart 71
R.2 C Quick Reference 72
R.3 Java Quick Reference 77
R.4 Unclean C Source Codes 87
Information
Algorithm / Program
Program Input
Program Output
Objective
Preliminaries
0.3 Pseudocode
Pseudocode is a way of designing a program which uses normal language statements in order to describe the logic
and the processing flow. In this document a pseudocode is used to describe algorithms.
To some extent, OOP is just a change in point of view. We can think of an object in standard programming terms as
nothing more than a set of variables together with some subroutines for manipulating those variables. In fact, it is
possible to use object-oriented techniques in any programming language. However, there is a big difference between
a language that makes OOP possible and one that actively supports it. An object-oriented programming language
such as Java includes a number of features that make it very different from a standard language. In order to make
effective use of those features, you have to "orient" your thinking correctly. Some of the Terminologies related with
OOP are:
0.6.2 Class
Class is a generic specification of like entity. In other words class describes an object. It is the blueprint of an object.
0.6.3 Encapsulation
The mechanism of hiding the internal details of an object.
0.6.4 Inheritance
The term inheritance refers to the fact that one class can acquire structure and behaviour of another class.
0.6.5 Polymorphism
Polymorphism means that different objects can respond to the same message in different ways.
0.7 Java
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a
core component of Sun Microsystems Java platform. The language derives much of its syntax from C and C++ but has
a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file)
that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is general-purpose,
concurrent, class-based, and object-oriented, and is specifically designed to have as few implementation
dependencies as possible. It is intended to let application developers "write once, run anywhere".
/*
<APPLET code=" myapplet.class" WIDTH="200" HEIGHT="200">
<PARAM NAME=”Speed” Value=”1000”>
</APPLET>
*/
import java.applet.*
class myapplet extends Applet{
…….
}
0.7.4 Serialization
Serialization is the process of converting an object into a sequence of bits so that it can be stored in a file or memory
buffer, or transmitted across a network connection. Java’s object serialization allows you to take any object that
implements the Serializable interface and turn it into a sequence of bytes that can later be fully restored to
regenerate the original object. Serializing an object is quite simple, as long as the object implements the Serializable
interface (this interface is just a flag and has no methods)
class Student implements Serializable {
String name;
}
GCC is often the compiler of choice for developing software that is required to execute on a wide variety of hardware
and/or operating systems. System-specific compilers provided by hardware or OS vendors can differ substantially,
complicating both the software's source code and the scripts which invoke the compiler to build it. With GCC, most
of the compiler is the same on every platform, so only code which explicitly uses platform-specific features must be
rewritten for each system.
GCC's external interface is generally standard for a UNIX compiler. Users invoke a driver program named gcc, which
interprets command arguments, decides which language compilers to use for each input file, runs the assembler on
their output, and then possibly runs the linker to produce a complete executable binary.
0.8.7 GEdit
gedit is a UTF-8 compatible text editor for the GNOME desktop environment, Mac OS X and Microsoft Windows.
Designed as a general purpose text editor, gedit emphasizes simplicity and ease of use. It includes tools for editing
source code and structured text such as markup languages. It is designed to have a clean, simple graphical user
interface according to the philosophy of the GNOME project, and it is the default text editor for GNOME. Released
under the terms of the GNU General Public License, gedit is free software. gedit includes syntax highlighting for
various program code and text markup formats. gedit also has GUI tabs for editing multiple files. Tabs can be moved
between various windows by the user. It supports a full undo and redo system as well as search and replace. Other
typical code oriented features include line numbering, bracket matching, text wrapping, current line highlighting,
automatic indentation and automatic file backup.
Some advanced features of gedit include multilanguage spellchecking and a flexible plugin system allowing to
dynamically add new features, for example snippets and integration with external applications including a Python or
Bash terminal. A number of plugins are included in gedit itself, with more plugins in the gedit-plugins package and
online.
An applet program
Execute applet
The applet output
C Application
Applet Program
C
Programming
1.0.12 Interactive program to count occurrence of a character. Use dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
void main()
{
char *str,find;
int len,count,i;
printf("Enter length string: ");
scanf("%d",&len);
str = (char *)malloc(sizeof(char)*len);
printf("Enter a string: ");
scanf("%s",str);
printf("Enter char to seach: ");
find=getch();
count=0;
for(i=0;str[i]!=0;i++)
{
if(str[i]==find)
count++;
}
printf("Occurrence of %c in %s is %d",find,str,count)
}
if(sum==numToCheck)
return 1;
else
return 0;
}
1.0.15 Interactive program to create a file and write your name into it
#include <stdio.h>
#include <stdlib.h>
int main()
{
char * myname="NIRANJAN";
char data[100];
FILE *fp;
fp =fopen("myfile.txt","w");
printf("Writing into the file..\n");
fputs(myname,fp);
fclose(fp);
fp =fopen("myfile.txt","r");
printf("Reading from file..\n");
fgets(data,100,fp);
fclose(fp);
printf("Data read is :%s\n",data);
return 0;
}
Develop an interactive C application which can calculate HCF and LCM between two given numbers.
Background
In mathematics, the Euclidean algorithm (also called Euclid's algorithm) is an efficient method for computing the
greatest common divisor (GCD), also known as the greatest common factor (GCF) or highest common factor (HCF). It
is named after the Greek mathematician Euclid, who described it in Books VII and X of his Elements. The GCD of two
numbers is the largest number that divides both of them without leaving a remainder. The Euclidean algorithm is
based on the principle that the greatest common divisor of two numbers does not change if the smaller number is
subtracted from the larger number. For example, 21 is the GCD of 252 and 105 (252 = 21 × 12 105 = 21 × 5) since 252
− 105 = 147, the GCD of 147 and 105 is also 21. Since the larger of the two numbers is reduced, repeating this
process gives successively smaller numbers until one of them is zero. When that occurs, the GCD is the remaining
nonzero number. By reversing the steps in the Euclidean algorithm, the GCD can be expressed as a sum of the two
original numbers each multiplied by a positive or negative integer, e.g., 21 = 5 × 105 + (−2) × 252.
The Euclidean algorithm has many theoretical and practical applications. It may be used to generate almost all the
most important traditional musical rhythms used in different cultures throughout the world. It is a key element of the
RSA algorithm, a public-key encryption method widely used in electronic commerce.
Algorithm
FUNCTION main
READ num1, num2
SET product = num1 * num2
WHILE num1 num2
IF num1 > num2 THEN num1=num1-num2
ELSEIF num1 < num2 THEN num2=num2-num1
ENDWHILE
SET hcf = num1
SET lcm = product / hcf
DISPLAY hcf, lcm
ENDFUNCTION
Num1 Num2
144 60
HCF LCM
12 720
Develop an interactive C application which can calculate HCF and LCM between two given numbers.
Background
A numeral system (or system of numeration) is a writing system for expressing numbers that is a mathematical
notation for representing numbers of a given set, using graphemes or symbols in a consistent manner. It can be seen
as the context that allows the numerals "11" to be interpreted as the binary symbol for three, the decimal symbol for
eleven, or a symbol for other numbers in different bases.
Ideally, a numeral system will:
Represent a useful set of numbers (e.g. all integers, or rational numbers)
Give every number represented a unique representation (or at least a standard representation)
Reflect the algebraic and arithmetic structure of the numbers.
Converting any system into decimal
Multiply each digit with its position value and sum up, that is the decimal value.
Converting decimal into any system
Perform integer division of the decimal by the new system base and write the intermediate reminders.
The last reminder is the most significant digit and the first reminder is least significant digit.
Represent the reminders in the new system.
Conversion procedure is as follows
Convert given number into decimal, and then convert into required base
Note: ASCII of character ‘A’ is 65, character ‘F’ is 70, character ‘0’ is 48 and character ‘9’ is 57.
ASCII of ‘A’-55=10, ASCII of ‘B’-55=11, ASCII of ‘C’-55=12, ASCII of ‘D’-55=13, ASCII of ‘E’-55=14, ASCII of ‘F’-55=15
Algorithm
FUNCTION toBaseN
PARAMS: num, base
RETURS: number IN BASE AS STRING
SET i=0
SET len=0
SET ALL ELEMENTS OF res TO NULL CHARACTER
WHILE num > 0
SET digit = num MOD base
IF base = 16 AND digit > 9 THEN
res[i] = 55 + digit
ELSE
res[i] = 48 + digit
ENDIF
num = num / base
i = i +1
ENDWHILE
res[i]=NULL CHARACTER
SET len = STRING LENGTH OF n
FOR i=0 TO (len/2)-1
temp = res[i]
res[i] = res [len – i – 1]
res [len – i – 1]=temp
i= i+ 1
ENDFOR
RETURN res
ENDFUNCTION
FUNCTION toDec
PARAMS: num AS STRING, base
RETURNS: res AS LONG
SET i=0
SET res=0
SET pos=1
SET len=STRING LENGTH OF num
31 Department of ECE – GCE Kannur
Computer Programming Lab
FOR i=len-1 TO 0
IF num[i] 48 AND num[i] 57 THEN res = res + (num[i] -48) * pos
ELSEIF num[i] 65 AND num[i] 70 AND base =16 THEN res = res + (num[i] -55) * pos
pos = pos * base
i = i-1
ENDFOR
RETURN res
ENDFUNCTION
FUNCTION main
READ strNum AS STRING, base, convertTobase
numDec = CALL toDec WITH strNum, base
strRes = CALL toBaseN WITH numDec, convertTobase
DISPLAY strRes
ENDFUNCTION
Result
2748
Develop a interactive C application which can generate Fibonacci and Prime series up to a specified limit.
Background
In mathematics, a prime number (or a prime) is a natural number that has exactly two distinct natural number
divisors: 1 and itself. The smallest twenty-five prime numbers (all the prime numbers under 100) are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.
The number 1 is by definition not a prime number. The fundamental theorem of arithmetic establishes the central
role of primes in number theory: any nonzero natural number n can be factored into primes, written as a product of
primes or powers of different primes (including the empty product of factors for 1). Moreover, this factorization is
unique except for a possible reordering of the factors. Primes are applied in several routines in information
technology, such as public-key cryptography, which makes use of the difficulty of factoring large numbers into their
prime factors. The procedure to test a number for prime is as follows. Divide the number to test by numbers from 2
to square root of it and check the reminder is zero or not. If any of the reminders is zero, the number is not prime,
else it is prime.
The Fibonacci Series is a sequence of numbers first created by Leonardo Fibonacci (fi-bo-na-chee) in 1202. They are
used in computer algorithms such as the Fibonacci search technique. They also appear in biological settings, such as
branching in trees, arrangement of leaves on a stem, the fruitlets of a pineapple. Calculating Nth Fibonacci number:
Nth Fibonacci number = Fn = Fn-1 + Fn-1 and the seeds are F0=0 and F1=1
Algorithm
FUNCTION main
READ numOfTerms
SET oldNum=0
SET newNum=1
SET fibNum = oldNum + newNum
SET count =0
DISPLAY oldNum, newNum, fibNum
count = 3
WHILE count <= numOfTerms
fibNum = oldNum + newNum
oldNum = newNum
newNum = fibNum
DISPLAY fibNum
count = count + 1
ENDWHILE
ENDFUNCTION
FUNCTION main
INPUT numOfTerms
SET count = 0
SET num=3
WHILE count <= numOfTerms
FOR i=2 TO num
IF num MOD i =0 THEN BREAK THE LOOP
ENDFOR
IF i = num THEN
DISPLAY num
count = count + 1
ENDIF
num = num + 1
ENDWHILE
ENDFUNCTION
Number of terms
15
Develop an interactive C application to calculate ex , sin(x) and cos(x) using Taylor’s series
Background
In mathematics, the Taylor series is a representation of a function as an infinite sum of terms calculated from the
values of its derivatives at a single point. The Taylor series may be regarded as the limit of the Taylor polynomials. The
Taylor series of a real or complex function ƒ(x) that is infinitely differentiable in a neighbourhood of a real or complex
number a is the power series
f n (a) f ' (a) f '' (a) f ''' (a)
( x a)n f (a) ( x a) ( x a) 2 ( x a)3
n 0 n! 1! 2! 3!
Taylor’s series for some functions
Exponential function:
xn x1 x2 x3
ex 1
n 0 n! 1! 2! 3!
Trigonometric functions: x in radians
( 1) n 2 n 1 x3 x5
sin x x x
n 0 (2n 1)! 3! 5!
( 1) n 2 n x 2 x 45
cos x x 1
n 0 (2n)! 2! 4!
Algorithm
FUNCTION TaylorSeries
PARAMS: value, seriesType
RETURNS: sumOfSeries AS DOUBLE
SET limit =10
IF seriesType = exponential THEN
SET sum=1
FOR n=1 TO limit
sum = sum + (value POWER n) / (CALL fact WITH n)
n= n+ 1
ENDFOR
FUNCTION main
READ x, seriesType
IF seriesType = exponential THEN CALL TaylorSeries WITH x * / 180, seriesType
ELSEIF seriesType = sin THEN CALL TaylorSeries WITH x * / 180, seriesType
ELSEIF seriesType = cos THEN CALL TaylorSeries WITH x * / 180, seriesType
ENDFUNCTION
x
3
ex sin(x) cos(x)
20.08 0.0523 0.9986
Develop a C application which is capable of manipulating string such as string search, string replace.
Background
A C string is a character sequence stored in a one-dimensional character array and terminated with a null character
('\0', called NULL in ASCII). So when you define a string you should be sure to have sufficient space for the null
terminator. In ASCII table, the null terminator has value 0. The length of a C string is found by searching for the (first)
NULL byte. You can loop through a string by using a subscript (array index). String search can be performed by
character by character comparison. While performing string replacement, you can use dynamic memory allocation if
widening of the string is required.
Algorithm
FUNCTION str_len
PARAMS: str AS STRING
RETURNS len AS INTEGER
SET len=0
WHILE str[len] NULL CHARACTER
len=len+1
ENDWHILE
RETURN len
ENDFUNCTION
FUNCTION str_find
PARAMS: str AS STRING, find AS STRING, pos
RETURNS: POSITION OF FIRST OCCURANCE OF find IN str
SET len_str = CALL str_len WITH str
SET len_find = CALL str_len WITH find
FOR i=pos TO len_str-1
IF len_find (len_str – i) THEN
FOR j=0 TO len_find-1
IF find[j] str[i+j] THEN BREAK THE LOOP
j= j+ 1
ENDFOR
IF j=len_find THEN RETURN i
ELSE
BREAK THE LOOP
ENDIF
ENDFOR
RETURN -1
ENDFUNCTION
FUNCTION str_rep
PARAMS: str AS STRING, find AS STRING, replace AS STRING, pos
RETURNS: res AS STRING
FUNCTION main
READ str, find, replace
pos = CALL str_find WITH str, find, 0
IF pos<0 THEN
DISPLAY ―NOT FOUND‖
RETURN
ELSE
DISPLAY ―FOUND AT POSITION ‖, pos
res = CALL str_rep WITH str, find, replace, pos
ENDIF
DISPLAY res
ENDFUNCTION
Status Result
FOUND AT POS ITION 6 YOU SHOULD HAVE IT
Background
The ordinary matrix product is the most often used method to multiply matrices. It is defined between two matrices
only if the width of the first matrix equals the height of the second matrix. Multiplying an m×n matrix with an n×p
matrix results in an m×p matrix. The ordinary matrix product is not commutative:
Two arrays A, which is m x n, and B, which is n x p. The Product AB is determined as the dot products of the ith row in
A and the jth column in B placed in ith row and jth column of the resulting m x p matrix C.
The iterative equation c[i,j] = c[i,j] + a[i,k] * b[k,j]
Note: i represents a row index and j represents a column index
Algorithm
FUNCTION showMatrix
PARAM: mat AS MATRIX, rows, cols
RETUNRS: NOTHING
FOR i=0 TO rows-1
FOR j=0 TO cols-1
DISPLAY mat[i][j]
j= j+ 1
ENDFOR
i= i + 1
ENDFOR
ENDFUNCTION
FUNCTION readMatrix
PARAM: mat AS MATRIX, rows, cols
RETUNRS: NOTHING
FOR i=0 TO rows-1
FOR j=0 TO cols-1
READ mat[i][j]
j= j+ 1
ENDFOR
i= i + 1
ENDFOR
ENDFUNCTION
FUNCTION main
READ rowsA, colsA, rowsB, colsB
IF col1 row2 THEN DISPLAY "MULTIPLICATION NOT POSSIBLE" RETURN
CALL readMatrix WITH matrixA rowsA, colsB
CALL readMatrix WITH matrixB rowsB, colsB
FOR i=0 TO rowsA-1
FOR j=0 TO colsB-1
SET matrixC[i][j] = 0
FOR k=0 TO colsA-1
matrixC[i][j] = matrixC[i][j] + matrixA[i][k] * matrixB[k][j]
k = k +1
ENDFOR
j= j+ 1
ENDFOR
i= i+ 1
ENDFOR
CALL showMatrix WITH matrixA, rowsA, colsA
CALL showMatrix WITH matrixA, rowsB, colsB
CALL showMatrix WITH matrixC, rowsA, colsB
ENDFUNCTION
Product
30 24 18
84 69 54
138 114 90
Background
In algebra, the determinant is a special number associated with any square matrix. The fundamental geometric
meaning of a determinant is a scale factor for measure when the matrix is regarded as a linear transformation. Thus a
2 × 2 matrix with determinant 2 when applied to a set of points with finite area will transform those points into a set
with twice the area. Determinants are important in calculus and multi-linear algebra.
A minor Mij of the matrix A is the determinant of the n-1 by n-1 matrix formed by removing the ith row and the jth
column from matrix A. The cofactor matrix is the matrix of determinants of the minors A i j multiplied by -1(i+j). The
determinant is calculated from the sum of minors multiplied by cofactors taken over a single row or column.
Determinant =|A| = ∑ ai jCij , in which Cij is the cofactor of aij is, Cij = (−1)i+j·Mij
The following algorithm recursively calculates matrix minors by eliminating rows and columns. The recursion stops
when the matrix is reduced to a 2x2 matrix. The determinant is calculated over first row.
Note: i represents a row index and j represents a column index
Determinate of 2 x 2 matrix a[2][2] = a[0][0] * a[1][1] – a[1][0] * a[0][1]
Algorithm
FUNCTION calcDeterminant
PARAMS: matrix, order
RETURNS: determinant AS float
INITIALIZE ALL ELEMENTS OF matrixMinor TO ZERO
IF order =2 THEN determinant = matrix[0][0] * matrix[1][1] – matrix[1][0] * matrix[0][1]
ELSE
determinant = 0
FOR column1 = 0 TO order -1
FOR row=1 TO order -1
SET column2 = 0
FOR column=0 TO order -1
IF column =column1 CONTINUE LOOP
matrixMinor[row -1][column2] = a[row][column]
column2 = column2 + 1
column = column + 1
ENDFOR
row = row +1
ENDFOR
determinant= determinant+(-1 POWER column1 )* matrix[0][column1] *
(CALL calcDeterminant WITH matrixMinor ,order-1)
column1 = column1 + 1
ENDFOR
ENDIF
RETURN determinant
ENDFUNCTION
FUNCTION main
READ order
CALL readMatrix WITH matrix, order, order
determinant = CALL calcDeterminant WITH matrix, order
DISPLAY determinant
ENDFUNCTION
Background
For a square matrix A, the inverse is written A-1. When A is multiplied by A-1 the result is the identity matrix I. Non-
square matrices do not have inverses.
Note: Not all square matrices have inverse. A square matrix which has an inverse is called invertible or non-singular,
and a square matrix without an inverse is called noninvertible or singular.
Cofactor Ai,j is defined as the determinant of the square matrix of order (n-1) obtained from A by removing the row
number i and the column number j multiplied by (-1)i+j.
Cofactor matrix is the matrix formed by cofactors of all elements.
Transpose of cofactor matrix is called adjoint
Generally A-1 = (adjoint A) / (determinant of A)
The algorithm calculate cofactor matrix by recursion and transpose it. Inverse is calculated by using determinant
subroutine implemented in the previous experiment.
Note: i represents a row index and j represents a column index.
Algorithm
FUNCTION generateCofactorMatrix
PARAMS: matrix, order, matrixResult
RETURNS: NOTHING
FUNCTION transposeMatrix
PARAMS: matrix, order
RETURNS: NOTHING
FOR row=1 TO order-1
FOR column=0 TO row-1
temp = matrix[row][column]
matrix[row][column] = matrix[column][row]
matrix[column][row] = temp
column = column + 1
ENDFOR
row = row + 1
ENDFOR
ENDFUNCTION
Order Matrix
1 3 1
3 1 1 2
2 3 4
Inverse
2 9 -5
0 -2 1
-1 -3 2
Develop an interactive C application to solve simultaneous equations using Jordan Elimination method.
Background
In linear algebra system of linear equations can be solved by performing elementary row operations. Here row
operations are performed until the coefficient matrix is reduced to identity matrix. The algorithm assumes that
diagonal elements of coefficient matrix are not zero.
a11 x1 +a12 x 2 +a13 x 3 =b1
a21 x1 +a22 x 2 +a23 x 3 =b2
A Coefficient Matrix a31 x1 +a32 x 2 +a33 x 3 =b3
B Constant Matrix a11 a12 a13 x1 b1
X Matrix of Unknowns a21 a22 a23 x 2 = b2
a31 a32 a33 x3 b3
AX=B
Algorithm
FUNCTION main
READ numberOfUnknowns
SET order = numberOfUnknowns
PROMT FOR coeffient term MATRIX
CALL readMatrix WITH matrixCoefficients, order, order
PROMT FOR constant term MATRIX
FOR i=1 TO order-1
READ matrixConstants[i]
i= i+ 1
ENDFOR
2 3 7 29
1 4 2 15
3 2 1 10
X1 X2 X3
1 2 3
Background
C supports the file-of-structures concept. Once you open the file you can read a structure, write a structure, or seek
to any structure in the file. This file concept supports the concept of a file pointer. When the file is opened, the
pointer points to record 0 (the first record in the file). Any read operation reads the currently pointed-to structure
and moves the pointer down one structure. Any write operation writes to the currently pointed-to structure and
moves the pointer down one structure. Seek moves the pointer to the requested record. Keep in mind that C
considers everything in the disk file as blocks of bytes read from disk into memory or read from memory onto disk. C
uses a file pointer, but it can point to any byte location in the file. In this algorithm, a structure Student is used as
record. Description of record is as follows.
Student
ClassNo Integer
Name String ( character array)
Percentage Float
Note: fread(&std, sizeof(Student) , 1,fp); Reads one record from the file into the variable std.
fwrite(&std, sizeof(Student) , 1,fp); Writes one record of value std into file.
fseek ( fp ,n*sizeof(Student) , SEEK_SET ); Moves the file pointer to the nth record.
For seek, you should open file in “rb+” mode
Algorithm
FUNCTION main
CREATE STRUCTURE Student WITH MEMBERS classNo, name, percentage
CREATE NEW Student std
DISPLAY ―1. READ DATA‖
DIPLAY ―2. SEARCH STUDENT & MODIFY‖
DISPLAY ―3. CALCULATE CLASS AVERAGE‖
DISPLAY ―4. LIST ALL‖
DISPLAY ―5. EXIT‖
READ CHOICE
IF CHOICE=1 THEN
READ count
OPEN FILE ―student.dat‖ IN WRITE BINARY MODE
FOR i=0 TO count
READ classNo, name, percentage
SET std.classNo = classNo
SET std.name = name
SET std.percentage = percentage
WRITE std INTO FILE ―student.dat‖ AS RECORD
i= i+ 1
ENDFOR
CLOSE FILE ―student.dat‖
ELSEIF CHOICE=2 THEN
READ nameToSearch, newClassNo, newPercentage
OPEN FILE ―student.dat‖ IN READ BINARY MODE
SET FOUND=FALSE
SET COUNT=0
IF FOUND=TRUE THEN
SET std.classNo = newClassNo
SET std.name = nameToSearch
SET std.percentage = newPercentage
OPEN FILE ―student.dat‖ IN READ AND WRITE MODE (use c file open mode: rb+)
SEEK FILE TO SIZEOF(Student)*COUNT
WRITE std INTO FILE ―student.dat‖ AS RECORD
CLOSE FILE ―student.dat‖
DISPLAY ―Modified‖
ELSE
DISPLAY ―Cannot find‖
ENDIF
ELSEIF CHOICE=3 THEN
SET avg=0
SET count =i
OPEN FILE ―student.dat‖ IN READ BINARY MODE
WHILE NOT END OF FILE student.dat‖
READ NEXT std as RECORD FROM ―student.dat‖
avg = avg + std.percentage
ENDWHILE
CLOSE FILE ―student.dat‖
DISPLAY avg/count
ELSEIF CHOICE=4 THEN
OPEN FILE ―student.dat‖ IN READ BINARY MODE
WHILE NOT END OF FILE student.dat‖
READ NEXT std as RECORD FROM ―student.dat‖
DISPLAY std.classNo, std.name, std.percentage
ENDWHILE
CLOSE FILE ―student.dat‖
ELSEIF CHOICE=5 THEN
EXIT MAIN
ENDIF
ENDFUNCTION
Menu Choice
1.READ DATA 2
2. SEARCH STUDENT & MODIFY Search Name New Class No New Percentage
3. CALCULATECLASS AVERAGE Kiran M 11 90
4. LIST ALL Status
5. EXIT Modified
Choice Choice
1 3
Count Average
3 84.3333
Class No Name Percentage Choice
10 Anil K 78 4
Class No Name Percentage Class No Name Percentage
9 Kiran M 89 10 Anil K 78
Class No Name Percentage 11 Kiran M 90
12 Sunil K 85 12 Sunil K 85
Develop an interactive C application to setup a singly linked list with only one numeric data item.
Background
A linked list is a data structure that consists of a sequence of data records such that in each record there is a field that
contains a reference (i.e., a link) to the next record in the sequence. Linked lists are among the simplest and most
common data structures; they provide an easy implementation for several important abstract data structures,
including stacks, queues, hash tables, symbolic expressions, and skip lists. The principal benefit of a linked list over a
conventional array is that the order of the linked items may be different from the order of the data items are stored
in memory or on disk. For that reason, linked lists allow insertion and removal of nodes at any point in the list, with a
constant number of operations. On the other hand, linked lists by themselves do not allow random access to the
data, or any form of efficient indexing. Thus, many basic operations — such as obtaining the last node of the list, or
finding a node that contains a given datum, or locating the place where a new node should be inserted — may
require scanning of most of the list elements.
Structure of a Node
Node
data Integer
next POINTER TO Node
Singly Linked List
Deletion Operation
FUNCTION addAtEnd
PARAMS: POINTER TO headNode, newData
RETURNS: POINTER TO Node
CREATE POINTER TO Node newNode
ALLOCATE MEMORY FOR newNode
CREATE POINTER TO Node currentNode
newNode data = newData
newNode next = END OF LIST (NULL)
currentNode = headNode
IF headNode next = END OF LIST (NULL) THEN
headNode next = newNode
ELSE
WHILE currentNode next END OF LIST
currentNode=currentNode next
ENDWHILE
currentNode next=newNode
ENDIF
ENDFUNCTION
FUNCTION length
PARAMS: POINTER TO headNode
RETURNS: listLength AS INTERGER
CREATE POINTER TO Node currentNode
currentNode = headNode
listLength =0
WHILE currentNode END OF LIST
listLength = listLength + 1
currentNode = currentNode next
ENDWHILE
RETURN listLength
ENDFUNCTION
FUNCTION searchNode
PARAMS: POINTER TO headNode, findData
RETURNS: POINTER TO Node
CREATE POINTER TO Node currentNode
currentNode = headNode
WHILE currentNode END OF LIST
IF currentNode data =findData THEN RETURN currentNode
currentNode = currentNode next
ENDWHILE
RETURN EMPTY NODE
END FUNCTION
FUNCTION insertAfterNode
PARAMS: POINTER TO headNode, insertAfterData, newData
RETURNS: NOTHING
CREATE POINTER TO Node newNode
ALLOCATE MEMORY FOR newNode
CREATE POINTER TO Node prevNode
CREATE POINTER TO Node currentNode
currentNode = headNode
newNode data = newData
newNode next = END OF LIST (NULL)
WHILE currentNode END OF LIST
IF currentNode = insertAferData THEN
newNode next currentNode next
currentNode next=newNode
RETURN
ENDIF
currentNode = currentNode next
ENDWHILE
ENDFUNCTION
FUNCTION displayList
PARAMS: POINTER TO headNode
RETURNS: NOTHING
SET listLen = CALL length WITH HeadNode
DISPLAY listLen
CREATE POINTER TO Node currentNode
currentNode = headNode
WHILE currentNode END OF LIST
DISPLAY currentNode data
currentNode = currentNode next
ENDWHILE
ENDFUNCTION
FUNCTION MAIN
CREATE POINTER TO Node headNode
DISPLAY ―1. Add at Begining of List‖
DISPLAY ―2. Add at End of List‖
DISPLAY ―3. Insert after specified data of List‖
DISPLAY ―4. Search & Delete‖
DISPLAY ―5. Display List'
DISPLAY ―6. Exit‖
49 Department of ECE – GCE Kannur
Computer Programming Lab
FOR I=0 TO 100
READ choice
IF choice=1 THEN
READ data
headNode=CALL addAtBegining WITH headNode, data
CALL displayList WITH headNode
ELSEIF choice=2 THEN
READ data
CALL addAtEnd WITH headNode, data
CALL displayList WITH headNode
ELSEIF choice=3 THEN
READ insertAfterData, newData
CALL insertAfterNode WITH headNode, insertAfterData, newData
CALL displayList WITH headNode
ELSEIF choice=4 THEN
READ findData
foundNode=CALL searchNode WITH headNode,findData
IF foundNode END OF LIST THEN
DISPLAY ―Not found‖
ELSE
CALL deleteNode WITH headNode, foundNode
DISPLAY ―Deleted‖
CALL displayList WITH headNode
ENDIF
ELSEIF choice=5 THEN
CALL displayList WITH headNode
ELSEIF choice=6 THEN
EXIT MAIN
ENDIF
ENDFOR
ENDMAIN
Java
Programming
}
}
}
}
class parent{
String name;
int num;
parent(){
System.out.println("I am the parent!");
num = 123;
}
void digitSum(){
int sum =0;
for(;num>0;num/=10)
sum+=num%10;
System.out.print("Sum of digits: " + sum);
}
}
class child extends parent{
child(){
System.out.println("I am child inherited from parent class!");
name = "kid";
System.out.println("My inherited instance variables are:");
System.out.println("name=" + name);
System.out.println("num=" + num);
}
}
try{
//The following statement try to access an element which does not exists
//So catch ArrayIndexOutOfBoundsException
nums[10]=20;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("You have accessed an element which does not exists");
System.out.println(e.toString());
}
System.out.println("------------------------------------------------------------");
try{
//The following statements will try to read possibly non-exisitng file
//So catch FileNotFoundException
FileInputStream fin = new FileInputStream ("Invalidfile.txt");
}
catch(FileNotFoundException e){
System.out.println("Requested file not found!");
System.out.println(e.toString());
}
System.out.println("------------------------------------------------------------");
}
}
58 Department of ECE – GCE Kannur
Computer Programming Lab
2.0.17 Reading from Standard Input - Keyboard
import java.io.*;
public class KBInput{
public static void main(String args[]){
String stringVal="";
char charVal='1';
int intVal=0;
float floatVal=0.0f;
double doubleVal=0.0;
InputStreamReader iStream = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(iStream);
try{
System.out.println("Enter an Integer");
intVal = Integer.parseInt(in.readLine());
System.out.println("Enter a String");
stringVal = in.readLine();
System.out.println("Enter a Character");
charVal = (char)in.read();
}
catch(Exception e){
System.out.println("Failed read from Keyboard: " + e.toString());
}
System.out.println("The Values are:");
System.out.println("Integer value: " + intVal);
System.out.println("Float value: " + floatVal);
System.out.println("Double value: " + doubleVal);
System.out.println("String value: " + stringVal);
System.out.println("Character value: " + charVal);
}
}
g.setColor(Color.green);
g.fillOval(50,50,150,150);
g.setColor(Color.blue);
g.drawString(name,100,100);
}
}
Develop a java application to illustrate the inheritance phenomenon. Create a class named
‘twoTerminalComponent’ with three members representing terminal 1 Voltage (term1Voltage), terminal 2
Voltage (term2Voltage) and component Name (componentName). Include a method named ‘applyVoltage’
which accepts terminal voltages and displays direction of current (From terminal 1 to terminal 2 or terminal
2 to terminal 1). Derive a subclass named ‘resistor’ from ‘twoTerminalComponent’. The ‘resistor’ has three
members resistance, current and power. Add a method to calculate current and power
(calculateCurrentAndPower) in the ‘resistor’. Illustrate inheritance using these classes.
Background
Create the class hierarchy shown in the class diagram.
Implement the class twoTerminalComponent with three twoTerminalComponent
members term1Voltage, term2Voltage and #term1Voltage : int
componentName. Based on terminalVoltage display #term2Voltage : int
#componentName : string
current direction in the applyVoltage method. Derive a +applyVoltage(in term1Voltage : int, in term2Voltage : int) : void
class resistor from the twoTerminalComponent and add
member variables resistance, current and power.
Implement calculateCurrentAndPower method to
calculate current and power. In the main function first resistor
#resistance : float
create a resistor object, apply sum voltage to it and call #current : float
its calculateCurrentAndPower method. Create a #power : float
twoTerminalComponent object reference and assign +calculateCurrentAndPower() : void
previously created resistor object to it. Apply some
voltage to it. Then call calculateCurrentAndPower
method of resistor object.
Program Source
class twoTerminalComponent{
int term1Voltage;
int term2Voltage;
String componentName;
void applyVoltage(int term1Voltage, int term2Voltage){
this.term1Voltage=term1Voltage;
this.term2Voltage=term2Voltage;
System.out.println("Terminal Voltage 1: " + term1Voltage+"V");
System.out.println("Terminal Voltage 2: " + term2Voltage+ "V");
if(term1Voltage>term2Voltage){
System.out.println("Current flowing from 1 to 2");
}
else if(term1Voltage==term2Voltage){
System.out.println("Current not flowing");
}
else {
System.out.println("Current flowing from 2 to 1");
}
}
}
}
Develop a java application to illustrate polymorphism using method overloading and object references.
Create a class vehicle having two members vehicleName and speed. Add five methods to vehicle to initialize
the speed (start), increase the speed (accelerate), decrease the speed (applyBreak), display the
speed(showSpeed) and display the vehicleName (showInfo). Derive a class car from vehicle and add one
more member regNumber. Include a constructor in car to initialise vehicleName and regNumber. Overload
and override the function accelerate in car, one with char argument gear and another with int argument
dSpeed. The first method should change speed depending on the gear and the next function should
increment the speed by an amount dSpeed. Override showInfo method in car to display details of the car.
Illustrate polymorphism with these classes.
Background
Build the class hierarchy shown in the class diagram. Implement
vehicle
vehicle class with members, vehicleName and speed. Implement
#vehicleName : string
start method to set speed to 1, accelerate method to increment #speed : int
speed, applyBreak method to decrement speed, showSpeed #start() : void
method display speed and showInfo method display #accelerate() : void
#showInfo() : void
vehicleName. Derive a class car from it with a new member #showSpeed() : void
regNumber. Implement a constructor in the car to initialise #applyBreak() : void
vehicleName and regNumber. Overload and override accelerate
method in car. First one to accept a gear and change speed to car
that gear. (A: 10Km/hr, B: 20 Km/hr, C: 30Km/hr, D: 40 Km/hr & #regNumber : string
Program Source
class vehicle {
String vehicleName;
int speed;
void accelerate(){
++speed;
showSpeed();
}
void start(){
speed=1;
System.out.println("Started...");
showSpeed();
}
void showInfo(){
System.out.println("Vehicle: " + vehicleName);
}
void showSpeed(){
System.out.println("Vehicle Speed: " + speed + "Km/Hr");
}
void applyBreak(){
if(speed>0){
speed=speed-5;
if(speed<=0)
speed=0;
}
System.out.println("*****************************************");
car martutiCar =new car("KL 11 / 1234");
martutiCar.showInfo();
martutiCar.start();
martutiCar.accelerate(10);
martutiCar.accelerate('D');
martutiCar.accelerate('R');
martutiCar.applyBreak();
System.out.println("*****************************************");
vehicle = martutiCar;
vehicle.showInfo();
vehicle.accelerate();
vehicle.accelerate();
vehicle.applyBreak();
}
}
Create a class student having five fields name and regNo. Add constructor to initialise members and method
to display members. Illustrate serialization with this class
Background
Create class student with constructor to initialise members. The student class must implement the interface for
serialization. Open the file using FileOutputStream or FileInputStram. Chain it to ObjectInputStream or
ObjectOutputStram. Use readObject and writeObject methods of ObjectInputStream and ObjectOutputStream for
reading and writing object.
Program Source
import java.io.*;
class student implements Serializable{
String name;
int regNo;
public student(String name, int regNo){
this.name = name;
this.regNo = regNo;
}
public void showDetails(){
System.out.println("Name:\t" + name);
System.out.println("regNo:\t" + regNo);
}
}
public class testFileIO{
public static void main(String args[]){
try{
student std1 = new student("Anoop", 1001);
FileOutputStream fOut=new FileOutputStream("Student.txt");
ObjectOutputStream oOut=new ObjectOutputStream(fOut);
oOut.writeObject(std1);
oOut.flush();
oOut.close();
System.out.println("\n\nSaved student having following details into file 'Student.txt'");
std1.showDetails();
}
catch(Exception e){
System.out.println("Exception during serialisation");
}
try{
student std1;
FileInputStream fIn=new FileInputStream("Student.txt");
ObjectInputStream oIn=new ObjectInputStream(fIn);
student std2=(student)oIn.readObject();
oIn.close();
System.out.println("\n\nRetrieved student having following details from file 'Student.txt'");
std2.showDetails();
}
catch(Exception e){
System.out.println("Exception during serialisation");
}
}
}
Saved student having following details into file 'Student.txt'
Name: Anoop
regNo: 1001
Retrieved student having following details from file 'Student.txt'
Name: Anoop
regNo: 1001
Implement an applet program to display a sine wave. Accept frequency and amplitude as parameter from
Browser
Background
The Expression for sampled sine wave
n 2000
y ( n) amplitude sin(2 frequency n)
n 0
Choose a suitable value for sample interval dn. Read parameters amplitude and frequency from the applet tag using
getParameter() convert it into float using Float.parseFloat(), calculate 2000 samples using the above equation and
store it in an array. Draw the samples using drawLine method of Graphics object. Draw a lines connecting from (n-1)th
samples to nth samples for all values of n from 0 to 2000.
Algorithm
/*
<applet code="sineWave.class" width="500" height="500">
<param name="frequency" value="10">
<param name="amplitude" value="200">
</applet>
*/
import java.applet.Applet;
import java.awt.*;
g.setColor(Color.red);
for(int x=1;x<SAMPLE_LEN;x++)
g.drawLine( x-1, screenHeight/2-y[x-1],x, screenHeight/2-y[x]);
g.setColor(Color.green);
g.drawLine( 0, screenHeight/2,screenWidth, screenHeight/2);
g.setColor(Color.blue);
g.drawString("Simple Sine Wave",10,20);
g.drawString("Amplitude:" + amplitude ,10,40);
g.drawString("Frequency:" + frequency ,10,60);
}
}
References
Dec Hex Description Dec Hex Char Description Dec Hex Char Dec Hex Char
0 0 null 32 20 space 64 40 @ 96 60 `
1 1 start of heading 33 21 ! 65 41 A 97 61 a
2 2 start of text 34 22 " 66 42 B 98 62 b
3 3 end of text 35 23 # 67 43 C 99 63 c
4 4 end of transmission 36 24 $ 68 44 D 100 64 d
5 5 enquiry 37 25 % 69 45 E 101 65 e
6 6 acknowledge 38 26 & 70 46 F 102 66 f
7 7 bell 39 27 ' 71 47 G 103 67 g
8 8 backspace 40 28 ( 72 48 H 104 68 h
9 9 horizontal tab 41 29 ) 73 49 I 105 69 i
10 A new line 42 2A * 74 4A J 106 6A j
11 B vertical tab 43 2B + 75 4B K 107 6B k
12 C new page 44 2C , 76 4C L 108 6C l
13 D carriage return 45 2D - 77 4D M 109 6D m
14 E shift out 46 2E . 78 4E N 110 6E n
15 F shift in 47 2F / 79 4F O 111 6F o
16 10 data link escape 48 30 0 80 50 P 112 70 p
17 11 device control 1 49 31 1 81 51 Q 113 71 q
18 12 device control 2 50 32 2 82 52 R 114 72 r
19 13 device control 3 51 33 3 83 53 S 115 73 s
20 14 device control 4 52 34 4 84 54 T 116 74 t
21 15 negative acknowledge 53 35 5 85 55 U 117 75 u
22 16 synchronous idle 54 36 6 86 56 V 118 76 v
23 17 end of trans. block 55 37 7 87 57 W 119 77 w
24 18 cancel 56 38 8 88 58 X 120 78 x
25 19 end of medium 57 39 9 89 59 Y 121 79 y
26 1A substitute 58 3A : 90 5A Z 122 7A z
27 1B escape 59 3B ; 91 5B [ 123 7B {
28 1C file separator 60 3C < 92 5C \ 124 7C |
29 1D group separator 61 3D = 93 5D ] 125 7D }
30 1E record separator 62 3E > 94 5E ^ 126 7E ~
31 1F unit separator 63 3F ? 95 5F _ 127 7F DEL
C Preprocessor
Purpose Preprocessor
include library file #include <fillename>
include user file #include "fillename"
replacement text #define name text
replacement macro #define name(var) text
Example. #define max(A,B) ((A)>(B) ? (A) : (B)) };
undefine #undef name
quoted string in replace #
Example. #define msg(A) printf("%s = %d", #A, (A))
concatenate args and rescan ##
conditional execution #if, #else, #elif, #endif
is name defined and not defined? #ifdef, #ifndef
name defined? defined(name)
line continuation char /
Data Types/Declarations
Purpose Function
character (1 byte) char
integer int
real number (single, double precision) float, double
short (16 bit integer) short
long (32 bit integer) long
positive or negative signed
non-negative modulo 2 unsigned
pointer to int, float,: : : int*, float*,: : :
enumeration constant enum tag {name = value ,: : : };
constant (read-only) value type const name;
declare external variable extern
internal to source file static
local persistent between calls static
no value void
structure struct tag {: : : };
create new name for data type typedef type name;
size of an object (type is size_t) sizeof object
size of a data type (type is size_t) sizeof(type)
Constants
Purpose Function
sufix: long, unsigned, flooat 65536L, -1U, 3.0F
exponential form 4.2e1
prefix: octal, hexadecimal 0, 0x or 0X
Example. 031 is 25, 0x31 is 49 decimal
character constant (char, octal, hex) 'a', '\ooo', '\xhh'
newline, cr, tab, backspace \n, \r, \t, \b
special characters \\, \?, \', \"
string constant (ends with ―\0‖) "abc: : : de"
Structures
struct tag { structure template
declarations declaration of members
};
Purpose Function
create structure struct tag name
member of structure from template name.member
member of pointed-to structure pointer -> member
single object, multiple possible types union
bit field with b bits unsigned member: b;
Flow Constructs
Purpose Function
if statement if (condition1 ) statement 1
else if (condition2) statement 2
else statement 3
while statement while (condition)
statement
for statement for (initialization ; condition ; increment )
statement
do statement do
{
Statement
}
while(condition);
switch statement switch (expr)
{
case const 1 : statement 1 break;
case const 2 : statement 2 break;
default: statement
}
String Operations
s,t are strings, cs,ct are constant strings
Purpose Function
length of s strlen(s)
copy ct to s strcpy(s,ct)
concatenate ct after s strcat(s,ct)
compare cs to ct strcmp(cs,ct)
only first n chars strncmp(cs,ct,n)
pointer to first c in cs strchr(cs,c)
pointer to last c in cs strrchr(cs,c)
copy n chars from ct to s memcpy(s,ct,n)
74 Department of ECE – GCE Kannur
Computer Programming Lab
copy n chars from ct to s (may overlap) memmove(s,ct,n)
compare n chars of cs with ct memcmp(cs,ct,n)
pointer to first c in first n chars of cs memchr(cs,c,n)
put c into firrst n chars of s memset(s,c,n)
Input/Output <stdio.h>
Standard I/O
Purpose Function
standard input stream stdin
standard output stream stdout
standard error stream stderr
end of file (type is int) EOF
get a character getchar()
print a character putchar(chr)
print formatted data printf("format",arg ,: : : )
print to string s sprintf(s,"format",arg 1 ,: : : )
read formatted data scanf("format",&name ,: : : )
read from string s sscanf(s,"format",&name 1 ,: : : )
print string s puts(s)
File I/O
Purpose Function
declare file pointer FILE *fp;
pointer to named file fopen("name","mode")
modes: r (read), w (write), a (append), b (binary)
end of file (type is int) EOF
get a character getc(fp)
write a character putc(chr,fp)
write to file fprintf(fp,"format",arg ,: : : )
read from file fscanf(fp,"format",arg 1 ,: : : )
read and store n items to *ptr fread(*ptr,itemsize,n,fp)
write n items to file fwrite(*ptr, itemsize,n,fp)
close file fclose(fp)
non-zero if already reached EOF feof(fp)
read line to string s (< max chars) fgets(s,max,fp)
write string s fputs(s,fp)
Storage Allocation
Purpose Function
allocate storage malloc(size), calloc(nobj,size)
change size of storage newptr = realloc(ptr,size);
deallocate storage free(ptr);
C Keywords
auto break case char const continue default do
double else enum extern float for goto if
Variable Declaration:
<datatype> <variable name>
Example: int num1;
Variable Initialization:
<datatype> <variable name> = value
Example: double num2 = 3.1419;
Arrays
An array which can be of any data type is created in two steps – array declaration and memory allocation.
Array declaration
<datatype> [ ] <arrayname>;
Examples int[] myarray1;
double[] myarray2;
Memory Allocation
The new keyword allocates memory for an array.
Syntax
<arrayname> = new <array type> [<number of elements>];
Examples
myarray1 = new int[10];
myarray2 = new double[15];
Flow Control:
1. if……..else statements
Syntax:
if(condition){
statements;
}
else{
statements;
}
2. for loop
Syntax:
for(initialization; condition; increment){
statements;
}
3. while loop
Syntax:
while(condition){
statements;
}
4. do….While loop
Syntax:
do{
statements;
}
while(condition);
5. switch statement
Syntax:
switch(variable){
case(value1):
statements;
break;
case(value2):
statements;
break;
default:
statements;
break;
}
Class Declaration
A class must be declared using the keyword class followed by the class name.
Syntax
class <classname>{
———— Body of the class
A typical class declaration is as follows:
<modifier> class <classname> extends <superclass name> implements <interface name>{
—————Member variable declarations;
—————Method declarations and definitions
}
Member variable declarations
<access specifier> <static/final/transient/volatile> <datatype> <variable name>
Example: public final int num1;
Method declarations
<access specifier> <static/final> <return type> <method name> <arguments list>{
Method body;
}
Example: public int sum(int a, int b)
Interface declaration
Interface methods do not have any implementation and are abstract by default.
Syntax
interface <interface name>{
void abc();
void xyz();
}
Using an interface
A class implements an interface with the implements keyword.
Syntax
class <classname> extends <superclass name> implements <interface name>{
class body;
—————————;
}
Packages
A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java
packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather
than one at a time. ...
Importing Package
To use a package's classes inside a Java source file, it is convenient to import the classes f rom the package with an
import declaration.
Example
import java.util.*; //Import all classes in util package;
import java.util.Date //Import Date class in util package
String
The + operator joins two strings together. If either operand is String, the other is converted to String and concatenated
with it. These are common String methods. In all of these prototypes, i and j are int indexes into a string, s and t are
Strings, and c is a char. cs is a CharacterSequence
Method Description
Length
i= s.length() length of the string s.
Comparison (note: use these instead of == and !=)
i= s.compareTo(t) compares to s. returns <0 if s<t, 0 if ==, >0 if s>t
i= s.compareToIgnoreCase(t) same as above, but upper and lower case are same
b= s.equals(t) true if the two strings have equal values
b= s.equalsIgnoreCase(t) same as above ignoring case
b= s.startsWith(t) true if s starts with t
b= s.startsWith(t, i) true if t occurs starting at index i
b= s.endsWith(t) true if s ends with t
Searching -- Note: All "indexOf" methods return -1 if the string/char is not found
i= s.contains(cs) True if cs can be found in s.
i= s.indexOf(t) index of the first occurrence of String t in s.
i= s.indexOf(t, i) index of String t at or after position i in s.
i= s.indexOf(c) index of the first occurrence of char c in s.
i= s.indexOf(c, i) index of char c at or after position i in s.
i= s.lastIndexOf(c) index of last occurrence of c in s.
i= s.lastIndexOf(c, i) index of last occurrence of c on or before i in s.
i= s.lastIndexOf(t) index of last occurrence of t in s.
i= s.lastIndexOf(t, i) index of last occurrence of t on or before i in s.
Getting parts
c= s.charAt(i) char at position i in s.
s1 = s.substring(i) substring from index i to the end of s.
s1 = s.substring(i, j) substring from index i to BEFORE index j of s.
Creating a new string from the original
s1 = s.toLowerCase() new String with all chars lowercase
s1 = s.toUpperCase() new String with all chars uppercase
s1 = s.trim() new String with whitespace deleted from front and back
s1 = s.replace(c1, c2) new String with all c1 characters replaced by character c2.
s1 = s.replace(cs2, cs3) new String with all cs2 substrings replaced by cs3.
Search & Replace
b= s.matches(str) true if str matches the entire string in s.
s1 = s.replaceAll(str, t) replaces each substring that matches str with String t
s1 = s.replaceFirst(str, t) replaces first substring that matches str with String t
sa = s.split(str) array of all substrings terminated by str or end
sa = s.split(str, count) limited to applying str only count times.
Static Methods for Converting to String
s= String.valueOf(x) Converts x to String, where x is any type value (primitive or object).
s= String.format(f, x...) Use format f to convert variable number of parameters, x to a string.
If s is null or not a valid representation of a number of that type, these methods will throw (generate) a
NumberFormatException
Exception Handling Syntax
try{
//code to be tried for errors
}
catch(ExceptionType1 obj1){
//Exception handler for ExceptionType1
}
catch(ExceptionType2 obj2){
//Exception handler for ExceptionType2
}
finally{
//code to be executed before try block ends. This executes whether or not an exception occurs in the try block.
}
List of exceptions
Essential exception classes include
Exception Description
ArithmeticException Caused by exceptional conditions like divide by zero
ArrayIndexOfBoundsException Thrown when an array is accessed beyond its bounds
ArrayStoreException Thrown when an incompatible type is stored in an array
ClassCastException Thrown when there is an invalid cast
IllegalArgumentException Thrown when an inappropriate argument is passed to a method
IllegalMonitorStateException Illegal monitor operations such as waiting on an unlocked thread
IndexOutOfBounds Exception Thrown to indicate that an index is out of range.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a number.
SecurityException Thrown when security is violated.
ClassNotFound Exception Thrown when a class is not found.
IllegalAccess Exception Thrown when a method does not have access to a class.
Instantiation Exception Thrown when an attempt is made to instantiate an abstract class or an interface.
Java I/O
Class Purpose
BufferedlnputStream Provides the ability to buffer the input. Supports mark() and reset() methods.
BufferedOutputStream Provides the ability to write bytes to the underlying output stream without making a call to
the underlying system.
BufferedReader Reads text from a character or String from stream – int read(),String readLine()
BufferedWriter Writes text to character
DatalnputStream Allows an application to read primitive data types from an underlying input stream
DataOutputStream Allows an application to write primitive data types to an output stream
File Represents disk files and directories
FilelnputStream Reads bytes from a file in a file system
FileOutputStream Writes bytes to a file
ObjectlnputStream Reads bytes i.e. desterilizes objects using the readObject() method
ObjectOutputStream Writes bytes i.e. serializes writeObject() method
PrintStream Provides the ability to print different data values in an efficient manner
RandomAccessFile Supports reading and writing to a random access file
Stream Chaining
You can combine streams into chains to achieve more advanced input and output operations. For instance, reading
every byte one at a time from a file is slow. It is faster to read a larger block of data from the disk and then iterate
through that block byte for byte afterwards. To achieve buffering you can wrap your InputStream in an
BufferedInputStream. Here is an example:
java.appletApplet class
Methods of the java.appletApplet class:
Method Description
init() Invoked by the browser or the applet viewer to inform that the applet has been
loaded
start() Invoked by the browser or the applet viewer to inform that applet execution has
started
stop() Invoked by the browser or the applet viewer to inform that applet execution has
stopped
destroy() Invoked by the browser or the appletviewer to inform that the applet has been
reclaimed by the Garbage Collector
getDocumentBase() Returns the URL of the HTML page that loads the applet
getCodeBase() Returns the URL of the applet's class file
getParameter(String name) Returns the value of a named applet parameter as a string
showStatus(String msg) Displays the argument string on the applet's status
java.awt.Graphics class
The Graphics class is an abstract class that contains all the essential drawing methods like drawLine(), drawOval(),
drawRect() and so on. A Graphics reference is passed as an argument to the paint () method that belongs to the
java.awt.component class.
Color Constants
Color.BLACK Color.DARK_GRAY Color.GRAY Color.LIGHT_GRAY Color.WHITE Color.MAGENTA Color.RED
Reserve Words
abstract do if package synchronized
default assert
if(base==16)
num=num+(n[i]-55)*pos;
}
pos=pos*base;
}
return num;
}
}
void primes(int count)
{
int c=0;
int d, l,n;
for(n=2;n<1000;n++)
{
l=(int)sqrt(n);
/*printf("%d",l);*/
for(d=2;d<=l;d++)
{
if(n%d==0)
break;
}
if(d>l)
{
c=c+1;
if(c>count)
return;
printf("%d, ",n);
}
}
}
fn_2=fn_1;
fn_1=fn;
printf("\n\n%lf",exp1(x,0));
printf("\n\n%lf",exp1(x*v,1));
printf("\n\n%lf",exp1(x*v,2));
return 0;
}
double exp1(float v,int fn)
{
double sum=0;
int n;
int sign;
if(fn==0)
{
n=0;
sum=1;
for(n=1;n<14;n++){
sum+=pow(v,n)/fact(n);
printf("\n%d - %lf / %ld\n",n,pow1(v,n),fact(n));
}
}
else if(fn==1)
{
n=0;
sum=0;
sign=1;
for(n=1;n<14;n+=2){
sum+=sign * pow1(v,n)/fact(n);
//printf("\n%d - %lf / %ld\n",n,pow1(v,n),fact(n));
sign=sign * -1;
}
}
else if(fn==2)
{
n=0;
sum=1;
sign=-1;
89 Department of ECE – GCE Kannur
Computer Programming Lab
for(n=2;n<14;n+=2){
sum+=sign * pow1(v,n)/fact(n);
//printf("\n%d - %lf / %ld\n",n,pow1(v,n),fact(n));
sign=sign * -1;
}
}
return sum;
}
double pow1(float x, int y)
{
int i=1;
double pow=1;
for( i=1;i<=y;i++)
pow=pow * x;
return pow;
}
long fact(int n){
int i;
long fact=1;
for(i=2;i<=n;i++)
fact = fact * i;
return fact;
}
for(i=0;i<row1;i++)
for(j=0;j<col2;j++)
{
c[i][j]=0;
for(k=0;k<col1;k++){
c[i][j]=c[i][j] + a[i][k] * b[k][j];
}
}
for(i=0;i<row1;i++)
{
printf("\n");
91 Department of ECE – GCE Kannur
Computer Programming Lab
for(j=0;j<col2;j++)
printf("%d\t",c[i][j]);
}
}
float determinant( int a[3][3], int n )
{
int i, j, j1, j2;
int d = 0;
int m[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
if (n == 2)
d = a[0][0]*a[1][1] - a[1][0]*a[0][1];
else
{
d = 0;
for (j1 = 0; j1 < n; j1++ )
{
for (i = 1; i < n; i++)
{
j2 = 0;
for (j = 0; j < n; j++)
{
if (j == j1) continue;
m[i-1][j2] = a[i][j];
j2++;
}
}
d = d + pow(-1.0, j1)*a[0][j1]*determinant( m, n-1 );
}
}
return d;
}
main()
{
double a[3][3]={{1,3,1},{1,1,2},{2,3,4}};
double b[3][3]={{9,8,7},{6,5,4},{3,2,1}};
double c[3][3]={{0,0,0},{0,0,0},{0,0,0}};
double d;
int i,j,k;
printf("\n\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
92 Department of ECE – GCE Kannur
Computer Programming Lab
printf("%lf\t",b[i][j]);
}
cofact(a,3,b);
d=determinant(a,3);
printf("\n\nDeteminant %lf",d);
Transpose(b,3);
for(i=0;i<3;i++)
{ printf("\n");
for(j=0;j<3;j++)
b[i][j]=b[i][j]/d;
}
printf("\n\n");
for(i=0;i<3;i++)
{ printf("\n");
for(j=0;j<3;j++)
printf("%lf\t",b[i][j]);
}
}
void cofact(double a[][3],int n,double b[][3])
{
int i,j,ii,jj,i1,j1;
double det;
double c[3][3];
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=0;
for (j=0;j<n;j++){
for (i=0;i<n;i++){
i1 = 0;
for (ii=0;ii<n;ii++) {
if (ii == i)
continue;
j1 = 0;
for (jj=0;jj<n;jj++) {
if (jj == j)
continue;
c[i1][j1] = a[ii][jj];
j1++;
}
i1++;
}
det = determinant(c,n-1);
b[i][j] = pow(-1.0,i+j+2.0) * det;
}
}
}
double determinant( double a[][3], int n )
{
int i, j, j1, j2;
double d = 0;
double m[3][3];
for(i=0;i<3;i++)
for(j=0;j<3;j++)
m[i][j]=0;
if (n == 2)
d = a[0][0]*a[1][1] - a[1][0]*a[0][1];
else
{
d = 0;
for (j1 = 0; j1 < n; j1++ )
{
j2++;
}
}
d = d + pow(-1.0, j1)*a[0][j1]*determinant( m, n-1 );
}
}
return d;
}
void Transpose(double a[][3],int n)
{
int i,j;
double tmp;
for (i=1;i<n;i++) {
for (j=0;j<i;j++) {
tmp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = tmp;
}
}
}
#include<string.h>
struct student{
int no;
char name[100];
};
typedef struct student Student;
void write_file()
{
FILE * fp;
Student std;
fp=fopen("std.dat","wb");
std.no=1;
strcpy(std.name,"ANOOP");
fwrite (&std , sizeof(Student) , 1,fp );
std.no=2;
strcpy(std.name,"ARUN");
fwrite (&std , sizeof(Student) , 1, fp );
std.no=3;
strcpy(std.name,"ANIL");
fwrite (&std , sizeof(Student) , 1, fp );
std.no=4;
strcpy(std.name,"AKHIL");
fwrite (&std , sizeof(Student) , 1, fp );
std.no=5;
strcpy(std.name,"ANAND");
fwrite (&std , sizeof(Student) , 1, fp );
fclose(fp);
}
int search(char * name)
{
FILE * fp;
int pos=0;
Student std;
fp=fopen("std.dat","rb");
while(!feof(fp))
{
fread(&std, sizeof(Student) , 1,fp);
if(strcmp(std.name,name)==0){
fclose(fp);
pos++;
printf("Found at pos=%d\n",pos);
return pos;
}
pos++;
}
return -1;
}
void display_file()
{
FILE * fp;
Student std;
fp=fopen("std.dat","rb");
while(!feof(fp))
{
fread(&std, sizeof(Student) , 1,fp);
if(!feof(fp))
printf("%d. %s\n",std.no,std.name);
}
fclose(fp);
}
95 Department of ECE – GCE Kannur
Computer Programming Lab
void edit_file(char * name, int newNo)
{
FILE * fp;
Student std;
int pos=search(name)-1;
if(pos<0)
return;
fp=fopen("std.dat","rb+");
fseek ( fp ,pos*sizeof(Student) , SEEK_SET );
std.no=newNo;
strcpy(std.name,name);
fwrite (&std , sizeof(Student) , 1,fp );
fclose(fp);
}
main()
{
write_file();
display_file();
edit_file("AKHIL",101);
display_file();
return 0;
}
}
int length(Node* Head) {
Node* current = Head;
int count = 0;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
Node* searchNode(Node* Head, int match)
{
Node* current = Head;
while (current != NULL) {
if(current->data==match)
return current;
current = current->next;
}
printf("************** Cannot find node!***************\n");
return NULL;
}
Node* deleteNode(Node* Head, Node* node)
{
Node* current = Head;
Node* prev = NULL;
if(node==Head)
{
prev=Head->next;
free(node);
Head=NULL;
printf("*** Head modified while deletetion ***\n");
return prev;
}
while (current != NULL) {
if(current == node)
{
prev->next = current->next;
free(node);
return Head;
}
prev = current;
current = current->next;
}
return Head;
}
void insertAfterNode(Node* Head, int insertAferData, int newData){
Node* current = Head;
Node* newNode = NULL;
Node* tmp=NULL;
newNode = (Node *)malloc(sizeof(Node));
newNode->next=NULL;
while (current != NULL)
{
christy@gcek.ac.in
baburajmadathil@gcek.ac.in
abduljaleel@gcek.ac.in