Top Banner
K u v e m p u U n i v e r s i t y Assignments for B.Sc.(IT) Courses Name: Student ID: I confirm that this assignment is my own work and has not been presented for assessment in any other course. ............................... [STUDENT NAME]
32
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Assignment

K u v e m p u U n i v e r s i t y

Assignments for B.Sc.(IT) Courses

Name: Student ID:

I confirm that this assignment is my own work and has not been presented for assessment in any other course.

...........................................................................[STUDENT NAME]

Page 2: Assignment

K u v e m p u U n i v e r s i t y

Subject: Algorithms Subject Code: BSIT – 41

1. Define an algorithm. What are the properties of an algorithm?

Ans: An algorithm can be defined as a sequence of definite and effective instructions, which terminates with the production of correct output from the given input.

In other words, viewed little more formally, an algorithm is a step by step formalization of a mapping function to map input set onto an output set.

While designing an algorithm care should be taken to provide a proper termination for algorithm.

Thus, every algorithm should have the following five characteristic features:

1) Finiteness: - an algorithm terminates after a finite numbers of steps.

2) Definiteness: - each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any confusion.

3) Input:- an algorithm accepts zero or more inputs

4) Output:- it produces at least one output.

5) Effectiveness:- it consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in a finite amount of time.

2. Write a note on i) devising ii) validating and iii) testing of algorithms.

Ans: (i) Devising: The process of devising an algorithm is both an art and a science. This is one part that cannot be automated fully. Given a problem description, one have to think of converting this into a series of steps, which, when executed in a given sequence solve the problem. To do this, one has to be familiar with the problem domain and also the computer domains. This aspect may never be taught fully and most often, given a problem description, how a person precedes to convert it into an algorithm becomes a matter of his “style” – no firm rules become applicable here.

(ii) Validating: Once an algorithm has been devised, it becomes necessary to show that it works. i.e it computes the correct answer to all possible, legal inputs. One simple way is to code it into a program. However, converting the algorithms into programs is a time consuming process. Hence, it is essential to be reasonably sure about the effectiveness of the algorithm before it is coded. This process, at the algorithm level, is called “validation”.Several mathematical and other empirical methods of validation are available. Providing the validation of an algorithm is a fairly complex process and most often a complete theoretical validation, though desirable, may not be provided. Alternately, algorithm segments, which have been proved elsewhere, may be used and the overall working algorithm may be empirically validated for several test cases. Such methods, although suffice in most cases, may often lead to the presence of unidentified bugs or side effects later on.

(iii) Testing the Algorithm: The ultimate test of an algorithm is that the programs based on the algorithm should run satisfactorily. Testing a program really involves two phases a) debugging and b) profiling. Debugging is the process of executing programs with sample datasets to determine if the results obtained are satisfactory. When unsatisfactory results are generated, suitable changes are made in the program to get the desired results. On the other hand, profiling or performance measurement is the process of executing a correct program on different data sets to measure the time and space that it takes to compute the results.

Page 3: Assignment

However, it is pointed out that “debugging can only indicate the presence of errors but not the absence of it”. i.e., a program that yields unsatisfactory results with a sample data set is definitely faulty, but just because a program is producing the desirable results with one/more data sets cannot prove that the program is ideal. Even after it produces satisfactory results with say 10000 data sets, it’s results may be faulty with the 10001th set. In order to actually prove that a program is perfect, a process called “proving” is taken up. Here, the program is analytically proved to correct and in such cases, it is bound to yield perfect results for all possible sets of data.

3. What is a linear data structure? Give examples. Describe how an array is represented.

Ans: LINEAR DATA STRUTURES- A data structure in which every data element has got exactly two neighbors or two adjacent elements except two elements having exactly one data element is called a linear data structure. Otherwise it is called a nonlinear data structure.

Array and its representationArray is a finite ordered list of data elements of same type. In order to create an array it is

required to reserve adequate number of memory locations. The allocated memory should be contiguous in nature. The size of the array is finite and fixed up as a constant. Some of the important operations related to arrays are,

Creation () g A[n], Array created (reservation of adequate number of memory locations) memory reserved;

Write (A, i, e) g Updated array with ‘e’ at ith

position; Compare (i, j, Relationl operator) g

Boolean;

Read (A, i) g ‘e’ element at ith

position; Search (A, e) g Boolean;

4. Write algorithms to implement the following operations on a stack - create, push, pop.

Ans: Following are the algorithms to implement the operation on a stack.

a) Algorithm: Create

Output: S, Stack

created Method:

Declare S[SIZE] //Array of size=SIZE

Declare and Initialize T=0 //Top pointer to remember the number of elementsAlgorithm ends

b) Algorithm: Push

Input: (1) S, stack; (2) e, element to be inserted; (3) SIZE, size of the

stack; (4) T, the top pointer

Output: (1) S, updated; (2) T, updated

Method:

If (Isfull(S)) then

Print (‘stack overflow’)

Page 4: Assignment

Else T=T+1;

S[T] =e

If end

Algorithm ends

c) Algorithm: Pop

Input: (1) S, stack;

Output: (1) S, updated; (2) T, updated (3) ‘e’ element popped

Method:

If (Isempty(S)) then

Print (‘stack is

empty’)

Else e = S[T] T=T-1; If end

Algorithm ends

5. What is a graph? What are the two ways of representing a graph? Describe with the help of illustrative examples.

Ans: A graph that has neither self-loop nor parallel edges are called a simple graph, otherwise it is called general graph. It should also be noted that, in drawing a graph, it is immaterial whether the lines are drawn straight or curved, long or short: what is important is the incidence between the edges and vertices.

Because of its inherent simplicity, graph theory has a very wide range of applications in engineering, physical, social, and biological sciences, linguistics, and in numerous other areas. A graph can be used to represent almost any physical situation involving discrete objects and a relationship among them.

Although in the definition of a graph neither the vertex set V nor the edge set E need be finite, in most of the theory and almost all applications these sets are finite. A graph with a finite number of vertices as well as a finite number of edges is called a finite graph; otherwise, it is an infinite graph.

6. What is a circular queue ? Write algorithms to implement the insertion and deletion operations.

Ans: Circular Queue

A circular queue uses the same conventions as that of linear queue. Using Front will always point one position counterclockwise from the first element in the queue. In order to add an element, it will be necessary to move rear one position clockwise. Similarly, it will be necessary to move front one position clockwise each time a deletion is made. Nevertheless, the algorithms for create (), Isfull (), Isempty (), Front () and Rear () are same as that of linear queue. The algorithms for other functions are

Page 5: Assignment

Algorithm: Insertion

Input: (1) CQ, Circular Queue; (2) e, element to be inserted; (3) SIZE, size of the Circular Queue; (4) F, the front pointer; (5) R, the rear pointer

Output: (1) CQ, updated; (2) F, updated; (3) R, updated

Method:

If (Isfull (CQ)) thenPrint (‘overflow’) Else

R=R mod SIZE + 1; CQ[R] =e If (Isempty (CQ)) F=1; If end If ends Algorithm ends

Algorithm: Deletion

Input: (1) CQ, Circular Queue; (2) SIZE, size of the CQ; (3) F, the front pointer; (4) R, the rear pointer

Output: (1) CQ, updated; (2) F, updated; (3) R, updated; (4) e, element if deleted;Method:

If (Isempty (CQ)) then Print (‘Queue is empty’) Else

e = CQ[F] If (F==R)

F=R=0; Else F=F mod SIZE +1; If endIf endsAlgorithm ends

7. Write an algorithm to find the roots of a quadratic equation.

Ans: TO FIND THE ROOTS OF A QUADRATIC EQUATION The algorithm to find the solution to a quadratic equation is given below.

Algorithm: Quadratic_solver

Input : a,b,c the co-efficients of the Quadratic Equation

Output : The two roots of the Equation

Method

disc = ((b*b) –(4*a*c))

if (disc = 0)

display ‘roots are real and

Page 6: Assignment

equal’

r1 = -b/2a r2 = -b/2a display r1 display r2

else if(disc>0)

display ‘ roots are real and distinct’r1 = (-b+sqrt(disc))/2a r2 = (-b-sqrt(disc))/2a

else

display ‘roots are complex’

display ‘real part’,-b/2a

display ‘imaginary part’, sqrt(absolute_value_of(disc))

display ‘the two root exists in conjugates’

end_if

Algorithm ends

Page 7: Assignment

8. Develop an algorithm to generate all the prime numbers between the given 2 limits.

Ans: Prime number checking has been a very interesting problem for computer science for a very long time. A prime number is divisible by either 1 or itself and not by any other number. Prime number checking is technically called as Primality testing.

Algorithm: Primality_Testing (First approach)

Input: n , number

flag, test condition Output: flag updated Method

flag = 0for(i=2 to n/2 in steps of +1 and flag = 0)

if( n % i = 0) // n mod i

flag = 1

end-if end-for

if(flag = 0)

display ‘Number is prime’else

display ‘Number is not prime’end_if

Algorithm ends

Second Approach

Algorithm: Primality_Testing (Second approach)

Input : n , number

flag, test condition Output : flag updated Method

flag = 0for(i=2 to square_root(n) in steps of +1 and flag = 0)

if( n % i = 0) // n mod i

flag = 1

end_if end-for

if(flag = 0)display ‘Number is prime’

elsedisplay ‘Number is not prime’

end_ifAlgorithm ends

Page 8: Assignment

Write brief answers to the following questions:

1) Define algorithm. What are its properties?Ans: An algorithm can be defined as a sequence of definite and effective instructions, which

terminates with the production of correct output from the given input.

In other words, viewed little more formally, an algorithm is a step by step formalization of a mapping function to map input set onto an output set.

While designing an algorithm care should be taken to provide a proper termination for algorithm.

Thus, every algorithm should have the following five characteristic features:

1) Finiteness: - an algorithm terminates after a finite numbers of steps.

2) Definiteness: - each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any confusion.

3) Input:- an algorithm accepts zero or more inputs

4) Output:- it produces at least one output.

5) Effectiveness:- it consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in a finite amount of time.

3) Differentiate full and complete binary trees. . A “complete” binary tree is one which allows sequencing of the nodes and all the

previous levels are maximally accommodated before the next level is accommodated. i.e., the siblings are first accommodated before the children of any one of them. And a binary tree which is maximally accommodated with all leaves at the same level is called “full” binary tree. A full binary tree is always complete but complete binary tree need not be full. Fig. 6.1 (a) and (b) shows the examples for complete and full binary trees.

4) What are the demerits of recursion? Recursion has some demerits too, which often make it a not-so-favoured solution to a problem. Some of the demerits of recursive algorithms are listed below:

Many programming languages do not support recursion; hence recursive mathematical function is implemented using iterative methods.

Even though mathematical functions can be easily implemented using recursion it is always at the cost of execution time and memory space.

A recursive procedure can be called from within or outside itself and to ensure its proper functioning it has to save in some order the return addresses so that, a return to the proper location will result when the return to a calling statement is made.

The recursive programs needs considerably more storage and will take more time.

PART - B1. a) What are the characteristics of an algorithm? Describe with an example. The definiteness and effectiveness of an instruction implies the successful termination of

that instruction. However the above two may not be sufficient to guarantee the termination of the algorithm. Therefore, while designing an algorithm care should be taken to provide a proper termination for algorithm.

Thus, every algorithm should have the following five characteristic feature

Page 9: Assignment

1) Input

2) Output

3) Definiteness

4) Effectiveness

5) Termination

1) Finiteness: - an algorithm terminates after a finite numbers of steps.

2) Definiteness: - each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any confusion.

3) Input:- an algorithm accepts zero or more inputs

4) Output:- it produces at least one output.

5) Effectiveness:- it consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in a finite amount of time.

Therefore, an algorithm can be defined as a sequence of definite and effective instructions, which terminates with the production of correct output from the given input.

b) Write an algorithm to implement any three operations of a queue. Ans: Following are the algorithms to implement the operations of a queue.i) Algorithm:

Create Output: S,

Stack created

Method:

Declare S[SIZE] //Array of size=SIZE

Declare and Initialize T=0 //Top pointer to remember the number of elementsAlgorithm ends

ii) Algorithm: Push

Input: (1) S, stack; (2) e, element to be inserted; (3) SIZE, size of the

stack; (4) T, the top pointer

Output: (1) S, updated; (2) T, updated

Method:

If (Isfull(S)) then

Print (‘stack

overflow’) Else T=T+1;

S[T] =e

If end

Algorithm

ends

iii) Algorithm: Pop

Page 10: Assignment

Input: (1) S, stack;

Output: (1) S, updated; (2) T, updated (3) ‘e’ element popped

Method:

If (Isempty(S)) then

Print (‘stack is

empty’)

Else e = S[T] T=T-1; If end

Algorithm ends

2. a) Describe the two methods of representing a graph. A graph can be used to represent almost any physical situation involving discrete objects and

a relationship among them.Although in the definition of a graph neither the vertex set V nor the edge set E need be finite,

in most of the theory and almost all applications these sets are finite. A graph with a finite number of vertices as well as a finite number of edges is called a finite graph; otherwise, it is an infinite graph.

4. What are preorder, Inorder, postorder traversals of a binary tree? Design recursionalgorithms to implement them and explain with the help of an example. Ans: There are three major methods of traversals and the rest are reversals of them. They are:

1. Pre-order traversal

2. In-order traversal

3. Post-order traversal

Pre-Order Traversal

In this traversal, the nodes are visited in the order of root, left child and then right child. i.e.,

1 Visit the root node first.

2 Go to the first left sub-tree.

3 After the completion of the left sub-tree, Go to the right sub-tree.

Here, the leaf nodes represent the stopping criteria. We go to the sibling sub-tree after the traversal of a sub-tree. The pre-order traversal sequence for the binary tree shown in Fig. 6.3 is : A B D E G H C F I J K

In-Order Traversal

In this traversal, the nodes are visited in the order of left child, root and then right child. i.e., the left sub-tree is traversed first, then the root is visited and then the right sub-tree is traversed. Here also, the leaf nodes denote the stopping criteria. The in-order traversal sequence for the above considered example (Fig. 6.3) is: D B G E H A F J I K C

Page 11: Assignment

Post_Order Traversal

In this traversal, the nodes are visited in the order of left child, right child and then root. i.e., the left sub-tree is traversed first, then the sibling is traversed next. The root is visited last. The post-order traversal for the above example (Fig. 6.3) is: D G H E B J K I F C A

5. a) What is binary search? Develop a recursive algorithm for binary search. Ans: Binary search method is also relatively simple method. For this method it is

necessary to have the vector in an alphabetical or numerically increasing order. A search for a particular item with X resembles the search for a word in the dictionary. The approximate mid entry is located and its key value is examined. If the mid value is greater than X, then the list is chopped off at the (mid-1)th location. Now the list gets reduced to half the original list. The middle entry of the left-reduced list is examined in a similar manner. This procedure is repeated until the item is found or the list has no more elements. On the other hand, if the mid value is lesser than X, then the list is chopped off at (mid+1) th location. The middle entry of the right-reduced list is examined and the procedure is continued until desired key is found or the search interval is exhausted.

The algorithm for binary search is as follows,

Algorithm : binary search

Input : A, vector of n elements

K, search elementOutput : low –index of k

Method : low=1,high=n

While(low<=high-1)

{

mid=(low+high)/2 if(k<a[mid])

high=mid else low=mid if end

}

while end if(k=A[low]) {

write(“search successful”) write(k is at location low) exit(); }

Elsewrite (search unsuccessful);

if end; Algorithm ends.

Page 12: Assignment

7. a) What is validation and testing of algorithms? Ans: vadition:Once an algorithm has been devised, it becomes necessary to show that it works. i.e it computes the correct answer to all possible, legal inputs. One simple way is to code it into a program. However, converting the algorithms into programs is a time consuming process. Hence, it is essential to be reasonably sure about the effectiveness of the algorithm before it is coded. This process, at the algorithm level, is called “validation”.Testing: Testing a program really involves two phases a) debugging and b) profiling. Debugging is the process of executing programs with sample datasets to determine if the results obtained are satisfactory. When unsatisfactory results are generated, suitable changes are made in the program to get the desired results. On the other hand, profiling or performance measurement is the process of executing a correct program on different data sets to measure the time and space that it takes to compute the results.

b) Explain the terms with examplesi) Finite graphans: A graph with a finite number of vertices as well as a finite number of edges is called a finite graph

ii) Isolated and pendent verticesans:

A vertex having no incident edge is called an isolated vertex. In other words, isolated vertices are

vertices with zero degree. A vertex of one degree is called a pendent vertex or an end vertex.

iv) NULL graphAns: A graph must have at least one vertex is called a Null Graph

v) Path. Ans: a walk has the restriction of no repetition of vertices and no edge is retraced it is called a “path”.

8. Write short notes on : a) Debugging Debugging is the process of executing programs with sample datasets to determine if the results obtained are satisfactory. When unsatisfactory results are generated, suitable changes are made in the program to get the desired resultsb) The need for recursion

When iteration can be easily used and also supported by most programming languages, why do we need recursion at all? The answer is that iteration has certain demerits as is made clear below:

1. Mathematical functions such as factorial and fibonacci series generation can be easily implemented using recursion than iteration.

2. In iterative techniques looping of statement is very much necessary.

Page 13: Assignment

Subject: JAVA Programming

Subject Code: BSIT – 42

1) Explain basic features of Java.

BASIC FEATURES IN JAVA The fundamental forces that necessitates the invention of Java are Portability and Security

. Other factors also play an important role in modeling the final form of the Java language. Let’s briefly examine each of these words, with a view to better understanding what makes Java tick.

Simple, Object-oriented Distributed interpreted Robust, Secure Architecture neutral Portable Multi-threaded Dynamic

2) Explain how Java differs from C and C++.

Ans: JAVA DIFFERS FROM C AND C++

To build a better language. Java was improved on C++. It has changed and improved upon the powerful and difficult C++ features. The following are the differences from C and C++ that exist in Java:

I. Java does not have a preprocessor, and as such, does not have macros like #define. Constants can be created by using the final modifier when declaring class and instance variables.

II. Java does not have template classes as in C++.III. Java does not include C’s const keyword or the ability to pass by const reference explicitly.IV. Java classes are singly inherited, with some multiple-inheritance features provided

through interfaces.V. All functions must be methods. There are no functions that are not tied to classes.

VI. The goto keyword does not exist in Java (it’s a reserved word, but currently unimplemented).

a. You can, however, use labeled breaks and continues to break out of and continue executing complex switch or loop constructs.

VII. Java does not use pointersVIII. Java doesn’t contain the data types: struct, union, enum.

3) What is the difference between object oriented and procedure oriented programming ?

Ans: Procedure oriented programming: With procedural programming you are able to combine returning sequences of statements into one single place. A procedure call is used to invoke the procedure. With introducing parameters as well as procedures of procedures (sub procedures) programs can now be written more structured and error free. For example, if a procedure is correct, every time it is used it produces correct results. Consequently, in cases of

Page 14: Assignment

errors you can narrow down your search to those places, which are not proven to be correct.Object-Oriented Programming: In object oriented programming, a complex system

is decomposed in accordance to the key abstractions of the problem. Rather than decomposing the problems into steps, we identify objects, which are delivered directly from the vocabulary of the problem domain.we view the world (problem domain) as a set of autonomous agents that collaborate to perform some higher level behavior. Each object in the solution embodies its own unique behavior and each one models some object in the real world. The object is simply a tangible entity that exhibits some well defined behavior. Objects do things we ask them to perform what they do by sending the messages. OOP paradigm helps us to organize the inherent complexities of software systems.

4) Explain the following OOPs concept.

a) object and classes.

Ans: Object is a physical entity which represents a person, vehicle or a conceptual entity (thing in existence) like bank account, company etc.

A set of variables and functions used to describe an object is a “class”.A class defines the structure and behavior (data and code) that will be shared by a set of

objects. Each object of a given class contains the structure and behavior defined by the class, as if it were stamped out of a mould in the shape of a class. A class is a logical construct, an object has physical reality. When you create a class, you will specify the code and data that will constitute that class. Collectively, these elements are called the members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods, which define the use of the member variables.

b) Abstraction.

Ans: Abstraction - the act or process of leaving out of consideration one or more qualities of a

complex object so as to attend to others. Solving a problem with objects requires you to build

the objects tailored to your solution. We choose to ignore its inessential details, dealing instead

with the generalized and idealized model of the object.

c) Encapsulation.

Ans: The ability to provide users with a well-defined interface to a set of functions in a way, which hides their internal workings. In object oriented programming, the technique of keeping together data structures and the methods (procedures) which act on them. The easiest way to think of encapsulation is to reference phones. There are many different types of phones, which consumers can purchase today. All of the phones used today will communicate with each other through a standard interface. A phone made by GE can be used to call a phone made by Panasonic for example. Although their internal implementation may be different their public interface is the same. This is the idea of encapsulation.d) Inheritance.

Ans: Inheritance in object oriented programming means that a class of objects can inherit properties from another class of objects. When inheritance occurs, one class is then referred to as the ‘parent class’ or ‘superclass’ or ‘base class’. In turn, these serve as a pattern for a ‘derived class’ or ‘subclass’. Inheritance is an important concept since it allows reuse of class definition without requiring major code changes. Inheritance can mean just reusing code, or can mean that you have used a whole class of object with all its variables and functions.

e) Polymorphism.

Ans: Polymorphism is simply a name given to an action that is performed by similar objects. Polymorphism allows a common data-gathering message to be sent to each class and allows

Page 15: Assignment

each subclass object to respond to a message format in an appropriate manner to its own properties. Polymorphism encourages something we call ‘extendibility’. In other words, an object or a class can have it’s uses extended.

f) Message passing.

Ans: In an object based world the only way for anything to happen is by objects communicating with each other and acting on the results. This communication is called message passing and involves one object sending a message to another and (possibly) receiving a result.

5) What are the advantages of object oriented programming ?

Ans: OOP offers several advantages to both the program designer and the user. The important advantages are,

A. ReusabilityElimination of redundant code and use of existing classes through inheritance. Thus provides economy of expression.

B. Modularity.Programs can be the built from standard working modules.

C. Security.Principle of information hiding helps programmer to build secure programs.

D. Easy mapping.Object in the problem domain can be directly mapped to the objects in the program.

E. Scalability.Can be easily upgraded from small programs to large programs. Object oriented systems are also resilient to change and evolves over time in a better way.

F. Easy managementEasy management of software complexity.

6) Explain the structure of a Java program.

Ans: A Java program may contain many classes of which only one class defines a main method. Classes contain data members and methods that operate on the data members of the class. Methods may contain data type declarations and executable statements. To write a Java program, we first define classes and then put them together.

Documentation SectionThe documentation section comprises a set of comment lines giving the name of the program , the author and other details. Java also uses comment /**…*/ known as documentation comment

Package StatementThe first statement allowed in a Java file is a package statement. This statement declares a package

name and informs the compiler that the classes defined here belong to this package.Eg : package student;

Import StatementThe next thing after a package statement (but before any class definitions) may be a number of

import statements. This is similar to the #include statement in C. Example : Import student.test;

This statement instructs the interpreter to load the test class contained in the package student.

Interface StatementsAn interface is like a class but includes a group of method declarations. This is also an optional

Page 16: Assignment

section and is used only when we wish to implement the multiple inheritance feature in the program.

7) With an example explain Java tokens.

Ans: Java Language includes four types of tokens. They are :

Reserved Keywords- Keywords are an essential part of a language definition. They implement specific features of the language. Java language has reserved 60 words as keywords.

Identifiers- Identifiers are used for naming classes, methods, variables, objects, labels, package and interfaces in a program.

Literals- Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables.

Operators- An operator is a symbol that takes one or more arguments and operates on them to produce a result

8) With an example explain different data types in Java.

i) Integer TypesInteger types can hold whole numbers such as 123,-96,and 5639. The size of the values that can be stored depends on the integer data type we choose. Java supports four types of integers. Byte, short, int, and long.

ii) Floating Point TypesThere are two types for floating point numbers, float and double. They are used to store number with values to the right of the decimal point.

iii) Character TypeAnother data type you need to store and manipulate is single-character information. The primitive type used for storing a single character is char.

9) With an example explain all the operators in Java.

Ans: There are five basic arithmetic operators in Java: addition (+), subtraction (-), multiplication (*), division (/) and modulus (%). All operators can be used with all primitive numeric types (char, byte, short, int, long, float and double). In addition any two numeric types can be combined (mixed mode arithmetic). Although the operators can be used with any numeric type, Java actually only does arithmetic with the types int, long, float and double. Therefore, the following rules are used to first convert both operands into one of these four types:

1. If either operand is a double then the other is converted to double.2. if either operand is a float then the other is converted to float.3. if either operand is a long then the other is converted to a long.

4. both are converted to int

10) With an example explain the following statements in Java.

a) simple if

Ans: The general form of a simple if statement is if (test expression)

{

statement-block;

}

statement-x;

Page 17: Assignment

b) if..else

Ans: The if....else statement is an extension of the simple if statement. The general form is if (test expression)

{

True-block statement(s)

}

else

{

False-block statement(s)

}

statement-x

11) With an example explain the switch statement in Java.

Ans: The switch statement evaluates its expression, in this case the value of month, and executes the appropriate case statement. Thus, the output of the program is: August. Of course, you could implement this by using an if statement:

Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use, based on readability and other factors. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer value. Also, the value provided to each case statement must be unique.

12) Compare while and do..while statements in Java.

Ans: To perform an action repeatedly, Java provides certain loop statements. One of the loop statements is the while statement. The while statement contains a condition and a loop body. The condition is enclosed within parentheses. Similar to the while statement, the do-while statement is a loop statement provided by

Java. The statement helps to perform certain repetitive actions depending on a condition.

The major difference between the do-while statement and the while statement is that in the while statement, the loop body is executed only when the condition stated in the statement is true. In contrast, in the do-while loop, the loop body is executed at least once, regardless of the condition evaluating to true or false.

13) With an example explain for statement in Java.

Ans: To manage iterative actions, Java provides the for statement as an efficient alternative to the while statement. The for statement creates a loop in which a set of statements is repeatedly executed until the specified condition becomes false. The syntax of the for statement is

for(initialization expression; test condition; update expressions)

{statement1;statement2;

}

The for statement starts with the for keyword. This statement has three elements enclosed within parentheses.

14) With the help of an example program explain break and continue statements in Java.

Page 18: Assignment

Ans: The continue statement stops the current iteration of a loop and immediately starts the next iteration of the same loop. When the current iteration of a loop stops, the statements after the continue statement in the loop are not executed.

By using break, we can force immediate termination of loop, by passing the

Conditional expression and any remaining code in the body of the loop.

Subject: UNIX & Shell Programming Subject Code: BSIT - 43

