Unit-II Programming and Problem Solving (BE1/4 CSE-2)cbit.ac.in/files/Unit_IICP.pdf · Unit-II...

15
Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite number of steps. Characteristics of algorithms: Must have Well-ordered instructions Unambiguous operations Must produce at least one output Must be guaranteed to terminate May take zero or more inputs. Algorithms can be represented as step-form, Pseudo-code, Flow chart, Nasi-Schneiderman. Key features of an algorithm: Algorithms must have the following key features: a. Sequence (also known as process) b. Decision (also known as selection) c. Repetition (also known as iteration or looping) Sequence: Means that each step or process in the algorithm is executed in the specified order. Decision: In an algorithm the outcome of a decision is either true or false and it is based on some condition which will result in either true or false. Example: if marks greater than 35 then result is pass. The general form of decision is If <preposition> then <statement> The preposition is the condition and the statement is a set of statements executed for the truth value of the preposition. The other form is If <preposition> then <statement1> else <statement2> Here if the preposition evaluated to true statement1 is executed otherwise statement2 will be executed. Repetition constructs: Repetition can be implemented using the constructs like repeat loop, while loop and if…then .. goto loop. Repeat loop is used to repeat or iterate a statement or sequence of statements until some condition becomes true. The general form of repeat loop is: repeat Statement 1 Statement 2

Transcript of Unit-II Programming and Problem Solving (BE1/4 CSE-2)cbit.ac.in/files/Unit_IICP.pdf · Unit-II...

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite number of steps. Characteristics of algorithms:

Must have Well-ordered instructions

Unambiguous operations

Must produce at least one output

Must be guaranteed to terminate

May take zero or more inputs. Algorithms can be represented as step-form, Pseudo-code, Flow chart, Nasi-Schneiderman.

Key features of an algorithm: Algorithms must have the following key features: a. Sequence (also known as process) b. Decision (also known as selection) c. Repetition (also known as iteration or looping)

Sequence: Means that each step or process in the algorithm is executed in the specified order. Decision: In an algorithm the outcome of a decision is either true or false and it is based on some condition which will result in either true or false. Example: if marks greater than 35 then result is pass.

The general form of decision is If <preposition> then <statement> The preposition is the condition and the statement is a set of statements executed for the truth value of the preposition. The other form is If <preposition> then <statement1> else <statement2> Here if the preposition evaluated to true statement1 is executed otherwise statement2 will be executed. Repetition constructs: Repetition can be implemented using the constructs like repeat loop, while loop and if…then .. goto loop. Repeat loop is used to repeat or iterate a statement or sequence of statements until some condition becomes true. The general form of repeat loop is:

repeat Statement 1 Statement 2

…… ……. Statement N until <condition>

Here the loop is executed at least once since the condition is test at exit level. Some times this may lead to errors.

While construct: The while construct repeats a statement or set of statements as long as the condition is true. The general form of while is:

While <condition> begin Statement 1 Statement 2 …… ……. Statement N end

if .. goto construct: This is another looping construct. The general form of this construct is: Label: N

Statement 1 Statement 2 …… ……. Statement N if <condition> then goto N

Example: Write an algorithm to check whether a given number is prime or not?

Figure 1 Algorithm to check whether a given number is prime or not

Strategy for designing algorithm: There are three steps in the design of an algorithm. They are investigation step, top-down step and the stepwise refinement step. Investigations step:

1. Identify the outputs needed 2. Identify the input variables available 3. Identify the major decisions and conditions 4. Identify the statements required to transform inputs into outputs 5. Identify the environment available

Top-down development step: 1. Devise the overall problem solution by identifying the major components of the system.

The goal is to divide the problem into small manageable pieces that can be solved separately.

2. Verify the feasibility of breaking up the overall problem solution. Here the basic idea is to check that each small piece of solution is independent, and form the solution when they are integrated.

Stepwise refinement: 1. Work out each and every detail for each small piece of manageable solution

procedure. 2. Decompose any solution procedure into further smaller pieces and iterate until the

desired level of detail is achieved. 3. Group processes together which have some commonality 4. Group variables together which have some appropriate commonality 5. Test each small procedure for its detail and correctness and its interfacing with the

other small procedures.

