34
G. H. Raisoni College Of Engineering Digdoh hills, Hingna, Nagpur-16 Subject: Introduction to Programming List of practical 1. W AP TO CHECK A GIVEN NUMBER IS PRIME, EVEN OR ODD. 2. WAP TO FIND L.C.M OF NUMBERS. 3. WAP TO MULTIPLY TWO MATRICS. 4. WAP TO FIND SUM OF FOLLOWING SERIES USING CASE STATEMENT a. SINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE FOLLOWING USING ITERATION 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 6. WAP IN, WHICH ARRAY IS REPRESENTED AS AN ARRAY OF CHARACTERS TERMINATED BY CHAR (O), GIVEN 2 STRINGS Sl, S2 DETERMINE WHETHER Sl < S2, Sl=S2, Sl> S2. 7. WAP TO TEST WHETHER A STRING IS PALINDROME OR NOT, USING FUNCTION. 8. WAP TO SEARCH AN ELEMENT IN AN ARRAY USING BINARY & LINEAR SEARCH. 9. WAP TO SORT THE ELEMENTS IN AN ARRAY USING a) INSERTION SORT. b) SELECTION SORT. c) QUICK SORT. 1O.WAP TO DETERMINE A SADDLE POINT (IF EXISTS) IN A GIVEN 2D MATRIX USING PROCEDURES

G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Embed Size (px)

Citation preview

Page 1: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

G. H. Raisoni College Of Engineering

Digdoh hills, Hingna, Nagpur-16

Subject: Introduction to Programming

List of practical

1. W AP TO CHECK A GIVEN NUMBER IS PRIME, EVEN OR ODD.

2. WAP TO FIND L.C.M OF NUMBERS.

3. WAP TO MULTIPLY TWO MATRICS.

4. WAP TO FIND SUM OF FOLLOWING SERIES USING CASE STATEMENT

a. SINE SERIES.

b. COSINE SERIES.

c. EXPONENTIAL SERIES.

5. WAP TO PRINT THE FOLLOWING USING ITERATION

1

1 2 1

1 2 3 2 1

1 2 3 4 3 2 1

6. WAP IN, WHICH ARRAY IS REPRESENTED AS AN ARRAY OF CHARACTERS

TERMINATED BY CHAR (O), GIVEN 2 STRINGS Sl, S2 DETERMINE WHETHER

Sl < S2, Sl=S2, Sl> S2.

7. WAP TO TEST WHETHER A STRING IS PALINDROME OR NOT, USING

FUNCTION.

8. WAP TO SEARCH AN ELEMENT IN AN ARRAY USING BINARY &

LINEAR SEARCH.

9. WAP TO SORT THE ELEMENTS IN AN ARRAY USING

a) INSERTION SORT.

b) SELECTION SORT.

c) QUICK SORT.

1O.WAP TO DETERMINE A SADDLE POINT (IF EXISTS) IN A GIVEN 2D

MATRIX USING PROCEDURES

Page 2: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: - 1

------------------------------------------------------------------------------------------------

Aim: Study of if -else statement

Program: WAP TO CHECK A GIVEN NUMBER IS PRIME, EVEN OR ODD.

Theory: MAKING DECISIONS

Most programs need to make decisions. There are several statements

available in the Pascal language for this. The IF statement is one of them. The

RELATIONAL OPERATORS, listed below, allow the programmer to test various

variables against other variables or values.

Here is a table of the operators than can be used in conditions:

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

= Equal to

<> Not equal to

The format for the IF THEN Pascal statement is,

if condition_is_true then

execute_this_program_statement;

The condition (ie, A < 5 ) is evaluated to see if it's true. When the

condition is true, the program statement will be executed. If the condition is

not true, then the program statement following the keyword then will be

ignored. Executing more than one statement as part of an IF statements.

Page 3: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

To execute more than one program statement when an if statement

is true, the program statements are grouped using the begin and end

keywords. Whether a semi-colon follows the end keyword depends upon what

comes after it. When followed by another end or end. then it no semi-colon.

IF THEN ELSE

The IF statement can also include an ELSE statement, which specifies

the statement (or block or group of statements) to be executed when the

condition associated with the IF statement is false. Rewriting the previous

program using an IF THEN ELSE statement.

The 'if statement' executes the proceeding statement(s) conditionally.

This means that if an action comes to be true, then the statement(s) preceding

the if statement are executed, else these statements are skipped. It works like

this:

If this happens(action), then do this(reaction, if action is true).

OR:

If this happens(action), then do this(reaction, if action is true),

else do this(reaction, if action is false).

In Pascal, the 'if statement' should be written as follows:

If conditional expression then code ... ;{if one action}

OR:

If conditional expression then Begin instructions ... End;

{if more than one action is required}

Diagrams: Flowchart of program

Sample output:

Result: If else statement has been studied

Page 4: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Viva-Voce:

1. Explain sequential execution?

2. Why are control structures required in a program?

3. What conditional statement? How it is evaluated?

4. What is nested if- statement?

5. Write syntax of nested if statement

6. What are different forms of if?

7. Up to what level we can have nested if else statements.

8. Instead of if are there any replacements in Pascal.

9. What is an algorithm? State its Characteristics.

10. What are various data types available in Pascal?

Page 5: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: - 2

-------------------------------------------------------------------------------------------------

Aim: Study of while loop

Program: Write a program to find LCM of numbers.

Theory:

LOOPS: The most common loop in Pascal is the FOR loop. The statement

inside the for block is executed a number of times depending on the control

condition.

While loop The while loop repeats while a condition is true. The

condition is tested at the top of the loop and not at any time while the loop is

running as the name suggests. A while loop does not need a loop variable but if

you want to use one then you must initialize its value before entering the loop.

Repeat until loop The repeat until loop is like the while loop except that

it tests the condition at the bottom of the loop. It also doesn't have to have a

begin and an end if it has more than one command inside it.

If you want to use more than one condition for either the while or repeat

loops then you have to put the conditions between brackets.

Diagrams: Flowchart of programs

Sample output:

Result: While loop has been studied.

Viva-voce:

l. Explain while loop, how it is evaluated?

2. What is repeat-until loop? Write syntax.

3. Write syntax of while loop

4. What is difference between while -do & repeat-until loop?

5. Which operators are used with while loop?

6. What do you mean by Boolean expression?

7. What is Bottom-Up/Top-Down approach used in programming?

8. How Boolean expression can be used in program for decision-making.

Page 6: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: -3

-------------------------------------------------------------------------------------------------

Aim: Study of for loop and Array

Program: Write a program to multiply two matrices of any order

Theory:

LOOPS: The most common loop in Pascal is the FOR loop. The statement

inside the for block is executed a number of times depending on the control

condition.

The format's for the FOR command is,

FOR var_name := initial_value TO final_value DO

program_statement;

Arrays are variables that are made up of many variables of the same data

type but have only one name. Here is a visual representation of an array with 5

elements:

1 value 1

2 value 2

3 value 3

4 value 4

5 value 5

Arrays are declared in almost the same way as normal variables are

declared except that you have to say how many elements you want in the

array. We access each of the elements using the number of the elements

behind it in square brackets. It is a lot easier when you use a loop to access the

values in an array.

Page 7: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Diagrams: Flowchart of program

Sample output:

Result: for loop and Array have been studied

Viva voce:

l. What is difference between for and while loop?

2. What is the use of continue statement

3. What is break statement?

4. Difference between arrays and linked list?

5. How can you increase the size of a dynamically allocated array?

6. How can you increase the size of a statically allocated array?

7. What do you mean by scope of variable?

8. How many bytes of memory require for storing integer data.

9. How many bytes of memory require for storing character data.

10. How many bytes of memory require for storing Boolean data.

Page 8: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: -4

------------------------------------------------------------------------------------------------

Aim: Study of switch statement

Program: Write a program to evaluate the following series using switch

statement

a) Sine series

b) Cosine series

c) Exponential series

Theory:

Case: The case command is like an if statement but you can have many

conditions with actions for each one. The case statement is very similar to the

if statement, except in that the it does not accept literal conditional expressions

(i.e.: strings) but surprisingly enough, it allows single character conditional

expressions.

Here is how it works:

Case {variable of type: integer or character ONLY} of

{input statement- within inverted commas if of type char} : {code..}

{input statement- within inverted commas if of type char} : {code..}

...

End; {End Case}

Pascal supports the standard case statement with extensions for an

otherwise clause and ranges of constants. If expression does not match any of

the case values, the compiler executes the otherwise statement list. The

reserved word otherwise is not a case label, so it is not followed by a colon (:).

Also, the begin/end pair is optional in an otherwise statement.

You can use a range of constants instead of a single case value. A case

range must be in ascending order.

Page 9: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Diagrams: Flowchart of programs

Sample output:

Result: Switch statement has been studied.

Viva voce:

l. What is switch statement?

2. What is syntax of switch statement?

3. Can we initialize as

Switch (ch)

Begin

Case 'a':

Case 'A':

Write ("addition");

Break;

End;

4. Multiple IF statements & switch statements are same?

Page 10: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: -5

-------------------------------------------------------------------------------------------------

Aim: Study of nested for loop and iterative process.

Program: WAP TO PRINT THE FOLLOWING USING ITERATION

1

1 2 1

1 2 3 2 1

1 2 3 4 3 2 1

Theory:

Iteration Structures.

In the early days of computer programming, when programmers did not

have high-level languages like PASCAL, the programming of repetitive sections

of code was quite clumsy. For example, to make a section of code repeat N

times, one had to use assembly language constructs that incremented a

counter and tested it against N, using branch-on-zero and the infamous go-to

for transferring control to the partition of code that executed after the loop

ended.

If the programmer did not code the loop properly, the loop could

keep running... and running...forever (or until the computer was powered

down). This condition is called an infinite loop, and is more difficult to

accidentally program in Pascal than in assembly language.

A loop is a section of code that repeats itself. A loop index or loop

counter is an integer variable that is used to keep track of how many times a

loop has executed. A loop limit is a variable or constant that is integer-valued,

which determines the number of times a loop will execute, or a maximum value

of the loop index to be reached at loop termination. A loop increment is the step

size for incrementing the loop counter.

Page 11: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

In certain kinds of loops (WHILE..DO and REPEAT), there is no loop

index, but a loop predicate that is a logical predicate. When the predicate

evaluates to false, the loop terminates.

PASCAL supports the following three iteration structures:

FOR loop:

Purpose: Repeat statements within the loop while the loop index is

incremented within specified bounds.

Syntax: FOR loop-index := initial-value TO final-value DO

statements ; , where

loop-index is the counter to be incremented

initial-value is the beginning value of the loop index

final-value is the ending value of the loop index

WHILE..DO loop:

Purpose: The WHILE loop is also called a conditional loop, since it

terminates based on a condition encoded in a logical predicate.

Syntax: WHILE predicate DO statements; , where

Predicate is the controlling condition.

REPEAT..UNTIL loop:

Purpose: The REPEAT loop is another example of a conditional loop.

Syntax: REPEAT statements UNTIL predicate;, where

Predicate is the controlling condition.

Diagrams: Flowchart of program

Sample output:

Result: Nested-for loop have been studied

Page 12: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Viva voce:

l. What is nested-for do loop?

2. What do you mean by iterative process?

3 What is the difference between constant and variable?

4. Can we nest while loop in for loop?

5. Explain the difference between Testing & Verifying the program.

6. What are the various files are generated after successfully execution of

Program.

7. What do you mean by MAXINT? What its value?

8. What is the difference between FOR loop & WHILE loop?

9. What is the difference between FOR loop & REPEAT UNTIL loop?

10. What is the difference between WHILE loop & REPEAT UNTIL loop?

Page 13: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: - 6

-------------------------------------------------------------------------------------------------

Aim: Study of function and strings

Program: WAP IN WHICH ARRAY IS REPRESENTED AS AN ARRAY OF

CHARACTERS TERMINATED BY CHAR (O), GIVEN TWO STRINGS Sl, S2

DETERMIINE WHETHER Sl < S2, S l==S2, Sl > S2.

Theory:

Procedures: Procedures are just like small programs. Sometimes they

are called sub--programs. They help the programmer to avoid repetitions. A

procedure start off with a begin and ends up with an end;. It can also have its

own variables, which cannot be used with the main-program. To have an exact

definition of a procedure, you should compare a program which includes a

repeated section with another program avoiding the repeated sections by using

a procedure, which is called several times:

Functions: The second type of sub-program is called a function. The only

difference from the procedure is that the function returns a value at the end.

Note that a procedure cannot return a value. A function start and end in a

similar way to that of a procedure. If more than one value is required to be

returned by a module, you should make use of the variable parameter. A

function can have parameters too. If you change the sub-program from

procedure to a function, of the previous program, there will be no difference in

the output of the program. Just make sure which one is best when you can to

implement a module.

For example, if you don't need to return any values, a procedure is best.

However if a value should be returned after the module is executed, function

should be used instead.

Page 14: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

The Variable Parameter

Parameters of procedures may be variable. In this case, data may flow through

the variable in both ways. What I am trying to say is that you can pass data

and get data through the procedure using a variable parameter. Here is a

deceleration of a variable parameter:

Procedure <PROCEDURE_NAME(Var Variable_Name : Type);>

Function <FUNCTION_NAME(Var Variable_Name : Type);>

Introduction to Strings

Maybe you already know what is a string variable from previous program

examples that you have tried, but you don't know what operations and what

functions one can apply to them and how can they be manipulated in order to

obtain another form of string whatsoever.

In order to understand strings, one has to keep in mind that a string is

made up of an array of characters. The string data type is an in-built data type

that is an array of 256 characters

Type String = Packed Array [0..255] of Char.

When stored in memory, the processor should know where the string starts

and where it finishes. In order to know where the string finishes, in Pascal, the

0th element of a string is defined as the length of the string. So, if you try to

access character 0 of a string, the number of characters stored in that array is

returned, thus letting the processor to know where the string finishes.

Diagrams: Flowchart of program

Sample output:

Result: Function and string has been studied

Page 15: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Viva voce:

1. What is function?

2. What is call by value?

3 What is call by reference?

5. What does static variable mean?

6. What is a string in Pascal?

7. Difference between strdup and strcpy?

8. What is subprogram?

9. What are the various arguments passing techniques?

10. What is the difference between Function and Procedure?

Page 16: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: - 7

-------------------------------------------------------------------------------------------------

Aim: Study of function and string.

Program: WAP TO TEST WHETHER A STRING IS PALINDROME OR NOT

USING FUNCTION

Theory: A parameter list can be included as part of the procedure heading. The

parameter list allows variable values to be transferred from the main program

to the procedure.

The new procedure heading is:

procedure Name (formal_parameter_list);

The parameter list consists of several parameter groups, separated by

semicolons:

param_group_1; param_group2; ... ; param_groupn

Each parameter group has the form:

identifier_1, identifier_2, ... , identifier_n : data_type

The procedure is called by passing arguments (called the actual

parameter list) of the same number and type as the formal parameter list.

Procedure Name (a, b : integer; c, d : real);

The value in the main program was not affected by what happened in the

procedure.

This is called call-by-value. This passes the value of a variable to a

procedure.

Page 17: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Another way of passing parameters is call-by-reference. This creates a

link between the formal parameter and the actual parameter. When the formal

parameter is modified in the procedure, the actual parameter is likewise

modified.

Call-by-reference is activated by preceding the parameter group with a VAR:

VAR identifier 1, identifier 2, ..., identifier n : datatype;

In this case, constants and literals are not allowed to be used as actual

parameters because they might be changed in the procedure. Call-by-value

acts as copying a variable, then giving the copy to the procedure. The

procedure works on the copy and discards it when it is done. The original

variable is unchanged. Call-by-reference is giving the actual variable to the

procedure. The procedure works directly on the variable and returns it to the

main program.

In other words, call-by-value is one-way data transfer: main program to

procedure. Call-by-reference goes both ways.

Strings

In Turbo Pascal, a string is stored as a char array. The zeroth location in

the array contains a binary value equal to the usable length of the string, i.e.,

no characters past the subscript equal to this value are treated as being part of

the string.

Strings may be declared in two ways:

• longest_str : string;

• mystr : string[n];

Where n is the maximum number of characters which may be stored in the

string.

The first method results in a default maximum length of 255, the largest

unsigned binary number which can be stored in a byte. This is also the

absolute maximum length for a string in Turbo Pascal. This method of string

storage has ramifications for how text must be handled.

Page 18: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

The following declares a string called mystr. Pascal provides an array

consisting of sixteen consecutive bytes of memory. The subscripts used for the

array start with zero (0).

Concat Function

Syntax: NewString := Concat(str1, str2, ...)

where NewString, str1, str2, etc. are string identifiers

Concat is used to concatenate all of its parameters into a single string which is

then returned. This is equivalent to pasting one string onto the end of another.

Copy Function

Syntax: substr := Copy(mystr, n1, n2)

where substr and mystr are string identifiers;

n1 is the starting location for copying; and

n2 is how many characters are to be copied

Copy is used to copy a portion (or all) of a string into another string variable.

Delete Procedure

Syntax: Delete(mystr, nStart, nHowmany)

