C + 1102 1 Que Assignment.docx

  • Uploaded by: parwinder
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View C + 1102 1 Que Assignment.docx as PDF for free.

More details

  • Words: 8,134
  • Pages: 28
Q -1 What do you understand by Problem Solving? Describe the various problem solving tools available. Ans – Problem solving requires thinking and planning. As you know that the computer needs instructions to carry out any task. To write instructions we need programming languages. To write programs we need to think and plan out a solution. To solve problems on computers various problem solving tools are available. The algorithms, flow charts etc. are problem solving tools. In general, how a problem is solved has been explained below. 1 Problem Identification The objective of the Problem Identification is to gain agreement on the problem definition. Common obstacles that stand in the path of meeting this objective are (a) the customer has only a superficial understanding of the problem (b) the customer wants that solution formulation that is inconsistent with the prevailing system (c) the customer is thinking in the solution space based on insufficient understanding of the underlying problem, and finally (d) the requirements analyst lacks in domain knowledge. Educating the requirements analyst in the existing and proposed system as well as for the operational environment helps to lessen these adverse impacts. The other three obstacles are customer oriented and require an investigation into these inadequacies of the current system and the corresponding operational solutions. .2 Problem Analysis: If we are to use the computer as a problem-solving tool, then we must have a good analysis of the given problem. Here are some suggested steps on how to go about analyzing a certain problem for computer application: 1. Review the problem carefully and understand what you are asked to do. 2. Determine what information is given(input) and what result must be produced(output). 3. Assign names to each input and output items. 4. Determine the manner of processing that must be done on the input data to come up with the desired output (For example determining what formulas are needed to manipulate the given data).

3. Problem Solution: Step 1: Coding: In this step the programs are written using some program language. The algorithms and flow-charts etc. are converted to programs. Step 2: Testing and Debugging: The programs are then translated to the machine language using the language translators such as compilers. The programs are tested for all types of errors and the various types of errors are removed (debugged). Step 3: Documentation and Maintenance: Documentation is the process of writing explanation about the various programs in the form of comments and remarks. Documentation helps the other programmers ( who did not write the code ) to understand the program so that the program can be modified/improved if errors are found at a later stage. Program Maintenance means periodic review of the programs to ensure that they meet the revised needs of the organisation. 4 Algorithm Algorithm is a step by step procedure to solve a given problem. It is a kind of program written in a non-computer language. An algorithm is an ordered set of unambiguous, executable steps defining a terminating process. The way of stating the algorithm should be precise, easy to understand, and should be easy to convert it later to a computer program. Suppose we want to find the average of three numbers. We can write the steps as:

1. 2. 3. 4.

Read the numbers a, b, c Let d = (a+b+c)/3 Print d Stop

Flow Chart A flow chart is a graphical representation of the step by step instructions of any problem. It represents an algorithm, in the form of a chart, where the actions are shown by boxes of various shapes and flow of execution is indicated by arrows. Flow charts are just one way of using diagrams to illustrate problems and possible solutions. To construct a flow chart we need to think about the order in which the operations need to occur, then draw the chart. Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how

flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program. Flowcharts can be classified into two categories:

1. Program Flowcharts 2. System Flowcharts Program Coding When the flowchart or algorithm of a program is made , it must be translated into a form that a computer can use. So, the programmer converts the flowchart or algorithm into a program using various high level languages such as C. Clarity and simplicity are the major emphasis in coding. A program should be understandable and readable to others because once a program is made it can be read by others programmers later for modifications. The logic of the program should not be complex.

Program Testing and Execution The process which makes sure that the intended task is performed by the programmer is called testing. Testing is very time consuming step but it is also an important step for the development of the program. Testing is the task of detecting the errors in the program. There are generally two types of errors:1. Syntax Errors- When the rules of language are not properly followed, the syntax errors occurs. The syntax errors are detected by te compiler. The compilation of a program is unsuccessful if it contains the syntax errors. The compiler lists the errors with the line number of the error. 2. Logical Errors- the logical errors are made when the logic of the program is incorrect or errors made during the process of converting the logic from an algorithm to a program code. The program which contains logic errors can be successfully compiled or executed but it will produce incorrect results. Testing is of two types:1. Alpha testing- When the developing team of the program releases the version of the program internally for testing in a selected group either inside or outside the organization, Than that version of the program is called alpha version and the test conducted on the released version of the program is called alpha testing. 2. Beta Testing- When the version is released by the developing team for some additional testing to a selected group such as consumers, partners etc., then that released version is called the beta version and the test conducted on the released version is called the beta testing.

Execution When the program is free of syntax error and logic error it is executed successfully. The efficiency of the program depends on the execution time. The algorithm selected for the program should be efficient because the execution time depends on the efficiency of the algorithm. The execution time can be improved by adopting the coding techniques like the algorithm which is selected should be the fastest, fast arithmetic operations should be used, unnecessary calculations and multidimensional arrays should be avoided etc. Following flowchart shows the steps involved in executing the program:-

Q-2 What are decision Tables? What are their advantages? AnsDecision tables Decision tables are a precise, yet compact way to model complicated logic. Decision tables, like if-then-else and switch-case statements, associate conditions with actions to perform. But, unlike the control structures found in traditional programming languages, decision tables can associate many independent conditions with several actions in an elegant way. Decision tables are typically divided into four quadrants, as shown below.

Conditions

Condition alternatives

Actions

Action entries

Each condition corresponds to a variable, relation or predicate whose possible values are listed among the condition alternatives. Each action is a procedure or operation to perform, and the entries specify whether (or in what order) the action is to be performed for the set of condition alternatives the entry corresponds to. Many decision tables include in their condition alternatives the don't care symbol, a hyphen. Using don't cares can simplify decision tables, especially when a given condition has little influence on the actions to be performed. In some cases, entire conditions thought to be important initially are found to be irrelevant when none of the alternatives influence which actions are performed.

Apart from the basic four quadrant structure, decision tables vary widely in the way the condition alternatives and action entries are represented. Some decision tables use simple true/false values to represent the alternatives to a condition (similar to if-then-else), other tables may use numbered alternatives (similar to switch-case), and some tables even use fuzzy logic or probabilistic representations for condition alternatives. In a similar way, action entries can simply represent whether an action is to be performed (check the actions to perform), or in more advanced decision tables, the sequencing of actions to perform (number the actions to perform). The limited-entry decision table is the simplest to describe. The condition alternatives are simple boolean values, and the action entries are numbers, representing the order in which the actions in a given column are to be performed. Example A technical support company writes a decision table to diagnose printer problems based upon symptoms described to them over the phone from their clients.

Conditions

Printer does not print

Y

Y

Y

Y

N

N

N

N

A red light is flashing

Y

Y

N

N

Y

Y

N

N

Printer is unrecognised

Y

N

Y

N

Y

N

Y

N

Check the power cable

Actions

1

Check the printer-computer cable

1

2

Ensure printer software is installed

2

3

Check/replace ink

3

Check for paper jam

1

1 2

2

1 1

1

Of course, this is just a simple example (and it does not necessarily correspond to the reality of printer troubleshooting), but even so, it is possible to see how decision tables can scale to several conditions with many possibilities. Advantages of decision tables 1. Decision tables make it easy to observe that all possible conditions are accounted for. In the example above, every possible combination of the three conditions is given. In decision tables, when conditions are omitted, it is obvious even at a glance that logic is missing. Just as decision tables make it easy to audit control logic, decision tables demand that a programmer think of all possible conditions. With traditional control structures, it is easy to forget about corner/boundary cases, especially when the else

statement is optional. Since logic is so important to programming, decision tables are an excellent tool for designing control logic. 2. Easy to check for errors, contradictions, impossible situations etc. 3. Serve as input to decision table processors that produces computer program code Q-3 Describe what is meant by a program flow chart? AnsFlow Chart A flow chart is a graphical representation of the step by step instructions of any problem. It represents an algorithm, in the form of a chart, where the actions are shown by boxes of various shapes and flow of execution is indicated by arrows. Flow charts are just one way of using diagrams to illustrate problems and possible solutions. To construct a flow chart we need to think about the order in which the operations need to occur, then draw the chart. Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program. Flowcharts can be classified into two categories:

3. Program Flowcharts 4. System Flowcharts Program Flowchart: It is a diagrammatic representation of a sequence of instructions for solving a problem. System Flowchart: It is graphical representation of the flow of data throughout a data processing system and also in and out of the system. Flowcharts are constructed by using special geometrical symbols. The symbols commonly used in flow charts are: 1. Oval

This represents the START or STOP of the procedure.

2. Rectangle

Rectangle represents a process usually a primitive operation. If a process contains many primitive operations then rectangle with bars can be used. Diamond represents a decision box.

3. Diamond

4. Parallelogram This shape represents input/output operations. 5. Arrows

Arrows represents the flow lines.

All the flow charts begin with a START Point and finish with an STOP Point. These look like this on the chart :

START

Most of the boxes on a flow chart are instructions, which tell you what to do next. These appear in rectangular boxes like the one shown on the right:

STOP

PROCESS

Sometimes a question needs to be answered to decide what instruction should happen next. These questions are put in decision boxes like the one on the right: The various inputs and outputs to the program are shown by the rectangle symbol.

READ / PRINT

Guidelines for Drawing A Flowchart Flowcharts are usually drawn using some standard symbols; however, some special symbols can also be developed when required. Some standard symbols, which are frequently, required for flowcharting many computer programs are shown above. 1. Every flow chart has a START symbol and a STOP symbol 2. In drawing a proper flowchart, all necessary requirements should be listed out in logical order. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart. 3. The flow of sequence is generally from the top of the page to the bottom of the page. This can vary with loops which need to flow back to an entry point.

or

4. Only one flow line should come out from a process symbol. 5. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, should leave the decision symbol.

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

7. Write within standard symbols briefly. As necessary, you can use the annotation symbol to describe data or computational steps more clearly.

8. Use arrow-heads on connectors where flow direction may not be obvious. 9. There is only one flow chart per page. The page should have a page number and a title. 10. A flow chart on one page should not break and jump to another page 11. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication. 12. It is useful to test the validity of the flowchart by passing through it with a simple test data. Advantages of Using Flowcharts The benefits of flowcharts are as follows: 1. Communication: Flowcharts are good visual aid for communicating the logic of a system.

2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way. 3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes. 4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase. 5. Proper Debugging: The flowchart helps in debugging process. 6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part Q-4 Discuss the salient features of C language. AnsC is a general-purpose, structured programming language. It resembles other programming languages like Pascal, Java etc. A very rich library of data types and functions is available in C. The programs written in C are very compact and can be executed very fast. The programs written in C are highly portable. It was so powerful in its times that by 1973 UNIX OS was almost totally written in C. Special features of C language The special features of the C language are outlined below:                     

It is a block structured language with fundamental flow-construction statements. It has close interaction with the computer's inner working. Simple, contained, versatile, more expressive general purpose language. Excellent and efficient language for a variety of applications. It has high degree of language mobility. Functions can be written with a few lines of code thus making program development easier. It is fast and efficient. C is function oriented. Rich library of ready-programmed functions available. Rich set of operators are available. It has good control statements and excellent input/output facilities Dynamic storage allocation possible. Variables can be defined with high scope. C permits data conversion, mixed mode operations. Extensive variety of data types such as arrays, pointers, functions, unions, structures, registers are available. Parameter passing by value as well as by reference. Recursion feature is available. Functions can be compiled separately and called by any c program. C is more general and lacks restriction. Access to low level hardware via the use of pointers to refer to locations in memory. Easily manipulates with bits, bytes, and addresses. It is quite easy to interface an assembly function with a C program or a C function in an assembly program for real-time applications. It is mostly used for writing system programs and fast applications.

Q- 5 Name and describe the data types available in C. Ans- 9- Data types in C language Data types are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location. The data types are available in C can be classified as under: Please note that there is no boolean data type available in C. C data types

Basic data types

Derived data types

void

User-defined data types

array

struc

char

union

int

enum

float double

- C Data Types A variable with type char can hold only a single character, like 'a' or '*'. A variable with data type float or double can be assigned value in any format: an integer value, a real number, or a value in scientific format. Basic data types and their memory requirement Type

Bytes Bits

signed char

1

8

-128 -> +127

unsigned char

1

8

0 -> +255

short int

2

16

-32,768 -> +32,767

(32Kb)

unsigned short int

2

16

0 -> +65,535

(64Kb)

unsigned int

4

32

0 -> +4,294,967,295

( 4Gb)

int

4

32 -2,147,483,648 -> +2,147,483,647

( 2Gb)

long int

4

32 -2,147,483,648 -> +2,147,483,647

( 2Gb)

float

4

32

to the order of 10 38

8

64

double

Range

to the order of 10 308

Remarks

Notes: 1. These figures only apply to today's generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above. You can find out how much storage is allocated to a data type by using the sizeof operator. 2. short may be <= int 3. long may be >= int 4. unsigned without data type means int. Q-6 What is an operator? Describe several different types of operators included in C. Ans- Operators and Expressions: An operator in a language acts on one or more operands to yield a value. An operand is an entity on which an operator acts. Depending upon the number of operands required by the operator, the operators can be classified as unary, binary, or ternary operators. The unary operator requires only one operand, binary requires two, and ternary operators require three operands.

Unary operators: The unary arithmetic operator requires only one operand. For example in –5 and +7, - and + are unary operators. The other unary operators are: -- ++ sizeof cast ! Binary operators: These operators require two operands. The arithmetic operators +, -, /, *, and % are binary operators. Ternary operators: The one and only one ternary operator in C, also called ?: operator or conditional operator, requires three operands. This operator takes the form Test-operand ? operand-2 : operand-3 If test-operand is true, operand-2 is returned and operand-3 is not evaluated. Otherwise, operand-3 is returned and operand-2 is not evaluated. Example: big = a>b ? a : b This means that if a is greater than b then big is equal to a else big is equal to b. There are other classifications of operators also; they can be grouped as arithmetic operators, relational operators, logical operators, etc. The major classifications are as shown below:

Operators

Arithmetic

Relational

Logical

Assignment

Simple

Bitwise

Compound

1. Arithmetic operators: The symbols used for various arithmetic operations (like +, - etc.) are called arithmetic operators. The unary operators have only one entity involved, binary operators require two items. The binary arithmetic operators are given below:

Operato r +

Operation Addition

x + 100

-

Subtraction

200 - y

*

Multiplication

x*y

/

Division

x/y

%

Modulus

x%y

Example

Increment/Decrement operators: The operators ++ and – are called Increment and Decrement operators respectively. They are used to increment and decrement the values by one. For example: x=1; y=2; x++;

/*means x=x+1 */

++x;

/*same meaning i.e. x=x+1 */ /* different meaning if used in assignment statements */

y=x++;

/* means assign the value of x to y and then increment the value of x */

y=++x; */

/* means increment the value of x and then assign the value of x to y

y=x--; */

/* means assign the value of x to y and then decrement the value of x

y=--x; */

/* means decrement the value of x and then assign the value of x to y

2. Relational operators: These operators are used to compare various expressions. They check the relation between the expressions. The relation may less than, equal to, greater than etc. The relational operators are given below:

Operation

Operator

Example

<

Less than

x
<=

Less than or equal to

N <= 100

>

Greater than

I > 10

>= ==

Greater equal to Equal to

!=

Not equal to

than

or

ctr >= MAX M = = 1000 Seats != 0

3. Logical/Boolean operators: The logical operators are symbols that are used to combine or negate expressions containing relational operators. The operator && is called the 'and' operator, and is used to combine the two expressions. The expression exp1&&exp2 will be true if both exp1 and exp2 are true. In C, false is represented by zero and true is represented by non-zero value.

Operato Operatio r&& n And

Example x>1 && x<100

||

Or

Age>60 job="N"

!

Not

! ( x>100)

||

4. Assignment operators: These operators are very important component of C language. The assignment operator assigns a value to the variable on the left hand side of the assignment statement. The operator = is called assignment operator. The compound assignment is a shorthand method of assigning values to variables. It is a common practice to update the value of variable with the statement like sum = sum + x; The operator += comes handy in such situations. The same statement can be written as: sum+=x; The table below summarizes other such operators available in C.

Operato r = += -= *= /= %=

Operation

Example

Result

Assignment Addition update Subtraction Multiplication Division Modulo

x = 10 sum += x tot -= 1 x *= y x /= y x %= y

x=10 sum=sum+x tot=tot-1 x =x*y x = x/y x = x%y

Similarly, the bit-wise operators <<, >> &=, !=, and ^= can also be used in the same way. 5. Bitwise operators: C language permits the direct manipulation of bits stored in the memory with the help of bitwise operators. The various bitwise operators are given below:

Operato Operation r<< Left shift

Example X << 2

>>

Right Shift

X >> 2

&

AND of bits

X&Y

|

Inclusive OR of bits

X|Y

^

Exclusive OR of bits

X^Y

Q-7- What is the purpose of the 'for' statement? How does it differ from the while statement and the do-while statement? AnsThe for Statement : The for loop is useful when you want to execute a statement or a group of statements fixed number of time. The for statement is a widely used statement in many languages. The for statement has been explained below with the help of a diagram.

Keyword

Initialization Expression (

Test Expression ;

Increment Expression ;

for (expression1; expression2; expression3) { statement-one; statement-two; statement-three; statement-so-on; } statements-when-expression2-becomes-false;

)

In this statement, expression1 is used to initialise the variable the controls the loop e.g. counter=1. The expression2 is the test expression; the loop continues till the expression2 is true e.g. counter<10, and expression3 is called the increment expression e.g. counter=counter+1. These three expressions are separated by semicolon(;). Here follows the example of for statement. /* Program to find the sum of first N natural numbers */ #define N 100 #include <stdio.h> main() { int i,sum=0; for(i=1; i<=N; i++) sum = sum + i; printf("\n The sum of first %d natural numbers is %d ",n,sum);} The for statements can also be nested. But make sure that inner for statement is completely inside the outer for statement. The following program uses nested for statements. /* Program to print the N x N tables */ #define N 10 #include <stdio.h> main() { int i,j; for(i=1; i<=N; i++) { for(j=1; j<=N; j++) printf("%5d",i*j); printf("\n"); } The output of the above program is :