Tracing an algorithm to depict logic: An algorithm is a collection of procedures that result in providing solution to a problem. Tracing an algorithm primarily involves tracking the outcome of every procedure in the order they are placed. Tracking in tern means verifying every procedure one by one to determine and confirm the corresponding result that is to be obtained. This is in turn can be traced to offer an overall output from the implementation of the algorithm as a whole. Thus algorithm tracing means verifying the algorithm for its correctness with all possible inputs.

Specification for converting algorithms into programs: Once the algorithm for the solution of a problem is formed and represented using any one of the tools like pseudo-code, flowchart or step-form, it has to be transformed into some programming language code. The general procedure to convert an algorithm into a program is:

Code the algorithm into a program: Understand the syntax and control structures used in the language that has been selected and write the equivalent program instructions based on the algorithm that was created. Each statement in the algorithm may require one or more lines of programming code.

Desk-check the program: Check the program code by employing the desk-check method and make sure that the sample data selected produces the expected output.

Evaluate and modify, if necessary, the program: Based on the outcome of the desk-check the program, make program code changes, if necessary, or make changes to the original algorithm, if need be.

Do not reinvent the wheel: If the design code already exists, modify, do not remake it.

Flowchart: A flowchart is a graphical representation of an algorithm.

A flowchart comprises of a set of standard shaped boxes that are interconnected by flow lines to represent an algorithm.

Flowcharts play a vital role in the programming of a problem and are quiet helpful in understanding the logic of complicated and lengthy problems.

Flowcharts facilitate communication between programmers and business persons.

Once a flowchart is drawn it is easy to program in any high-level language and also helpful in explaining the program to others.

Flowchart is must for better documentation of a complex problem. Standards for flowcharts: The following standards should be adhered to while drawing flowcharts:

Flowchart must be drawn on white, unlined 8 ½ x11 paper, on one side only.

Flowcharts start on the top of the page and flow down and to the right

Only standard flowcharting symbols should be used.

A template to draw the final version of flowchart should be used.

The contents of each symbol should be printed legibly.

English should be used in flowcharts, not programming language.

The flowchart for each subroutine, if any, must appear on a separate page. Each subroutine must start with a terminal symbol with the subroutine name and a symbol labeled return at the end.

Draw the arrows between symbols with a straight edge and use arrowheads to indicate the direction of the logic flow.

Guidelines for drawing a flowchart: Flowcharts are usually drawn using standard symbols; however some special symbols can also be developed when required. Some standard symbols frequently required for flowcharting many computer programs are shown in Figure 2. Some of the guidelines in flowcharting are:

In drawing a proper flowchart, all necessary requirements should be listed out in a logical order.

There should be a logical start and stop to the flowchart.

The flowchart should be clear, neat, and easy to follow. There should be no ambiguity in understanding the chart.

The usual direction of the flow of a procedure or system is from left to right or top to bottom.

Only one flow line should emerge from a process symbol.

Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, can leave the decision symbol.

Only one flow line is used in conjunction with a terminal symbol.

The writing within standard symbols should be brief.

If the flowchart becomes complex, connector symbols should be used to reduce the number of flow lines. The intersection of flow lines should be avoided to make the flowchart a more effective and better way of communication.

Validity of the flowchart should be tested passing simple test data through it.

A sequence of steps or processes that are to be executed in a particular order is shown using process symbols connected with flow lines.

Selection of a process or step is depicted by the decision making and process symbols. Only one input indicated by one incoming flow line and one output flowing out of this structure exists. Decision symbols and process symbols are connected by flow lines.

Iteration or looping is depicted by a combination of process and decision symbols placed in proper order.

Figure 2 Flowchart symbols

Advantages of flow charts:

Communication: Flowcharts are better way of communicating the logic of a system to all concerned.

Effective analysis: Problems can be analysed in a more effective manner using flowcharts.

Proper documentation: Program flowcharts serve as a good program documentation needed for various development phases.

Efficient coding: Flowcharts act as a guide or blueprint during the systems analysis and program development phase.

Proper debugging: Flowcharts help in the debugging process.

Efficient program maintenance: The maintenance of an operating program becomes easy with the help of a flowchart.

Limitations:

Complex logic: Some time the program logic is quite complicated. In such situations a flowchart becomes complex and clumsy.

Alterations and modifications: The flowcharts need to be completely redrawn when alterations are required.

Reproduction: Since the flowchart symbols cannot by retyped in, the reproduction of a flowchart becomes a problem.

Loss of objective: The essentials of what has to be done can be easily be lost in the technical details f how it is to be done.

Example: Problem 1: Draw a flowchart to find the roots of a quadratic equation.

Figure 3 Flowchart for finding the root of a quadratic equation

Problem 2: Prepare a flowchart to read the marks of a student and classify them into different grades. If the marks secured are greater than or equal to 90, the student is awarded Grade A; if they are greater than or equal to 80 but less than 90, Grade B is awarded; if they are greater than or equal to 65 but less than 80, Grade C is awarded; otherwise Grade D is awarded.

Figure 4 Solution to problem 2.

Introduction to C Programming: Standardizations: Tokens:

Tokens are the basic lexical building blocks of source code.

Created by combining characters according to the rules of the programming language.

There are five classes of tokes namely identifiers, reserved words, operators, and constants.

Identifiers:

An identifier or name is a sequence of characters created by a programmer to identify or name or specific object. It is formed by a sequence of letters, digits, and underscores. In C, variables, arrays, functions and labels are named as identifiers.

Rules for creating identifiers: 1. First character must be an alphabetic character (lower-case or upper-case

letters) or an underscore ‘_’. 2. All characters must be alphabetic characters, digits, or underscores.

3. The first 31 characters of the identifier are significant. 4. Cannot duplicate a keyword ( a keyword is one which has special meaning to C).

Examples: number1, roll_number, name etc.

Keywords:

These are the vocabulary of C.

These words have predefined uses and cannot be used for any other purpose in a C program.

They are always written in lowercase letters. The complete list of C keywords are: Auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef unon unsigned void volatile while keywords were added in in C99: inline restrict _Bool _Complex and Imaginary.

Constant:

A constant is an explicit data value written by the programmer and its value is known to the compiler at compile time.

Compiler may deal with the value of constant in several ways depending on the type of constant and its context. Ex: the binary equivalent of the constant may be inserted directly into the output code stream.

C permits integer constant, floating point constants, character constants and string constants.

Integer constant is always assumed to be of type int and can be expressed in decimal, octal, and hexadecimal notations. Examples: 523, 0234 (0ctal), 0x34ab (hexadecimal)

A floating-point constant consists of an integer part, a decimal point, a fractional part, and an exponent field containing an e or E followed by an integer. Both the integer and the fractional parts are digit sequences. Example: 0.234F, 5.6023f, 2.345E-2 or 2.345e-2 etc.

Figure Specification of different constants.

A character constant consists of a single character enclosed in single quotes. Example: ‘c’, ‘\n’,’+’ etc.

A String constant is a sequence of characters enclosed in double quotes. The compiler stores the character sequence in an available memory. It also records the address of the first character and appends an additional null character (‘\0’) at the end of the sequence. Example: “CBIT, Hyd”.

Assignment operator:

Is the single equal to sign (=). The general form of the assignment operator is Variable_name = expression; Example: c=a+b; I=10;

The assignment operator replaces the contents the location c with the summed contents of a and b, contents of I with the contents of I plus one respectively.

The operand to the left of the assignment operator is an lvalue that denotes left value. Operators:

An operator is a symbol that specifies the mathematical, logical, or relational operation to be performed.

C operators are classified into arithmetic, assignment, relational, equality, logical, bitwise and other categories.

Figure 5: Different operators

Figure 6: Classification of operators in C language

Arithmetic operators in C:

These operators are used to perform arithmetic operations like addition, subtraction, multiplication, division etc. There are three types of operators in C: binary, unary and ternary.

Binary operators: Needs two operands. C provides five basic arithmetic binary operators. These are:

o Except the for remainder (%), all other arithmetic operators can accept a mix of integers and real operands.

o If operands are integers, the result will be an integer and if one or both of the operands are reals then the result will be a real (or double to be exact).

o When both operands of the division operator (/) are integers, the division is performed as an integer division not the normal division. Integer division always results in an integer outcome. i.e. the result is always rounded off by ignoring the remainder. Example 5/2 gives 2, -5/2 gives -2.