1. How the Unix is different from other OS?

Ans: Unix is an increasingly popular operating system. Traditionally used on minicomputers and workstations in the academic community, Unix is now available on personal computers, and the business community is choosing Unix for its openness. Previous PC and mainframe users are now looking to Unix as their operating system solution. Several versions of Unix and Unix-like systems have been made that are free or very cheap and include source code. These versions are useful to the modern-day hobbyist, who can now run a Unix system at home for little investment and an opportunity to experiment with the operating system or make changes to suit particular needs.

2. What are Internal & External commands?

Ans: Some commands in Unix are internal, built into the shell. For example, the cd command is built-in. That is, the shell interprets the command and changes the current directory. On the other hand, cat command is an external program stored in the file /bin/cat. The shell doesn’t start a separate process to run internal commands. External commands require the shell to run a new subprocess; this takes some time, especially if the system is busy.

3. How do you change your password in Unix?

Ans: The passwd command is used to change a login password. The login password is one of the most important defenses against security breaches. A password should be such that it is easily remembered by the user and difficult to guess by others.

4. What are different types of files in Unix?

Ans: Unix has different file types. Each file type is handled by its own set of commands. Commands like cd, pwd, mkdir are used exclusively with directories.

5. Define Hard Links.

Ans: In Unix, a single copy of a file can have several names, which are links to the same file. Since all the filenames refer to the same file, they have the same inode number. The second column in output of the ls–l command gives the number of links that a file has. The number is 1 for unlinked files.

6. What are absolute pathnames?

Ans: A pathname gives the file’s position in the file system. An absolute or full pathname specifies the location of a file in relation to the top of the file system which is the / (root).

An absolute pathname starts at the / (root ) directory and lists each directory along the path to the destination file (or directory).An absolute pathname uses a slash ( / ) between each directory name in the path to indicate different directories.

Page 19: Assignment

7. What is the output of the command “$ file *”?

Ans: $ file *abs.dat: ascii text absdel.cob: English text add.lst: emptycob: directoryhist: commands text

8. When do we use “wc” command?

Ans: The command wc reads the input from the file file1.txt.$ wc < file1.txtmany commands allow the input file to be specified without the redirection notation.

I. Explain the parent-child relationship in Unix file system.

Ans: In UNIX all files are related to one another and are organized in a hierarchical (inverted tree) structure. This is called the UNIX file system and at the very top of the tree is the root directory, named “/” which serves as the reference point for all the files. The root directory has a number of subdirectories, which in turn can have subdirectories and files. Therefore, every file except the root will have a parent.

PART - A

2. On which variable terminal setting is done ? Name any three terminal settingkeys.

Ans: All terminals and keyboards are not similar and the keyboard operation depends on the terminal settings. The terminal settings are found in the TERM variable. So when commands do not work as expected, the following keystrokes can be tried.

[ctrl-h] erases text[ctrl-c] or [Delete] Interrupts a command[ctrl-d] Terminates a login session

3. Explain key features of UNIX. Ans: Every user has to login with a username and password. The system administrator is responsible for creating user accounts. While assigning user accounts, the system administrator takes care to see that:

the account name is atleast three characters long and not more than eight characters long. no two accounts have the same name. the account name chosen is preferably related to the user’s name. account names have only lower case letters and numbers. uppercase letters and

punctuation’s should be avoided

4. What is script command, with command explain how to create script file of asession? Ans: The sample script commands is almost trivial - it does nothing more than execute three simple commands that you could just as easily type into the standard input. The shell can actually do much

Page 20: Assignment

more. It is, in fact, a sophisticated programming language, with many of the same features found in other programming languages, including

Variables Input/output function Arithmetic operations Conditional expressions Selection structures Repetition structures

5. What happens if a directory permission charged? Ans: The permissions assigned by a program when it creates a file or directory, a user mask is

specified with the umask command.The user mask is a numeric value that determines the access permissions when a file or

directory is created. Consequently, when a file or directory is created, its permissions are set to the permissions specified by the creating program minus the permission values denied by the umask value.

9. What is a process ? Name two important attributes of a process. Ans: A process is born when a program starts execution and exists as long as the program is running. After execution the process is said to die.The name of the process is usually the name of the program being executed.

In Unix, the kernel is responsible for the process management. It determines the time and priority allocated to each process so that multiple processes can share the CPU resources. A process executes for a finite period of time and then gives control to another process. Sometimes the kernel stores pages of the processes in the swap area of the disk before calling them again for execution.

Processes also have attributes. Some of the attributes are maintained in a structure called the process table by the kernel. The process table is stored in the memory. The important attributes of a process are:

1. The process-id (PID). Each process is identified by a unique number called the process-id which is alloted by the kernel when the process is born.

2. The parent PID (PPID) The PID of the parent is also a process attribute. When many processes have the same PPID it is easier to kill the parent process rather than the children separately.

Other attributes are inherited by a child process from its parent.As soon as a user logs into the system, the kernel starts a process called the shell. The

command representing the process could be any one of the shells, namely, sh, ksh, csh or Bash. Any Unix command typed at the shell prompt, is an input to the shell process. The shell process remains alive until the user logsout of the system.

PART - B1) Explain unix file system and give the difference between relative and absolutepath name. Ans: A pathname gives the file’s position in the file system. An absolute or full pathname specifies the location of a file in relation to the top of the file system which is the / (root).

An absolute pathname starts at the / (root ) directory and lists each directory along the path to the destination file (or directory).An absolute pathname uses a slash ( / ) between each directory name in the path to indicate different directories.

Example:$ cd /user/user1/cprogA full pathname can become very lengthy and tedious to enter.

A relative pathname specifies a file in relation to the current directory and hence the relative

Page 21: Assignment

pathname depends on the current directory. A relative pathname starts from the current directory. In a relative pathname, a single dot ( . ) represents the current working directory and two dots ( .. ) represent the parent of the current working directory.

For files or directories in the current working directory, the relative path of a file or directory is the file name or directory name itself. The parent of user1 is users and the relative pathname of the parent is .. (double dot) and the relative pathname of the root directory is ../.. (double dot/double dot).

ExampleChange to the directory set1 which is in cprog located in the working directory.$ cd cprog/set1Move up the file system tree by using the .. (double dot)$ pwd/user/user1/cprog/set1$ cd ..$ pwd/user/user1/cprogAny number of sets of .. (double dot) with a / (slash) can be used$ pwd/user/user1/cprog$ cd ../..$ pwd/user

b) Give the difference between Hard Link and Symbolic Link. Ans: Hard Link, a single copy of a file can have several names, which are links to the same

file. Since all the filenames refer to the same file, they have the same inode number. The second column in output of the ls–l command gives the number of links that a file has.

A symbolic link is a special file that contains the pathname of the file to which it is linked. This is unlike the hard link wherein the linked file also contains the contents of the file to which it is linked. Symbolic links are also called as soft links and are more flexible. They can be used to link to directories, or to files on other file systems. When a target file is deleted, a symbolic link to that file becomes unusable. This is unlike a hard link where the contents of the file are preserved.

4. a) What is a process? Explain the mechanism of creation in unix. Ans: A process is born when a program starts execution and exists as long as the program is running. After execution the process is said to die.The name of the process is usually the name of the program being executed.

In Unix, the kernel is responsible for the process management. It determines the time and priority allocated to each process so that multiple processes can share the CPU resources. A process executes for a finite period of time and then gives control to another process. Sometimes the kernel stores pages of the processes in the swap area of the disk before calling them again for execution.

Processes also have attributes. Some of the attributes are maintained in a structure called the process table by the kernel. The process table is stored in the memory. The important attributes of a process are:

1. The process-id (PID). Each process is identified by a unique number called the process-id which is alloted by the kernel when the process is born.

2. The parent PID (PPID) The PID of the parent is also a process attribute. When many processes have the same PPID it is easier to kill the parent process rather than the children separately.

Other attributes are inherited by a child process from its parent.

Page 22: Assignment

As soon as a user logs into the system, the kernel starts a process called the shell. The command representing the process could be any one of the shells, namely, sh, ksh, csh or Bash. Any Unix command typed at the shell prompt, is an input to the shell process. The shell process remains alive until the user logsout of the system.

7. a) What are positional parameters? Explain the command used to set thepositional parameters.

Ans: The positional parameters are useful for capturing command-line arguments but they have a limitation: once the script begins running, the positional parameters connot be used for obtaining more input from the standard input. For this you have to use the read statement. Let’s modify the previous program to make use of read:

#!/bin/sh

# Illustrate the use of positional parameters, user-defined

# Variables and the read command. echo ‘What is your name?’read name

echo “Well, $name, you typed $# arguments:”

echo $*In this script, name is a user-defined variable. The read command obtains the user’s response

and stores it in name. With this modification, the script display.args works something like this:$ display.args Welcome to the world of UNIX

The shell script would respond by prompting you for your name: What is your name?Suppose you were to typeSachin TendulkarThe computer would respond withWell, Sachin Tendulkar, you typed 6 arguments: Welcome to the world of UNIX.