Académique Documents
Professionnel Documents
Culture Documents
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.
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.
DOUBLE
STRING
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))
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.
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
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.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.
code, such as 1 (integer constant) or 2.3 ( oat constant) or String constant (a string: a piece of
5.3) Operators
Pascal supplies six classes of operators:
Arithmetic operators Bit operators Boolean operators Set operators Relational operators String operators
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
Bit Operators Operator Operation ~ & | ! bitwise not bitwise and bitwise or Operands Result integer integer integer integer integer integer 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
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
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
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.
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.
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;
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:
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.
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.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
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:
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
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:
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.
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.
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.
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.
By value
* variable
By reference
variable
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)
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
Sample Program :
main() { fun(); fun(); fun(); } fun() { static int i=3; i++; printf(\n%d,i); } Output: 4 5 6
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> )
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.
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).
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:
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.
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; }
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.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.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.
Polymorphism is of two types. They are 1) Function overloading 2) Operator overloading. Function overloading means we can use the same function name to create functions that perform a variety of different tasks. Eg: An overloaded add ( ) function handles different data types as shown below. // Declarations i. int add( int a, int b); //add function with 2 arguments of same type ii. int add( int a, int b, int c); //add function with 3 arguments of same type iii. double add( int p, double q); //add function with 2 arguments of different type C++ has the ability to provide the operators with a special meaning for a data type.This mechanism of giving such special meanings to an operator is known as Operator overloading.
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(); }
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.
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 };
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 ( ); }
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( ).
overloading is also a branch of polymorphism. When the exiting operator or function operates on new data type it is overloaded. This feature of polymorphism leads to the concept of virtual methods. 19.2.2 )Function overloading Function overloading means we can use the same function name to create functions that perform a variety of different tasks. Eg: An overloaded add ( ) function handles different data types as shown below. // Declarations i. int add( int a, int b); //add function with 2 arguments of same type ii. int add( int a, int b, int c); //add function with 3 arguments of same type iii. double add( int p, double q); //add function with 2 arguments of different type 19.2.3) Virtual functions : Polymorphism refers to the ability to call different functions by using only one type of function call. Suppose a programmer wants to code vehicles of different shapes such as circles, squares, rectangles, etc. One way to define each of these classes is to have a member function for each that makes vehicles of each shape. Another convenient approach the programmer can take is to define a base class named Shape and then create an instance of that class. The programmer can have array that hold pointers to all different objects of the vehicle followed by a simple loop structure to make the vehicle, as per the shape desired, by inserting pointers into the defined array. This approach leads to different functions executed by the same function call. Polymorphism is used to give different meanings to the same concept. This is the basis for Virtual function implementation. In polymorphism, a single function or an operator functioning in many ways depends upon the usage to function properly. In order for this to occur, the following conditions must apply: All different classes must be derived from a single base class. In the above example, the shapes of vehicles (circle, triangle, rectangle) are from the single base class called Shape. The member function must be declared virtual in the base class.
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() {
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");
} The Output of this Program would be: Microwave::Price() Microwave::type() Compuer::Price() In item::type() In item::display() In item::price() radio::type()
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.
// 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 <class T> class Z { public: Z() {} ; ~Z() {} ; void f(){} ; void g(){} ; };
int main() { Z<int> zi ; //implicit instantiation generates class Z<int> Z<float> zf ; //implicit instantiation generates class Z<float> 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 <iostream> #include "stack.h" using namespace std ; void main() { typedef Stack<float> FloatStack ; typedef Stack<int> 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
Popping elements from fs 5.5 4.4 3.3 2.2 1.1 Stack Empty
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.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.
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).
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:
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.
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:
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
Note that a scheme with ContractEmployee extending NonexemptEmployee might also be a reasonable approach
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
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"); } }
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.
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.