where mystr is a string identifier; and

nStart and nHowmany are integers

Delete eliminates nHowmany characters from mystr starting with the nStartth

character.

Insert Procedure

Syntax: Insert(newstr, mystr, nLocation)

where newstr is a string identifier or constant;

mystr is a string identifier; and

nLocation is an integer

Insert puts newstr into mystr starting at nLocation.

Page 19: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Length Function

Syntax: len = Length(mystr)

where len is an integer and mystr is the identifier of a string variable

Length returns the length of a string by checking the zeroth location in the

array.

Pos Function

Syntax: Location := Pos(substr, mystr)

where substr is the substring being looked for and mystr is the string being

searched.

Pos returns as an integer the location (subscript) of where substr was found to

start in mystr.

Str Procedure

Syntax: Str(number, mystr)

where number is a numeric data type and mystr is a string identifier.

Str is used to convert an integer, real, etc. into a string. This procedure has

little utility. It is provided basically to mirror/reverse the effect of the procedure

Val.

Upcase Function

Syntax: NewChar := Upcase(OldChar)

where NewChar and OldChar are of type char.

Upcase takes the char OldChar and returns the uppercase version of it.

Consequently, if the character stored in OldChar is not a lowercase alphabetic,

no change occurs and the original character is returned.

This function is very useful when handling user input.

Page 20: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Val Procedure

Syntax: Val(mystr, number, errorflag)

where mystr is a string identifier; number is a numeric data type; and errorflag

is an integer.

Val attempts to convert the string mystr into its numeric representation of the

same type as that of number. If the attempt fails because an character illegal

for the given data type is found, its position in the string is placed in errorflag.

A value of 0 indicates that the conversion was successful. This procedure is

extremely useful in checking user input so as to avoid run-time errors when

the user mistypes.

Diagrams: Flowchart of program

Sample output:

Result: function and string have been studied.

Viva voce:

1. What is the difference between string and array of character?

2. Can relational operations be performed on string?

3. What is the only non-relational operation possible on string?

4. What do you mean by linear programming?

5. What do you mean by modular programming?

6. How does modular programming increase readability?

7. What are the types of subprograms in Pascal?

8. How are procedures and functions declared?

9. What is meant by scope of variable?

10. Explain Formal and actual parameters?

Page 21: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: - 8

-----------------------------------------------------------------------------------------------

Aim: Study of Searching algorithm

Program: WAP TO SEARCH AN ELEMENT IN AN ARRAY USING

a) BINARY SEARCH

b) LINEAR SEARCH

Theory:

The Binary search

Binary search involves binary decisions, decisions with two choices. At

each step in the process you can eliminate half of the data you're searching.

This is the way humans look up most information in big volumes, such as a

phonebook or a dictionary. We guess a place in the middle of the book, and

then move forward or backward depending on the location you're at relative to

the location of what you're looking for. This works because all of the data is

sorted, in alphabetical order in the case of a phonebook or dictionary.

Binary search is much faster than linear search for most data sets. If you

look at each item in order, you may have to look at every item in the data set

before you find the one you are looking for. With binary search, you eliminate

half of the data with each decision. If there are n items, then after the first

decision you eliminate n/2 of them. After the second decision you've eliminated

3n/4 of them. After the third decision you've eliminated 7n/8 of them. Etc.

In other words, binary search is O (log n). You can see that for a large data set,

binary search would be much better than linear search.

Binary search is a more specialized algorithm than sequential search as

it takes advantage of data that has been sorted. The underlying idea of binary

search is to divide the sorted data into two halves and to examine the data at

the point of the split.

Page 22: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Since the data is sorted, we can easily ignore one half or the other

depending on where the data we're looking for lies in comparison to the data at

the split. This makes for a much more efficient search than linear search.

Binary search is used on sorted arrays, but we see it more often when

used with binary search trees. Whereas linear search allows us to look for data

in O(n) time, where n is the number of elements being searched, binary search

allows us to do the same search in O(log n) time, a dramatic speed

enhancement. Binary search is one of the most common search algorithms and

is useful in most any real world application you might write.

The array that we are searching must be sorted for binary search to

work. For this example, we'll assume that the input array is sorted in

ascending order. The basic idea is that you divide the array being searched into

two sub arrays, and compare the middle element to the value for which you're

searching.

There are now three possible cases:

1. The value is equal to the middle element. In this case, the element has

been found and you are done.

2. The value is greater than the middle element. In this case, if the value

is in the array, it will be in the upper half of the array (i.e. one of the elements

after the middle element).

3. The value is less than the middle element. In this case, if the value is

in the array, it will be one of the elements in the lower half of the array, before

the middle element.

For cases 2 or 3, we take the proper sub array (either the array of

elements before the middle element or the one after it) and repeat the same

process: We compare the middle element in the sub array to the value. If the

value is equal to the middle element, we are done. Otherwise, we perform a

search on one of these new sub arrays.

Page 23: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Now in more detailed terms:

1. Compute the subscript of the middle element of the set being searched.

2. If the array bounds are "improper" then return "value not found."

3. Else if the target is the middle element, return the subscript of the middle

element.

4. Else if the target is less than the middle value then go back to step 1 and

search the sub array from "first" to "middle - 1."

5. Else go back to step 1 and search the sub array from "middle + 1" to "last."

Algorithm:

1. {Search for key in A[1..N]

2. lo := 1; hi := N+1;

3. while lo < hi-1 do {i.e. there are at least 2 elements}

4. begin

5. {INVARIANT: search key in A[1..N] iff key in A[lo..hi-1]}

6. mid := (lo+hi) div 2;

7. {assert: lo < mid < hi}

8. if key >= A[mid] then {must be in right part}

9. lo := mid

10. else {i.e. key < A[mid], search left}

11. hi := mid

12. end;

13. found := A[lo]=key {?is it there?}

The Linear search

The linear search, also known as the sequential search, are the most

basic search algorithms the basic strategy is straightforward. Every element in

the data set is examined in the order presented until the value being searched

for is found. If the value being searched for doesn't exist, a flag value is

returned (such as -1 for an array or NULL for a linked list).

Page 24: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Sequential search is at best O (1), at worst O (n), and on average O (n). If

the data being searched are not sorted, then it is a relatively efficient search.

However, if the data being searched are sorted, we can do much better.

Algorithm:

i := 1; m := n consider all elements:

i < m more than one element:

found := A[i] = x examine null element:

If the interval from i to m holds more than one element, we use a

particular search algorithm to ‾nd an element k which divides the interval into

a left interval from i to k and a right interval from k + 1 to m, where

1 � i � k < m � n

In choosing one of the subintervals, there are three cases to consider:

1. If A[k] < x there is no solution in the left interval.

2. If A[k] = x there is a solution in the left interval.

3. If A[k] > x there is no solution in the right interval.

We can now do yet another program piece:

if A[k] ¸ x choose subinterval:

then fchoose left intervalg m := k

else fchoose right intervalg i := k + 1

The only program piece that depends on a particular search

method is the one which partitions the current interval.

If we cut the current interval in half we have a binary search:

1. i := 1; m := n;

2. while i < m do

3. begin

4. k := (i + m) div 2;

5. if A[k] ¸ x then m := k

6. else i := k + 1

7. end;

8. found := A[i] = x

If the left interval consists of a single element only, we have a linear search:

Page 25: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Diagrams: Flowchart of program

Sample output:

Result: Searching Algorithm has been studied

Viva voce:

1. What is searching?

2. What is the need of searching?

3. What is meant by order of algorithm?

4. What is linear search?

5. What are the advantages of linear search algorithm?

6. What causes the inefficiency of the linear search algorithm?

7. Explain binary search algorithm

8. What is the advantage of the binary search method?

9. Distinguish binary and linear search.

10. What are packed arrays?

Page 26: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: - 9

-------------------------------------------------------------------------------------------------

Aim: Study of Sorting Algorithms

Program: WAP TO SORT THE ELEMENTS IN AN ARRAY USING

a) SELECTION SORT.

b) INSERTION SORT.

c) QUICK SORT.

Theory:

Selection Sort

The Selection Sort is a very basic sort. It works by finding the smallest

element in the array and putting it at the beginning of the list and then

repeating that process on the unsorted remainder of the data. Rather than

making successive swaps with adjacent elements like bubble sort, selection

sort makes only one, swapping the smallest number with the number

occupying its correct position.

The idea of selection sort is rather simple: we repeatedly find the next

largest (or smallest) element in the array and move it to its final position in the

sorted array. Assume that we wish to sort the array in increasing order, i.e. the

smallest element at the beginning of the array and the largest element at the

end. We begin by selecting the largest element and moving it to the highest

index position.

We can do this by swapping the element at the highest index and the

largest element. We then reduce the effective size of the array by one element

and repeat the process on the smaller (sub) array. The process stops when the

effective size of the array becomes 1 (an array of 1 element is already sorted).

Page 27: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Algorithm:

SELECTION_SORT

1. for i ← 1 to n-1 do

2. min j ← i;

3. min x ← A[i]

4. for j ← i + 1 to n do

5. If A[j] < min x then

6. min j ← j

7. min x ← A[j]

8. A[min j] ← A [i]

9. A[i] ← min x

Complexity

Time

The number of comparisons of elements is

(N-1) + (N-2) + ... + 1

= (N-1)*N/2

i.e. O(N2).

Space

The space-complexity is O (1), just a few scalar variables. NB. We do not

count the size of the array being sorted because that is given, not created

specifically for this algorithm.

Stability

Selection sort is not stable, i.e. the relative orders of equal keys are

sometimes changed.

Page 28: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Insertion Sort

Unlike other simple sorts like selection sort and bubble sort which rely

primarily on comparing and swapping, the insertion sort achieves a sorted data

set by identifying an element that out of order relative to the elements around

it, removing it from the list, shifting elements up one place and then placing

the removed element in its correct location.

The idea behind insertion sort is:

1. Put the first 2 items in correct relative order.

2. Insert the 3rd item in the correct place relative to the first 2.

3. Insert the 4th item in the correct place relative to the first 3.

4. etc.

As for selection sort, a nested loop is used; however, a different invariant

holds: after the ith time around the outer loop, the items in A [0] through A [i-1]

are in order relative to each other (but are not necessarily in their final places).

Also, note that in order to insert an item into its place in the (relatively) sorted

part of the array, it is necessary to move some values to the right to make

room.

Algorithm:

INSERTION_SORT

1. For j = 2 to length [A] do

2. key = A[j]

