Download as pdf or txt
Download as pdf or txt
You are on page 1of 99

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

Department of ECE GCE Kannur

Computer Programming Lab

Contents
Preliminaries
0.1 0.1.1 0.1.2 0.1.3 0.2 0.3 0.4 0.4 .1 0.4 .2 0.4 .3 0.5 0.6 0.6.1 0.6.2 0.6.3 0.6.4 0.6.5 0.7 0.7.1 0.7.2 0.7.3 0.7.3 0.7.4 0.8 0.8.1 0.8.2 0.8.3 0.8.4 0.8.5 0.8.6 0.8.7 0.8.8 Introduction Understand the needs Define the solution Map the solution Programming Language Pseudocode Prerequisites for software development Knowledge of a Programming Language Text Editor Tool Compiler & Interpreter Tool C Language Object Oriented Programming (OOP) Object Class Encapsulation Inheritance Polymorphism Java Java Language Principles Java Platform Java Applets Embedding Applet into web page Serialization Software Development Tools GNU Compiler Collection GCC Options Compiling & Running C Program using GCC OpenJDK Open Java Development Kit OpenJDK Installation Compiling & Running Java Programs GEdit Configuring gedit to Compile C and Java

7 7 7 7 7

7 7 7 7 8 8 9 9 9 9 9 9 9 9 10 10 10 11 11 11 11 11 11 11 12 12

Department of ECE GCE Kannur

Computer Programming Lab

C Programming
1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 Simple C Programs HCF & LCM Calculator Number System Converter Fibonacci & Prime Series Generator Taylor's Series Evaluator String Manipulator Matrix Product Calculator Determinant Calculator Matrix Inverse Calculator Equation Solver Using Jordan Elimination Method Simple Student Record Manipulator Singly Linked List Builder

25 30 31 33 34 36 38 40 41 43 45 47

Java Programming
2.0 2.1 2.2 2.3 2.4 Simple Java Programs Inheritance Polymorphism Serialization Reading & Writing Object Sine Wave Applet

53 60 62 65 66

References
R.1 R.2 R.3 R.4 ASCII Chart C Quick Reference Java Quick Reference Unclean C Source Codes

71 72 77 87

Conventions Used in this Document

Experiment Information Algorithm / Program Program Input Program Output Objective

Department of ECE GCE Kannur

Computer Programming Lab

Preliminaries

Department of ECE GCE Kannur

Computer Programming Lab

Department of ECE GCE Kannur

Computer Programming Lab

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.
7 Department of ECE GCE Kannur

Computer Programming Lab

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:

Department of ECE GCE Kannur

Computer Programming Lab

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.

Department of ECE GCE Kannur

Computer Programming Lab

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,
/* <APPLET code=" myapplet.class" WIDTH="200" HEIGHT="200"> <PARAM NAME=Speed Value=1000> </APPLET> */ import java.applet.* class myapplet extends Applet{ . }

0.7.4 Serialization Serialization is the process of converting an object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection. Javas 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; }

10

Department of ECE GCE Kannur

Computer Programming Lab

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

11

Department of ECE GCE Kannur

Computer Programming Lab

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

Choose Preferences from the Edit menu of gedit. A preference window will be loaded.

From Ubuntu Desktop go to Application Accessories-gedit Text Editor to launch gedit

12

Department of ECE GCE Kannur

13

Just above the Help button you can see a New Tool button - click it In the view tab enable External Tools. Then click Configure Plugin button at the bottom

In the View tab disable Text Wrapping, enable Line Numbers, enable Bracket Matching. In the Editor tab enable Automatic Indentation. Also enable Autosave and set time limit as 1 minute

Department of ECE GCE Kannur

Computer Programming Lab

14

In the Edit box type the shown Compile and Run commands Give a name Build & Run C for the New Tool Give a name Build & Run C for the New Tool

Department of ECE GCE Kannur

Computer Programming Lab

15

The final screen should look like this. Compilation commands are listed at the end this section Select Current Document from the Save list Choose a Shortcut Key (F5)

Department of ECE GCE Kannur

Computer Programming Lab

16

Add a new tool Run Applet to display applet. Assign a short cut key F11. Compilation commands are listed at the end of this section

Final screen for Java Build & Run Configuration. Assign a short cut key F9. Compilation commands are listed at the end this section

For Compiling Java add a new tool named Build & Run Java

Department of ECE GCE Kannur

Computer Programming Lab

17

Compile it by pressing F5 or clicking Build & Run C menu item Create a new file and save with .c extension

Click Tools-External Tools Menu. You can view all of your tools now.

Department of ECE GCE Kannur

Computer Programming Lab

18

Run the program and you will see a new popup window on which the output is displayed.

Program after fixing of error. chAr is changed to char

You can see compilation errors (if exists) just below the editor textbox, the Shell Output

Department of ECE GCE Kannur

Computer Programming Lab

19

The java output window

Compile and run it using the tool Here is a simple java program

Department of ECE GCE Kannur

Computer Programming Lab

Computer Programming Lab

The applet output

Execute applet

An applet program

20

Department of ECE GCE Kannur

Computer Programming Lab

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

Create the C soure file with gedit hello.c


Java Standalone Application

Compile using gcc gcc hello.c

Execute the output file a.out ./a.out

Create the Java soure file with gedit hello.java


Applet Program

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

21

Department of ECE GCE Kannur

Computer Programming Lab

22

Department of ECE GCE Kannur

Computer Programming Lab

C Programming

23

Department of ECE GCE Kannur

Computer Programming Lab

24

Department of ECE GCE Kannur

Computer Programming Lab

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);
25 Department of ECE GCE Kannur

Computer Programming Lab

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++; } }

26

Department of ECE GCE Kannur

Computer Programming Lab

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); }
27 Department of ECE GCE Kannur

Computer Programming Lab

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=&num; *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; }
28 Department of ECE GCE Kannur

Computer Programming Lab

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; }

29

Department of ECE GCE Kannur

Computer Programming Lab

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 ELSEIF num1 < num2 THEN ENDWHILE SET hcf = num1 SET lcm = product / hcf DISPLAY hcf, lcm ENDFUNCTION

num1=num1-num2 num2=num2-num1

Num1 144 HCF 12

Num2 60 LCM 720

30

Department of ECE GCE Kannur

Computer Programming Lab

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 31

Department of ECE GCE Kannur

Computer Programming Lab FOR i=len-1 TO 0 IF num[i] 48 AND num[i] 57 ELSEIF num[i] 65 AND num[i] 70 AND base =16 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 THEN res = res + (num[i] -48) * pos THEN res = res + (num[i] -55) * pos

Number
ABC

Base
16

To Base
10

Result
2748

32

Department of ECE GCE Kannur

Computer Programming Lab

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
33

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377

Prime Series

2, 3, 5, 7, 11, , 13, 17, 19, 23, 29, 31, 37 Department of ECE GCE Kannur

Computer Programming Lab

1.4. TAYLOR'S SERIES EVALUATOR Develop an interactive C application to calculate ex , sin(x) and cos(x) using Taylors 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

n 0

f n (a) ( x a)n n!

f (a)

f ' (a) ( x a) 1!

f '' (a) ( x a) 2 2!

f ''' (a) ( x a)3 3!

Taylors series for some functions Exponential function:

ex
n 0

xn x1 1 n! 1!

x2 2!

x3 3!

Trigonometric functions: x in radians

( 1) n 2 n 1 x3 x5 sin x x x 3! 5! n 0 (2n 1)! ( 1) n 2 n x 2 x 45 cos x x 1 2! 4! n 0 (2n)!


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

34

Department of ECE GCE Kannur

Computer Programming Lab 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 * ELSEIF seriesType = sin THEN CALL TaylorSeries WITH x * ELSEIF seriesType = cos THEN CALL TaylorSeries WITH x * ENDFUNCTION

/ 180, / 180, / 180,

seriesType seriesType seriesType

x 3 ex 20.08 sin(x) 0.0523 cos(x) 0.9986

35

Department of ECE GCE Kannur

Computer Programming Lab

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) 36 Department of ECE GCE Kannur

Computer Programming Lab 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
YOU MAY HAVE IT

Find String
MAY

Replace String
SHOULD

Status
FOUND AT POS ITION 6

Result
YOU SHOULD HAVE IT

37

Department of ECE GCE Kannur

Computer Programming Lab

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 mn matrix with an np matrix results in an mp 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

38

Department of ECE GCE Kannur

Computer Programming Lab


Rows A Cols A Rows B Cols B Matrix A Matrix B

1 2 3
3 3 3 3

9 8 7 6 5 4 3 2 1

4 5 6 7 8 9

Product

30 84

24 69

18 54

138 114 90

39

Department of ECE GCE Kannur

Computer Programming Lab

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 A i j multiplied by -1(i+j). The determinant is calculated from the sum of minors multiplied by cofactors taken over a single row or column. Determinant =|A| = ai jCij , in which Cij is the cofactor of aij is, Cij = (1)i+jMij 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

2
3

-2 0 5 4 1 5
26

-1 3

40

Department of ECE GCE Kannur

Computer Programming Lab

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. Nonsquare 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 41 Department of ECE GCE Kannur

Computer Programming Lab 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

1 3 1
3

1 1 2 2 3 4
Inverse

2 0

9 -2

-5 1 2

-1 -3

42

Department of ECE GCE Kannur

Computer Programming Lab

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.

a11 x1 +a12 x 2 +a13 x 3 =b1

a21 x1 +a22 x 2 +a23 x 3 =b2

A B X

Coefficient Matrix Constant Matrix Matrix of Unknowns

a31 x1 +a32 x 2 +a33 x 3 =b3 a11 a21 a31 AX=B a12 a22 a32 a13 a23 a33 x1 b1 x 2 = b2 x3 b3

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 a 2i the first row multiplied by a 21, 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 a n1, so that after that subtraction a n1 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 a 32, so that after that subtraction a32 becomes 0 Subtract from the fourth row a 4i 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

43

Department of ECE GCE Kannur

Computer Programming Lab 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 1

X2 X3 2 3

44

Department of ECE GCE Kannur

Computer Programming Lab

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 Name Percentage

Integer String ( character array) Float

The size of the record is the size of Student structure in bytes Note: fread(&std, sizeof(Student) , 1,fp); fwrite(&std, sizeof(Student) , 1,fp); fseek ( fp ,n*sizeof(Student) , SEEK_SET ); Reads one record from the file into the variable std. Writes one record of value std into file. 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

45

Department of ECE GCE Kannur

Computer Programming Lab 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 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

(use c file open mode: rb+)

Menu 1.READ DATA 2. SEARCH STUDENT & MODIFY 3. CALCULATECLASS AVERAGE 4. LIST ALL 5. EXIT Choice 1 Count 3 Class No Name Percentage 10 Anil K 78 Class No Name Percentage 9 Kiran M 89 Class No Name Percentage 12 Sunil K 85

Choice 2 Search Name Kiran M Status Modified Choice 3 Average 84.3333 Choice 4 Class No 10 11 12

New Class No 11

New Percentage 90

Name Anil K Kiran M Sunil K

Percentage 78 90 85

46

Department of ECE GCE Kannur

Computer Programming Lab

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
Singly Linked List
Data1

Next

Data2

Next

Data3

Next

Data3

NULL

Head Node

Node

Node

Tail Node

Sample Singly Linked List


11

Next

22

Next

33

Next

55

NULL

Insertion Operation
11

44 22

NEXT
55

Next

Next

33

Next

NULL

Deletion Operation
11

Next

22

Next

33

Next

44

Next

55

NULL

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

47

Department of ECE GCE Kannur

Computer Programming Lab

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 48 Department of ECE GCE Kannur

Computer Programming Lab 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 49 Department of ECE GCE Kannur

Computer Programming Lab FOR I=0 TO 100 READ choice IF choice=1 THEN READ data headNode=CALL addAtBegining WITH headNode, data CALL displayList WITH headNode ELSEIF choice=2 THEN READ data CALL addAtEnd WITH headNode, data CALL displayList WITH headNode ELSEIF choice=3 THEN READ insertAfterData, newData CALL insertAfterNode WITH headNode, insertAfterData, newData CALL displayList WITH headNode ELSEIF choice=4 THEN READ findData foundNode=CALL searchNode WITH headNode,findData IF foundNode END OF LIST THEN DISPLAY Not found ELSE CALL deleteNode WITH headNode, foundNode DISPLAY Deleted CALL displayList WITH headNode ENDIF ELSEIF choice=5 THEN CALL displayList WITH headNode ELSEIF choice=6 THEN EXIT MAIN ENDIF ENDFOR ENDMAIN

Menu 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 Choice 1 Data 11 Choice 3 Insert After Data New Data 11 12 Choice 3 Insert After Data New Data 12 13 Choice 3

Insert After Data 13 Choice 2 Data 15 Choice 5 List Length 5 Choice 4 Find Data 13 Status Deleted Choice 5 List Length 4

New Data 14

List 11, 12, 13, 14, 15

List 11, 12, 14, 15

50

Department of ECE GCE Kannur

Computer Programming Lab

Java Programming

51

Department of ECE GCE Kannur

Computer Programming Lab

52

Department of ECE GCE Kannur

Computer Programming Lab

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); } }

53

Department of ECE GCE Kannur

Computer Programming Lab

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++) { 54 Department of ECE GCE Kannur

Computer Programming Lab 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"); } }

55

Department of ECE GCE Kannur

Computer Programming Lab

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();

56

Department of ECE GCE Kannur

Computer Programming Lab 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; } 57 Department of ECE GCE Kannur

Computer Programming Lab 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("------------------------------------------------------------"); } } 58 Department of ECE GCE Kannur

Computer Programming Lab

2.0.17 Reading from Standard Input - Keyboard


import java.io.*; public class KBInput{ public static void main(String args[]){ String stringVal=""; char charVal='1'; int intVal=0; float floatVal=0.0f; double doubleVal=0.0; InputStreamReader iStream = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(iStream); try{ System.out.println("Enter an Integer"); intVal = Integer.parseInt(in.readLine()); System.out.println("Enter 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 } System.out.println("The Values are:"); System.out.println("Integer value: " System.out.println("Float value: " System.out.println("Double value: " System.out.println("String value: " System.out.println("Character value: " } } Keyboard: " + e.toString()); + + + + + intVal); floatVal); doubleVal); stringVal); 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); } } 59 Department of ECE GCE Kannur

Computer Programming Lab

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. 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; } 60 Department of ECE GCE Kannur
twoTerminalComponent #term1Voltage : int #term2Voltage : int #componentName : string +applyVoltage(in term1Voltage : int, in term2Voltage : int) : void

resistor #resistance : float #current : float #power : float +calculateCurrentAndPower() : void

Computer Programming Lab 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

61

Department of ECE GCE Kannur

Computer Programming Lab

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 cars 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. 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; } 62 Department of ECE GCE Kannur

vehicle #vehicleName : string #speed : int #start() : void #accelerate() : void #showInfo() : void #showSpeed() : void #applyBreak() : void car #regNumber : string #car() #showInfo() : void #accelerate(in gear : char) : void #accelerate(in dSpeed : char) : void

Computer Programming Lab 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(); } } 63 Department of ECE GCE Kannur

Computer Programming Lab 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

64

Department of ECE GCE Kannur

Computer Programming Lab

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

65

Department of ECE GCE Kannur

Computer Programming Lab

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
n 2000

y ( n)
n 0

amplitude sin(2

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); } }

66

Department of ECE GCE Kannur

Computer Programming Lab

67

Department of ECE GCE Kannur

Computer Programming Lab

68

Department of ECE GCE Kannur

Computer Programming Lab

References

69

Department of ECE GCE Kannur

Computer Programming Lab

70

Department of ECE GCE Kannur

Computer Programming Lab

R.1 ASCII Table (7-Bit)


Dec Hex Description null start of heading start of text end of text end of transmission enquiry acknowledge bell backspace horizontal tab new line vertical tab new page carriage return shift out shift in data link escape device control 1 device control 2 device control 3 device control 4 negative acknowledge synchronous idle end of trans. block cancel end of medium substitute escape file separator group separator record separator unit separator Dec Hex Char Description Dec Hex Char Dec Hex Char

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F

space

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F

! " # $ % & ' ( ) * + , . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?

@ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F

` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ DEL

71

Department of ECE GCE Kannur

Computer Programming Lab

R.2 C Quick Reference Program Structure/Functions


Statement type func(type 1 , : : : ); type name; int main(void) { declarations statements } type func(arg 1 , : : : ) { declarations statements return value; } /* */ int main(int argc, char *argv[]) exit(arg); Description function prototype variable declaration main routine local variable declarations

function definition local variable declarations

/* */ comments main with args terminate execution

C Preprocessor
Purpose Preprocessor #include <fillename> include library file #include "fillename" include user file #define name text replacement text #define name(var) text replacement macro Example. #define max(A,B) ((A)>(B) ? (A) : (B)) }; #undef name undefine # 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 character (1 byte) integer real number (single, double precision) short (16 bit integer) long (32 bit integer) positive or negative non-negative modulo 2 pointer to int, float,: : : enumeration constant constant (read-only) value declare external variable internal to source file local persistent between calls no value structure create new name for data type size of an object (type is size_t) size of a data type (type is size_t) Function char int float, double short long signed unsigned int*, float*,: : : enum tag {name = value ,: : : }; type const name; extern static static void struct tag {: : : }; typedef type name; sizeof object sizeof(type)

72

Department of ECE GCE Kannur

Computer Programming Lab

Initialization
Purpose initialize variable initialize array initialize char string Function type name=value; type name[]={value 1 ,: : : }; char name[]="string";

Constants
Purpose sufix: long, unsigned, flooat exponential form prefix: octal, hexadecimal Example. 031 is 25, 0x31 is 49 decimal character constant (char, octal, hex) newline, cr, tab, backspace special characters string constant (ends with \0) Function 65536L, -1U, 3.0F 4.2e1 0, 0x or 0X 'a', '\ooo', '\xhh' \n, \r, \t, \b \\, \?, \', \" "abc: : : de"

Pointers, Arrays & Structures


Purpose declare pointer to type declare function returning pointer to type declare pointer to function returning type generic pointer type null pointer constant object pointed to by pointer address of object name array multi-dim array Function type *name; type *f(); type (*pf)(); statement void * NULL *pointer &name name[dim] name[dim ][dim ]

Structures
struct tag { structure template declarations declaration of members }; Purpose Function struct tag name create structure name.member member of structure from template pointer -> member member of pointed-to structure union single object, multiple possible types unsigned member: b; bit field with b bits

Operators (grouped by precedence)


Purpose struct member operator struct member through pointer increment, decrement plus, minus, logical not, bitwise not indirection via pointer, address of object cast expression to type size of an object 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 assignment operators expression evaluation separator 73 Function name.member pointer->member ++, -+, -, !, ~ *pointer, &name (type) expr sizeof *, /, % +, <<, >> >, >=, <, <= ==, != & ^ | && || expr 1 ? expr 2 : expr 3 +=, -=, *=, : : : , Department of ECE GCE Kannur

Unary operators, conditional expression and assignment operators group right to left; all others group left to right.

Computer Programming Lab

Flow of Control
Purpose statement terminator block delimiters exit from switch, while, do, for next iteration of while, do, for go to label return value from function Function ; {} break; continue; label : statement char name[]="string"; return expr;

Flow Constructs
Purpose if statement while statement for statement do statement Function if (condition1 ) statement 1 else if (condition2) statement 2 else statement 3 while (condition) statement for (initialization ; condition ; increment ) statement do { Statement } while(condition); switch (expr) { case const 1 : statement 1 break; case const 2 : statement 2 break; default: statement }

switch 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 alphanumeric? alphabetic? control character? decimal digit? printing character (not incl space)? lower case letter? printing character (incl space)? printing char except space, letter, digit? space, formfeed, newline, cr, tab, vtab? upper case letter? hexadecimal digit? convert to lower case convert to upper case Function isalnum(c) isalpha(c) iscntrl(c) isdigit(c) isgraph(c) islower(c) isprint(c) ispunct(c) isspace(c) isupper(c) isxdigit(c) tolower(c) toupper(c)

String Operations

s,t are strings, cs,ct are constant strings Purpose length of s copy ct to s concatenate ct after s compare cs to ct only first n chars pointer to first c in cs pointer to last c in cs copy n chars from ct to s 74

Function strlen(s) strcpy(s,ct) strcat(s,ct) strcmp(cs,ct) strncmp(cs,ct,n) strchr(cs,c) strrchr(cs,c) memcpy(s,ct,n) Department of ECE GCE Kannur

Computer Programming Lab copy n chars from ct to s (may overlap) compare n chars of cs with ct pointer to first c in first n chars of cs put c into firrst n chars of s memmove(s,ct,n) memcmp(cs,ct,n) memchr(cs,c,n) memset(s,c,n)

Input/Output <stdio.h>

Standard I/O Purpose standard input stream standard output stream standard error stream end of file (type is int) get a character print a character print formatted data print to string s read formatted data read from string s print string s

Function stdin stdout stderr EOF getchar() putchar(chr) printf("format",arg ,: : : ) sprintf(s,"format",arg 1 ,: : : ) scanf("format",&name ,: : : ) sscanf(s,"format",&name 1 ,: : : ) puts(s)

File I/O
Purpose Function FILE *fp; declare file pointer fopen("name","mode") pointer to named file modes: r (read), w (write), a (append), b (binary) EOF end of file (type is int) getc(fp) get a character putc(chr,fp) write a character fprintf(fp,"format",arg ,: : : ) write to file fscanf(fp,"format",arg 1 ,: : : ) read from file fread(*ptr,itemsize,n,fp) read and store n items to *ptr fwrite(*ptr, itemsize,n,fp) write n items to file fclose(fp) close file feof(fp) non-zero if already reached EOF fgets(s,max,fp) read line to string s (< max chars) fputs(s,fp) write string s

Codes for Formatted I/O:"%-+ 0w:pmc"


Purpose + space 0 w p m h short, l long, L long double c conversion character: d,i integer c single char f float lf double x,X hexadecimal n number of chars written Function left justify print with sign print space if no sign pad with leading zeros min field width precision conversion character: u unsigned S char string e,E exponential o octal p pointer

Standard Utility Functions <stdlib.h>


Purpose absolute value of int n absolute value of long n pseudo-random integer [0,RAND_MAX] set random seed to n terminate program execution pass string s to system for execution 75 Function abs(n) labs(n) frand() srand(n) exit(status) system(s) Department of ECE GCE Kannur

Computer Programming Lab

Conversions
Purpose convert string s to double convert string s to integer convert string s to long Function atof(s) atoi(s) atol(s)

Storage Allocation
Purpose allocate storage change size of storage deallocate storage Function malloc(size), calloc(nobj,size) newptr = realloc(ptr,size); free(ptr);

Mathematical Functions <math.h>

Arguments and returned values are double Purpose trig functions inverse trig functions hyperbolic trig functions exponentials & logs powers rounding

Function sin(x), cos(x), tan(x) asin(x), acos(x), atan(x) sinh(x), cosh(x), tanh(x) exp(x), log(x), log10(x) pow(x,y), sqrt(x) ceil(x), floor(x), fabs(x)

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

76

Department of ECE GCE Kannur

Computer Programming Lab

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 boolean char byte short int long float double Purpose Truth value Character Signed integer Signed integer Signed integer Signed integer Real number Real number Contents true or false Unicode characters 8 bit two's complement 16 bit two's complement 32 bit two's complement 64 bit two's complement 32 bit IEEE 754 floating point 64 bit IEEE 754 floating point Default Value* fales \u0000 (byte) 0 (short) 0 0 0L 0.0f 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];

77

Department of ECE GCE Kannur

Computer Programming Lab

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) 78 Department of ECE GCE Kannur

Computer Programming Lab

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 Classes Interfaces Constructors Inner Classes Methods Field variables Constructors Inner Classes Methods Field variables Constructors Inner Classes Methods Field variables Classes Interfaces Constructors Inner Classes Methods Field variables Description 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.

public

protected

May be accessed by other classes in the same package or from any subclasses of the class in which they are declared.

private

May be accessed only from within the class in which they are declared.

no modifier

May only be accessed from within the package in which they are declared.

79

Department of ECE GCE Kannur

Computer Programming Lab

Attribute modifies
Modifier Used on abstract class interface method final class method field variable native method static class method field initializer Meaning Contains unimplemented methods and cannot be instantiated. All interfaces are abstract. Optional in declarations No body, only signature. The enclosing class is abstract 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. Platform-dependent. No body, only signature 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. 80 Department of ECE GCE Kannur

Computer Programming Lab

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; type int long float double int i; long l; float f; double d; Example statement i = Integer.parseInt(s); l = Long.parseLong(s); f = Float.parseFloat(s); 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 ArithmeticException ArrayIndexOfBoundsException ArrayStoreException ClassCastException IllegalArgumentException IllegalMonitorStateException IndexOutOfBounds Exception NullPointerException NumberFormatException SecurityException ClassNotFound Exception IllegalAccess Exception Instantiation Exception Description Caused by exceptional conditions like divide by zero Thrown when an array is accessed beyond its bounds Thrown when an incompatible type is stored in an array Thrown when there is an invalid cast Thrown when an inappropriate argument is passed to a method Illegal monitor operations such as waiting on an unlocked thread Thrown to indicate that an index is out of range. Invalid use of a null reference. Invalid conversion of a string to a number. Thrown when security is violated. Thrown when a class is not found. Thrown when a method does not have access to a class. Thrown when an attempt is made to instantiate an abstract class or an interface.

Java I/O
Class BufferedlnputStream BufferedOutputStream BufferedReader BufferedWriter DatalnputStream DataOutputStream File FilelnputStream FileOutputStream ObjectlnputStream ObjectOutputStream PrintStream RandomAccessFile Purpose Provides the ability to buffer the input. Supports mark() and reset() methods. Provides the ability to write bytes to the underlying output stream without making a call to the underlying system. Reads text from a character or String from stream int read(),String readLine() Writes text to character Allows an application to read primitive data types from an underlying input stream Allows an application to write primitive data types to an output stream Represents disk files and directories Reads bytes from a file in a file system Writes bytes to a file Reads bytes i.e. desterilizes objects using the readObject() method Writes bytes i.e. serializes writeObject() method Provides the ability to print different data values in an efficient manner Supports reading and writing to a random access file

81

Department of ECE GCE Kannur

Computer Programming Lab

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 available() close() mark(int readlimit) read() read (byte b[] ) skip(long n) ) Description Returns the number of bytes that can be read Closes the input stream and releases associated system resources Marks the current position in the input stream Abstract method which reads the next byte of data from the input stream Reads bytes from the input stream and stores them in the buffer array 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 close() write(int b) write(byte b [ ] ) flush () Description Closes the output stream, and releases associated system resources Writes a byte to the output stream Writes bytes from the byte array to the output stream 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.

82

Department of ECE GCE Kannur

Computer Programming Lab

Methods of the Graphics class


Method drawLine(int x1, int y1, int x2, int y2) drawRect(int x, int y, int h, int w) fillRect(int x, int y, int h, int w) drawOval(int x, int y, int h, int w) fillOval(int x, int y, int h, int w) drawString(String str,int x,int y) setColor (Color c) setFont (Color c) Description Draws a line between (x1,y1) and (x2,y2) passed as parameters Draws a rectangle or specified width and height at a specified location Draws a circle or an ellipse that fills within a rectangle of specific coordinates Draws the text given as a specified string Sets the specified color of the graphics context Sets the specified font of the graphics context

Color Constants
Color.BLACK Color.DARK_GRAY Color.GRAY Color.PINK Color.ORANGE Color.LIGHT_GRAY Color.WHITE Color.MAGENTA Color.CYAN Color.BLUE Color.RED

Color.YELLOW Color.GREEN

Reserve Words
abstract boolean break byte case catch char class const do double else if package synchronized this implements private import

protected throw public return short static strictfp super switch throws transient true try void volatile while

extends instanceof false final finally float for int interface long native new null

continue goto default assert

83

Department of ECE GCE Kannur

Computer Programming Lab

84

Department of ECE GCE Kannur

Computer Programming Lab

Unclean C Source Codes

85

Department of ECE GCE Kannur

Computer Programming Lab

86

Department of ECE GCE Kannur

Computer Programming Lab

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; } 87 Department of ECE GCE Kannur

Computer Programming Lab 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; 88 Department of ECE GCE Kannur

Computer Programming Lab 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 #include #include #include <stdio.h> <stdlib.h> <float.h> <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; 89 Department of ECE GCE Kannur

Computer Programming Lab for(n=2;n<14;n+=2){ sum+=sign * pow1(v,n)/fact(n); //printf("\n%d - %lf / %ld\n",n,pow1(v,n),fact(n)); sign=sign * -1; } } return sum; } double pow1(float x, int y) { int i=1; double pow=1; for( i=1;i<=y;i++) pow=pow * x; return pow; } long fact(int n){ int i; long fact=1; for(i=2;i<=n;i++) fact = fact * i; return fact; }

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; } 90 Department of ECE GCE Kannur

Computer Programming Lab 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"); 91 Department of ECE GCE Kannur

Computer Programming Lab 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++) 92 Department of ECE GCE Kannur

Computer Programming Lab printf("%lf\t",b[i][j]); } cofact(a,3,b); d=determinant(a,3); printf("\n\nDeteminant %lf",d); Transpose(b,3); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) b[i][j]=b[i][j]/d; } printf("\n\n"); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) printf("%lf\t",b[i][j]); } } void cofact(double a[][3],int n,double b[][3]) { int i,j,ii,jj,i1,j1; double det; double c[3][3]; for(i=0;i<3;i++) for(j=0;j<3;j++) c[i][j]=0; for (j=0;j<n;j++){ for (i=0;i<n;i++){ i1 = 0; for (ii=0;ii<n;ii++) { if (ii == i) continue; j1 = 0; for (jj=0;jj<n;jj++) { if (jj == j) continue; c[i1][j1] = a[ii][jj]; j1++; } i1++; } det = determinant(c,n-1); b[i][j] = pow(-1.0,i+j+2.0) * det; } } } double determinant( double a[][3], int n ) { int i, j, j1, j2; double d = 0; double m[3][3]; for(i=0;i<3;i++) for(j=0;j<3;j++) m[i][j]=0; if (n == 2) d = a[0][0]*a[1][1] - a[1][0]*a[0][1]; else { d = 0; for (j1 = 0; j1 < n; j1++ ) {

93

Department of ECE GCE Kannur

Computer Programming Lab 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; }

94

Department of ECE GCE Kannur

Computer Programming Lab

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); } 95 Department of ECE GCE Kannur

Computer Programming Lab void edit_file(char * name, int newNo) { FILE * fp; Student std; int pos=search(name)-1; if(pos<0) return; fp=fopen("std.dat","rb+"); fseek ( fp ,pos*sizeof(Student) , SEEK_SET ); std.no=newNo; strcpy(std.name,name); fwrite (&std , sizeof(Student) , 1,fp ); fclose(fp); } main() { write_file(); display_file(); edit_file("AKHIL",101); display_file(); return 0; }

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 {

96

Department of ECE GCE Kannur

Computer Programming Lab 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) {

97

Department of ECE GCE Kannur

Computer Programming Lab 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; }

98

Department of ECE GCE Kannur

Computer Programming Lab

We appreciate your comments and corrections. Send your comments and suggestions to:

christy@gcek.ac.in baburajmadathil@gcek.ac.in abduljaleel@gcek.ac.in

99

Department of ECE GCE Kannur

You might also like