The do…while Statement

Sometime, it is desirable to execute the body of loop at least once, even if the test expression evaluate to false. Do…while loop is helpful in such situations. It executes the body of the loop and then tests the expression. If the expression is true the loop will be repeated, else the loop will be terminated. The syntax of the do…while loop is:

do statement; } while (expression);

do { statement-one; statement-two; statement-three; statement-so-on; } while (expression);

And the program to demonstrate the working of the do…while loop is given below: /* Program to find the sum of digits of a number */ #include <stdio.h> main() { int n,sum,digit; sum=0; printf("Enter number :"); scanf("%d",&n); do { digit=n%10; /* Extract right most digit */ sum = sum + digit; n = n /10; } while (n>0); printf("The sum of the digits is %d\n",sum); } Output Enter number : 1234 The sum of the digits is 10

Q-8- What is the purpose of using arrays? Ans- Arrays Arrays are one of the most powerful programming tools available. They provide the programmer with a way of organizing a collection of homogeneous data items (i.e. items that have the same type and same length) into a single data structure. Thus, an array is a collection of data items that are represented by a common name and all items are stored in contiguous memory locations. We can refer to various elements of the array just like any other variables. Then why use arrays? Well, the answer lies in the following situation. Suppose we want to find the average of three numbers. We can name the variables as a, b, and c. Fine! What happens if the number of variables is 100 or even more? If becomes very difficult to name the variables as a1, a2, a3…a100. But, with the help of arrays this becomes much simpler.

3

3 3

5

3 2

1-D array

2-D array

3-D array

Figure 4.5-One-dimensional, two-dimensional, and three-dimensional arrays 4.5.1 Declaring Arrays The method of defining arrays is similar to that of variables. An array contains elements of same type. To declare an array marks containing 10 integers, we declare it as: int marks[10]; Here, the name of the array is marks. It has 10 elements. First element is marks[0], second element marks[1], and last element of this array is marks[9]. The number 10, here, specifies the dimension of the array. Since we have specified only one dimension, this is a onedimensional array. One-dimensional arrays are also called lists or vectors. To declare two-dimensional arrays, we specify both the dimensions. The data items that are in the form of a table (i.e. rows and columns) can be easily represented by a 2-dimensional array. The 2-dimensional arrays are also called a matrix. Some examples of twodimensional arrays are: int x[10][10]; float y[100][100]; In the similar way, we can declare multi-dimensional arrays. 4.5.2 Initializing Arrays Just like the ordinary variables, the arrays can also be initialised. In the next program an array is declared as a global variable. The global variable are declared before the function (usually the main function) in which they are used.

