Upload
nikhila-janet
View
164
Download
0
Tags:
Embed Size (px)
Citation preview
Computer Programming Lab Manual
Document Version 1.0 Revision 0.0
Christy James Jose Celine Mary Stuart
Baburaj M Abdul Jaleel N
August 2010
Computer Programming Lab
2 Department of ECE – GCE Kannur
Computer Programming Lab
3 Department of ECE – GCE Kannur
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.2 Programming Language 7 0.3 Pseudocode 0.4 Prerequisites for software development 7 0.4 .1 Knowledge of a Programming Language 7 0.4 .2 Text Editor Tool 7 0.4 .3 Compiler & Interpreter Tool 7 0.5 C Language 8 0.6 Object Oriented Programming (OOP) 8 0.6.1 Object 9 0.6.2 Class 9 0.6.3 Encapsulation 9 0.6.4 Inheritance 9 0.6.5 Polymorphism 9 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 0.8 Software Development Tools 11 0.8.1 GNU Compiler Collection 11 0.8.2 GCC Options 11 0.8.3 Compiling & Running C Program using GCC 11 0.8.4 OpenJDK – Open Java Development Kit 11 0.8.5 OpenJDK Installation 11 0.8.6 Compiling & Running Java Programs 11 0.8.7 GEdit 12 0.8.8 Configuring gedit to Compile C and Java 12
Computer Programming Lab
4 Department of ECE – GCE Kannur
C Programming 1.0 Simple C Programs 25 1.1 HCF & LCM Calculator 30 1.2 Number System Converter 31 1.3 Fibonacci & Prime Series Generator 33 1.4 Taylor's Series Evaluator 34 1.5 String Manipulator 36 1.6 Matrix Product Calculator 38 1.7 Determinant Calculator 40 1.8 Matrix Inverse Calculator 41 1.9 Equation Solver Using Jordan Elimination Method 43 1.10 Simple Student Record Manipulator 45 1.11 Singly Linked List Builder 47
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
Conventions Used in this Document
Experiment
Information
Algorithm / Program
Program Input
Program Output
Objective
Computer Programming Lab
5 Department of ECE – GCE Kannur
PPrreelliimmiinnaarriieess
Computer Programming Lab
6 Department of ECE – GCE Kannur
Computer Programming Lab
7 Department of ECE – GCE Kannur
0.1 Introduction A program is the description of how to do something. It consists of a series of instructions for computer to carry out
specific task. Process of defining the series of instructions and any fixed data required to perform the defined task constitute a program. Thus, in order to design a program, you must determine three basic elements:
The instructions that must be performed.
The order in which those instructions are to be executed.
The fixed data required to execute the instructions
Before your new program enters to a computer, there are several steps to be taken. They are: 0.1.1 Understand the needs
You must be able to state clearly what the computer will produce as the final result of the activities. At this stage you should be able to answer the following.
What are the objectives of the program?
What are the desired inputs?
What are the desired outputs?
0.1.2 Define the solution At this point you must have the knowledge of the output the computer has to produce. You need to look at the
information that is available and those are needed. You might have to define the equations, logical procedures, or other methods you need to manipulate the raw input data to generate the final desired output.
0.1.3 Map the solution The third step in programming is to lay out the solution in its proper sequence. Remember that the order in which
actions are taken is just as important as the actions themselves. You need to organize the solution procedure into its proper sequence, taking choices and alternatives into account.
0.2 Programming Language A programming language is an artificial language designed to express computations that can be performed by a machine, particularly a computer. Programming languages can be used to create programs that control the behaviour
of a machine, to express algorithms precisely, or as a mode of human communication. Many programming languages have some form of written specification of their syntax (form) and semantics (meaning). Some languages are defined
by a specification document. 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.
0.4 Prerequisites for software development Before developing a program you must have the following bits and pieces.
0.4 .1 Knowledge of a Programming Language Programming language is used to realize a computer program. In depth knowledge of a programming language is
essential for developing an optimized solution.
0.4 .2 Text Editor Tool Text Editor is a software used to create and modify text files. Text editors are often provided with operating systems or software development packages, and can be used to construct programming language source code.
0.4 .3 Compiler & Interpreter Tool Computer can understand only machine language. So a compiler is required for the translation from highlevel
programming language into machine language. An interpreter translates high-level instructions into an intermediate form, which it then executes. The interpreter, on the other hand, can immediately execute high-level programs. For
this reason, interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly.
Computer Programming Lab
8 Department of ECE – GCE Kannur
0.5 C Language C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone
Laboratories for use with the UNIX operating system. Although C was designed for implementing system software it is also widely used for developing portable application software. C is one of the most popular programming languages of all time and there are very few computer architectures for which a C compiler does not exist. C has greatly
influenced many other popular programming languages, most notably C++, which began as an extension to C. C is an imperative (procedural) systems implementation language. It was designed to be compiled using a relatively
straightforward compiler, to provide low-level access to memory, to provide language constructs that map efficiently to machine instructions, and to require minimal run-time support. C was therefore useful for many applications that had formerly been coded in assembly language.
Like most imperative languages C has facilities for structured programming and allows lexical variable scope and recursion, while a static type system prevents many unintended operations. In C, all executable code is contained within functions. Function parameters are always passed by value. Pass-by-reference is simulated in C by explicitly
passing pointer values. Heterogeneous aggregate data types (struct) allow related data elements to be combined and manipulated as a unit. C program source text is free-format, using the semicolon as a statement terminator.
C also exhibits the following more specific characteristics:
Variables may be hidden in nested blocks
Partially weak typing; for instance, characters can be used as integers
Low-level access to computer memory by converting machine addresses to typed pointers
Function and data pointers supporting adhoc run-time polymorphism
Array indexing as a secondary notion, defined in terms of pointer arithmetic
A pre-processor for macro definition, source code file inclusion, and conditional compilation
Complex functionality such as I/O, string manipulation, and mathematical functions consistently delegated
to library routines
A relatively small set of reserved keywords
A large number of compound operators, such as +=, -=, *= and ++ etc.
0.6 Object Oriented Programming (OOP)
Object Oriented Programming (OOP) represents an attempt to make programs more closely model the way people think about and deal with the world. In the older styles of programming, a programmer who is faced with some problem must identify a computing task that needs to be performed in order to solve the problem. Programming
then consists of finding a sequence of instructions that will accomplish that task. But at the heart of object-oriented programming, instead of tasks we find objects -- entities that have behaviours, that hold information, and that can
interact with one another. Programming consists of designing a set of objects that somehow model the problem at hand. Software objects in the program can represent real or abstract entities in the problem domain. This is supposed to make the design of the program more natural and hence easier to get right and easier to understand.
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:
Computer Programming Lab
9 Department of ECE – GCE Kannur
0.6.1 Object The real entities that have behaviours, attributes that hold information and interacts with one another through
messaging. 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".
0.7.1 Java Language Principles There were five primary goals in the creation of the Java language
Simple, object oriented, and familiar.
Robust and secure.
Architecture neutral and portable.
Execute with high performance.
Interpreted, threaded, and dynamic.
0.7.2 Java Platform One characteristic of Java is portability, which means that computer programs written in the Java language must run
similarly on any supported hardware/operating-system platform. This is achieved by compiling the Java language code to an intermediate representation called Java bytecode, instead of directly to platform-specific machine code.
Java bytecode instructions are analogous to machine code, but are intended to be interpreted by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java
Runtime Environment (JRE) installed on their own machine for standalone Java applications, or in a Web browser for Java applets. Standardized libraries provide a generic way to access host-specific
features such as graphics, threading and networking. A major benefit of using bytecode is porting. However, the overhead of
interpretation means that interpreted programs almost always run more slowly than programs compiled to native executables would. Just-in-Time compilers were introduced from an early stage that
compiles bytecodes to machine code during runtime. Over the years, this JVM built-in feature has been optimized to a point where the JVM's performance competes with natively compiled C code.
Computer Programming Lab
10 Department of ECE – GCE Kannur
0.7.3 Java Applets A Java applet is an applet delivered to the users in the form of Java bytecode. Java applets can run in a Web browser
using a Java Virtual Machine (JVM), or in Sun's Applet Viewer, a stand-alone tool for testing applets. Java applets are executed in a sandbox by most web browsers, preventing them from accessing local data like clipboard or file system. The code of the applet is downloaded from a web server and the browser either embeds the applet into a web page
or opens a new window showing the applet's user interface. A Java applet extends the class java.applet.Applet. The class must override methods from the applet class to set up a user interface inside itself. As applet inherits from
container, it has largely the same user interface possibilities as an ordinary Java application, including regions with user specific visualization.
0.7.3 Embedding Applet into web page The applet can be displayed on the web page by making use of the applet HTML element. An embedded Java applet: <HTML>
<BODY>
<APPLET code="HelloWorld.class" WIDTH="200" HEIGHT="40">
This is where HelloWorld.class runs.
</APPLET>
</BODY>
</HTML>
Here is the syntax for the APPLET tag. <APPLET CODE = appletFile WIDTH = pixels HEIGHT = pixels>
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value>
. . .
Alternate HTML
</APPLET>
An applet can be viewed using the appletviewer program also. For that you need to supply the filename which contain the APPLET tag.
You can add APPLET tag at the beginning of your java source file as a comment and use the same source file as argument of appletviewer. Sample Source File which contain APPLET tag as comment at the beginning,
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;
}
/* <APPLET code=" myapplet.class" WIDTH="200" HEIGHT="200">
<PARAM NAME=”Speed” Value=”1000”>
</APPLET>
*/ import java.applet.*
class myapplet extends Applet{
…….
}
Computer Programming Lab
11 Department of ECE – GCE Kannur
0.8 Software Development Tools
0.8.1 GNU Compiler Collection The GNU Compiler Collection (usually shortened to GCC) is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain. As well as being the
official compiler of the unfinished GNU operating system, GCC has been adopted as the standard compiler by most other modern Unix-like computer operating systems, including GNU/Linux, the BSD family and Mac OS X. GCC has
been ported to a wide variety of processor architectures, and is widely deployed as a tool in commercial, proprietary and closed source software development environments. Originally named the GNU C Compiler, because it only handled the C programming language, GCC 1.0 was released in 1987, and the compiler was extended to compile C++
in December of that. 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.2 GCC Options
The common syntax is gcc [option] [filename]
filename: Name of the source file with extension. Extension selects the compiler. Some of the options are: (Options are case sensitive) -o file Place executable output in file file. If -o is not specified, the default is to put an executable file in a.out
-w Inhibit all warning messages. -W Print extra warning messages
GCC Installation The following commands can be issued from Debian Linux (like Ubuntu) terminal to install GCC
$ sudo apt-get update
$ sudo apt-get install gcc-4.4
0.8.3 Compiling & Running C Program using GCC
Compilation command $ gcc sourcefile.c
Run Command – Default executable file is ‘a.out’ $ ./a.out
0.8.4 OpenJDK – Open Java Development Kit
OpenJDK is a free and open source implementation of the Java programming language. The implementation is licensed under the GNU General Public License (GPL) with a linking exception, which exempts components of the Java class library from the GPL licensing terms. OpenJDK was initially based only on the JDK 7.0 (Java Development
Kit) version of the Java platform.
0.8.5 OpenJDK Installation The following command can be issued from Debian Linux (like Ubuntu) terminal to install GCC
$ sudo apt-get install openjdk-6-jdk
0.8.6 Compiling & Running Java Programs Invoking Compiler
$ javac sourcefile.java
Computer Programming Lab
12 Department of ECE – GCE Kannur
Run command $ java sourcefile
Running Applets $ appletviewer filecontaingAPPLETtag
Note: Assuming that filecontaingAPPLETtag contain the necessary APPLET tag – See section 0.7.3
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.
0.8.8 Configuring gedit to Compile C and Java
Fro
m U
bu
ntu
Des
kto
p g
o t
o
Ap
plic
atio
n –
Acc
esso
rie
s-ge
dit
Te
xt
Edit
or
to la
un
ch g
edit
Cho
ose
Pre
fere
nce
s fr
om
the
Ed
it m
enu
of
ged
it.
A p
refe
ren
ce w
indo
w w
ill b
e lo
ade
d.
Computer Programming Lab
13 Department of ECE – GCE Kannur
In t
he V
iew
tab
dis
abl
e Te
xt W
rap
pin
g, e
nab
le
Lin
e N
um
ber
s, e
nab
le B
rack
et M
atch
ing
.
In t
he E
dit
or
tab
en
able
Au
tom
atic
Ind
enta
tio
n.
Als
o e
nabl
e A
uto
save
and
set
tim
e lim
it a
s 1
m
inu
te
In t
he v
iew
tab
en
ab
le E
xter
na
l To
ols
. Th
en
clic
k
Co
nfi
gure
Plu
gin
bu
tto
n a
t th
e b
ott
om
Just
abo
ve t
he H
elp
but
ton
you
can
see
a N
ew
Too
l but
ton
- cl
ick
it
Computer Programming Lab
14 Department of ECE – GCE Kannur
Giv
e a
nam
e B
uild
& R
un
C f
or
the
New
To
ol
Giv
e a
nam
e B
uild
& R
un
C f
or
the
New
To
ol
In t
he E
dit
bo
x ty
pe t
he s
how
n C
om
pile
an
d R
un
com
man
ds
Computer Programming Lab
15 Department of ECE – GCE Kannur
Cho
ose
a S
ho
rtcu
t K
ey (
F5)
Sele
ct C
urr
ent
Do
cum
ent
fro
m t
he
Save
list
The
fina
l scr
een
sho
uld
loo
k lik
e th
is. C
om
pila
tio
n
com
man
ds a
re li
sted
at
the
en
d t
his
sec
tio
n
Computer Programming Lab
16 Department of ECE – GCE Kannur
For
Co
mpi
ling
Java
add
a n
ew t
oo
l nam
ed
Bu
ild &
Ru
n J
ava
Fin
al s
cree
n f
or
Java
Bu
ild &
Ru
n C
on
figu
rati
on.
Ass
ign
a s
hort
cu
t ke
y F9
. Co
mp
ilati
on
co
mm
ands
are
liste
d a
t th
e e
nd
th
is s
ecti
on
Ad
d a
new
to
ol R
un
Ap
ple
t to
dis
play
ap
plet
.
Ass
ign
a s
hort
cut
key
F11
. Co
mpi
lati
on
com
ma
nds
are
liste
d a
t th
e e
nd
of
this
sec
tio
n
Computer Programming Lab
17 Department of ECE – GCE Kannur
Clic
k To
ols
-Ext
ern
al T
oo
ls M
enu.
Yo
u ca
n vi
ew a
ll
of
your
to
ols
no
w.
Cre
ate
a n
ew f
ile a
nd
sav
e w
ith
.c e
xten
sio
n
Co
mpi
le i
t b
y p
ress
ing
F5 o
r cl
icki
ng B
uild
& R
un
C
men
u it
em
Computer Programming Lab
18 Department of ECE – GCE Kannur
You
can
see
com
pila
tio
n e
rro
rs (i
f ex
ists
) ju
st
belo
w t
he e
dito
r te
xtbo
x, t
he S
he
ll O
utp
ut
Pro
gram
aft
er f
ixin
g o
f er
ror.
chA
r is
ch
ange
d t
o
char
Run
the
pro
gram
an
d yo
u w
ill s
ee a
new
po
pup
win
dow
on
whi
ch t
he o
utp
ut is
dis
pla
yed
.
Computer Programming Lab
19 Department of ECE – GCE Kannur
Her
e is
a s
impl
e ja
va p
rogr
am
Co
mp
ile a
nd
ru
n it
usi
ng
the
too
l
The
java
out
put
win
dow
Computer Programming Lab
20 Department of ECE – GCE Kannur
An
ap
plet
pro
gram
Exec
ute
ap
ple
t
The
appl
et o
utp
ut
Computer Programming Lab
21 Department of ECE – GCE Kannur
0.8.8 Tool Scripts for Building and Running Programs – To be used with gedit
0.8.8 The Build & Run C Tool Script #!/bin/sh
if gcc $GEDIT_CURRENT_DOCUMENT_PATH
then
gnome-terminal -x sh -c "./a.out; sleep 10"
fi
0.8.8 The Build & Run Java Tool Script #!/bin/sh
if javac $GEDIT_CURRENT_DOCUMENT_PATH
then
gnome-terminal -x sh -c "java ${GEDIT_CURRENT_DOCUMENT_NAME%\.*}; sleep 10"
fi
0.8.8 The Build & Run Applet Tool Script #!/bin/sh
if javac $GEDIT_CURRENT_DOCUMENT_PATH
then
appletviewer $GEDIT_CURRENT_DOCUMENT_PATH
fi
0.8.11 The Flow of Solution Development C Application
Java Standalone Application
Applet Program
Create the C soure file with gedit
hello.c
Compile using gcc
gcc hello.c
Execute the output file a.out
./a.out
Create the Java soure file with gedit
hello.java
Compile using javac
javac hello.java
Load class file into JVM
java hello
Create the Java soure file with
gedit. Add APPLET as comment at the
begining of the program
helloApplet.java
Compile using javac
javac helloApplet.java
Run Applet using appletviewer
appletviewer helloApplet.java
Computer Programming Lab
22 Department of ECE – GCE Kannur
Computer Programming Lab
23 Department of ECE – GCE Kannur
CC
PPrrooggrraammmmiinngg
Computer Programming Lab
24 Department of ECE – GCE Kannur
Computer Programming Lab
25 Department of ECE – GCE Kannur
1.0 Simple C Programs
1.0.1 First Program
#include <stdio.h>
void main()
{
printf(―Hello World\n‖);
}
1.0.2 Interactive program to find square of a number
#include <stdio.h>
void main()
{
int num,square;
printf(―Enter a number:‖);
scanf(―%d‖,&num);
square=num * num;
printf(―The Square is %d\n‖,square);
}
1.0.3 Program to print all numbers below 200 divisible by 7
#include <stdio.h>
void main()
{
int num;
for(num=1;num<=200;num++)
{
if(num%7==0)
printf(―%d\n‖,num);
}
}
1.0.4 Program to find biggest of three numbers
#include <stdio.h>
void main()
{
int num1,num2,num3,big;
printf(―Enter 3 numbers: ‖);
scanf(―%d%d%d‖,&num1, &num2, &num3);
big= num1>num2 ? num1 : num2;
if(big<num3)
big=num3;
printf(―Biggest is %d‖,big);
}
1.0.5 Interactive program to print grade from the given percentage
#include <stdio.h>
void main()
{
float percentage;
printf(―Enter a percentage:‖);
scanf(―%f‖,& percentage);
if(percentage>=90)
printf(―Grade is A+‖);
else if(percentage>=80)
printf(―Grade is A‖);
Computer Programming Lab
26 Department of ECE – GCE Kannur
else if(percentage>=70)
printf(―Grade is B+‖);
else if(percentage>=60)
printf(―Grade is C+‖);
else if(percentage>=50)
printf(―Grade is C+‖);
else if(percentage>=40)
printf(―Grade is D+‖);
else
printf(―No Grade failed!‖);
}
1.0.6 Interactive program to accept a single digit number and spell it
#include <stdio.h>
void main()
{
int num,i;
printf(―Enter a single number:‖);
scanf(―%d‖,&num);
switch(num)
{
case 0: printf(―Zero‖);break;
case 1: printf(―One‖);break;
case 2: printf(―Two‖);break;
case 3: printf(―Three‖);break;
case 4: printf(―Four‖);break;
case 5: printf(―Five‖);break;
case 6: printf(―Six‖);break;
case 7: printf(―Seven‖);break;
case 8: printf(―Eight‖);break;
case 9: printf(―Nine‖);break;
default: printf(―Error‖);
}
}
1.0.7 Interactive program to accept a number and print multiplication table
#include <stdio.h>
void main()
{
int num,i;
printf(―Enter a number:‖);
scanf(―%d‖,&num);
i=1;
while(i<=10)
{
printf(―%d x %d = %d\n‖,i,num,i*num);
i++;
}
}
Computer Programming Lab
27 Department of ECE – GCE Kannur
1.0.8 Interactive program to find the smallest from an array
#include <stdio.h>
void main()
{
int nums[50],count,i,big;
printf(―Enter count:‖);
scanf(―%d‖,&count);
printf(―Enter %d numbers:‖,count);
for(i=0;i<count;i++)
{
scanf(―%d‖,&nums[i]);
}
big=nums[0];
for(i=1;i<count;i++)
{
if(big> nums[i])
big=nums[i];
}
printf(―The Smallest is %d‖,big);
}
1.0.9 Interactive program to find length of a string
#include <stdio.h>
void main()
{
char str[100],i;
printf(―Enter a string: ―);
scanf(―%s‖,str);
i=0;
while(str[i]!=‘\0‘)
{
i++;
}
printf(―Length of %s is %d‖,str,i);
}
1.0.10 Program to illustrate structure
#include <stdio.h>
struct std
{
char name[100];
int regno;
float mark;
};
typedef struct std student;
void main()
{
student std1, std2;
printf(―Enter student name, register number and mark:‖);
scanf(―%s‖,&std1.name);
scanf(―%d‖,&std1.regno);
scanf(―%f‖,&std1.mark);
printf(―The student details are: ―);
scanf(―Name: %s\n‖,std1.name);
scanf(―Regno: %d\n‖,std1.regno);
scanf(―Mark: %f\n‖,std1.mark);
}
Computer Programming Lab
28 Department of ECE – GCE Kannur
1.0.11 Interactive program to find address of variable and modify its value using pointer
#include <stdio.h>
void main()
{
int num,val;
int *ptr;
printf(―Enter a number: ―);
scanf(―%d‖,&num);
printf(―Enter a new value: ―);
scanf(―%d‖,&val);
ptr=#
*ptr=val;
printf(―Address of number %X\n‖,ptr);
printf(―Value of number is now %d―,num);
}
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)
}
1.0.13 Interactive program to find average of two numbers using function
#include <stdio.h>
float avg(int a,int b);
void main()
{
int num1, num2;
float average;
printf(―Enter two numbers‖);
scanf(―%d%d‖,&num1,&num2);
average=avg(num1,num2);
printf(―The average is %f‖,average);
}
float avg(int a,int b)
{
float avg;
avg=(a+b)/2.0;
return avg;
}
Computer Programming Lab
29 Department of ECE – GCE Kannur
1.0.14 Interactive program to generate Armstrong numbers below 10000000 using function
#include <stdio.h>
int isArmstrong(long num);
int main()
{
long number;
for(number=2; number<10000000; number++)
if(isArmstrong(number)==1)
printf("%ld\n",number);
return 0;
}
/* Armstrong Number => Sum of cubes of digits and number are equal. */
int isArmstrong(long numToCheck)
{
long num;
int digit;
long sum=0;
num=numToCheck;
while(num>0)
{
digit = num % 10;
sum = sum + digit * digit * digit;
num = num /10;
}
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;
}
Computer Programming Lab
30 Department of ECE – GCE Kannur
1.1. HCF & LCM CALCULATOR
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
Computer Programming Lab
31 Department of ECE – GCE Kannur
1.2. NUMBER SYSTEM CONVERTER
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
Computer Programming Lab
32 Department of ECE – GCE Kannur
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
Number Base To Base ABC 16 10
Result 2748
Computer Programming Lab
33 Department of ECE – GCE Kannur
1.3. FIBONACCI & PRIME SERIES GENERATOR
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
Fibonacci Series Prime Series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 2, 3, 5, 7, 11, , 13, 17, 19, 23, 29, 31, 37
Computer Programming Lab
34 Department of ECE – GCE Kannur
1.4. TAYLOR'S SERIES EVALUATOR
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 ' '' '''
2 3
0
( ) ( ) ( ) ( )( ) ( ) ( ) ( ) ( )
! 1! 2! 3!
nn
n
f a f a f a f ax a f a x a x a x a
n
Taylor’s series for some functions
Exponential function:
1 2 3
0
1! 1! 2! 3!
nx
n
x x x xe
n
Trigonometric functions: x in radians
3 5
2 1
0
( 1)sin
(2 1)! 3! 5!
nn
n
x xx x x
n
2 452
0
( 1)cos 1
(2 )! 2! 4!
nn
n
x xx x
n
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
ELSEIF seriesType = sin THEN
SET sum=0
SET SIGN =1
FOR n=1 TO limit
sum = sum + sign * (value POWER n) / (CALL fact WITH n)
sign =sign * -1
n = n + 2
ENDFOR
ELSEIF seriesType = cos THEN
SET sum=1
SET SIGN =-1
FOR n=2 TO limit
sum = sum + sign * (value POWER n) / (CALL fact WITH n)
sign =sign * -1
n = n + 2
ENDFOR
ENDIF
RETURN sum
ENDFUNCTION
Computer Programming Lab
35 Department of ECE – GCE Kannur
FUNCTION fact
PARAMS: num
RETURNS: fact AS LONG
SET fact = 1
FOR i=2 TO NUM
fact = fact * i
i = i + 1
ENDFOR
RETURN fact
ENDFUNCTION
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
Computer Programming Lab
36 Department of ECE – GCE Kannur
1.5. STRING MANIPULATOR
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
SET len_str = = CALL str_len WITH str
SET len_find = = CALL str_len WITH find
SET len_replace = CALL str_len WITH replace
ALLOCATE ( len_str + len_replace – len_find + 1) BYTES FOR res
FOR i=0 TO pos-1
res[i] = str[i]
i = i + 1
ENDFOR
FOR i=0 TO len_replace-1
res[pos+i]=replace[i]
i = i + 1
ENDFOR
SET len_rest = len_str - (pos + len_find)
Computer Programming Lab
37 Department of ECE – GCE Kannur
FOR i=0 TO len_str-1
res[pos+len_replace+i]=str[pos + len_find + i]
ENDFOR
res[pos+len_replace + len_rest]=NULL CHARACTER
RETURN res
ENDFUNCTION
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
String Find String Replace String YOU MAY HAVE IT MAY SHOULD
Status Result FOUND AT POSITION 6 YOU SHOULD HAVE IT
Computer Programming Lab
38 Department of ECE – GCE Kannur
1.6. MATRIX PRODUCT CALCULATOR
Develop an interactive C application to find product of two matrices.
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
Computer Programming Lab
39 Department of ECE – GCE Kannur
Rows A Cols A Rows B Cols B Matrix A Matrix B
3 3 3 3
1 2 3
4 5 6
7 8 9
9 8 7
6 5 4
3 2 1
Product
30 24 18
84 69 54
138 114 90
Computer Programming Lab
40 Department of ECE – GCE Kannur
1.7. DETERMINANT CALCULATOR
Develop an interactive C application to calculate determinant of a given square matrix.
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 Ai 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
Order Matrix
Determinant
3
2 -2 0
-1 5 1
3 4 5
26
Computer Programming Lab
41 Department of ECE – GCE Kannur
1.8. MATRIX INVERSE CALCULATOR
Develop an interactive C application to calculate inverse of a given square matrix.
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
INITIALIZE ALL ELEMENTS of matrixMinor TO ZERO
FOR column=0 TO order-1
FOR row=0 TO order-1
row1=0
FOR rowI=0 TO order -1
IF rowI=row THEN CONTINUE
column1=0
FOR columnJ=0 TO order-1
IF columnJ = column THEN CONTINUE
matrixMinor[row1][ column1] = a[rowI][ columnJ]
column1 = column1 + 1
columnJ = columnJ + 1
ENDFOR
row1 = row1 + 1
rowI = rowI + 1
ENDFOR
determinant = CALL calcDeterminant WITH matrixMinor, order -1
matrixResult[row][column]= (-1 POWER (i+j+2)) * determinant
row = row + 1
ENDFOR
column = column + 1
ENDFOR
ENDFUNCTION
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
Computer Programming Lab
42 Department of ECE – GCE Kannur
FUNCTION main
READ order
CALL readMatrix WITH matrix, order, order
determinant = CALL calcDeterminant WITH matrix, order
CALL generateCofactorMatrix WITH matrix, order, matrixCofactor
CALL transposeMatrix WITH matrixCofactor
FOR i=0 TO rows-1
FOR j=0 TO cols-1
matrixCofactor=mat[i][j] / determinant
j = j + 1
ENDFOR
i= i + 1
ENDFOR
CALL showMatrix WITH matrixCofactor
ENDFUNCTION
Order Matrix
3
1 3 1
1 1 2
2 3 4
Inverse
2 9 -5
0 -2 1
-1 -3 2
Computer Programming Lab
43 Department of ECE – GCE Kannur
1.9. EQUATION SOLVER USING JORDAN ELIMINATION METHOD
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.
A Coefficient Matrix
B Constant Matrix X Matrix of Unknowns
11 1 12 2 13 3 1
21 1 22 2 23 3 2
31 1 32 2 33 3 3
11 12 13 1 1
21 22 23 2 2
31 32 33 3 3
a x +a x +a x =b
a x +a x +a x =b
a x +a x +a x =b
a a a x b
a a a x = b
a a a x b
AX=B
Brief idea of the algorithm Perform the following operations on matrix A
Divide the first row by a11, so that the new a11 becomes 1
Subtract from the second row a2i the first row multiplied by a21, so that after that subtraction a21 becomes 0
Subtract from the third row a3i the first row multiplied by a31, so that after that subtraction a31 becomes 0
….
Subtract from the nth row ani the first row multiplied by an1, so that after that subtraction an1 becomes 0. Now the first column of matrix A is agree with identity matrix
Divide the second row by a22, so that the new a22 becomes 1
Subtract from the first row a1i the second row multiplied by a12, so that after that subtraction a12 becomes 0
Subtract from the third row a3i the second row multiplied by a32, so that after that subtraction a32 becomes 0
Subtract from the fourth row a4i the second row multiplied by a42, so that after that subtraction a42 becomes 0
…
Subtract from the nth row Ani the second row multiplied by an2, so that after that subtraction an2 becomes 0.
Now the first two columns of matrix A agree with identity matrix
and so on.
Finally the matrix A will become a identity matrix
Perform the same elemental transformation on matrix B also. Now the solution xn= bn
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
Computer Programming Lab
44 Department of ECE – GCE Kannur
FOR i=0 TO order-1
diagonalElement = matrixCoefficients[i][i]
FOR j=0 TO order-1
matrixCoefficients[i][j] = matrixCoefficients[i][j] / diagonalElement
j = j + 1
ENDFOR
matrixConstants[i] = matrixConstants[i] / diagonalElement
FOR k=0 TO order-1
IF k=i THEN CONTINUE
elementToEliminate = matrixCoefficients[k][i]
FOR j=0 TO order-1
matrixCoefficients[k][j]=matrixCoefficients[k][j]- elementToEliminate *
matrixCoefficients[i][j]
j = j + 1
ENDFOR
matrixConstants[k] = matrixConstants[k] - elementToEliminate * matrixConstants[i]
k = k + 1
ENDFOR
i = i + 1
ENDFOR
FOR i=1 TO order-1
DISPLAY matrixConstants[i]
i = i + 1
ENDFOR
ENDFUNCTION
Coefficient Matrix Constant matrix
2 3 7
1 4 2
3 2 1
29
15
10
X1 X2 X3
1 2 3
Computer Programming Lab
45 Department of ECE – GCE Kannur
1.10. SIMPLE STUDENT RECORD MANIPULATOR
Develop an interactive C application to manipulate student record.
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
The size of the record is the size of Student structure in bytes
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
Computer Programming Lab
46 Department of ECE – GCE Kannur
WHILE NOT END OF FILE student.dat‖
READ NEXT std as RECORD FROM ―student.dat‖
IF std.name = nameToSearch THEN
SET FOUND=TRUE
BREAK THE LOOP
ENDIF
COUNT=COUNT+1
ENDWHILE
CLOSE FILE ―student.dat‖
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. SEARCH STUDENT & MODIFY 3. CALCULATE CLASS AVERAGE
4. LIST ALL 5. EXIT
2
Search Name New Class No New Percentage Kiran M 11 90
Status 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
Computer Programming Lab
47 Department of ECE – GCE Kannur
1.11. SINGLY LINKED LIST BUILDER
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
Data1 Next Data2 Next Data3 Next Data3 NULL
11 Next 22 Next 33 Next 55 NULL
11 Next 22 Next 33 Next 55 NULL
44 NEXT
11 Next 22 Next 33 Next 55 NULL44 Next
Singly Linked List
Sample Singly Linked List
Insertion Operation
Deletion Operation
Head Node Tail NodeNode Node
Building linked list in C Associating pieces of information.
User-define type Node using struct.
Include struct field for data. Specify links
Include struct field for POINTER to next linked list element.
Reserving memory to be used.
Allocate memory DYNAMICALLY (as you need it).
malloc()
Using Links to access information.
Use -> and . operators
Computer Programming Lab
48 Department of ECE – GCE Kannur
Algorithm CREATE STRUCTURE Node WITH MEMBERS data AS INTERGER, next AS LINK(POINTER) TO Node
CREATE NEW TYPE Node as STRUCTURE Node
FUNCTION addAtBegining
PARAMS: POINTER TO headNode, newData
RETURNS: POINTER TO Node
CREATE POINTER TO Node newNode
ALLOCATE MEMORY FOR newNode
newNode data = newData
newNode next = END OF LIST (NULL)
IF headNode = END OF LIST (NULL)THEN
RETURN newNode
ELSE
newNode next = headNode
RETRUN newNode
ENDIF
ENDFUNCTION
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
Computer Programming Lab
49 Department of ECE – GCE Kannur
FUNCTION deleteNode
PARAMS: POINTER TO headNode, POINTER TO nodeToDelete
RETURNS: POINTER TO Node
CREATE POINTER TO Node currentNode
CREATE POINTER TO Node prevNode
currentNode = headNode
IF (nodeToDelete=headNode) THEN
prevNode=headNode next
FREE MEMORY ALLOCATED FOR nodeToDelete
headNode= prevNode
RETURN prevNode
ENDIF
WHILE currentNode END OF LIST
IF currentNode = nodeToDelete THEN
prevNode next = currentNode next
FREE MEMORY ALLOCATED FOR nodeToDelete
RETURN HeadNode
ENDIF
prev=current
currentNode = currentNode next
ENDWHILE
RETURN HeadNode
ENDFUNCTION
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‖
Computer Programming Lab
50 Department of ECE – GCE Kannur
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
Menu
Insert After Data New Data 1. Add at Beginning of List
2. Add at End of List 3. Insert after specified data of List 4. Search & Delete
5. Display List 6. Exit
13 14
Choice 2
Data
15
Choice
Choice
1 5
Data
List Length List
11 5 11, 12, 13, 14, 15
Choice
Choice
3 4
Insert After Data New Data
Find Data
11 12 13
Choice
Status
3 Deleted
Insert After Data New Data
Choice
12 13 5
Choice
List Length List
3 4 11, 12, 14, 15
Computer Programming Lab
51 Department of ECE – GCE Kannur
JJaavvaa
PPrrooggrraammmmiinngg
Computer Programming Lab
52 Department of ECE – GCE Kannur
Computer Programming Lab
53 Department of ECE – GCE Kannur
2.0.1 Simple Java Programs
2.0.1 First Java program //Save in the file ‗first.java‘
class first{
public static void main(String args[]){
System.out.println("Hello World\n");
}
}
2.0.2 Program to find square of a number class square{
public static void main(String args[]){
int num=10;
int square;
square = num * num;
System.out.println("The square of " + num + " is " + square);
}
}
2.0.3 Program to check number is odd or even class oddOrEven{
public static void main(String args[]){
int num=10;
if(num%2==0)
System.out.println(―Even‖);
else
System.out.println(―Odd‖);
}
}
2.0.4 Program to print numbers below 100 containing 7 class contains7{
public static void main(String args[]){
int num;
for(num=1;num<=100;num++){
if(num % 10 == 7 || num % 100 == 7)
System.out.println(num);
}
}
}
2.0.5 Program to calculate digit sum class contains7{
public static void main(String args[]){
int num=1234;
int n,sum,digit;
n=num;
while(num>0){
digit=num%10;
sum = sum + digit;
num/=10;
}
num=n;
System.out.println(―Sum of digits of ― + num + ― is ― + sum);
}
}
Computer Programming Lab
54 Department of ECE – GCE Kannur
2.0.6 Factorial of a number class factTest{
public static void main(String args[]){
long fact;
for(int num=1;num<=10;num++){
fact=factorial(num);
System.out.println("Factorial of " + num + " is " + fact);
}
}
public static long factorial(int n){
if(n==1 || n==0)
return 1;
long f=1;
for(int i=2;i<=n;i++)
f = f * i;
return f;
}
}
2.0.7 Basic String Operations class stringOperations{
public static void main(String args[]){
String str="Programming Java";
String strToAdd = " is Interesting!";
int len = str.length();
System.out.println("The String is : " + str );
System.out.println("Length of String is " + len);
String res = str + strToAdd;
System.out.println("Concatenation using + operator: " + res);
res = str.concat(strToAdd);
System.out.println("Concatenation using concat function: " + res);
res=res.replaceFirst("Java","C");
System.out.println("After replacement: " + res);
System.out.println("String in uppercase: " + res.toUpperCase());
int fromChar = 8, toChar=12;
res = res.substring(fromChar-1,toChar-1);
System.out.println("Characters from " + fromChar + " to " + toChar + " are: " + res);
str = "Java";
System.out.println("New value of string is : " + str );
if(str.compareTo("java") == 0)
res = "Yes";
else
res = "No";
System.out.println("String equal to java? " + res);
res = str.compareTo("Java") == 0 ? "Yes" : "No";
System.out.println("String equal to Java? " + res);
res = str.compareToIgnoreCase("java") == 0 ? "Yes" : "No";
System.out.println("The string equal to java(Ignore case)? " + res);
}
}
2.0.8 Matrix Transpose class transpose{
public static void main(String args[]){
int N=3;
int matrix[][] = { {1,2,3},{4,5,6},{7,8,9} };
int res[][] = new int[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
res[i][j] = matrix[j][i];
System.out.println("Original Matrix");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
Computer Programming Lab
55 Department of ECE – GCE Kannur
System.out.printf("%4d", matrix[i][j]);
}
System.out.println();
}
System.out.println("Transposed Matrix");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.printf("%4d", res[i][j]);
}
System.out.println();
}
}
}
2.0.9 The Circle Class class circleTest{
public static void main(String args[]){
circle c1 = new circle();
c1.radius = 10.3f;
c1.showInfo();
}
}
class circle{
float radius;
float calculateArea(){
float area = 3.4159f * radius * radius;
return area;
}
void showInfo(){
System.out.println("Radius is " + radius);
float val = calculateArea();
System.out.println("Area is " + val);
}
}
2.0.10 Rectangular class with constructor class rectangleTest{
public static void main(String args[]){
rectangle r1 = new rectangle(1.2f,2.7f);
r1.showInfo();
}
}
class rectangle{
float length;
float breadth;
rectangle(float tmpLength, float tmpBreadth){
length=tmpLength;
breadth=tmpBreadth;
}
float calculateArea(){
float area = length * breadth;
return area;
}
void showInfo(){
System.out.println("Length is " + length + "m");
System.out.println("Breadth is " + breadth + "m");
float val = calculateArea();
System.out.println("Area is " + val + "square m");
}
}
Computer Programming Lab
56 Department of ECE – GCE Kannur
2.0.11 Object Counter – Concept of class variable class objectCounter{
public static void main(String args[]){
A a1,a2,a3,a4,a5;
a1 = new A();
a2 = new A();
a3 = new A();
A a[]=new A[100];
for(int i=0;i<a.length;i++)
a[i] = new A();
a4 = new A();
a5 = new A();
}
}
class A{
//class variable
static int count;
A(){
count++;
System.out.println(" I am the " + count + "th instance of class A");
}
}
2.0.12 Function overloading – Polymorphism class functionOverloading{
public static void main(String args[]){
sum s = new sum();
s.add(2,3);
s.add(2.3f,3.4f);
s.add('A','B');
s.add("Add is ","overloaded");
}
}
class sum{
void add(char a, char b){
String res="";
res = res+a;
res = res+b;
System.out.println("Added two characters! Result:" + res);
}
void add(int a, int b){
int res = a + b;
System.out.println("Added two integers! Result:" + res);
}
void add(float a, float b){
float res = a + b;
System.out.println("Added two real numbers! Result:" + res);
}
void add(String a, String b){
String res = a.concat(b);
System.out.println("Added two Strings! Result:" + res);
}
}
2.0.13 Simple Inheritance class simpleInheritance{
public static void main(String args[]){
System.out.println("Creating parent .......");
parent p = new parent();
System.out.println("Creating child ........");
child c = new child();
Computer Programming Lab
57 Department of ECE – GCE Kannur
System.out.println("Calling child's inherited method ........");
c.digitSum();
}
}
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);
}
}
2.0.14 Method overriding
class methodOverriding{
public static void main(String args[]){
parent p = new parent();
child c = new child();
int num1=10, num2=30;
System.out.println("a=" + num1 + ", b=" + num2);
System.out.println("Calling parents's sum method.");
p.sum(num1,num2);
p.showResult();
System.out.println("Calling parents's difference method.");
p.difference(num1,num2);
p.showResult();
System.out.println("Calling child's sum method.");
c.sum(num1,num2);
c.showResult();
System.out.println("Calling child's difference method.");
c.difference(num1,num2);
c.showResult();
}
}
class parent{
int res;
void sum(int a, int b){
res = a + b;
}
void difference(int a, int b){
res = a-b;
}
Computer Programming Lab
58 Department of ECE – GCE Kannur
void showResult(){
System.out.println("Result is :" + res);
}
}
class child extends parent{
void sum(int a, int b){
res = a * 2 + b * 4;
}
void difference(int a, int b){
res = a /2 - b/3;
}
}
2.0.15 Unhandled Exception class exceptionTest1{
public static void main(String args[]){
System.out.println("You can see some error messages below because program cannot handle exception");
System.out.println("Following statements will create division by zero exception\n");
int a=10,b=10,c=2,d;
d = c/(a-b);
}
}
2.0.16 Exception Handling import java.io.*;
class exceptionHandling{
public static void main(String args[]){
int a=10,b=10,c=2,d;
int nums[]=new int[10];
A a1;
System.out.println("------------------------------------------------------------");
try{
//The following statement cause division by zero error. So handle it
d = c/(a-b);
}
catch(Exception e){
System.out.println("An error has occured! Details of error follows");
System.out.println(e.toString());
}
System.out.println("------------------------------------------------------------");
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("------------------------------------------------------------");
}
}
Computer Programming Lab
59 Department of ECE – GCE Kannur
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 an Float Value");
floatVal = Float.parseFloat(in.readLine());
System.out.println("Enter an Double Value");
doubleVal = Double.parseDouble(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);
}
}
2.0.18 Applet to display your name in a circle /*
<applet code="nameDisplay.class" width="500" height="500">
<param name="myname" value="RAJ">
</applet>
*/
import java.applet.Applet;
import java.awt.*;
public class nameDisplay extends Applet{
String name;
public void init(){
name=getParameter("myname");
}
public void paint(Graphics g){
g.setColor(Color.green);
g.fillOval(50,50,150,150);
g.setColor(Color.blue);
g.drawString(name,100,100);
}
}
Computer Programming Lab
60 Department of ECE – GCE Kannur
2.0. INHERITANCE
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 members term1Voltage , term2Voltage and
componentName. Based on terminalVoltage display current direction in the applyVoltage method. Derive a 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 create a resistor object, apply sum voltage to it and call its calculateCurrentAndPower method. Create a
twoTerminalComponent object reference and assign previously created resistor object to it. Apply some voltage to it. Then call calculateCurrentAndPower
method of resistor object.
+applyVoltage(in term1Voltage : int, in term2Voltage : int) : void
#term1Voltage : int
#term2Voltage : int
#componentName : string
twoTerminalComponent
+calculateCurrentAndPower() : void
#resistance : float
#current : float
#power : float
resistor
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");
}
}
}
class resistor extends twoTerminalComponent{
float current;
float resistance;
float power;
resistor(float resistance){
componentName="Resistor";
this.resistance=resistance;
}
Computer Programming Lab
61 Department of ECE – GCE Kannur
void calculateCurrentAndPower(){
current=(term2Voltage-term1Voltage)/resistance;
power=current*current*resistance;
System.out.println("Current flowing = " + current + "A");
System.out.println("Power=" + power + "W");
}
}
public class inheritanceTest{
public static void main(String args[]){
resistor R1 = new resistor(100);
R1.applyVoltage(100, 200);
R1.calculateCurrentAndPower();
twoTerminalComponent component;
component=R1;
component.applyVoltage(200, 50);
R1.calculateCurrentAndPower();
}
}
Terminal Voltage 1: 100V
Terminal Voltage 2: 200V
Current flowing from 2 to 1
Current flowing = 1.0A
Power=100.0W
Terminal Voltage 1: 200V
Terminal Voltage 2: 50V
Current flowing from 1 to 2
Current flowing = -1.5A
Power=225.0W
Computer Programming Lab
62 Department of ECE – GCE Kannur
2.0. POLYMORPHISM
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 class with members, vehicleName and speed. Implement start method to set speed to 1, accelerate method to increment speed, applyBreak method to decrement speed, showSpeed
method display speed and showInfo method display vehicleName. Derive a class car from it with a new member
regNumber. Implement a constructor in the car to initialise vehicleName and regNumber. Overload and override accelerate method in car. First one to accept a gear and change speed to
that gear. (A: 10Km/hr, B: 20 Km/hr, C: 30Km/hr, D: 40 Km/hr & R: -5Km/hr). Second one to accept a speed change amount (dSpeed) and to change speed according to it. Override the
showInfo method to display car’s vehicleName and regNumber. In the main function create a vehicle object start, accelerate,
break it. Create a car object and start, accelerate, accelerate to a gear, accelerate with a speed change amount and break it. Assign the car object to vehicle object reference and perform start,
accelerate, break.
#start() : void
#accelerate() : void
#showInfo() : void
#showSpeed() : void
#applyBreak() : void
#vehicleName : string
#speed : int
vehicle
#car()
#showInfo() : void
#accelerate(in gear : char) : void
#accelerate(in dSpeed : char) : void
#regNumber : string
car
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;
}
Computer Programming Lab
63 Department of ECE – GCE Kannur
else if(speed<0){
speed=speed+5;
if(speed>0)
speed=0;
}
System.out.println("Breaking...");
showSpeed();
}
}
class car extends vehicle{
String regNumber;
car(String RegNumber){
vehicleName="Car";
this.regNumber=RegNumber;
}
void showInfo(){
super.showInfo();
System.out.println("RegNo: " + regNumber);
}
void accelerate(char gear){
switch(gear){
case 'A': speed=10; break;
case 'B': speed=20; break;
case 'C': speed=30; break;
case 'D': speed=40; break;
case 'R': speed=-5; break;
}
showSpeed();
}
void accelerate(int dSpeed){
speed=speed+dSpeed;
showSpeed();
}
}
public class polymorphismTest{
public static void main(String args[]){
vehicle vehicle=new vehicle();
vehicle.start();
vehicle.accelerate();
vehicle.accelerate();
vehicle.accelerate();
vehicle.showSpeed();
vehicle.applyBreak();
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();
}
}
Computer Programming Lab
64 Department of ECE – GCE Kannur
Started...
Vehicle Speed: 1Km/Hr
Vehicle Speed: 2Km/Hr
Vehicle Speed: 3Km/Hr
Vehicle Speed: 4Km/Hr
Vehicle Speed: 4Km/Hr
Breaking...
Vehicle Speed: 0Km/Hr
*****************************************
Vehicle: Car
RegNo: KL 11 / 1234
Started...
Vehicle Speed: 1Km/Hr
Vehicle Speed: 11Km/Hr
Vehicle Speed: 40Km/Hr
Vehicle Speed: -5Km/Hr
Breaking...
Vehicle Speed: 0Km/Hr
*****************************************
Vehicle: Car
RegNo: KL 11 / 1234
Vehicle Speed: 1Km/Hr
Vehicle Speed: 2Km/Hr
Breaking...
Vehicle Speed: 0Km/Hr
Computer Programming Lab
65 Department of ECE – GCE Kannur
2.3 SERIALIZATION – READING AND WRITING OBJECT
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
Computer Programming Lab
66 Department of ECE – GCE Kannur
2.4 SINE WAVE APPLET
Implement an applet program to display a sine wave. Accept frequency and amplitude as parameter from Browser
Background
The Expression for sampled sine wave 2000
0
( ) sin(2 )n
n
y n amplitude frequency n
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.*;
public class sineWave extends Applet{
int y[];
final float PI = 3.14159265f;
int SAMPLE_LEN=2000;
float frequency;
float amplitude;
public void init(){
frequency = Float.parseFloat(getParameter("frequency"));
amplitude = Float.parseFloat(getParameter("amplitude"));
y=new int[SAMPLE_LEN];
float angle=0, n=0,dn=.001f;
for(int i=0;i<SAMPLE_LEN;i++){
angle = 2 * PI * frequency * n;
y[i]=(int) (amplitude * Math.sin(angle));
n+=dn;
}
}
public void paint(Graphics g) {
Dimension dimension = getSize();
int screenHeight = dimension.height;
int screenWidth = dimension.width;
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);
}
}
Computer Programming Lab
67 Department of ECE – GCE Kannur
Computer Programming Lab
68 Department of ECE – GCE Kannur
Computer Programming Lab
69 Department of ECE – GCE Kannur
RReeffeerreenncceess
Computer Programming Lab
70 Department of ECE – GCE Kannur
Computer Programming Lab
71 Department of ECE – GCE Kannur
R.1 ASCII Table (7-Bit)
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
Computer Programming Lab
72 Department of ECE – GCE Kannur
R.2 C Quick Reference Program Structure/Functions Statement Description
type func(type 1 , : : : ); function prototype type name; variable declaration
int main(void)
{
main routine
declarations local variable declarations
statements
}
type func(arg 1 , : : : )
{
declarations
statements
return value;
}
function definition local variable declarations
/* */ /* */ comments int main(int argc, char *argv[]) main with args exit(arg); terminate execution
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)
Computer Programming Lab
73 Department of ECE – GCE Kannur
Initialization Purpose Function initialize variable type name=value;
initialize array type name[]={value 1 ,: : : };
initialize char string char name[]="string";
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"
Pointers, Arrays & Structures Purpose Function declare pointer to type type *name;
declare function returning pointer to type type *f();
declare pointer to function returning type type (*pf)(); statement
generic pointer type void *
null pointer constant NULL
object pointed to by pointer *pointer
address of object name &name
array name[dim]
multi-dim array name[dim ][dim ]
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;
Operators (grouped by precedence) Purpose Function struct member operator name.member
struct member through pointer pointer->member
increment, decrement ++, --
plus, minus, logical not, bitwise not +, -, !, ~
indirection via pointer, address of object *pointer, &name
cast expression to type (type) expr
size of an object sizeof
multiply, divide, modulus (remainder) *, /, %
add, subtract +, -
left, right shift [bit ops] <<, >>
relational comparisons >, >=, <, <=
equality comparisons ==, !=
and [bit op] &
exclusive or [bit op] ̂
or (inclusive) [bit op] |
logical and &&
logical or ||
conditional expression expr 1 ? expr 2 : expr 3
assignment operators +=, -=, *=, : : :
expression evaluation separator ,
Unary operators, conditional expression and assignment operators group right to left; all others group left to right.
Computer Programming Lab
74 Department of ECE – GCE Kannur
Flow of Control Purpose Function statement terminator ;
block delimiters { … }
exit from switch, while, do, for break;
next iteration of while, do, for continue;
go to label : statement
label char name[]="string";
return value from function return expr;
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
}
ANSI Standard Libraries <assert.h> <ctype.h> <errno.h> <float.h> <limits.h>
<locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h>
<stddef.h> <stdio.h> <stdlib.h> <string.h> <time.h>
Character Class Tests <ctype.h> Purpose Function alphanumeric? isalnum(c)
alphabetic? isalpha(c)
control character? iscntrl(c)
decimal digit? isdigit(c)
printing character (not incl space)? isgraph(c)
lower case letter? islower(c)
printing character (incl space)? isprint(c)
printing char except space, letter, digit? ispunct(c)
space, formfeed, newline, cr, tab, vtab? isspace(c)
upper case letter? isupper(c)
hexadecimal digit? isxdigit(c)
convert to lower case tolower(c)
convert to upper case toupper(c)
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)
Computer Programming Lab
75 Department of ECE – GCE Kannur
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)
Codes for Formatted I/O:"%-+ 0w:pmc" Purpose Function - left justify + print with sign space print space if no sign 0 pad with leading zeros w min field width p precision m conversion character: h short, l long, L long double c conversion character: d,i integer u unsigned c single char S char string f float e,E exponential lf double o octal x,X hexadecimal p pointer n number of chars written
Standard Utility Functions <stdlib.h> Purpose Function absolute value of int n abs(n)
absolute value of long n labs(n)
pseudo-random integer [0,RAND_MAX] frand()
set random seed to n srand(n)
terminate program execution exit(status)
pass string s to system for execution system(s)
Computer Programming Lab
76 Department of ECE – GCE Kannur
Conversions Purpose Function convert string s to double atof(s) convert string s to integer atoi(s)
convert string s to long atol(s)
Storage Allocation Purpose Function allocate storage malloc(size), calloc(nobj,size)
change size of storage newptr = realloc(ptr,size);
deallocate storage free(ptr);
Mathematical Functions <math.h> Arguments and returned values are double
Purpose Function
trig functions sin(x), cos(x), tan(x)
inverse trig functions asin(x), acos(x), atan(x)
hyperbolic trig functions sinh(x), cosh(x), tanh(x)
exponentials & logs exp(x), log(x), log10(x)
powers pow(x,y), sqrt(x)
rounding ceil(x), floor(x), fabs(x)
C Keywords
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
Computer Programming Lab
77 Department of ECE – GCE Kannur
R.3 Java Quick Reference Syntax for a standalone application in Java: class <classname>{
public static void main(String args[]){
statements;
————————;
————————;
}
}
Primitive Data Types Data Type Purpose Contents Default Value*
boolean Truth value true or false fales
char Character Unicode characters \u0000
byte Signed integer 8 bit two's complement (byte) 0
short Signed integer 16 bit two's complement (short) 0
int Signed integer 32 bit two's complement 0
long Signed integer 64 bit two's complement 0L
float Real number 32 bit IEEE 754 floating point 0.0f
double Real number 64 bit IEEE 754 floating point 0.0d
Java naming conventions: Variable Names: Can start with a letter, ‗$‘ (dollar symbol),or ‗_‘ (underscore); Cannot start with a number or a reserved word. Method Names: Verbs or verb phrases with first letter in lowercase, and the first letter of subsequent words capitalized; cannot be reserved words. Class And Interface Names: Descriptive names that begin with a capital letter, by convention; cannot be a reserved word. Constant Names: They are in capitals.
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];
Computer Programming Lab
78 Department of ECE – GCE Kannur
Multi-dimensional arrays Syntax: <datatype> <arrayname>[ ] [ ] = new <datatype> [number of rows][number of columns]; Example: int myarray[][] = new int[4][5];
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)
Computer Programming Lab
79 Department of ECE – GCE Kannur
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
Access Modifies and Visibility Modifier Used with Description
public
Classes Interfaces Constructors Inner Classes Methods Field variables
A Class or Interface may be accessed from outside its package. Constructors, Inner Classes, Methods and Field variables may be accessed from wherever their class is accessed.
protected
Constructors Inner Classes Methods Field variables
May be accessed by other classes in the same package or from any subclasses of the class in which they are declared.
private
Constructors Inner Classes Methods Field variables
May be accessed only from within the class in which they are declared.
no modifier
Classes Interfaces Constructors Inner Classes Methods Field variables
May only be accessed from within the package in which they are declared.
Computer Programming Lab
80 Department of ECE – GCE Kannur
Attribute modifies Modifier Used on Meaning abstract class
interface method
Contains unimplemented methods and cannot be instantiated. All interfaces are abstract. Optional in declarations No body, only signature. The enclosing class is abstract
final class method field variable
Cannot be subclassed Cannot be overridden and dynamically looked up Cannot change its value. static final fields are compile-time constants. Cannot change its value.
native method Platform-dependent. No body, only signature static class
method field initializer
Make an inner class top-level class A class method, invoked through the class name. A class field, invoked through the class name one instance, regardless of class instances created. Run when the class is loaded, rather than when an instance is created.
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.
Computer Programming Lab
81 Department of ECE – GCE Kannur
Converting Strings to Numbers To convert a string value to a number (for example, to convert the String value in a text field to an int), use these methods. Assume the following declarations:
String s; int i; long l; float f; double d;
type Example statement int i = Integer.parseInt(s);
long l = Long.parseLong(s);
float f = Float.parseFloat(s);
double d = Double.parseDouble(s);
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
Computer Programming Lab
82 Department of ECE – GCE Kannur
The java.io.InputStream class The inputstream class is at the top of the input stream hierarchy. This is an abstract class which cannot be instantiated. Hence, subclasses like the Datainputstream class are used for input purposes.
Methods of the Inputstream class Method Description available() Returns the number of bytes that can be read close() Closes the input stream and releases associated system resources mark(int
readlimit)
Marks the current position in the input stream
read() Abstract method which reads the next byte of data from the input stream read (byte b[] ) Reads bytes from the input stream and stores them in the buffer array skip(long n)
)
Skips input a specified stream number of bytes from the stream
The java.io.OutputStream class The outputstream class which is at the top of the output stream hierarchy, is also an abstract class, which cannot be instantiated. Hence, subclasses like DataOutputStream and PrintStream are USed for output purposes.
Methods of the Outputstream class Method Description close() Closes the output stream, and releases associated system resources write(int b) Writes a byte to the output stream write(byte b [ ] ) Writes bytes from the byte array to the output stream flush () Flushes the output stream, and writes buffered output bytes
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: FileInputStream fin = new FileInputStream("file.txt ")); //Can read bytes only
BufferedInputStream in = new BufferedInputStream(fin); //Chained to read block of characters
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.
Computer Programming Lab
83 Department of ECE – GCE Kannur
Methods of the Graphics class Method Description drawLine(int x1, int y1, int x2, int y2) Draws a line between (x1,y1) and (x2,y2) passed as parameters drawRect(int x, int y, int h, int w)
fillRect(int x, int y, int h, int w)
Draws a rectangle or specified width and height at a specified location
drawOval(int x, int y, int h, int w)
fillOval(int x, int y, int h, int w)
Draws a circle or an ellipse that fills within a rectangle of specific coordinates
drawString(String str,int x,int y) Draws the text given as a specified string setColor (Color c) Sets the specified color of the graphics context setFont (Color c) Sets the specified font of the graphics context
Color Constants
Color.BLACK Color.DARK_GRAY Color.GRAY Color.LIGHT_GRAY Color.WHITE Color.MAGENTA Color.RED
Color.PINK Color.ORANGE Color.YELLOW Color.GREEN Color.CYAN Color.BLUE
Reserve Words
abstract do if package synchronized
boolean double implements private this
break else import protected throw
byte extends instanceof public throws
case false int return transient
catch final interface short true
char finally long static try
class float native strictfp void
const for new super volatile
continue goto null switch while
default assert
Computer Programming Lab
84 Department of ECE – GCE Kannur
Computer Programming Lab
85 Department of ECE – GCE Kannur
UUnncclleeaann CC SSoouurrccee CCooddeess
Computer Programming Lab
86 Department of ECE – GCE Kannur
Computer Programming Lab
87 Department of ECE – GCE Kannur
R.4 Unclean C Source Codes These are C programs which do not agree with any coding conventions such as variable naming convention, function
naming convention etc. However these programs really lack readability, they are included for reference purpose. The intention is to give you an outline of the implementation of algorithms described in section 1.0. Note that these programs should not be used as source code for your experiments.
R.4.1HCF & LCM Calculator #include <stdio.h>
main()
{
int n1=144,n2=60;
int a=n1, b=n2;
while(a!=b){
if(a>b)
a=a-b;
else if(a<b)
b=b-a;
else
break;
}
printf("HCF = %d, LCM=%d of (%d, %d)",a,n1*n2/a,n1,n2);
}
R.4.2 Number System Converter #include<stdio.h>
#include<string.h>
char * ToBaseN(long num, int base,char *n);
long toDec(char * n,int base);
main()
{
char n[]="ABC";
int base=16,newBase=10;
char n1[50];
printf("\nOriginal: %s",n);
printf("\nDecmial: %ld",toDec(n,base));
printf("\nConverted: %s",ToBaseN(toDec(n,base),newBase,n1));
}
char * ToBaseN(long num, int base, char * n)
{
int d;
int i=0;
int len;
char t;
while(num>0){
d=num%base;
if(base==16 && d>9){
n[i]=55 + d;
}
else
n[i]=48 + d;
num/=base;
i++;
}
n[i]='\0';
len=strlen(n);
for(i=0;i<len/2;i++)
{
t=n[i];
n[i]=n[len-i-1];
n[len-i-1]=t;
}
return n;
}
Computer Programming Lab
88 Department of ECE – GCE Kannur
long toDec(char * n,int base)
{
int i=0;
long num=0;
int pos=1;
for(i=strlen(n)-1;i>=0;i--)
{
if(n[i]>=48 && n[i]<=57)
{
num=num+(n[i]-48)*pos;
}
else if(n[i]>=65 && n[i]<=70)
{
if(base==16)
num=num+(n[i]-55)*pos;
}
pos=pos*base;
}
return num;
}
R.4.3 Fibonacci & Prime Series Generator #include <math.h>
#include<stdio.h>
void primes(int );
void fibs(int );
int main()
{
primes(10);
printf("\n");
fibs(10);
}
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);
}
}
}
void fibs(int count)
{
int fn,fn_1,fn_2, f0=0,f1=1,i;
printf("%d, %d, ",f0,f1);
fn_1=f1;
fn_2=f0;
Computer Programming Lab
89 Department of ECE – GCE Kannur
for(i=1;i<count;i++)
{
fn=fn_1 +fn_2;
printf("%d, ",fn);
fn_2=fn_1;
fn_1=fn;
}
}
R.4.4 Taylor's Series Evaluator #include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
double exp1(float v,int fn);
double pow1(float x,int y);
long fact(int n);
int main()
{
float pi=3.14156;
float v=pi/180;
float x=3;
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;
Computer Programming Lab
90 Department of ECE – GCE Kannur
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;
}
R.4.5 String Manipulator #include <stdio.h>
#include <stdlib.h>
int str_len(char *str);
int str_str(char *str, char *find,int pos);
int str_srh(char *str, char *find);
char * str_rep(char *str, char *find, char *replace ,int pos);
int main()
{
char str[]="YOU MAY HAVE IT";
char find[]="IT";
char replace[]="SHOULD";
printf("\n\n%s\n\n%s",str,str_rep(str,find,replace,str_str(str,find,0)));
return 0;
}
int str_len(char *str)
{
int i=0;
for(i=0;str[i];i++)
;
return i;
}
int str_str(char *str, char *find,int pos)
{
int len_str,len_find;
len_str=str_len(str);
len_find=str_len(find);
int i=0;
int j=0;
for(i=pos;i<len_str;i++)
{
if(len_find<=(len_str - i))
{
for(j=0;j<len_find;j++)
{
if(find[j]!=str[i+j])
break;
}
Computer Programming Lab
91 Department of ECE – GCE Kannur
if(j==len_find)
{
printf("Found at %d\n",i);
return i;
}
}
else
break;
}
printf("Not found\n");
return -1;
}
char * str_rep(char *str, char *find , char *replace ,int pos)
{
char *tmp;
int len_str,len_find,len_replace,len_rest,i;
len_str=str_len(str);
len_find=str_len(find);
len_replace=str_len(replace);
tmp = (char *)malloc(len_str + len_replace - len_find + 1);
for(i=0;i<pos;i++)
tmp[i]=str[i];
for(i=0;i<len_replace;i++)
tmp[pos+i]=replace[i];
len_rest = len_str - (pos + len_find);
for(i=0;i<len_rest;i++)
tmp[pos+len_replace+i]=str[pos + len_find + i];
tmp[pos+len_replace + len_rest]='\0';
return tmp;
}
R.4.6 Matrix Product Calculator #include <stdio.h>
main()
{
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int b[3][3]={{9,8,7},{6,5,4},{3,2,1}};
int c[3][3]={{0,0,0},{0,0,0},{0,0,0}};
int i,j,k;
int row1, col1, row2, col2;
row1 = 3;
col1 = 3;
row2 = 3;
col2 = 3;
if(col1 != row2)
{
printf("MULTIPLICATION NOT POSSIBLE");
return 0;
}
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");
Computer Programming Lab
92 Department of ECE – GCE Kannur
for(j=0;j<col2;j++)
printf("%d\t",c[i][j]);
}
}
R.4.7 Determinant Calculator #include<stdio.h>
#include<math.h>
float determinant( int a[3][3], int n );
main()
{
int a[3][3]={{2,-2,0},{-1,5,1},{3,4,5}};
int i,j;
printf("\n\nDeteminant %f",determinant(a,3));
}
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;
}
R.4.8 Matrix Inverse Calculator #include<stdio.h>
#include<math.h>
double determinant( double a[][3], int n );
void cofact(double a[][3],int n,double b[][3]);
void Transpose(double a[][3],int n);
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++)
Computer Programming Lab
93 Department of ECE – GCE Kannur
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++ )
{
Computer Programming Lab
94 Department of ECE – GCE Kannur
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;
}
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;
}
}
}
R.4.9 Equation Solver Using Jordan Elimination Method #include<stdio.h>
int main()
{
float a[3][3]={{2.0,3.0,7.0},{1.0,4.0,2.0}, {3.0,2.0,1.0} };
float b[3]={29.0,15.0,10.0};
float d,f,g;
int i,j,k;
for(i=0;i<3;i++)
{
d=a[i][i];
for(j=0;j<3;j++){
a[i][j]=a[i][j]/d;
}
b[i]=b[i]/d;
for(k=0;k<3;k++)
{
if(k==i)
continue;
f=a[k][i];
for(j=0;j<3;j++)
{
a[k][j]=a[k][j]-f*a[i][j];
}
b[k]=b[k]-f*b[i];
}
}
for( i=0;i<3;i++)
printf("x%d=%f\t",(i+1),b[i]);
return 0;
}
Computer Programming Lab
95 Department of ECE – GCE Kannur
R.4.10 Simple Student Record Manipulator #include <stdio.h>
#include <stdlib.h>
#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);
}
Computer Programming Lab
96 Department of ECE – GCE Kannur
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;
}
R.4.11 Singly Linked List Builder #define NULL 0
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node * next;
};
typedef struct node Node;
Node* Head = NULL;
Node* addAtBeg(Node* Head, int newData)
{
Node* newNode = NULL;
newNode = (Node *)malloc(sizeof(Node));
newNode->data = newData;
newNode->next=NULL;
if(Head==NULL)
{
return newNode;
}
else
{
newNode->next = Head;
return newNode;
}
}
void addAtEnd(Node* Head, int newData)
{
Node* newNode = NULL;
Node* current = Head;
newNode = (Node *)malloc(sizeof(Node));
newNode->data = newData;
newNode->next=NULL;
if(Head->next == NULL)
{
Head->next=newNode;
}
else
{
Computer Programming Lab
97 Department of ECE – GCE Kannur
while (current->next != NULL)
{
current = current->next;
}
}
current->next=newNode;
}
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)
{
Computer Programming Lab
98 Department of ECE – GCE Kannur
if(current->data==insertAferData)
{
newNode->next=current->next;
newNode->data=newData;
current->next=newNode;
return;
}
current = current->next;
}
printf("******Insert Failed: Cannot find node!*********\n");
}
void printList(Node* Head){
printf("Length of List: %d\n",length(Head));
printf("***********************************************\n");
Node* current = Head;
int count = 0;
while (current != NULL) {
count++;
printf("%d -> ",current->data);
current = current->next;
}
printf("END\n***********************************************\n");
}
int main()
{
int c;
Node* Head=NULL;
Head=addAtBeg(Head,11);
insertAfterNode(Head,11,22);
insertAfterNode(Head,22,44);
insertAfterNode(Head,22,33);
addAtEnd(Head,55);
insertAfterNode(Head,55,66);
printList(Head);
printList(Head);
Node* found=searchNode(Head,11);
if(found!=NULL)
Head=deleteNode(Head,found);
printList(Head);
found=searchNode(Head,22);
if(found!=NULL)
Head=deleteNode(Head,found);
printList(Head);
found=searchNode(Head,33);
if(found!=NULL)
Head=deleteNode(Head,found);
printList(Head);
found=searchNode(Head,44);
if(found!=NULL)
Head=deleteNode(Head,found);
printList(Head);
found=searchNode(Head,55);
if(found!=NULL)
Head=deleteNode(Head,found);
printList(Head);
found=searchNode(Head,66);
if(found!=NULL)
Head=deleteNode(Head,found);
printList(Head);
return 0;
}
Computer Programming Lab
99 Department of ECE – GCE Kannur
We appreciate your comments and corrections.
Send your comments and suggestions to: