Vous êtes sur la page 1sur 113

# BASIC Language

PRACTICAL NO: 1
Aim:- Introduction to BASIC language.
Problem Definition: -To Theory:
The BASIC was first developed at Dartmouth University by John Kemeny and Thomas Kurtz and Introduced on May 1, 1964. BASIC stands for Beginner's All-purpose Symbolic Instruction Code and is an easy-to-understand programming language that was popular during 1970 - 1980. Their aim was to create a language that would be easy, have few rules to learn and would facilitate the teaching of programming to beginners. The eight design principles of BASIC were: 1. Be easy for beginners to use. 2. Be a general-purpose programming language. 3. Allow advanced features to be added for experts (while keeping the language simple for beginners). 4. Be interactive. 5. Provide clear and friendly error messages. 6. Respond quickly for small programs. 7. Not to require an understanding of computer hardware. 8. Shield the user from the operating system. describe the basic language features, language keywords, syntax in brief and write a program to accept and display the name of a user.

## 1.1 Character Set :

BASIC provides following character sets: Letters Digits Special characters Blank Quote :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. :012345 6789 :+-*()=.,\$ : In the text we shall denote blank by the character ^. : (single quote) or (double quote)

## 1.2 Expressions, Numbers and variables:

Expression in BASIC look like mathemeatical formulas and are formed from numbers, variables, operations and functions. A number may contain upto nine digits with or without a decimal point and possibly with a minus sign. EXAMPLE: 5 2.5 123456789 .123456789 -123456

A variable in BASIC is denoted by any letter, or by any letter followed by a digit. Variables are assigned a value by LET or READ statements EXAMPLE: A X N5 X0 K9 COST X(6)

Expressions are formed by combing variables and numbers together with arithmetic operators and parenthesis. EXAMPLE: (A1 + X)*(B - C) In addition to the arithmetic operations, some standard functions may be used. Following are the standard BASIC functions. Functions name SIN(X) COS(X) TAN(X) ATN(X) EXP(X) ABS(X) LOG(X) SQR(X) INT(X) RND(X) Purpose Sine of X Cosine of X Tangent of X arctangent( in radiance) of X natural exponential of X, eX absolute value of X, |X| Natural logarithm of X Square root of X Integer part of X Random value.

## 1.3 Data types in BASIC

Data Types INTEGER LONG SINGLE Suffix % & ! Explanation A 16 bit signed integer variable. A 32 bit signed integer variable. A single precision 32 bit floating point variable. A double precision 64 bit floating point variable. A variable length string variable.

DOUBLE

STRING

## 1.4 Declaring variables

The DIM statement is used to specify a data type for a variable. Variables declared should not end with a suffix. The syntax is as follows: DIM variable AS type Example: DIM userrname AS STRING DIM age AS INTEGER username = "John Smith" age = 23 The code above is equivalent to username\$ = "John Smith" age% = 23

## 1.5 Elementary BASIC statements

All lines in a program starts with a line number. These serve to identify lines in a program, each one of this is called statements. Thus a program is made up of statements most of which are instructions to be performed by the computer. Line number also tell the order in which the statements are performed by the computer. Before the program is run by the computer, it sorts out and edits the program, putting the statements into the order specified by their line numbers. Statements in BASIC are as explained below: 1) LET Form: <Line number> LET <variable> = <expression> Example: 100 LET X=X+1

Comment: It is used to perform certain computation and assign a value to a certain variable. 2) READ Form: <Line number> READ <List of Variables> Example: 150 READ X, Y, Z(K+I, J)

Comment: A READ statement causes the variables listed in it to be given in order the next available numbers in the collection of DATA statements. 3) DATA Form: <Line number> DATA <List of numbers> Example: 300 DATA 4, 2, 1.5

Comment: Before the program is run, the computer takes all the DATA statements in the order in which they appear and creates a large data block. Each time a READ statement is encountered the data block is supplies the next available number of numbers. 4) PRINT Form: <Line number> PRINT <List of expressions to be printed> Example: 100 print X,Y, Z, B*B-4*A*C, EXP(LOG(17))

## Form: <Line number> PRINT <any string to be printed>

Example: 150 PRINT BASIC Program Comment: Numerical quantities prined need not be simple variables, they may be any expressions. There may be any number of expressions appeared by commas, but they will be printed 5 to a line. Example: 200 PRINT X=, X,Y=, Y Comment: Labels and expressions may appear in the same print statement. 5) END Form: <Line number> END Example: 999 END Comment: An END statement is required in all programs. It must also be the statement with the highest line number in the program. 6) REM Form: REM <Any string of characters whatsoever> Example: 10 REM This is the end of Program Comment: This statement is used to give the comment in a program. 7) GOTO Form: <line number > GOTO <line number> Example: 150 GOTO 75 Comment: It is also called unconditional go to, it is used to interrupt the normal sequence of executing statements in the increasing order of their line numbers. 8) CLS Form: <line number> CLS Example: 10 CLS Comment: It is used to clear (clean) the computer screen. It can be written at any line into a program. 9) LOCATE Form: <line number>LOCATE [row], [col]

row is the screen line number, a numeric expression within the range of 1 to 25. col is the screen column number, a numeric expression within the range of 1 to 40, or 1 to 80. Example: 10 LOCATE 6,18 Comment: It is used to move the cursor to a specified position on the active screen.

Sample Program:
Program that will print Hello World in the output.

10 REM Program to print the hello message 20 REM on the output screen infinitely 30 CLS 40 PRINT Hello All 50 PRINT Welcome to BASIC World 60 END Output:

PRACTICAL NO: 2
Aim: - To implement various operators in BASIC.
Problem Definition:- Write a program to find the cube of a number entered by the user. Theory:
Programming languages generally support a set of operators that are similar to operations in mathematics. A language may contain a fixed number of built-in operators (e.g. + - * = in C and C++), or it may allow the creation of programmer-defined operators. The specification of a language will specify the precedence and associatively of the operators it supports. Most programming language operators take one or two operands, with a few supporting more operands (e.g., the ?: operator in C). The position of the operator with respect to its operands may be prefix, infix or postfix.

## 2.1 Operators in BASIC:

1) Arithmetic operators: + * / ^ 2) Relational Operators = <> > < >= <= 3) Logical operators NOT AND OR XOR EQV Addition Subtraction Multiplication Division Exponential Equal Not equal Greater than Less than Greater than or equal to Less than or equal to

## 2.2 Getting user input at run-time

Two commands or functions that allow you to get user input at run-time are:

## The INPUT statement The INKEY\$ function

1. The INPUT statement The INPUT statement reads data from the user and stores it to a memory variable. The syntax is as follows: INPUT [prompt] ; [variable] Or INPUT [prompt] , [variable] Or INPUT [variable] Example: DIM yourname AS STRING PRINT "Enter your name:"; INPUT yourname PRINT "Hello"; yourname; ". Have a nice day!" 2. The INKEY\$ function The INKEY\$ function reads a character from the keyboard. Its main advantage over the INPUT appropriate in games. Example: The program below displays a sentence repeatedly until the Escape (Esc) key is pressed. DO PRINT "Press the escape (Esc) key to stop!" LOOP UNTIL INKEY\$ = CHR\$(27)

Sample Program:
Program to perform arithmetic operation like Addition, Subtraction, Multiplication and Division of two numbers. REM PROGRAM ON ARITHMETIC OPERATORS REM PROGRAM TO FIND ADDITION SUBTRACTION MULTIPLICATION AND DIVISION REM OF TWO NUMBERS DIM N1 AS INTEGER DIM N2 AS INTEGER DIM SUM AS INTEGER DIM DIFF AS INTEGER DIM PROD AS INTEGER DIM DIVI AS SINGLE CLS INPUT "ENTER TWO NUMBERS SEPARATED BY A COMMA:"; N1, N2 LET S = N1 + N2 LET D = N1 - N2 LET P = N1 * N2 LET Q = N1 / N2 PRINT "THE SUM IS ", S PRINT "THE DIFFERENCE IS ", D PRINT "THE PRODUCT IS ", P PRINT "THE QUOTIENT IS ", Q END OUTPUT:

PRACTICAL NO: 3
Aim: - To implement various control structures in BASIC.
Problem Definition: - Write a program to find greatest of three numbers. Theory:
3.1) Loop control structures
The computer normally executes instructions of a program one after other unless it is instructed otherwise. The order of execution can be controlled by various instructions. Basically there are two types of transfer of control: Unconditional transfer of control Conditional transfer of control

Unconditional transfer : a) GOTO statement. Syntax: Form: <line number> GOTO <line number> Example: 150 GOTO 75 Conditional Transfer: a) IF - THEN - ELSE statement Syntax: IF condition1 THEN [ List of instructions to be executed if condition1 is met] END IF Or IF condition1 THEN [ List of instructions to be executed if condition1 is met ] ELSE [ List of instructions to be executed if condition1 is not met ] END IF

Or IF condition1 THEN [ Do what if to do condition1 is met ] ELSEIF condition2 THEN [ Do what if to do condition1 is not met and condition2 is met] ELSE [ Do what if neither condition1 nor condition2 are met ] END IF Example: CLS PRINT "Enter your score in maths: "; INPUT score IF Score >= 40 THEN PRINT "You have passed the test." ELSE PRINT "You have failed the test." END IF b) SELECT CASE statement: Syntax: SELECT CASE testexpression CASE expressionlist1 [statementblock-1] CASE expressionlist2 [statementblock-2]]... CASE ELSE [statementblock-n]] END SELECT Example: PRINT "1. Play Tennis" PRINT "2. Play Cards" PRINT "3. Exit" INPUT "Enter your choice"; choice SELECT CASE choice CASE 1 PRINT "You have chosen to play Tennis" CASE 2 PRINT "You have chosen to play Cards" CASE 3

## 3.2 ) Loop control structures

As repeating a process is a fundamental thing in writing a computer program. Thus BASIC language provides a set of loop control structures, these are used to execute a set of statements repeatedly. Following are the loop control structures available in a BASIC language. a) The FOR NEXT Statement The FOR NEXT statement is used to repeat a block of instructions a specified number of times. The syntax is as follows: FOR counter = start TO end [STEP increment] [block of instructions] NEXT In the FOR NEXT statement a block of instructions is executed a number of times. The value of the variable counter is incremented by 1 until it equals to the value of end. The variable counter, by default, increases by 1. You can change the rate at which the variable counter increments after each revolution by using the STEP parameter: Example: DIM counter AS INTEGER FOR counter = 1 TO 10 PRINT counter NEXT b) The DO LOOP statement The DO - LOOP statement executes a block of instructions while or until a condition is true. The syntax is: DO [List of instructions] LOOP UNTIL condition is met or DO [List of instructions] LOOP WHILE condition is met

As in the FOR - NEXT statement counter is incremented automatically, in case of DO LOOP we have to increment the counter explicitly. Example: 'This program displays a sentence 5 times CLS DIM counter AS INTEGER counter = 0 DO PRINT "Hello! How are you" counter = counter + 1 LOOP UNTIL counter = 5

c) The WHILE WEND statement The WHILE WEND statement is another way to execute a loop. In this the condition is checked before executing a loop Syntax: WHILE condition [List of instructions] WEND Example: DIM x AS INTEGER x=0 WHILE x < 5 x=x+1 PRINT x WEND

Sample Program:
Program to check whether the number entered by the user at run time is prime or not. REM PROGRAM TO FIND WHETHER THE NUMBER ENTERED BY THE USER REM IS PRIME OR NOT 'CLS PRINT INPUT "ENTER A NUMBER ? ", N PRINT 'Test if multiple of 2 D = N - 2 * INT(N / 2) IF D = 0 THEN GOTO 100 'Test if multiple of 3 D = N - 3 * INT(N / 3) IF D = 0 THEN GOTO 100 'Test if multiple of 6i-1 and 6i+1 from i=6 to sqr(N)+1 FOR I = 6 TO INT(SQR(N)) + 1 STEP 6 D = N - (I - 1) * INT(N / (I - 1)) IF D = 0 THEN GOTO 100 D = N - (I + 1) * INT(N / (I + 1)) IF D = 0 THEN GOTO 100 NEXT I PRINT " Prime number.": END 100 PRINT " Not a prime number." END Output:

PRACTICAL NO. 4
Aim:- To implements the concept of functions.
Problem Definition: - Write a program to convert temperature from Celsius to farhenite Theory:
In making large programs, we may need to repeat parts of the code again and again. Functions and subroutines/procedures are subprograms. Once defined they can be used any number of times in a program. They provide the feature of reusability of code and provide modularity. Thus subprograms make the task of writing and understanding complex program easier.

## 4.1) Procedure vs. Function

A procedure DOES something and does not return anything for the programmer. For example, a procedure might be used to set the screen mode and palette. A function does something and RETURNS a value. For example, if we need to find the average of two values, you might write a function that takes in two numbers and returns the average.

4.2) Functions
To create function open the Edit menu and select "New Function...". A small dialog box opens prompting for the name of the Function. You may use any alphanumeric characters (A-Z, 0-9) as long as start with a letter. (This is the same concept as for all variables.) Type in a name that is descriptive of the code that will be within the function.

In the image above, the new function name will be "average". When you press enter after the new name, you are automatically switched to the "average" function window. The editor contains nothing more than: FUNCTION average END FUNCTION

To view functions, click View --> Subs and the dialog box appears with all the subs and functions to choose from. Or we can also use F2 key. Syntax: FUNCTION name [(parameterlist)] [STATIC] [statementblock] name = expression [statementblock] END FUNCTION Name :The name of the function and the data type it returns, specified by a data-type suffix (%, &, !, #, or \$). Parameterlist : One or more variables that specify parameters to be passed to the function when it is called: variable[( )] [AS type] [, variable[( )] [AS type]]... variable type A Basic variable name. The data type of the variable (INTEGER, LONG, SINGLE, DOUBLE, STRING, or a user-defined data type). STATIC :Specifies that the values of the function's local variables are saved between function calls. Expression :The return value of the function. When you call the function, you can specify that an argument's value will not be changed by the function by enclosing the argument in parentheses.

4.3) Subroutines:
The same method can be used for creating subroutines, but while selecting from edit select New SUB. Syntax:

Procedure. SUB name[(parameterlist)] [STATIC] [statementblock] END SUB Name :Name of the SUB procedure, up to 40 characters long, with no data type suffix. Parameterlist :One or more variables that specify parameters to be passed to the SUB procedure when it is called: variable[( )] [AS type] [, variable[( )] [AS type]]... variable type A Basic variable name. The data type of the variable (INTEGER, LONG, SINGLE, DOUBLE, STRING, or a user-defined data type). STATIC : Specifies that the values of the SUB procedure's local variables are saved between function calls. When you call the SUB procedure, you can specify that an argument's value will not be changed by the procedure by enclosing the argument in parentheses.

Sample Program:
Program to find the factorial of a given number. DECLARE FUNCTION factorial! (n!) INPUT "Factorial of"; n PRINT factorial(n) END FUNCTION factorial (n) IF n = 1 THEN factorial = n ELSE factorial = n * factorial(n - 1) END IF END FUNCTION Output:

PASCAL Language

PRACTICAL NO. 5
Aim:- Introduction to PASCAL Language.
Problem Definition: - To describe the basic language features, language keywords,
syntax in brief and implement a program to find circumference of a circle.

Theory:
The earliest computers were programmed in machine code and assembly. This type of programming is tedious and error prone, as well as extremely difficult to understand and modify. Programming is a time-consuming and expensive process. High level languages were developed to resolve this problem. High level languages provide a set of instructions that read like English, but can be translated by a program called a compiler into machine code. Pascal is one such language. The Pascal language was named for Blaise Pascal, a French mathematician who was a pioneer in computer development history. In 1641, at the age of eighteen, Pascal constructed the first arithmetical machine, arguably the first computer. Niklaus Wirth completed development of the original Pascal programming language in 1970(ISO 7185). He based it upon the block structured style of the Algol programming language. Easy syntax, rather verbose, yet easy to read. Ideal for teaching. Strongly typed. Procedural. Case insensitive. Allows nested procedures. Easy input/output routines built-in.

## 5.1) Pascal Tokens:

Tokens are the basic lexical building blocks of source code: they are the words of the language: characters are combined into tokens according to the rules of the programming language. There are five classes of tokens: reserved words These are words which have a fixed meaning in the language. They cannot be changed or redefined. identifiers These are names of symbols that the programmer defines. They can be changed and re-used. They are subject to the scope rules of the language. operators These are usually symbols for mathematical or other operations: +, -, * and so on. separators This is usually white-space. constants Numerical or character constants are used to denote actual values in the source

code, such as 1 (integer constant) or 2.3 ( oat constant) or String constant (a string: a piece of

## 5.2) Data Types

The various data types available in PASCAL are summarized below. 1. Simple-type Data a. Standard data types i. Integer ii. Real iii. Char iv. Boolean b. User defined data types i. Enumerated ii. Subrange 2. String-type data 3. Structured-type data a. Arrays b. Records c. Sets d. Files 4. Pointer-type data Variables: An identifier whose value is change during the execution of a program is called a variable. Syntax: VAR name1, name2, name3 : type; Example: VAR row,col:integer;

5.3) Operators
Pascal supplies six classes of operators:

Arithmetic operators Bit operators Boolean operators Set operators Relational operators String operators

## Arithmetic Operators Operator Operation

+ * / div mod

Operands
integer integer integer integer

Result

or real integer or real or real integer or real or real integer or real or real real
integer integer

## truncated division integer modulo

integer

Bit Operators Operator Operation ~ & | ! bitwise not bitwise and bitwise or Operands Result integer integer integer integer integer integer integer

## bitwise or (same as |) integer

Boolean Operators Operator Operation and and then not or or else Conjunction Operands Result boolean boolean boolean boolean boolean boolean

Similar to boolean and boolean Negation Disjunction Similar to boolean or boolean boolean boolean

Set Operators Operator Operation + * in Set union Set difference Set intersection Operands Any set type Any set type Any set type Result Same as operands Same as operands Same as operands

Member of a specified set 2nd arg:any set type boolean 1st arg:base type of 2nd arg

Relational Operators Operator Operation = <> < <= > >= Equal Not equal Less than Less than or equal Greater than Greater than or equal Operand Any real, integer, boolean, char, record, array, set, or pointer type Any real, integer, boolean, char, record, array, set, or pointer type Any real, integer, boolean, char, string, or set type Any real, integer, boolean, char, string, or set type Any real, integer, boolean, char, string, or set type Any real, integer, boolean, char, string, or set type Results boolean boolean boolean boolean boolean boolean

String Operators With the string concatenation operator, the plus sign (+), you can concatenate any combination of varying, array of char, constant strings, and single characters. Precedence of Operators Operators ~, not, *, /, div, mod, and, &, |, !, +, -, or, Precedence Highest . .

=, <>, <, <=, >, >=, in, . or else, and then Lowest

## 5.4) Data input and output

Input is what comes into the program. It can be from the keyboard, the mouse, a file on disk, a scanner, a joystick, etc. The basic format for reading in data is: read (Variable_List); Variable_List is a series of variable identifiers separated by commas. read treats input as a stream of characters, with lines separated by a special end-of-line character. readln, on the other hand, will skip to the next line after reading a value, by automatically moving past the next end-of-line character: readln (Variable_List); For writing data to the screen, there are also two statements write (Argument_List); writeln (Argument_List);

## 5.5) Pascal Program structure

The basic structure of a Pascal program is: PROGRAM ProgramName (FileList); CONST (* Constant declarations *) TYPE (* Type declarations *) VAR (* Variable declarations *) (* Subprogram definitions *) BEGIN (* Executable statements *) END.

Sample Program:
Program to print Hello World in the output. program Hello; begin writeln ('Hello, world.') end. Output:

PRACTICAL NO. 6
Aim:- To implement conditional control structures .
Problem Definition: - Write a program to check whether the student is pass or fail
depending on the marks secured by the students.

Theory:
Pascal is a structured programming language, meaning that the flow of control is structured into standard statements. It allows two types of conditional control structures. 1. The IF structure 2. The CASE Structure

6.1) IF structure
It is a simple conditional control structures that allows some action to be taken only if a given logical statement has a specified value. Syntax a) if Boolean Expression then Statement b) if Boolean Expression then Statement1 else Statement2

## 6.2) CASE Structure

It allows some particular group of statements to be chosen from several available groups. The selection will be based upon the curreent value of the expression referred to as the selector. Syntax: CASE expression OF Case label list1: statement1; Case labellist2: statement2; ... Case label listn: statement; END;

Sample Program:
Write a complete program to find the day respective of day number enter by the user if the day number enter by the user is not valid then prompt the user to enter the day number again. program day; label start; var dayno:integer; begin start: writeln('enter the day number from 1 to 7'); readln(dayno); case dayno of 1:writeln('today is sunday'); 2:writeln('today is monday'); 3:writeln('today is tuesday'); 4:writeln('today is wednesday'); 5:writeln('today is thursday'); 6:writeln('today is friday'); 7:writeln('today is saturday'); else begin writeln('invalid day number'); writeln('try again'); goto start; end; end; end. Output:

PRACTICAL NO: 7
Aim:- To implement the concept of loop control structures.
Problem Definition: - Write a program to display the output in following way.
1 1 1 1 1 2 2 2 2

3 3 3

4 4

Theory:
Many programs demands for executing the group of consecutive statements repeatedly. To have this facility Loop control structures are used. Looping means repeating a statement or compound statement over and over until some condition is met. There are three types of loops:

fixed repetition - only repeats a fixed number of times pretest - tests a Boolean expression, then goes into the loop if TRUE posttest - executes the loop, then tests the Boolean expression

## 7.1) The for loop

In Pascal, the fixed repetition loop is the for loop. Syntax: for index := StartingLow to EndingHigh do statement; The index variable must be of an ordinal data type. We can use the index in calculations within the body of the loop, but you should not change the value of the index.

In the for-to-do loop, the starting value MUST be lower than the ending value, or the loop will never execute! If you want to count down, you should use the for-downto-do loop: for index := StartingHigh downto EndingLow do statement; In Pascal, the for loop can only count in increments (steps) of 1.

## 7.2) The while do Loop

In Pascal the pretest loop is the while . Do loop. Syntax: while BooleanExpression do statement; The loop continues to execute until the Boolean expression becomes FALSE. In the body of the loop, we must somehow affect the Boolean expression by changing one of the variables used in it. Otherwise, an infinite loop will result: The WHILE ... DO loop is called a pretest loop because the condition is tested before the body of the loop executes. So if the condition starts out as FALSE, the body of the while loop never executes

## 7.3) The repeat until loop

In Pascal the posttest loop is the repeat until loop. repeat statement1; statement2; until Boolean Expression; In a repeat loop, compound statements are built in we don't need to use begin-end. Also, the loop continues until the Boolean expression is TRUE, whereas the while loop continues until the Boolean expression is FALSE. This loop is called a posttest loop because the condition is tested after the body of the loop executes. The REPEAT loop is useful when you want the loop to execute at least once, no matter what the starting value of the Boolean expression is.

Sample Program:
Program to find the Fibonacci series up to first ten numbers. program Fibonacci; var Fibonacci1, Fibonacci2 : integer; temp : integer; count : integer; begin (* Main *) writeln ('First ten Fibonacci numbers are:'); count := 0; Fibonacci1 := 0; Fibonacci2 := 1; repeat write (Fibonacci2:7); temp := Fibonacci2; Fibonacci2 := Fibonacci1 + Fibonacci2; Fibonacci1 := Temp; count := count + 1 until count = 10; writeln; end. (* Main *)

Output:

PRACTICAL NO: 8
Aim:-To implement concept of functions.
Problem Definition: Write a program to find the sum of following series
Sum= 1/1! + 2/2! + 3/3! + 4/4! + .n/n!

Theory:
Function is a special type of procedures which returns a value. Procedures accept data or variables when they are executed. Functions also accept data, but have the ability to return a value to the procedure or program which requests it. Functions are used to perform mathematical tasks.

## 8.1 Characteristics of functions

A function

begins with the keyword function is similar in structure to a procedure somewhere inside the code associated with the function, a value is assigned to the function name a function is used on the right hand side of an expression can only return a simple data type

8.2 Functions
Syntax function Function_name (Parameter list) : return_data_type; begin statement1 statement2 end After the parenthesis which declare those variables accepted by the function, the return data type (preceeded by a colon) is declared.

Example:

function ADD_TWO ( value1, value2 : integer ) : integer; begin ADD_TWO := value1 + value2 end;

## The following line demonstrates how to call the function,

result := ADD_TWO( 10, 20 ); thus, when ADD_TWO is executed, it equates to the value assigned to its name (in this case 30), which is then assigned to result.

Sample Program:

## Program to find the sum of following series

Sum= 1 + 22 + 32 + 44 + .n2
Program series_program; Var sum, n, i:integer; Function series(n1:integer):integer; Begin sum:=0; for i=1 to n1 do sum:=sum + i*i; series:=sum ; End; Begin writeln(enter number upto which series is to be generated); readln(n); sum:=series(n); writeln(sum of the series is, sum); End.

Output:

FORTRAN Language

Practical No. 9
Aim: Introduction to FORTRAN Language.
Problem Definition:- Implement a program that will print This is my First program in
the output.

## Theory :1.1) What is Fortran?

Fortran is a general purpose programming language, mainly intended for mathematical computations in e.g. engineering. Fortran is an acronym for Formula Translation, and was originally capitalized as FORTRAN. However, following the current trend to only capitalize the first letter in acronyms, we will call it Fortran. Fortran was the first ever high-level programming language. The work on Fortran started in the 1950's at IBM and there have been many versions since. By convention, a Fortran version is denoted by the last two digits of the year the standard was proposed. Thus we have

## Fortran 66 Fortran 77 Fortran 90 (95)

The most common Fortran version today is still Fortran 77, although Fortran 90 is growing in popularity. Fortran 95 is a revised version of Fortran 90 which (as of early 1996) is expected to be approved by ANSI soon. There are also several versions of Fortran aimed at parallel computers. The most important one is High Performance Fortran (HPF), which is a de-facto standard. Users should be aware that most Fortran 77 compilers allow a superset of Fortran 77, i.e. they allow non-standard extensions. In this tutorial we will emphasize standard ANSI Fortran 77.

## 1.2) Why learn Fortran?

Fortran is the dominant programming language used in engineering applications. It is therefore important for engineering graduates to be able to read and modify Fortran code. From time to time, so-called experts predict that Fortran will rapidly fade in popularity and soon become extinct. These predictions have always failed. Fortran is the most enduring computer programming language in history. One of the main reasons Fortran has survived and will survive is software inertia. Once a company has spent many man-years and perhaps millions of dollars on a software product, it is unlikely to try to translate the software to a different language. Reliable software translation is a very difficult task.

1.3) Portability
A major advantage Fortran has is that it is standardized by ANSI and ISO (see footnotes). Consequently, if your program is written in ANSI Fortran 77, using nothing outside the standard, then it will run on any computer that has a Fortran 77 compiler. Thus, Fortran programs are portable across machine platforms. Footnotes: ANSI = American National Standards Institute ISO = International Standards Organization

## 1.4) Writing Simple Fortran Programs

This section is intended to get you started writing elementary programs in Fortran. We will not attempt to explain all the peculiarities of the Fortran programming language. We will try and explain the logic behind those parts of the language which are easily explained, and treat as arbitrary rules to be learned by rote those which are either actually arbitrary, or too time consuming to attempt to explain.

Sample Program:
To describe the basic features of the FORTRAN language, language keywords, syntax in brief and implement a program that will print Hello World in the output. Here is the world's simplest `useful' Fortran program: C Hello World Program PRINT *, 'Hello world' STOP END C-> It is used for commenting a line, write C in first coloumn.

Output:

## 1.5) Program structure

The program starts with the word `program' simply because F90 programs must do so. The program must also be given a name, so we have called it `hello'. It must also end with the words `end program', hence the last line. The use of the program name in the last line is optional in most F90 dialects, but it is good practice to include it. print *, 'HelloWorld' What this does is to print on the computer screen the text: `Hello world' This instruction is formally called a `procedure call'. It causes something to be done; what is does is predefined by the word `print' which the language recognises as meaning `print or otherwise display some information'. What is printed is determined by the programmer-supplied text included between the two quote symbols. (NB these are both the same single closing quote on the keyboard.) Any text (except for another single quote!) which appears there will be `printed out'. A piece of text in quotes is refered to as a `text string' or `character string' or sometimes just a `string'. And the `*,' ? For the time being, please just accept that it is necessary. If you leave it out, the program will not work! For future reference: you will encounter other types of procedure call in the language. All have the properties that (a) what is done is predefined and associated with the name of the procedure, here `print'. How it is done, or with or to what is usually specified by the programmer, as is the case here with the text to be printed.

## 1.6) Running the program

To use the system you need to execute the very short batch file G77SETUP.BAT to set up the G77 environment. It adds the folder that holds the executable files, \G77\BIN, to your path and defines an environment variable LIBRARY_PATH that points to the library folder \G77\LIB (this variable tells the compiler where to find the library files.) The default locations are assumed to be in the folder C:\G77 . If a user prefers to install G77 in another drive (e.g., in F:\G77) then the file G77SETUP.BAT must be corrected. The file G77SETUP.BAT _must_ be run _everytime_ a user opens a "console" window (aka, "DOS" window) in order to run G77. The command G77 will compile and link your program and produce an executable that can only be run under Windows 95 or Windows NT,not under DOS . A simple demonstration program called hello.f. To compile this just use: G77 hello.F This generates a file A.EXE, which can be executed simply using A The compiler by default names the produced executable file as "A.EXE". If one wishes to override this default behavior, then one can specify the desired name of the produced executable, using the "-o" compiler option. E.g., to produce an executable with the name hello.exe the above command should be: G77 hello.F -o hello.EXE Things to Try with the Simple Program Load the program into a text editor, e.g. by typing: textedit hello.f Change the message Change the text in the quotes to something else. `Save' the program file from the editor, compile it again and type a.out, which will execute the new version of the program.

Add another message You can include as many `print' instruction of the form shown as you like, provided that each is either on a separate line. Try adding another message this way. EPCF90 and most versions of Fortran also allow instructions to be separated by a semicolon `;'. Thus the following are equivalent: 1) print *, 'This is my 1st program..' print *, 'Hello!' STOP END 2) print *, 'This is my 1st program..' ; print *, 'Hello!' STOP END

Try these two forms. Add a message to the reader of the program It cannot be stressed too strongly that a good program is easy to follow and makes sense to the reader! You can add `comments' which do not cause the program to take anny additional action, but which help the reader to follow what is going on. Any line or part of a line beginning with an exclamation mark `!' is treated in this way. Arithmetic in Programs As well as printing messages, computer can of course do arithmetic. Here is a simple program to do a calculation: C C program arithmetic program to do a calculation print *, 'This program calculates 23.6*log(4.2)/(3.0+2.1)' print *, 23.6*log(4.2)/(3.0+2.1) STOP END

## Save, compile and run this program.

OUTPUT : -

1.7) Variables
This is a key section which you must understand before proceeding further! Seek help if you are not entirely clear about it after trying the examples. Consider the following program program variable real :: x ! This defines a variable called x ! x = 23.6*log(4.2)/(3.0+2.1) ! This gives it a value ! print *, 'The value of x is ', x ! .. and then print it out end program The overall effect of this is essentially the same as the previous program, except that it involves a new kind of entity, vital to effective programming, called a variable. It is so called because the value which it takes can be changed by equating it to different expressions on the right hand side of an instruction which always takes the form: variable name = expression The form of this assignment instruction is identical to that of evaluating a formula, It is convenient to think of a variable in this context as being the same as a variable in a set of equations, although it is in fact a more general and flexible concept than that. At the very least, the use of variables facilitates the writing and developing of programs, and makes them easier to understand. Consider the use of a program to evaluate expressions involving variables, whose values depend on other variables, i.e. a set of equations. This involves a slightly modified version of the previous program:

## 1.8) Program Variable

real :: x, y ! This defines variables called x and y ! y = sqrt(23.6) ! calculate y x = 23.6*log(1.0+y)/(3.0+y) ! calculate x which involves y ! print *, 'The value of x is ', x print *, 'The value of y is ', y ! .. and then print them out STOP END

The instruction: real :: x, y is called a declaration of the variables x and y. It consists of the word real to indicate that the variables will be used to represent general or real numbers (as opposed to whole numbers or integers, which can also be be used in certain circumstances, see later). It is followed by a list of the names to be given to the variables. These can be any combination of letters or numbers, but must start with a letter. The names may not include spaces, but the underscore character `_' may be used and is very useful in improving readability. The two colons `::' are part of the illogical richness of Fortran. They may sometimes be left out, but this is not advised. You should try to choose variable names which help the readers understanding of the program. In general you should not use meaningless name like `x' and `y', unless these have been used in the specification of the problem. Where standard symbols exist, e.g. `P' for pressure or `T' for temperature, use these with variants, e.g. T1, T2 or use descriptive names, e.g. T_reactor, Column_Pressure. Names can be up to 256 characters long, but typing very long names becomes tedious (and they can be mis-spelled).

1.9) Parameters
The programming language also allows for the use of parameters which are named entities, like variables, but are given a value once, and may not have their values changed. Parameters are declared in a similar manner to variables, but must be given their constant values at the same time as they are declared.