o It is not possible to divide a number by zero which results in division-by-zero exception.

o To obtain a real division one of the operand must be a real operand. o The remainder operator (%) always expects integers for both of its operands. It

returns the integer part of remainder obtained after dividing the operands. Example: 5%2=1.

The outcome of an arithmetic operation to be large for storing in a designated variable. This situation is called an overflow.

Unary operators: The unary ‘–’ operator negates the value of its operand (clearly, a

signed number). A numeric constant is assumed positive unless it is preceded by the negative operator. That is, there is no unary ‘+’. It is implicit. Remember that -x does not change the value of x at the location where it permanently resides in memory.

Unary increment and decrement operators ‘++’ and ‘--’ operators increment or decrement the value in a variable by 1.

Basic rules for using ++ and – – operators: The operand must be a variable but not a constant or an expression. The operator ++ and -- may precede or succeed the operand.

Postfix: • (a) x = a++;

First action: store value of a in memory location for variable x. Second action: increment value of a by 1 and store result in memory location for

variable a. • (b) y = b––;

First action: put value of b in memory location for variable y. Second action: decrement value of b by 1 and put result in memory location for

variable b.

Prefix :

• (a) x = ++a; First action: increment value of a by 1 and store result in memory location for

variable a. Second action: store value of a in memory location for variable x.

• (b) y = ––b; First action: decrement value of b by 1 and put result in memory location for

variable b. Second action: put value of b in memory location for variable y.

Relational operators: C provides six relational operators for comparing numeric quantities. Relational

operators evaluate to 1, representing the true outcome, or 0, representing the false outcome.

Logical operators: C provides three logical operators for forming logical expressions. Like the relational

operators, logical operators evaluate to 1 or 0. Logical negation is a unary operator that negates the logical value of its single operand.

If its operand is non-zero, it produces 0, and if it is 0, it produces 1. Logical AND produces 0 if one or both its operands evaluate to 0. Otherwise, it produces

1. Logical OR produces 0 if both its operands evaluate to 0. Otherwise , it produces 1.

Bitwise operators: C provides six bitwise operators for manipulating the individual bits in an integer

quantity . Bitwise operators expect their operands to be integer quantities and treat them as bit sequences.

Bitwise negation is a unary operator that complements the bits in its operands. Bitwise AND compares the corresponding bits of its operands and produces a 1

when both bits are 1, and 0 otherwise. Bitwise OR compares the corresponding bits of its operands and produces a 0

when both bits are 0, and 1 otherwise. Bitwise exclusive or compares the corresponding bits of its operands and

produces a 0 when both bits are 1 or both bits are 0, and 1 otherwise.

Conditional operator:

The conditional operator has three expressions.

It has the general form expression1 ? expression2 : expression3

First, expression1 is evaluated; it is treated as a logical condition.

If the result is non-zero, then expression2 is evaluated and its value is the final result. Otherwise, expression3 is evaluated and its value is the final result.

For example,int m = 1, n = 2, min;

min = (m < n ? m : n); /* min is assigned a value 1 */

In the above example, because m is less than n, m<n expression evaluates to be true, therefore, min is assigned the value m, i.e., 1.

Comma operator:

This operator allows the evaluation of multiple expressions, separated by the comma, from left to right in order and the evaluated value of the rightmost expression is accepted as the final result. The general form of an expression using a comma operator is

Expression M = (expression1, expression2, …,expression N);

where the expressions are evaluated strictly from left to right and their values discarded, except for the last one, whose type and value determine the result of the overall expression.

Sizeof operator:

• C provides a useful operator, sizeof, for calculating the size of any data item or type. It takes a single operand that may be a type name (e.g., int) or an expression (e.g.,100) and returns the size of the specified entity in bytes .The outcome is totally machine-dependent.

For example:

EXPRESSION EVOLUATION: PRECEDENCE & ASSOCIATIVITY:

• Evaluation of an expression in C is very important to understand. Unfortunately there is no ‘BODMAS’ rule in C language as found in algebra.

• The precedence of operators determines the order in which different operators are evaluated when they occur in the same expression. Operators of higher precedence are applied before operators of lower precedence.

http://nptel.ac.in/courses/106104128