/* Program to initialize a global array */ #define <stdio.h> int x[6] = { 10,20,30,40,50,60 }; main() { int i; for(i = 0; i < 6; i++) printf("Array Element# %d is %d\n",i+1,x[i]); } Output Array Element# 1 is 10 Array Element# 2 is 20 Array Element# 3 is 30 Array Element# 4 is 40 Array Element# 5 is 50 Array Element# 6 is 60 Arrays can be declared at the time of initialisation if their initial values are known at that time. To declare local arrays, slightly different approach is used. We use the keyword static before declaring the array as follows: static int x[6] = { 10,20,30,40,50,60 }; the same program can be re-written as follows: /* Program to initialize a local array */ #define <stdio.h> main() { static int x[6] = { 10,20,30,40,50,60 }; int i; for(i = 0; i < 6; i++)

printf("Array Element# %d is %d\n",i+1,x[i]); } It is not always necessary to specify the size of the array if it is being initialised. For example, C allows the array to be declared as follows: int x[] = { 10,20,30,40,50,60 }; Initialising two-dimensional arrays A two dimensional array can be initialised at the time of its declaration as follows: data-type array-name[no-of-rows][no-of-cols] = { {elements of first row }, {elements of second row }, … {elements of last row } }; The example of 2-D array is shown below: int array[2][4] ={ {1,2,3,4}, {5,6,7,8} };or int array[2][4] ={ 1,2,3,4, 5,6,7,8 };or int array[][4] ={ 1,2,3,4, 5,6,7,8 }; The first declaration implies that the values for rows can be mentioned with inner braces. If the number of elements in the braces are less than the required number then the remaining values are taken as zeroes and if the values are more than required, then they are discarded. The inner braces can be omitted allowing the numbers to be written in one continuous sequence. The outer dimension can also be omitted at the time of initialisation as the count will be supplied by the compiler. Q-9 What are structures? Write the advantages of using structures. Ans- Structures A structure in C is a collection of items of different types. You can think of a structure as a "record" is in Pascal or a class in Java without methods. Structures are very useful in creating complex data structures. A structure provides a means of grouping variables under a single name for easier handling and identification. Complex hierarchies can be created by nesting structures. Structures may be copied to and assigned. They are also useful in passing groups of logically related data into functions.

6.3.1 Declaring Structures A structure is declared by using the keyword struct followed by an optional structure tag followed by the body of the structure. The variables or members of the structure are declared within the body. Here is an example of a structure that would be useful in representing the Cartesian coordinates of a point on a computer screen, that is, the pixel position. struct point { int x; int y; }; The struct declaration is a user defined data type. Variables of type point may be declared similarly to the way variables of a built in type are declared. Here point is a structure tag and upperLeft is a variable. struct point { int x; int y; } upperLeft; The structure tag provides a shorthand way of declaring structures. struct point NewPoint; //NewPoint declared from data type point The C language allows data types to be named using the keyword typedef. For example: typedef double Money; in a similar way we can typedef structures also. This is illustrated next. 6.3.2 Using Structures The individual members of a structure can be accessed using "." operator. Given typedef struct point { int x; int y; } Dot; .... struct DOT location;

// Dot becomes new data type & location // becomes a variable of Dot type.

The x coordinate is location.x The y coordinate is location.y It is also possible to create hierarchies by nesting structures. A rectangle could be represented as follows.

typedef struct rect { Dot upperLeft; Dot upperRight; Dot lowerLeft; Dot lowerRight; } Box; 6.3.3 Initializing Structures Structures can be initialized at the time of their declaration as illustrated below:

struct point { int x; int y; } Corner = {10,20};

This makes Corner.x = 10 and Corner.y = 20. Q-10- What is procedure oriented programming? Explain the features of object oriented programming?

Ans- Procedural 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. After the sequence is processed, flow of control proceeds right after the position where the call was made With introducing parameters as well as procedures of procedures (subprocedures) 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 errors you can narrow your search to those places which are not proven to be correct. Now a program can be viewed as a sequence of procedure calls. The main program is responsible to pass data to the individual calls, the data is processed by the procedures and, once the program has finished, the resulting data is presented The main program coordinates calls to procedures and hands over appropriate data as parameters.

Figure 8.3.2- Procedural Programming

To sum up: Now we have a single program which is divided into small pieces called procedures. To enable usage of general procedures or groups of procedures also in other programs, they must be separately available. For that reason, modular programming allows grouping of procedures into modules. Features of Object Oriented Programming

The basic features used in object oriented programming include objects, classes, Data abstraction, Inheritance, Polymorphism and message passing. Let us discuss these concepts: 8.5.1 Objects

The field of object orientation is a large and growing one. Object orientation is about trying to represent the ‘objects’ that we find in the real world in software. Objects are the elements through which we perceive the world around us. We know that all these elements have recognizable identities and particular behaviors. Objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: your dog, your desk, your television set, your bicycle. These real-world objects share two characteristics: They all have state and behavior. For example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). Bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears). Another key element in object oriented methodology is that objects can be classified into types again a natural response to our environment. The basic philosophy of using objects in programs is that the world is composed of interacting, classifiable and identifiable objects and therefore programs too can usefully be structured in this way. An object is a software bundle of related variables and methods. Software objects are often used to model real-world objects you find in everyday life. Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function (subroutine) associated with an object. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as a software object in the program that controls an electronic exercise bike.

The most important thing about object oriented approach to software is that it unifies inside ‘objects’ two things – data and processes. These have traditionally separated in programming paradigms. The object's variables make up the center, or nucleus, of the object. Methods surround and hide the object's nucleus from other objects in the program. Packaging an object's variables within the protective custody of its methods is called encapsulation. This conceptual picture of an object-a nucleus of variables packaged within a protective membrane of methods-is an ideal representation of an object and is the ideal that designers of object-oriented systems strive for. Encapsulating related variables and methods into a neat software bundle is a simple yet powerful idea that provides two primary benefits to software developers: 



Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. You can give your bicycle to someone else, and it will still work. Information hiding: An object has a public interface that other objects can use to communicate with it. The object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it. You don't need to understand the gear mechanism on your bike to use it.\ 8.4.2 Class A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behavior (change gears, brake) in common. However, each bicycle's state is independent of and can be different from that of other bicycles. In object-oriented software, it's also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. We can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. A software blueprint for objects is called a class. The class for our bicycle example would declare the instance variables necessary to contain the current gear, the current cadence, and so on, for each bicycle object. The class would also declare and provide implementations for the instance methods that allow the rider to change gears, brake, and change the pedaling cadence After you've created the bicycle class, you can create any number of bicycle objects from the class. When you create an instance of a class, the system allocates

enough memory for the object and all its instance variables. Each instance gets its own copy of all the instance variables defined in the class. A class is an actual representation of an ADT. It therefore provides implementation details for the data structure used and operations. We play with the ADT Integer and design our own class for it: class Integer { attributes: int i methods: setValue(int n) Integer addValue(Integer j) } In the example above as well as in examples which follow we use a notation which is not programming language specific. In this notation class {...} denotes the definition of a class. Enclosed in the curly brackets are two sections attributes: and methods: which define the implementation of the data structure and operations of the corresponding ADT. Again we distinguish the two levels with different terms: At the implementation level we speak of ``attributes'' which are elements of the data structure at the ADT level. The same applies to ``methods'' which are the implementation of the ADT operations. In our example, the data structure consists of only one element: a signed sequence of digits. The corresponding attribute is an ordinary integer of a programming language. We only define two methods setValue() and addValue() representing the two operations set and add. Definition (Class) A class is the implementation of an abstract data type (ADT). It defines attributes and methods which implement the data structure and operations of the ADT, respectively. Instances of classes are called objects. Consequently, classes define properties and behavior of sets of objects. An object is an instance of a class.

8.5.3 Data Encapsulation and Data Abstraction Encapsulation is the practice of including in an object everything it needs, (both data and methods) hidden from other objects in the system. The internal state of an object is not accessible from outside and cannot be altered by external changes to the application. Abstraction refers to the act of representing essential features of an object without including the background details or explanation. These essential features are the states and behavior of the object. They include the attributes and the functions to operate on these attributes. The attributes are called data members and the functions that operate on these data are called methods or member functions.