More Programs
The first programs you write will almost certainly not be correct! You practice in `debugging' programs, Program (1) which will fail to compile. And Program (2) which may appear to be correct but will fail.

1) program crunch ! there is/are something(s) wrong with this program ! find out what and correct it real :: a, b, c a = 10.0 b = 23.5 c = a*b print *,'What is wrong with this? print *, 'Nothing now..' print *, c is, c ! STOP END

2) program crunch_again ! This program has a different kind of error from the first one real :: a,b,c print *,'Does this work?' a = 10.0 c = 3.5+a c = c*b b = 23.0 print *, 'a, b and c are:', a, b, c ! STOP END

Result: - We have studied about how to compile a program in fortran compiler and
understand the basic features.

Practical No: 10
Aim:- To implement the concept of various control structures.
Problem Definition:Write a program that reads in an arbitrary integer and determines if it is a whether the entered number is Odd or Even number or Not.

## Theory :2.1) IF-THEN-ELSE-END IF

The most general form of the IF-THEN-ELSE-END IF statement is the following: IF (logical-expression) THEN statements-1 ELSE statements-2 END IF where statements-1 and statements-2 are sequences of executable statements, and logicalexpression is a logical expression. The execution of this IF-THEN-ELSE-END IF statement goes as follows:

the logical-expression is evaluated, yielding a logical value if the result is .TRUE., the statements in statements-1 are executed if the result is .FALSE., the statements in statements-2 are executed after finish executing statements in statements-1 or statements-2, the statement following END IF is executed.

## 2.2) SELECT CASE Statement

Fortran has one more selective execution statement, SELECT CASE, and could be very handy if it is used properly. The SELECT CASE statement is also usually referred to as the CASE statement. The following is its syntactic form: SELECT CASE (selector) CASE (label-list-1) statements-1 CASE (label-list-2) statements-2 CASE (label-list-3) statements-3 .............

## 2.3) General DO-Loop with EXIT

The general DO-loop is actually very simple. But, to use it properly, you need to be very careful, since it may never stop. The general DO-loop has a form as follows: DO Statements END DO Between DO and END DO, there are statements. These statements are executed over and over without any chance to get out of the DO-loop. Here is an example, REAL :: x, y, z DO READ(*,*) x y = x*x z = x*x*x WRITE(*,*) x, ' square = ', y, ' cube = ', z END DO One iteration of this loop consists of reading a value for x, computing its square and cube to y and z, respectively, and displaying the results. Then, the execution goes back to the top and executes the four statements again. Consequently, this loop is executed over and over and has no chance to stop at all. A loop that never stops is usually referred to as an infinite loop. To stop the iteration of a DO-loop, we need something else.

## 2.4) The EXIT Statement

The EXIT is as simple as writing down the word EXIT. It is used to bail out the containing loop. DO statements-1 EXIT statements-2 END DO In the above, statements-1 is executed followed by the EXIT statement. Once the EXIT statement is reached, the control leaves the inner-most DO-loop that contains the EXIT statement. Therefore, in the above case, statements-2 will never be executed.

Since it must be some reason for bailing out a DO-loop, the EXIT statement is usually used with an IF or even an IF-THEN-ELSE-END IF statement in one of the following forms. Note that these are not the only cases in which you can use EXIT. DO statements-1 IF (logical-expression) EXIT statements-2 END DO

DO statements-1 IF (logical-expression) THEN statements-THEN EXIT END IF statements-2 END DO For each iteration, statements in statements-1 are executed, followed the evaluation of the logical-expression. If the result is .FALSE., statements instatements-2 are executed. This completes one iteration and the control goes back to the top and executes statements-1 again for next iteration. If the result of evaluating logical-expression is .TRUE., the first form will executes EXIT, which immediately stops the execution of the DO-loop. The next statement to be executed is the one following END DO.

Sample Program :An positive integer no. is greater than or equal to 2 then it is a prime number, if the only divisor of this integer is 1 and itself.Write a program that reads in an arbitrary integer and determines if it is a prime number or Not.

PROGRAM Prime INTEGER :: Number INTEGER :: Divisor READ(*,*) Number IF (Number < 2) THEN WRITE(*,*)'Illegal input' ELSE IF (Number == 2) THEN WRITE(*,*)Number, ' is a prime' ELSE IF (MOD(Number,2) == 0) THEN WRITE(*,*) Number, ' is NOT a prime' ELSE Divisor = 3 DO IF (Divisor*Divisor>Number.OR.MOD(Number,Divisor)==0) EXIT Divisor = Divisor + 2 END DO IF (Divisor*Divisor > Number) THEN WRITE(*,*) Number, ' is a prime' ELSE WRITE(*,*) Number, ' is NOT a prime' END IF END IF STOP END OUTPUT:-

Result:- In this way have studied about how to perform condition operation by using If Else.

Practical No :11
Aim:To implement the concept of subprograms.

Problem Defination :- Write a program to calculate the Qube of number. Theory :Designing Functions

3.1) Syntax
In addition to intrinsic functions, Fortran allows you to design your own functions. A Fortran function, or more precisely, a Fortran function subprogram, has the following syntax: type FUNCTION function-name (arg1, arg2, ..., argn) IMPLICIT NONE [specification part] [execution part] [subprogram part] END FUNCTION function-name Here are some elaborations of the above syntax:

The first line of a function starts with the keyword FUNCTION. Before FUNCTION, the type gives the type of the function value (i.e., INTEGER,REAL, LOGICAL and CHARACTER) and after FUNCTION is the name you assign to that function. Following the function-name, there is a pair of parenthesis in which a number of arguments arg1, arg2, ..., argn are separated with commas. These arguments are referred to as formal arguments. Formal arguments must be variable names and cannot be expressions. Here are a examples: 1. The following is a function called Factorial. It takes only one formal argument n and returns an INTEGER as its function value. INTEGER FUNCTION Factorial(n) 1. The following is a function called TestSomething. It takes three formal arguments a, b and c, and returns a LOGICAL value (i.e., .TRUE. or.FALSE.) as its function value. LOGICAL FUNCTION TestSomething(a, b, c) A function must be ended with END FUNCTION followed by the name of that function. Between FUNCTION and END FUNCTION, there are the IMPLICIT NONE, specification part, execution part and subprogram part. These are exactly identical to that of a PROGRAM.

If a function does not need any formal argument, it can be written as type FUNCTION function-name () IMPLICIT NONE [specification part] [execution part] [subprogram part] END FUNCTION function-name where arg1, arg2, ..., argn are left out. But, the pait of parenthesis must be there.

3.2) Semantics
The meaning of a function is very simple:

A function is a self-contained unit that receives some "input" from the outside world via its formal arguments, does some computations, and then returns the result with the name of the function. Thus, since the function returns its result via the name of the function, somewhere in the function there must exist one or more assignment statements like the following: function-name = expression where the result of expression is stored to the name of the function. However, the name of the function cannot appear in the right-hand side of any expression. That is, the name of the function, used as a variable name, can only appear in the left-hand side of an expression. This is an artificial restriction in this course only.

A function receives its input values from formal arguments, does computations, and saves the result in its name. When the control of execution reaches END FUNCTION, the value stored in the name of the function is returned as the function value. To tell the function about the types of its formal arguments, all arguments must be declared with a new attribute INTENT (IN). The meaning of INTENT (IN) indicates that the function will only take the value from the formal argument and must not change its content. Any statements that can be used in PROGRAM can also be used in a FUNCTION.

## Sample Program :- You will want to use a function if you need to do a

complicated calculation that has only one result.Write a program to calculate the squre of number.Example program where the sum was called and then squared in one line. C PROGRAM SUBDEM REAL A,B,C,SUM,SUMSQ CALL INPUT( + A,B,C) CALL CALC(A,B,C,SUM,SUMSQ) CALL OUTPUT(SUM,SUMSQ) END SUBROUTINE INPUT(X, Y, Z) REAL X,Y,Z PRINT *,'ENTER TWO NUMBERS => ' READ *,X,Y,Z RETURN END SUBROUTINE CALC(A,B,C, SUM,SUMSQ) REAL A,B,C,SUM,SUMSQ SUM = A + B + C SUMSQ = SUM **2 RETURN END SUBROUTINE OUTPUT(SUM,SUMSQ) REAL SUM, SUMSQ PRINT *,'The sum of the numbers you entered are: ',SUM PRINT *,'And the square of the sum is:',SUMSQ RETURN END

OUTPUT:-

Result:- With this exercise we have understand how the function perform the operations.

Practical No :12
Aim:To implement parameter passing methods .

Problem Definition:- Write a program to swap the two numbers without using third
variable using call by value and call by reference mechanism.

Theory:4.1) Intoduction
Each individual parameter can be passed by value or by reference (which places the address of the parameter on the stack). In Fortran, C, and C++, all addresses are the same size (4 bytes), so there is no passing by near or far reference. You need to make sure that for every call, the calling program and the called routine agree on how each parameter is passed. Otherwise, the called routine receives bad data. The C/C++ technique for passing parameters is always the same, regardless of calling convention: All parameters are passed by value, except for arrays, which are translated into the address of the first member. To pass data by reference, pass a pointer to it. The Fortran technique for passing parameters changes depending on the calling convention specified. By default, Fortran passes all data by reference (except the hidden length argument of strings, which is a special case). If the Cor STDCALL attribute is used, the default changes to passing all data by value. In Fortran, use the VALUE and REFERENCE attributes to specify pass by value or pass by reference. In mixed-language programming, it is a good idea to always specify passing technique explicitly rather than relying on defaults. For example, the following C declaration sets up a call to a Fortran subroutine: extern void __stdcall TESTPROC( int ValParm, int *RefParm ); In the following example, the definition of TESTPROC in Fortran declares how each parameter is passed. TheREFERENCE attribute is not strictly necessary in this example, but using it is a good idea, in case you later change the calling convention. SUBROUTINE TESTPROC( VALPARM, REFPARM ) INTEGER*4 VALPARM [VALUE] INTEGER*4 REFPARM [REFERENCE] END

The following table summarizes parameter-passing defaults. Note that an array name in C is equated to its starting address. Therefore, arrays are passed by reference. To pass an array by value, declare a structure with the array as its only member.

## 4.2) C/C++ and Fortran Defaults for Passing Parameters Language

C/C++ Fortran variable variable [VALUE]

By value
* variable

By reference

variable

## 4.3) Call by value

The initial value of a call by value parameter is the value of the corresponding argument(i.e. the value of the argument is copied into the parameter as part of calling the procedure). As this mechanism is very common, a short example should suffice: Although obvious to those familiar with call by value (i.e. probably everyone reading this write up), I'd like to emphasize a few points in order to be able to refer back to them in the following sections:

The assignment to w within by value doesn't affect the value of a. The fact that the value of the argument is copied into w means that the argument can be an expression (i.e. an r value) as illustrated by the second call to by value)

## 4.4) Call by reference

The call by reference mechanism is fundamentally different than the mechanisms discussed above. A call by reference parameter is a reference to the argument. As such, any use within a procedure of a call by reference parameter is actually a use of the argument. The name of this mechanism, call by reference, is a reflection of how the word reference is usually used instead of use. e.g. any reference within a procedure to a call by reference parameter is actually a reference to the argument.

Optimizing compiler writers don't much like call by reference as it can be very difficult to determine what impact a change to a global variable might have on call by reference parameters and vice-versa. For example, the compiler may have to assume that any assignment to a global variable could have modified the argument associated with any call by reference parameter whose type is the same as the global variable. Similarly, it may have to assume that any assignment to a call by reference parameter could have modified any global variable of the same type as the parameter in addition to possibly modifying the argument associated with any other call by reference parameter of the same type.

Sample Program: Write a program to swap the two numbers using call by value and call by
reference mechanism.

subroutine iswap (a, b) integer a, b Local variables integer tmp tmp = a a=b b = tmp return end

program callex integer m, n m=1 n=2 PRINT *,'Before Swap function calling:' PRINT *,'m => ',m PRINT *,'n => ',n PRINT *,'After Swap function called:' call iswap(m, n) PRINT *,'m => ',m PRINT *,'n => ',n write(*,*) m, n stop end

OUTPUT:-

Result:- With the help to this program, we studied how to call a function by various ways.

`C` Language

Practical No. 13
Aim: To implement the concept of various storage classes
Theory: Problem Defination:
With the help of static variable write a program to print following output. a = 15, sa = 15 a = 15, sa = 20 a = 15, sa = 25 a = 15, sa = 30 a = 15, sa = 35 a = 15, sa = 40 a = 15, sa = 45 a = 15, sa = 50 a = 15, sa = 55 a = 15, sa = 60

## 13.1) STORAGE CLASS IN C

From C compilers point of view, a variable name identifies some physical location within the computer where the string of bits representing the variables value is stored. There are basically two kinds of locations in a computer where such a value may be kept Memory and CPU registers. It is the variables storage class that determines in which of these two locations the value is stored. Moreover, a variables storage class tells us: (a) Where the variable would be stored. (b) What will be the initial value of the variable, if initial value is not specifically assigned.(i.e. the default initial value). (c) What is the scope of the variable; i.e. in which functions the value of the variable would be available. (d) What is the life of the variable; i.e. how long would the variable exist. There are four storage classes in C: (a) Automatic storage class (b) Register storage class (c) Static storage class (d) External storage class

## 13.2) AUTOMATIC STORAGE CLASS

features of a variable defined to have an automatic storage class are as under: The Storage Memory. Default initial value An unpredictable value, which is often called a garbage value. Scope Local to the block in which the variable is defined. Life Till the control remains within the block in which the variable is defined. Following program shows how an automatic storage class variable is declared, and the fact that if the variable is not initialized it contains a garbage value. main( ) { auto int i, j ; printf ( "\n%d %d", i, j ) ; } The output of the above program could be... 1211 221 where, 1211 and 221 are garbage values of i and j. When you run this program you may get different values, since garbage values are unpredictable. So always make it a point that you initialize the automatic variables properly, otherwise you are likely to get unexpected results. The keyword for this storage class is auto, and not automatic.

## 13.3) REGISTER STORAGE CLASS

The features of a variable defined to be of register storage class are as under: Storage - CPU registers. Default initial value - Garbage value. Scope - Local to the block in which the variable is defined. Life - Till the control remains within the block in which the variable is defined. Variables can be declared as a register as follows: register int var;

## 13.4) STATIC STORAGE CLASS

The features of a variable defined to have a static storage class are as under: Storage Memory. Default initial value Zero. Scope Local to the block in which the variable is defined. Life Value of the variable persists between different function calls.

Sample Program :
main() { fun(); fun(); fun(); } fun() { static int i=3; i++; printf(\n%d,i); } Output: 4 5 6

## 13.5) EXTERNAL STORAGE CLASS

The features of a variable whose storage class has been defined as external are as follows: Storage Memory. Default initial value Zero. Scope Global. Life As long as the programs execution doesnt come to an end. External variables are declared outside all functions. Declaration for external variable is as follows: extern int var;

Sample Program :
Program to find out area of a rectangle which implements the concept of global variable #include<stdio.h> #include<conio.h> int l=5, b=10,area; main() { area =rect(l,b); printf("area of rectangle is %d", area); } rect() { area= l *b; }

Output :
Area of a rectangle is 50

Sample Program :
Program to implement recursive function to find sum of digits of a given number using static variable #include<stdio.h> #include<conio.h> main() { int n,s; clrscr(); printf("\nEnter any 5 digit no"); scanf("%d",&n); s=recsum(n); printf("\nsum of digits of %d is %d ", n,s); getch(); } recsum(int n) { static int s=0; int r; if(n==0) return 0; r=n%10; s+=r; recsum(n/10); return s; }

Output : If 5 digit no. is 12345 then sum of its digit is 15. Result : Thus we studied different storage classes and compare the features of a variable
i.e. its storage, default initial value and scope and life.

Practical No.14
Aim: Implementation using conditional and unconditional transfer of control.
Problem Definition:
Write a program to identify whether given number is prime or odd or even.

Theory:
14.1) Conditional Statement:
In C Conditional statement controls the sequence of statement execution, depending on the value of a integer expression. If-else construct is a conditional statement in C. Syntax: { <statement list1> } else { <statement list2> } The else clause is optional. If integer expression in if is true then statement list1 will execute. If it is false statement list2 will execute skipping statement list1. if ( <integer expression> )

## 14.2) Unconditional statement:

An unConditional statement allows you to direct the program's flow to another part of your program without evaluating conditions. goto statement is used as unconditional statement in C. it is used to alter the program execution sequence by transferring the control to some other part of the program. Most unconditional statements requires a programmer defined keyword called a label. A label is like a bookmark in your program. A label is identified by 2 colons (:) suffixed. The goto statement redirects the program's flow to the specified label (suffixed by a single colon) without any expectation of returning to the goto statement.

Syntax: goto a1. . a1: .. Where a1 is the label. Sample Program: identify whether given number is prime or odd or even. #include <stdio.h> #include<conio.h> int main() { int num1,num2,num3; printf(\enter three numbers); scanf(%d%d%d,&num1,&num2,&num3); if(num1>num2) { If(num1>num3) printf(\n %d is greatest,num1); else printf(\n%d is greatest,num3); } else If(num2>num3) printf(%d is greatest,num2); return 0; }

Output:

Program for unconditional statement: main() { int value,i; i=0; while(i<=10) { printf("enter number:"); scanf("%d",&value); if(value<=0) { printf("Zero or -ve value found"); goto error; } i++; } error: printf("Input data error"); } Output:

Practical No.15
Aim:Implementation using Bitwise operators.
Problem Defination:
Write a program in C for finding value of following expression. res= ~((A&B)| (C^D)) Accept values of A,B ,C and D from user.

Theory:
A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. Following are bitwise operators.

## Introduction: 15.1) Logical Operators:

15.1.1) NOT

The bitwise NOT, or complement, is a unary operation that performs logical negation on each bit, forming the ones' complement of the given binary value. Digits which were 0 become 1, and vice versa. The bitwise NOT operator is represented by "~" (tilde). For ex. In C NOT of variable var1 is represented as ~var1.

15.1.2) OR
A bitwise OR takes two bit patterns of equal length, and produces another one of the same length by matching up corresponding bits (the first of each; the second of each; and so on) and performing the logical inclusive OR operation on each pair of corresponding bits. In each pair, the result is 1 if the first bit is 1 OR the second bit is 1 OR both bits are 1; otherwise, the result is 0. Bitwise OR in C is represented by | (pipe) For example: A | B.

15.1.3) XOR
A bitwise exclusive or takes two bit patterns of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if the two bits are different, and 0 if they are the same. In the C programming language family, the bitwise XOR operator is "^" (caret).

15.1.4) AND
A bitwise AND takes two binary representations of equal length and performs the logical AND operation on each pair of corresponding bits. In each pair, the result is 1 if the first bit is 1 AND the second bit is 1. Otherwise, the result is 0. In the C programming language family, the bitwise AND operator is "&" (ampersand).

## 15.2) Shift Operators

In C-inspired languages, the left and right shift operators are "<<" and ">>", respectively. The number of places to shift is given as the second argument to the shift operators. For example, X = y << 2; Assigns x the result of shifting y to the left by two bits. X = 4 >> y Assigns x the result of shifting y to the right by 4 bits.

Sample Program:Write a program in C for finding value of following expression. res= ((A&B)| (C^D)) Accept values of A,B ,C and D from user. #include<stdio.h> #include<conio.h> void main() { int A,B,C,D,res; clrscr(); printf("\nenter values of a,b,c,d"); scanf("%d%d%d%d",&A,&B,&C,&D); res=((A&B)|(C^D)); printf("A= %d\tB= %d\tC= %d\tD=%d\n\tres= %d",A,B,C,D,res); getch(); } Output:

## Result: Result of given expression.

Practical No.16
Aim:Implementation of file handling operations.
Problem Defination :
Write a program in C for creating sequential file containing library data for 3 records having following fields. Also perform read, search and append operation. Book_name, author_name, book_price.

Theory:
A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. In C, we input/output data using streams. We can associate a stream with a device (i.e. the terminal) or with a file. C supports two types of files: o Text Stream Files o Binary Stream Files Text streams consist of sequential characters divided into lines. Each line terminates with the newline character (\n). Binary streams consist of data values such as integers, floats or complex data types, using their memory representation. A file is an independent entity with a name recorded by the operating system. A stream is created by a program. To work with a file, we must associate our stream name with the file name recorded by the OS.

## 16.1) Steps in Processing a File

1. Create the stream via a pointer variable using the FILE structure: FILE* fp; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file.

## 16.2) Standard I/O functions in C

1. fopen() Syntax: fopen(filename, mode); The file mode tells C how the program will use the file. The filename indicates the system name and location for the file. We assign the return value of fopen to our pointer variable:

## fp = fopen(MYFILE.DAT, w); fp = fopen(A:\\MYFILE.DAT, w);

2. fclose() When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. To close a file, we use fclose and the pointer variable: fclose(fp); 3. fscanf() This function is used to read data from file. Its syntax is fscanf(fp,%s%d,&name,&id); 4. fprintf() This function is used to write data into file. Its syntax is fprintf(fp,%s%d, name,id); 5. fseek() This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place within a file and modify it. Syntax is: fseek(FILE *stream, long int offset, int whence) The value of whence must be one of the constants SEEK_SET, SEEK_CUR, or SEEK_END, to indicate whether the offset is relative to the beginning of the file, the current file position, or the end of the file, respectively. Offset is number of bytes to skip over. The offset can be either positive or negative, denting forward or backward movement in the file.

Sample Program: #include<stdio.h> #include<conio.h> struct bakery_item { char name[10]; int qty; float price; }bitem; int main() { FILE *fp; int ch,i; clrscr(); fp=fopen("item.txt","wb"); if(fp==NULL) { printf("\n\t\topen error"); return; } else { for(i=0;i<2;i++) { printf("\nEnter item name"); scanf("%s",&bitem.name); printf("\nEnter item quantity"); scanf("%d",&bitem.qty); printf("\nEnter item price"); scanf("%f",&bitem.price); fwrite(&bitem,sizeof(bitem),1,fp); } } fclose(fp); printf("\n\t1.display\n\t2.append"); printf("\nEnter your choice:"); scanf("%d",&ch); switch(ch) { case 1: fp=fopen("item.txt","rb"); if(fp==NULL) { printf("\n\t\tdisplay error"); return;

} while(fread(&bitem,sizeof(bitem),1,fp)!=NULL&&!feof(fp)) printf("\n%s\t%d\t%f",bitem.name,bitem.qty,bitem.price); fclose(fp); break; case 2: fp=fopen("item.txt","a+"); if(fp==NULL) { printf("\n\t\tappend error"); return; } printf("\nEnter item name"); scanf("%s",&bitem.name); printf("\nEnter item quantity"); scanf("%d",&bitem.qty); printf("\nEnter item price"); scanf("%f",&bitem.price); fwrite(&bitem,sizeof(bitem),1,fp); fseek(fp,0,SEEK_SET); while(fread(&bitem,sizeof(bitem),1,fp)!=NULL&&!feof(fp)) printf("\n%s\t%d\t%f",bitem.name,bitem.qty,bitem.price); fclose(fp); break; } getch(); return; }

## Fig: output of append operation Result: Result of all file operations.

C++ Language

Practical No.17
Aim: Introduction to Object oriented programming language (C++)
Problem Definition:Create a Class called CARD that maintains a library card catalog
entry. Class stores a books Title, Author and Number of copies for the book. Use public member function Store ( ) to store books information and a public member function called Show ( ) to display information

Theory:
Following concepts are used in Object oriented programming Objects. Classes. Data abstraction and Encapsulation. Inheritance. Polymorphism. Dynamic binding. Message passing.

17.1) Objects:
Objects are basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. Each object has the data and code to manipulate the data and theses object interact with each other. Ex: If fruit has been defined as a class then the statement Fruit mango; Will create an object mango belonging to the class fruit.

17.2) Classes:
The entire set of data and code of an object can be made a user-defined data Type with the help of a class. Once a class has been defined, we can create any Number of objects belonging to the classes. Classes are user-defined data types and behave like built-in types of the programming language. A class is a way to bind the data and its associated functions together.It allows the data(and functions)to be hidden.A class specification has two parts. 1. Class declaration 2. Class function definations.

The general form of a class declaration is class class_name { Private: Variable declarations; Functions declarations; Public: Variable declarations; Functions };

A simple class example: Class item { int number; float cost; //variables declaration private by defaults public: void getdata(int a,float b); // functions declarations using prototype void putdata(void); };

17.3) Encapsulation
Wrapping up of data and function within the structure is called as encapsulation

## 17.4) Data abstraction

The insulation of data from direct access by the program is called as data hiding or information binding.The data is not accessible to the outside world and only those functions, which are wrapped in the class, can access it.Abstraction refers to the act of representing essential features without including the background details or explanations.

17.5) Inheritance
Inheritance is the process by which objects of one class acquire the properties of another class. It supports the concept of hierarchical classification. It provides the idea of reusability.

## 17.6) Dynamic binding or late binding?

Binding refers to the linking of a procedure to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at the run-time.

17.7) Polymorphism.
Polymorphism is the ability to take more than one form. An operation may Exhibit different behaviors in different. The behavior depends upon the type of data used.

## 17.8) Message passing

A message for an object is a request for execution of a procedure and therefore will invoke a function (procedure) in the receiving object that generates the desired result.Message passing involves specifying the name of the object,the name of the function(massage) and the information to be sent. Following code explain the simple concept like class and object.

Program:Define class student to store the name, roll no. and branch of student. It contains member functions to read & print data. Test this class with main () to read & print information for single student object. #include<iostream.h> #include<conio.h> class student { private: char name[25]; int roll_no; char branch[10]; public: void read() { cout<<"Enter name of student"<<endl; cin>>name; cout<<"Enter roll no. of student"<<endl; cin>>roll_no; cout<<"Enter branch of student"<<endl; cin>>branch; } void print()

{ cout<<"Name of student:"<<name<<endl; cout<<"Roll no. of student:"<<roll_no<<endl; cout<<"Branch of student:"<<branch<<endl; } }; void main() { student s; clrscr(); s.read(); cout<<"Information of student"<<endl; s.print(); getch(); }

## Sample Input and Output

Enter name of student Saurabh Enter roll no. of student 3N-54 Enter branch of student IT Information of student Name of student: Saurabh Roll no. of student: 3N-54 Branch of student:- IT

Practical No:18
Aim: To implement the concept of Inheritance.
Problem Definition: Create a base class BASE which contains M & N as data members.
It contains three member functions Input_MN( ), Get_M( ) and Display_M( ) to accept the value of M & N, to return the value of M and to display the value of M. Create one another class called DERIVED, which is derived from BASE in PUBLIC mode. DERIVED contains P as data members. Include the member function Multiply ( ), which multiplies the value of P and M and Display( ) to show the value of P.

Theory:
Inheritance is the process by which objects of one class acquire the properties of another class. It supports the concept of hierarchical classification. It provides the idea of reusability. We can add additional features to an existing class without modifying it by deriving a new class from it.

The main advantages of the inheritance are 1) Reusability of the code 2) To increase the reliability of the code 3) To add some enhancements to the base class

## 18.2 ) Single Inheritance

Single inheritance is the process of creating new classes from an existing base class.The existing class is known as the base class and the newly created class is called as a derived class. Defining the derived class The declaration of a singly derived class is as that same of an ordinary class.A derived class consist of the following components 1) The keyword class 2) The name of the derived class 3) A single colon

4) The type of derivation (provate,public,protected) 5) The name of the base class or parent class 6)The remainder of the class defination Following is the syntax of the derived class declration

18.3 ) Syntax
Class derived_class_name : private/public/protected base_class_name { Private: //data members Public: //data members //methods Protected: //data members };

## 18.4 ) Types of the Inheritance

1) If a single class is derived from a single base class is called single Inheritance. In below example A is called base class and B is called derived class Ex:
A

class A{..}; //base class class B:public A{}; //B derived from A

2) If a class is derived from more than one base class, it is called multiple Inheritance
A B

3) If a number of classes are derived from a single base class then it is called hierarchical inheritance.
A

Ex: class A{..}; //base class class B:public A{}; //B derived from A class C:public A{.}; //C derived from A class D:public A{.}; //D derived from A 4) If a class is derived from a class, which in turn is derived from another class,is called multilevel inheritance. This process can be extended to any number of levels. Ex: class A{..}; //base class class B:public A{}; //B derived from A class C:public B{.}; //C derived from B
A

5) Hybrid Inheritance is the combination of one or more types of inheritance. Ex Combination of Multilevel Inheritance Multiple inheritance.

6)
A

Program:
// Single inheritance

A program consists of a base class and a derived class. The base class data members are name,roll number.The derived class data members are height and weight.The members functions getdata( ) are used to get information and display( ) used todisplay the contents on the screen #include<iostream.h> #include<conio.h> class B // base class { private: char name[20]; int rollno; public: void getadta( ) ; void display( ); }; class P : public B { private: float height; // derived class

float weight; public: void getdata( ); void display ( ); }; void B :: getdata( ) { cout<< Enter a name \n; cin>> name; cout<<Enter roll number \n cin>> rollno; } void B : :display( ) { cout <<Name=<<name; cout<<Roll No= << rollno; } Void P : : getdata( ) { cout<<Enter height \n; cin>>height; cout<<Enter weight \n; cin>>weight; } void P :: display( ) { B :: display( );

cout<<Height=<<height; cout<<Weight= <<weight; } void main( ) { cout<<Enter the following information; P p; //object creation p.getdate( ); p.display ( ); }

## Sample Input and output

Enter the following information Enter a name abc Enter roll number 15 Enter height 134.45 Enter weight 66.67 Name= abc Roll No= 15 Height=134.45 Weight=66.67

Practical No:19
Aim:To implement the concept of polymorphism
Problem definition: Create a class BASE that contains virtual function show( ) and Create a
class derived that having base class as BASE ,that override the virtual show( ).

## Theory: 19.1 ) Introduction

Polymorphism is the ability to use an operator or method in different ways. Polymorphism gives different meanings or functions to the operators or methods. Poly, referring to many, signifies the many uses of these operators and methods. A single method usage or an operator functioning in many ways can be called polymorphism. Below is a simple example of the above concept of polymorphism: 6 + 10 The above refers to integer addition. The same + operator can be used with different meanings with strings: "Exforsys" + "Training" The same + operator can also be used for floating point addition: 7.15 + 3.78

## 19.2 )Types of polymorphism:

Polymorphism is a powerful feature of the object oriented programming language C++. A single operator + behaves differently in different contexts such as integer, float or strings referring the concept of polymorphism. The above concept leads to operator overloading. The concept of

Sample Program:
In the below example, the member function for making the Type should be made as virtual to the base class. #include <stdio.h> class item { public: virtual void price() { printf("In item::price()\n"); } virtual void type() { printf("In item::type()\n"); } void display(); }; void item::display(){printf("In item::display()\n");} class microwave:public item { public: void price() { printf("Microwave::Price()\n"); }

void type() { printf("Microwave::type()\n"); } }; class computer:public item { public: void price() { printf("Compuer::Price()\n"); } }; class radio:public item { public: void type() { printf("radio::type()\n"); } }; int main() {

## microwave m1; computer c1; radio r1;

item *i=&m1; i->price(); i->type(); printf("\n"); i=&c1; i->price(); i->type(); i->display(); printf("\n"); i=&r1; i->price(); i->type(); printf("\n");

## microwave m2; i=&m2; i->price(); i->type(); i->display(); printf("\n"); return 0;

} The Output of this Program would be: Microwave::Price() Microwave::type() Compuer::Price() In item::type() In item::display() In item::price() radio::type()

## Microwave::Price() Microwave::type() In item::display()

Practical No:20
Aim:To implement the concept of
Template

Problem definition:Create a vector class template for performing the scalar product of int
type vectors as well as float type vectors.

Theory:
Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

## 20.1 ) Types of Template:

1. Function templates 2. Class templates

## 20.1.1) Function templates

A function template behaves like a function except that the template can have arguments of many different types (see example). In other words, a function template represents a family of functions. For example, the C++ Standard Library contains the function template max(x, y) which returns either x or y, whichever is larger. max() could be defined like this, using the following template: template <class myType> myType max (myType a, myType b) { return (a>b?a:b); } One definition of a function which works with different kinds of data types. A function template does not occupy space in memory. The actual definition of a function template is generated when the function is called with a specific data type. The function template does not save memory. #include <iostream> int main() {

// This will call max <int> (by argument deduction) std::cout << max(3, 7) << std::endl; // This will call max<double> (by argument deduction) std::cout << max(3.0, 7.0) << std::endl; // This type is ambiguous; explicitly instantiate max<double> std::cout << max<double>(3, 7.0) << std::endl; return 0; } This function template can be instantiated with any copy-constructible type for which the expression (y < x) is valid. For user-defined types, this implies that the less-than operator must be overloaded. 20.1.2) Class templates A class template provides a specification for generating classes based on parameters. Class templates are commonly used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments.[1] The C++ Standard Library contains many class templates, in particular the containers adapted from the Standard Template Library, such as vector. For example: template <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } };

The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to declare an object of this class to store two integer values of type int with the values 115 and 36 we would write: mypair<int> myobject (115, 36); this same class would also be used to create an object to store any other type: mypair<double> myfloats (3.0, 2.18); 20.1.3) Template Instantiation

When the compiler generates a class, function or static data members from a template, it is referred to as template instantiation. A class generated from a class template is called a generated class. A function generated from a function template is called a generated function. A static data member generated from a static data member template is called a generated static data member.

The compiler generates a class, function or static data members from a template when it sees an implicit instantiation or an explicit instantiation of the template. Consider the following sample. This is an example of implicit instantiation of a class template. template &ltclass T> class Z { public: Z() {} ; ~Z() {} ; void f(){} ; void g(){} ; };

int main() { Z&ltint> zi ; //implicit instantiation generates class Z&ltint> Z&ltfloat> zf ; //implicit instantiation generates class Z&ltfloat> return 0 ;

Sample Program:
Create the required classes by plugging in the actual type for the type parameters. This process is commonly known as "Instantiating a class". Here is a sample driver class that uses the Stack class template. #include &ltiostream> #include "stack.h" using namespace std ; void main() { typedef Stack&ltfloat> FloatStack ; typedef Stack&ltint> IntStack ;

FloatStack fs(5) ; float f = 1.1 ; cout << "Pushing elements onto fs" << endl ; while (fs.push(f)) { cout << f << ' ' ;

f += 1.1 ; } cout << endl << "Stack Full." << endl << endl << "Popping elements from fs" << endl ; while (fs.pop(f)) cout << f << ' ' ; cout << endl << "Stack Empty" << endl ; cout << endl ;

IntStack is ; int i = 1.1 ; cout << "Pushing elements onto is" << endl ; while (is.push(i)) { cout << i << ' ' ; i += 1 ; } cout << endl << "Stack Full" << endl << endl << "Popping elements from is" << endl ; while (is.pop(i)) cout << i << ' ' ; cout << endl << "Stack Empty" << endl ; } Program Output Pushing elements onto fs

## 1.1 2.2 3.3 4.4 5.5 Stack Full.

Popping elements from fs 5.5 4.4 3.3 2.2 1.1 Stack Empty

## Beyond Syllabus JAVA

Practical No: 1
Aim: Introduction to Java Language.
Theory: 1.1) Introduction
Java was started as a project called "Oak" by James Gosling in June 1991. Gosling's goals were to implement a virtual machine and a language that had a familiar C-like notation but with greater uniformity and simplicity than C/C++. The first public implementation was Java 1.0 in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms. It was fairly secure and its security was configurable, allowing for network and file access to be limited. The major web browsers soon incorporated it into their standard configurations in a secure "applet" configuration. popular quickly. New versions for large and small platforms (J2EE and J2ME) soon were designed with the advent of "Java 2". Sun has not announced any plans for a "Java 3". In 1997, Sun approached the ISO/IEC JTC1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process. Java remains a proprietary de facto standard that is controlled through the Java Community Process. Sun makes most of its Java implementations available without charge, with revenue being generated by specialized products such as the Java Enterprise System. Sun distinguishes between its Software Development Kit (SDK) and Runtime Environment (JRE) which is a subset of the SDK, the primary distinction being that in the JRE the compiler is not present. There were five primary goals in the creation of the Java language: 1. It should use the object-oriented programming methodology. 2. It should allow the same program to be executed on multiple operating systems. 3. It should contain built-in support for using computer networks. 4. It should be designed to execute code from remote sources securely. 5. It should be easy to use by selecting what was considered the good parts of other objectoriented languages. To achieve the goals of networking support and remote code execution, Java programmers sometimes find it necessary to use extensions such as CORBA, Internet Communications Engine, or OSGi.

## 1.2) Object orientation

The first characteristic, object orientation ("OO"), refers to a method of programming and language design. Although there are many interpretations of OO, one primary distinguishing idea is to design software so that the various types of data it manipulates are combined together with their relevant operations. Thus, data and code are combined into entities called objects. An object can be thought of as a self-contained bundle of behavior (code) and state (data). The principle is to separate the things that change from the things that stay the same; often, a change to some data structure requires a corresponding change to the code that operates on that data, or vice versa. This separation into coherent objects provides a more stable foundation for a software system's design. The intent is to make large software projects easier to manage, thus improving quality and reducing the number of failed projects.

## 1.3 ) Platform independence

The second characteristic, platform independence, means that programs written in the Java language must run similarly on diverse hardware. One should be able to write a program once and run it anywhere. This is achieved by most Java compilers by compiling the Java language code "halfway" to bytecode (specifically Java bytecode)simplified machine instructions specific to the Java platform. The code is then run on a virtual machine (VM), a program written in native code on the host hardware that interprets and executes generic Java bytecode. Further, standardized libraries are provided to allow access to features of the host machines (such as graphics, threading and networking) in unified ways. Note that, although there's an explicit compiling stage, at some point, the Java bytecode is interpreted or converted to native machine instructions by the JIT compiler.

## 1.4) Automatic garbage collection

One idea behind Java's automatic memory management model is that programmers should be spared the burden of having to perform manual memory management. In some languages the programmer allocates memory to create any object stored on the heap and is responsible for later manually deallocating that memory to delete any such objects. If a programmer forgets to deallocate memory or writes code that fails to do so in a timely fashion, a memory leak can occur: the program will consume a potentially arbitrarily large amount of memory. In addition, if a region of memory is deallocated twice, the program can become unstable and may crash. Finally, in non garbage collected environments, there is a certain degree of overhead and complexity of user-code to track and finalize allocations.

1.5) Syntax
The syntax of Java is largely derived from C++. However, unlike C++, which combines the syntax for structured, generic, andobject-oriented programming, Java was built from the ground up to be virtually fully object-oriented: everything in Java is an object with the exceptions of atomic datatypes (ordinal and real numbers, boolean values, and characters) and everything in Java is written inside a class.

1.6) Applet
Java applets are programs that are embedded in other applications, typically in a Web page displayed in a Web browser. // Hello.java import java.applet.Applet; import java.awt.Graphics; public class Hello extends Applet { public void paint(Graphics gc) { gc.drawString("Hello, world!", 65, 95); } } This applet will simply draw the string "Hello, world!" in the rectangle within which the applet will run. This is a slightly better example of using Java's OO features in that the class explicitly extends the basic "Applet" class, that it overrides the "paint" method and that it uses import statements. <!-- Hello.html --> <html> <head> <title>Hello World Applet</title> </head> <body> <applet code="Hello" width="200" height="200"> </applet> </body> </html>

An applet is placed in an HTML document using the <applet> HTML element. The applet tag has three attributes set: code="Hello" specifies the name of the Applet class and width="200" height="200" sets the pixel width and height of the applet. (Applets may also be embedded in HTML using either the object or embed element, although support for these elements by Web browsers is inconsistent.

1.7) Servlet
Java servlets are server-side Java EE components that generate responses to requests from clients. // Hello.java import java.io.*; import javax.servlet.*; public class Hello extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Hello, world!"); pw.close(); } } The import statements direct the Java compiler to include all of the public classes and interfaces from the java.io and javax.servlet packages in the compilation. The Hello class extends the GenericServlet class; the GenericServlet class provides the interface for the server to forward requests to the servlet and control the servlet's lifecycle. The Hello class overrides the service(ServletRequest, ServletResponse) method defined by the Servlet interface to provide the code for the service request handler. The service() method is passed a ServletRequest object that contains the request from the client and a ServletResponse object used to create the response returned to the client. The service() method declares that it throws the exceptions ServletException and IOException if a problem prevents it from responding to the request.

## 1.8) Lack of OO purity and facilities

Java's primitive types are not objects. Primitive types hold their values in the stack rather than being references to values. This was a conscious decision by Java's designers for performance reasons. Because of this, Java is not considered to be a pure object-oriented programming language. However, as of Java 5.0, autoboxing enables programmers to write as if primitive types are their wrapper classes, and freely interchange between them for improved flexibility. Java designers decided not to implement certain features present in other OO languages, including: * multiple inheritance * operator overloading * class properties * tuples

## 1.9) Java Runtime Environment

The Java Runtime Environment or JRE is the software required to run any application deployed on the Java Platform. End-users commonly use a JRE in software packages and Web browser plugins. Sun also distributes a superset of the JRE called the Java 2 SDK (more commonly known as the JDK), which includes development tools such as the Java compiler, Javadoc, and debugger.

Prevent Errors like --> 'javac' is not recognized as an internal or external command 1. Go to http://java.sun.com and download the latest Version of Jave SDK or any Jace SDK as per your requirement and install on your system. 2. Accept all of the defaults and suggestions, but make sure that the location where Java will be installed is at the top level of your C: drive. Click on "Finish." You should have a directory (folder) named C:\j2sdk1.5.0_04, with subfolders C:\j2sdk1.5.0_04\bin and C:\j2sdk1.5.0_04\lib 4. Modify your system variable called "PATH" (so that programs can find where Java is located). To do this for Windows 2000 or XP, either right-click on the My Computer icon or select "System" on the control panel. When the window titled "System Properties" appears, choose the tab at the top named "Advanced." Then, click on "Environment Variables." In the bottom window that shows system variables, select "Path" and then click on "Edit..." Add C:\j2sdk1.5.0_04\bin as the first item in the list. Note that all items are separated by a semicolon,

with no spaces around the semicolon. You should end up with a path variable that looks something like C:\j2sdk1.5.0_04\bin;C:\WINNT\system32;C:\WINNT;C:\WINNT\system32\Wbem For Windows 98 or ME, open the file AUTOEXEC.BAT in Notepad. You should find a line in this file that begins SET PATH=... Modify this line to add C:\j2sdk1.5.0_04\bin; immediately after the equals sign. 5. Modify or create a system variable called "CLASSPATH," as follows. In the lower "System Variables" pane choose "New..." and type in Variable Name "CLASSPATH" and value (note that it begins with dot semicolon) .;C:\j2sdk1.5.0_04\lib 6. To test Java to see if everything is installed properly, open a command window (a DOS window) and type the command "javac" The result should be information about the Usage of javac and its options. If you get a result that "'javac' is not recognized as an internal or external command, operable program or batch file" then there is a problem and Java will not work correctly. Our first application will be extremely simple - the obligatory "Hello World". The following is the Hello World Application as written in Java. Type it into a text file or copy it out of your web browser, and save it as a file named HelloWorld.java. This program demonstrates the text output function of the Java programming language by displaying the message "Hello world!". Java compilers expect the filename to match the class name A java program is defined by a public class that takes the form: public class program-name { optional variable declarations and methods public static void main(String[] args) { statements } optional variable declarations and methods }

Sample Program
In your favorite editor, create a file called HelloWorld.java with the following contents:/** Comment * Displays "Hello World!" to the standard output.*/

class HelloWorld { public static void main (String args[]) { System.out.println("Hello World!"); //Displays the enclosed String on the Screen Console } }

To compile Java code, we need to use the 'javac' tool. From a command line, the command to compile this program is: javac HelloWorld.java For this to work, the javac must be in your shell's path or you must explicitly specify the path to the program (such as c:\j2se\bin\javac HelloWork.java). If the compilation is successful, javac will quietly end and return you to a command prompt. If you look in the directory, there will now be a HelloWorld.class file. This file is the compiled version of your program. Once your program is in this form, its ready to run. Check to see that a class file has been created. If not, or you receive an error message, check for typographical errors in your source code. You're ready to run your first Java application. To run the program, you just run it with the java command: java HelloWorld

Sample Run
Hello world! The source file above should be saved as myfirstjavaprog.java, using any standard text editor capable of saving as ASCII (eg - Notepad, Vi). As an alternative, you can download the source for this tutorial. HelloWorld.java

Note: It is important to note that you use the full name with extension when compiling (javac HelloWorld.java) but only the class name when running (java HelloWorld).

## 1.11) Java Data and Variables

There are 8 primitive data types. The 8 primitive data types are numeric types. The names of the eight primitive data types are: byte short int long float double char boolean There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. There is a fundamental difference between the method used to represent integers and the method used to represent floating point numbers. i) Type byte short int long ii) Type float Integer Primitive Data Types Size 8 bits 16 bits 32 bits 64 bits Range -128 to +127 -32,768 to +32,767 (about)-2 billion to +2 billion (about)-10E18 to +10E18

Floating Point Primitive Data Types Size 32 bits Range -3.4E+38 to +3.4E+38

double 64 bits -1.7E+308 to 1.7E+308 Examples int yr = 2006; double rats = 8912 ; For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and some type of objects into primitive data. The table shows primitive types and their wrapper classes: primitive type Wrapper type byte short int long float double char boolean Byte Short Int Long Float Double Character Boolean

Variables only exist within the structure in which they are defined. For example, if a variable is created within a method, it cannot be accessed outside the method. In addition, a different method can create a variable of the same name which will not conflict with the other variable. A java variable can be thought of as a little box made up of one or more bytes that can hold a value of a particular data type:

## Syntax: variabletype variablename = data; Source Code ( demonstrating declaration of a variable )

Sample Program:
Write a program to print range of data type in Java. class example { public static void main ( String[] args ) { long x = 123; //a declaration of a variable named x with a datatype of long System.out.println("The variable x has: " + x ); } } Source Code public class MaxDemo { public static void main(String args[]) { //integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE; //real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; //other primitive types char aChar = 'S'; boolean aBoolean = true; //Display them all. System.out.println("largest byte value is " + largestByte + "."); System.out.println("largest short value is " + largestShort + "."); System.out.println("largest integer value is " + largestInteger + "."); System.out.println("largest long value is " + largestLong + "."); System.out.println("largest float value is " + largestFloat + "."); System.out.println("largest double value is " + largestDouble + "."); } } Sample Run The largest byte value is 127. The largest short value is 32767. The largest integer value is 2147483647. The largest long value is 9223372036854775807. The largest float value is 3.4028235E38. The largest double value is 1.7976931348623157E308.

Practical No. 2
Aim: To implement the concept of inheritance
Problem definition :- Write a program to implement single level and multilevel
inheritance.

## Theory:2.1) What Is Inheritance?

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

A hierarchy of bicycle classes. The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here } This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. Inheritance creates a new class definition by building upon an existing definition (you extend the original class) The new class can, in turn, can serve as the basis for another class definition all Java objects use inheritance every Java object can trace back up the inheritance tree to the generic class Object The keyword extends is used to base a new class upon an existing class Several pairs of terms are used to discuss class relationships (these are not keywords)

note that traditionally the arrows point from the inheriting class to the base class, and the base class is drawn at the top - in the Unified Modeling Language (UML) the arrows point from a class to another class that it depends upon (and the derived class depends upon the base class for its inherited code) the parent class/child class terms are not recommended, since parent and child is more commonly used for ownership relationships (like a GUI window is a parent to the components placed in it)

A derived class instance may be used in any place a base class instance would work - as a variable, a return value, or parameter to a method Inheritance is used for a number of reasons (some of the following overlap) to model real-world hierarchies to have a set of pluggable items with the same "look and feel," but different internal workings to allow customization of a basic set of features when a class has been distributed and enhancements would change the way existing methods work (breaking existing code using the class) to provide a "common point of maintenance" When extending a class, you can add new properties and methods, and you can change the behavior of existing methods (which is called overriding the methods) you can declare a method with the same signature and write new code for it

you can declare a property again, but this does not replace the original property it shadows it (the original property exists, but any use of that name in this class and its descendants refers to the memory location of the newly declared element)

The Java API is a set of classes that make extensive use of inheritance

one of the classes used in the GUI is Window - its family tree looks like:

## 2.2) Payroll with inheritance

Our payroll program could make use of inheritance if we had different classes of employees: exempt employees, non-exempt employees, and contract employees

they all share basic characteristics such as getting paid (albeit via different algorithms), withholding, having to accumulate year-to-date numbers for numerous categories but they have different handling regarding payment calculations, benefits, dependents, etc. exempt employees get a monthly salary, while nonexempt get a wage * hours, contract employees are handled similarly to nonexempt, but cannot have dependents

Also, we have already seen some duplication of effort in that our dependents store some of the same information as employees (first and last names)

they use this information for the same purposes, so it might make sense to pull that common information into a base class

## This would leave us with an inheritance scheme as follows:

Note that a scheme with ContractEmployee extending NonexemptEmployee might also be a reasonable approach

## 2.3) Derived Class Objects

You can view a derived class object as having a complete base class object inside it

lets assume that the Entity class defines the properties name, energy, and position, and methodsmoveTo() and changeEnergy() the Playable class adds a property playerID

the Wizard class adds a spells property (an array of spells they can cast) and

a castSpell() method Any Wizard object contains all the elements inside its box, include those of the base classes

so, for example, the complete set of properties in a Wizard object is: o name o energy o position o playerID o spells a Wizard reference to a Wizard object has access to any public elements from any class in the inheritance chain from Object to Wizard code inside the Wizard class has access to all elements of the base classes (except those defined asprivate in the base class - those are present, but not directly accessible) a more complete description of access levels is coming up in a few pages

Note: although it appears that a base class object is physically located inside the derived class instance, it is not actually implemented that way

## 2.4) Simple Inheritance

When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance.

Sample Program:
Write a program to implement single level and multilevel inheritance. class A { int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B extends A{ public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } void display(){ System.out.println("B"); } }

## 2.5) Multilevel Inheritance

It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can go up to any number of level. e.g. class A { int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B extends A{ void Showb(){ System.out.println("B"); } } class C extends B{ void display(){ System.out.println("C"); } public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } }

## 2.6) Java does not support multiple Inheritance Multiple Inheritance

The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.

## 2.7) Super keyword

The super is java keyword. As the name suggest super is used to access the members of the super class.It is used for two purposes in java. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class. e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.

2.8) Super.member
Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions. class A{ int a; float b; void Show(){ System.out.println("b in super class: " + b); } } class B extends A{ int a; float b; B( int p, float q){ a = p; super.b = q; } void Show(){ super.Show(); System.out.println("b in super class: " + super.b); System.out.println("a in sub class: " + a); } public static void main(String[] args){ B subobj = new B(1, 5); subobj.Show(); } }

Output:
C:\>java B b in super class: 5.0 b in super class: 5.0 a in sub class: 1

Result:- We have studied various types of inheritance in Java Language and the object and derived
classes.