3. {Put A[j] into the sorted sequence A[1 . . j-1]

4. i ← j -1

5. while i > 0 and A[i] > key do

6. A[i+1] = A[i]

a. i = i-1

7. A[i+1] = key

Page 29: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Complexity

Time

The number of comparisons of elements in the worst case is

(N-1) + (N-2) + ... + 1

= (N-1)*N/2

i.e. O(N2).

The average case time-complexity is O ((N-1)*N/4), i.e. O (N2).

The best-case time complexity is when the array is already sorted, and is O (N).

Space

The space-complexity is O (1), just a few scalar variables.

Stability

Insertion sort is stable, i.e. the relative order of equal keys is not

changed, provided that you are careful about scanning the sorted region from

right to left.

Quick Sort

The basic version of quick sort algorithm was invented by C. A. R. Hoare

in 1960 and formally introduced quick sort in 1962. It is used on the principle

of divide-and-conquer. Quick sort is an algorithm of choice in many situations

because it is not difficult to implement, it is a good "general purpose" sort and

it consumes relatively fewer resources during execution.

The implementation below simply uses the first element of the list as the

pivot value. Once the pivot value has been selected, all values smaller than the

pivot are placed toward the beginning of the set and all the ones larger than the

pivot are placed to the right. This process essentially sets the pivot value in the

correct place each time. Each side of the pivot is then quick sorted.

Ideally, the pivot would be selected such that it was smaller than about half

the elements and larger than about half the elements. Consider the extreme

case where either the smallest or the largest value is chosen as the pivot: when

quick sort is called recursively on the values on either side of it, one set of data

will be empty while the other would be almost as large as the original data set.

Page 30: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

To improve the efficiency of the sort, there are clever ways to choose the

pivot value such that it is extremely unlikely to end up with an extreme value.

One such method is to randomly select three numbers from the set of data and

set the middle one as the pivot. Though the comparisons make the sort slightly

slower, a "good" pivot value can drastically improve the efficiency of quick sort.

1. Pick an element from the table you're sorting. We call this the 'pivot'.

2. Exchange the pivot with the right-most element in the table.

3. Go through the table from both left and right ends; from the left end,

search for elements

Greater than the pivot; from the right end, search for elements Smaller

than the pivot.

4. When you find these two elements, exchange them and go on.

5. When the two go-through cross, exchange the pivot and the element

where the left

Go-through is pointing.

6. The pivot is on its final place in the table, and to the left there's only

elements smaller than it, to the right there's only elements greater than it.

Now perform the same process for both sides of the table recursively.

Algorithm:

QuickSort

1. If p < r then

2. q Partition (A, p, r)

3. Recursive call to Quick Sort (A, p, q)

4. Recursive call to Quick Sort (A, q + r, r)

Page 31: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

PARTITION (A, p, r)

1. x ← A[p]

2. i ← p-1

3. j ← r+1

4. while TRUE do

5. Repeat j ← j-1

6. until A[j] ≤ x

7. Repeat i ← i+1

8. until A[i] ≥ x

9. if i < j

10. then exchange A[i] ↔ A[j]

11. else return j

Complexity

Time

In the best case, the partitions are of equal size at each recursive call,

and there are then log2 (N) levels of recursive calls. The whole array is scanned

at each level of calls, so the total work done is O (N*log (N)).

The average time complexity is also O (N*log (N)).

The worst case time complexity is O (N2). This occurs when the estimate

of the median is systematically always poor, e.g. on already sorted data, but

this is very unlikely to happen by chance.

Space

As coded above the best- and average-case space-complexity is O (log

(N)), for the stack-space used.

The worst-case space-complexity is O (N), but it can be limited to O (log

(N)) if the code is modified so that the smaller half of the array is sorted first

(and an explicit stack, or the tail-recursion optimization, used).

In that case, the best-case space-complexity becomes O (1)

Stability

Quick sort is not stable.

Page 32: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Diagrams: Flowchart of Programs

Sample output:

Result: Sorting algorithm has been studied

Viva voce:

1. What is the need for operations like sorting and searching?

2. Explain the bubble sort algorithm?

3. How does the selection sort algorithm work?

4. Which sorting method would be suitable for partially sorted data?

5. Which sorting method would be suitable for totally random data?

6. Which sorting method would be suitable for data that is sorted & Random in

parts?

7. What is recursion?

8. What are the three parts of recursive definition?

9. What happens if the termination condition in a recursive definition is

incorrect?

10. What is the difference between direct and indirect invocation?

11. Write down the complexity of each sorting algorithm.

Page 33: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Date:

PRACTICAL No: - 10

-------------------------------------------------------------------------------------------------

Aim: Study of multidimensional array and its internal representation in

memory.

Program: WAP TO DETERMINE A SADDLE POINT (IF EXISTS) IN A GIVEN

2D MATRIX USING PROCEDURES.

Theory:

2 Dimensional and Multi-Dimensional Arrays

Two Dimensional arrays and multi-dimensional are arrays which

store variables in a second or nth dimension having n*m storage locations.

Multi-dimensional arrays including the 2 dimensional arrays are declared by

using multiple square brackets placed near each other or using commas with

one square bracket as an alternative. Multi-dimensional arrays are rare and

are not important.

Multi-dimensional arrays are arrays where the elements have more than

one index. In the case of two-dimensional arrays these can be envisaged as

tables comprising a number of rows and column such that the row number

represents one index and the column number a second index:

The single and 2D dimensional arrays are the 2 most frequent

dimensions. Here is how multi-dimensional are declared:

my2DArray : Array[i..j][k..l] of <DataType>;

myMultiDimArray : Array[m..n][o..p][q..r][s..t]... of <DataType>;

Page 34: G. H. Raisoni College Of Engineering Digdoh hills, Hingna ...ghrce.raisoni.net/download/intro_programming.pdfSINE SERIES. b. COSINE SERIES. c. EXPONENTIAL SERIES. 5. WAP TO PRINT THE

Allocating Storage for Multidimensional Arrays

If you have an m x n array, it will have m * n elements and require

m*n*Element_Size bytes of storage. To allocate storage for an array you must

reserve this amount of memory. Multidimensional Arrays declaration syntax is

very similar to high level language array declaration syntax you use a

declaration like the following:

ArrayName: elementType [ comma_separated_list_of_dimension_bounds ];

Diagrams: Flowchart of program

Sample Output

Result: Multidimensional array and its internal representation has been

studied.

Viva voce:

1. What are arrays?

2. Is a multi-dimensional array an array of arrays?

3. How many dimensions are allowed in multidimensional array?

4. How does Turbo Pascal store a multidimensional array?

5. What is an index and why does it have to be unique?

6. What type of array is also known as a vector?

7. What is matrix?

8. Does Turbo Pascal store its entire array as packed? If so, why?

9. Explain the representation of a sparse matrix in memory.

10. How a sparse matrix is converted in Three Tuple Form.