8.5.4 Inheritance Generally speaking, objects are defined in terms of classes. Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. Inheritance means that one class inherits the characteristics of another class as part of its definition. Inheritance is appropriate when one class is ‘ a kind of’ other class e.g.: A is kind of B = ‘text window is a kind of window’ , ‘apple is a kind of fruit’, ‘racing bike is a kind of bicycle’. Inheritance allows a class A to inherit properties of a class B. We say ``A inherits from B''. Objects of class A thus have access to attributes and methods of class B without the need to redefine them. The following definition defines two terms with which we are able to refer to participating classes when they use inheritance. If class A inherits from class B, then B is called super class of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding super class are expected. This is due to the fact that objects of the subclass share the same behaviour as objects of the superclass. In the literature you may also find other terms for ``superclass'' and ``subclass''. Superclasses are also called parent classes. Subclasses may also be called child classes or just derived classes. Of course, you can again inherit from a subclass, making this class the superclass of the new subclass. This leads to a hierarchy of superclass/subclass relationships. For example, table is a part of the class ‘wooden furniture’ which is again a part of the class furniture. Each derived class shares the common characteristics with the class from which it is derived. A common drawing scheme is to use arrowed lines to indicate the inheritance relationship between two classes or objects. In our examples we have used ``inherits-from''. Consequently, the arrowed line starts from the subclass towards the super class as illustrated in the figure given below:

A simple inheritance graph.

Here, the sub class circle, derived from the super class point, has all the characteristics of point class and its own attributes. In OOP, the concept of inheritance provides the idea of reusability. That means we can add additional features to an existing class without modifying it. To achieve this, derive a new class from the existing one. The new class will have the combined features of both the classes.

Multiple Inheritance One important object-oriented mechanism is multiple inheritance. Multiple inheritance does not mean that multiple subclasses share the same super class. It also does not mean that a subclass can inherit from a class which itself is a subclass of another class. Multiple inheritance means that one subclass can have more than one super class. This enables the subclass to inherit properties of more than one super class and to ``merge'' their properties. As an example consider drawing program. Suppose we already have a class String which allows convenient handling of text. For example, it might have a method to append other text. In our program we would like to use this class to add text to the possible drawing objects. It would be nice to also use already existing routines such as move() to move the text around. Consequently, it makes sense to let a draw able text have a point which defines its location within the drawing area. Therefore we derive a new class DrawableString which inherits properties from Point and String as shown below: Derive a draw able string which inherits properties of Point and String.

Figure 8.5.4(b) - Multiple Inheritance We can use objects of class DrawableString like both points and strings. Multilevel Inheritance You can built hierarchies that contain as many layers of inheritance as you like. As mentioned, it is perfectly acceptable to use a derived class as a base class of another. For example, given three classes called A, B and C, C can be derived from B, which can be derived from A. When this type of situation occurs, each derived class inherits all of the traits found in all of its base classes. In this case, C inherits all aspects of B and A.

8.5.5 Polymorphism Polymorphism refers to the ability of an object to behave in different ways based on the context. The same function may exist in related classes. For instance both a general "Car" class and derived "Ford" and "Chevy" classes might have accelerate functions. A program using these classes might at run-time choose to use one of these classes and the correct accelerate function will be resolved as the program runs. A second form of polymorphism results from the overloading of functions. Multiple functions can have the same name but different arguments. The correct one is chosen based on the arguments used in its invocation.

8.5.6 Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. It is mainly of two types:1.Static Binding or Early Binding 2.Dynamic Binding or Late Binding Static binding is to be performed at the time of the compilation, but dynamic binding is the code that is associated with the procedure call is known until the time of call at the run time. Dynamic Binding is also called late binding or run time binding. Virtual functions are used to achieve dynamic binding. Dynamic binding provides more extensible and flexible software architectures. 8.5.7 Message Passing Message- A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-order functionality and more complex behavior. An object oriented program consists of a set of objects that communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B. Sometimes, the receiving object needs more information so that it knows exactly what to do; for example, when you want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with the message as parameters. The three components that comprise a message are: The object to which the message is addressed (YourBicycle) The name of the method to perform (changeGears) Any parameters needed by the method (lowerGear) Message Passing-A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-order functionality and more complex behavior. Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B. Messages provide two important benefits.  

An object's behavior is expressed through its methods, so (aside from direct variable access) message passing supports all possible interactions between objects. Objects don't need to be in the same process or even on the same machine to send and receive messages back and forth to each other.

Related Documents

1102
October 2019 22
Que Tal C[1]..
April 2020 12
1102-1704-1-pb.pdf
May 2020 5
Juanes 1102
June 2020 6
1102-comm
July 2020 6

More Documents from "api-26365311"