Está en la página 1de 187

Digital Communication

IT 3012

For

Second Semester

Sample Question

1. 2. 3.

What is multiplexing? Explain its application. (10 marks) What are the distinct characteristics of FDM use FDM application.(20 marks) Explain TDM (Time division Multiplexing) system and show TDM of analog and digital source is organized? (20 marks) 4. Describe Basic ISDN Interface. (20marks) 5. Describe primary ISDN Interface. (10 marks) 6. Explain the STS-1 overhead bit for line overhead and path overhead .(10 marks) 7. Draw the frame-format for SONET/SDH and show in the table from overhead octet of STS-1.(10 marks) 8. Write short notes on circuit-switching network. (10 marks) 9. Describe and explain for general architectural components for public telecommunication network. (10 marks) 10. What are the signaling functions and describe. (20 marks) 11. How many types of routing techniques in circuit-switched network? Explain them. (20marks) 12. Explain the elements of a circuit-switched node. (20marks) 13. State and explain cross-bar switch limitation. (10 marks) 14. Show the advantages of packet switching over circuit switching. (10marks) 15. Draw timing diagram for circuit-switch |& packet switching and describing and describe three types of delay. (10 marks) 16. Using diagram, show the effect of packet size on transmission time.(10 marks) 17. Compare the different communication switching techniques by using tables. (20 marks) 18. Draw the diagrams of External and Internal virtual circuit and diagram.(10 marks) 19. Explain fixed Routing and draw the table for central routing directory for a given packet-switched network. (20marks)
8 5

2 2 3 1 1 7 4 2 2

3 6 3 3 8 5 3 1 1 1 1 4 2 5 6

FIGURE

Example packed-switched network

20. Draw the diagram of sequence of events: X.25 protocol.(20 marks) 21. Explain Frame Relay Protocol Architecture. (20marks) 22. Why the congestion ad voidance procedures are used? Explain two bits in the address Field are used for congestion ad voidance procedure.(10 marks) 23. Draw and briefly explain the comparison of X.25 and frame relay protocol stacks. (10 marks)

IT - 3012 DIGITAL COMMUNICATION SAMPLE QUESTIONS & ANSWERS

CHAPTER (7) MULTIPLEXING


1. What is multiplexing? Explain its application.(8 marks) Solution: Two communicating stations will not utilize the full capacity of a data link. For efficiency, it should be possible to share that capacity, sharing is called multiplexing. Fig shows the multiplexing function in its simplest form. There are n inputs to the multiplexer. The multiplexer is connected by a single data link to a demultiplexer. The link is able to carries n separate channels of data. The multiplexer combines (multiplexes) data from the n input lines and transmits over a higher-capacity data link. The demultiplexer accepts the multiplexed data stream, separates (demultiplexes) the data according to channel, and delivers them to the appropriate output line.

1 link, n channel n inputs


MUX

DE MUX

n outputs

FIGURE. Multiplexing The widespread use of multiplexing in data communications can be explained by the following: 1. The higher the data rate, the more cost-effective the transmission facility. For a given application and over a given distance, the cost per kbps declines with an increase in the data rate of the transmission facility. 2. Most individual data-communicating devices require relatively modest data-rate support. For example, for most terminal and personal computer applications, a data rate of between 9600 bps and 64 kbps is generally adequate.

2.

What are the distinct characteristics of FDM use FDM application.(16 marks) Solution: FDM are possible when the useful bandwidth of the transmission medium exceeds the required bandwidth of signals to be transmitted. A number of signals can be carried simultaneously if each signal is modulated onto a different carrier frequency. Each modulated signal requires a certain bandwidth centered around its carrier frequency, referred to as a channel. To prevent interface, the channels are separated by guard bands, which are unused portions of the spectrum. The composite signal transmitted across the medium is analog. The input signals may be either digital or analog .Digital input, the input signal must be passed through modems to be converted to analog. Each input analog signal must then be modulated to the appropriate frequency band. A number of analog or digital signals [mi (t), i = 1, N ] are to be multiplexed onto the same transmission medium . Each signal mi (t) i, modulated onto a carrier frequency. The resulting modulated analog signals are then summed to produce a composite signal mc (t). The composite signal has a total bandwidth B. At the receiving end, the composite signal is passed through N band pass filters, each filter centered on frequency and having a bandwidth. The signal is again split into its component parts. Each component is then demodulated to recover the original signal.

3. Explain TDM (Time division Multiplexing) system and show TDM of analog and digital source is organized? Solution Time Division Multiplexing A number of signals [mi(t) , i=1,n] are to be multiplexed onto the same transmission medium. The signals carry digital data and are generally digital signals. The incoming data from each source are briefly buffered. Each buffer is typically one bit or one character in length. The buffers are scanned sequentially to form a composite digital data stream mc (t). The digital signal mc (t) may be transmitted directly or passed through a modem so that an analog signal is transmitted. The data are organized into frames. Each frame contains a cycle of time slots. The sequence of slots dedicated to one source, from frame, is called a channel. The slot length equals the transmitter buffer length, typically a bit or a character. The character interleaving technique is used with asynchronous sources. The bit-interleaving technique is used with synchronous sources and may also be used with asynchronous sources. At the receiver, the interleaved data are demultiplexed and routed to the appropriate destination buffer. The output source which will receive the input data at the same rate.

Time

c ch ch a c c han chh an6 an han 5 an3 4 f5f6 n2 f4 1 f3 frequency f2 f1

Figure: Frequency division multiplexing


Sub carrier fsc 1 Ssc1 (t)

m1 (t)

m2 (t)

Sub carrier fsc 2

Ssc2 (t)

Mc (t)

Transmitter fc

S(t) = FDM

mN (t)

Sub carrier fsc N

SscN (t)

(a) Transmitter

1 Mc f (t)

f sc 1 Bsc 1

f sc 2 Bsc 2

f sc N Bsc
N

(b) Spectrum of composite signal (positive f)


Bandpass filer , fsc 1 Demodulator fsc 1 Demodulator fsc 2 m 1 (t)

S (t)

Receiver

Bandpass filer , fsc 2

m 2 (t)

Bandpass filer , fsc N

Demodulator fsc N

m N (t)

( c) Receiver Figure: Frequency Division Multiplexing

frequency Time

Buffer m1 (t) m2 (t)

Scan operation

me (t)

Modem

S (t)

mn (t)

(a) Transmitter

m1(t) m2(t) mc(t) mn(t)

frame

frame N
1

1 2
1

Time slot: may be empty or occupied

(b) TDM frames


Scan Operation Buffer

(c) Receiver FIGURE Synchronous time-division multiplexing

source 1
2kHz, analog

TDM PAM signal

source 2
4kHz, analog f

16 kHz f - 4kHz

4 bit A/D

TDM PCM signal

2 bit buffer

64 kbps

source 3
2kHz, analog source 4 7.2 kbps , digital Pulse stuffing 8 kbps

2 bit buffer TDM signal


Scan

128 kbps 8 kbps

source 11 7.2 kbps , digital

Pulse stuffing

2 bit buffer

Figure: TDM of analog and digital sources

4.

Describe Basic ISDN Interface.(16marks)

Solution: Basic ISDN Interface The basic access structure consist of two 64 kbps B channels and one 16 kbps D cannel, 144 kbps, are multiplexed over a 192 kbps interface at the S or T reference point. The remaining capacity use for various framing and synchronization purposes. The B channel is the basic user channel. It can be use to carry digital data. The D channel can be use for a data transmission connection at a lower data rate. It is also use to carry control information needed to setup and terminate the B channel connections. Each frame of 48 bits includes 16 bits from each of the two B channel, and 4 bits from the D channel: The remaining bits have the following interpretation. In the TE to NT direction. Each frame begins with a framing bit (F) that is always transmitted as a positive pulse. This is followed by a dc balancing bit (L) that is set to a negative pulse to balance the voltage. The F-L pattern thus acts to synchronize the receiver on the beginning of the frame. The next eight bits (B1) are form the first B channel this is followed by another dc balancing bit (L). Next comes a bit from the D channel, followed by its balancing bit. This is followed by the auxiliary framing bit (FA), which is set to zero unless it is to be use in a multi-frame structure. There follows another balancing bit (N), eight bits (B2) from the second B channel, and another balancing bit (L); this is follow by bits from the D channel, first B channel, D channel again, second B channel, and the D channel, again. In the NT to TE direction is similar to the frame structure for transmission in the TE-to-NT direction. The following new bits replace some of the dc balancing bits. The activation bit (A) is use to activate or deactivate a TE. The N bit is normally set to binary one. The N and M bits may be use for multi-framing. The s bit is reserved. For other future standardization requirements. There are three types of traffic: B-channel traffic: No additional functionality is needed to control access to the two B channel is dedicated to a particular TE at any given time. D- channel traffic: The D channel is available for use by all the subscriber devices for both control signaling and packet transmission, so the potential for contention exits, There are two sub cases: Incoming traffic: The LAPD addressing scheme is sufficient to sort out the proper destination for each data unit. Outgoing traffic: Access must be regulated so that only one device at a time transmits. This is the purpose of the contention-resolution algorithm. + Fig: 7.10 from Page 18

5.

Describe primary ISDN Interface.(8marks) Solution: Primary ISDN Interface The primary interface multiplexes multiple channels across a single transmission medium. In the case of the primary interface, only a point-to-point configuration is allowed. Typically, the interface supports a digital PBX, and providing a synchronous TDM facility for access to ISDN. Two data rate are defined for the primary interface: 1.544 Mbps and 2.048 Mbps. The ISDN interface at 1.544 Mbps is based on the North American DS-1 transmission structure, which is use on the T1 transmission service. The bit stream is structured into repetitive 193 bit frames. Each frame consists of 24, 8 bit time slots and a framing bit, which is used for synchronization and other

management purposes. At a data rate of 1.544 Mbps, frames repeat at a rate of one every 125sec, or 8000 frames per second. The transmission structure is use to support 23 B channels and 164 kbps D channel. The line coding for the 1.544Mbps interface is AMI (Alternate Mark Inversion) using B825. The ISDN interface at 2.048 Mbps is based on the European transmission structure of the same data rate. The bit stream is structure into repetitive 256bit frames. Each frame consists of 32,8bit time slots. The first time slot is use for framing and synchronization purposes: the remaining 32 time slots support user channels. At a data rate of 2.048Mbps, frames repeat at a rate of one every 125sec, or 8000 frames per second. The transmission structure is used to support 30B channels and 1D channel. The line coding for the 2.048-Mbps interface is AMI using HDB3.
1 frame =193 bits, 125 sec Time slot 0
F

Time slot 1 12345678

Time slot 31 12345678

12345678

(a) Interface at 1.54 Mbps


1 frame =256 bits, 125 sec Time slot 0 12345678 framing channel Time slot 1 12345678 Time slot 2 12345678 Time slot 32 12345678

(b) Interface at 2.048 Mbps Fig: ISDN primary access frame formats 6. Explain the STS-1 overhead bit for line overhead and path overhead .(8marks) Solution: Line overhead H1-H3: Pointer bytes used in frame alignment and frequency adjustment of payload data. B2: Bit-interleaved parity for line level error monitoring. K1, K2: Two bytes allocated for signaling between line level automatic protection switching equipment. D4-D12: 576kbps data communication cannel for alarms, maintenance, control, monitoring and administration at the line level. Z1-Z2: Reserved for future use. E2: 64kbps PCM voice channel for line level orderwire. Path overhead J1:64kps channel used to repetitively send a 64-octed fixed-length string so a receiving terminal can continuously verity the intergrity of a path; the contents of the message are user programmable. B3: Bit-interleave parity at the path level. C2: STS path signal label to designate equipped versus unequipped STS signals. G1: Status byte sent from path terminating equipment back to path originating equipment to convey status of terminating equipment and path error performance. F2: 64 kbps channel for path user. H4: Multiframe indicator for pay load needing frames that are used when packing lower rate channel. Z3-Z5:Reserved for future use.

7. Draw the frame-format for SONET/SDH and show in the table from overhead octet of STS1.(8marks) Solution: SONET is intended to provided a specification for taking advantage of the high-speed digital transmission capacity of optical fiber. 90 octets Synchronous payload environment(SPE) Section overhead 8 octets Line overhead 6 octets 87 octets

Path overhead 1 octet Transport overhead 3 octets FIGURE STS1 Frame Format

Section overhead

Line overhead

Framing A1 BIP-8 B2 Data Com D1 Pointer H1 BIP-8 B2 Data Com D4 Data Com D7 Data Com D10 Growth Z1

Framing A2 Order Wire E1 Data Com D2 Pointer H2

STS-ID C1 User F1

Data Com D3 Pointer Action H3 APS K1 APS K2 Data Com D5 Data Com D8 Data Com D11 Growth Z2 Data Com D6 Data Com D9 Data Com D12 Order wire E2

(a) Section Overhead

Trace J1 BIP-8 B3 Signal level C2 Path status G1 User F2 Multiframe H4 Growth Z3 Growth Z3 Growth Z5 (b) Path overhead SONET/STS-1 overhead octets

Figure:

CHAPTER (8) CIRCUIT SWITCHING


8. Write short notes on circuit-switching network.(8 marks) Solution: Figure 8.1+

Communication via circuit switching implies that there is a dedicated communication path between two stations. That path is a connected sequence of links between network nodes. On each physical link, a logical channel is dedicated to the connection. Communication via circuit-switching involves three phases: 1. Circuit Establishment: Before any signals can be transmitted, on end-to-end circuit must be established. For example, station A sends a request to node 4 requesting a connection to station E. so, the link from A to 4 is a dedicated line. Node 4 must find the next node leading to node 6. Node 4 selects the link to node 5, and sends a message requesting connection to E. Therefore a dedicated path has been established from a through 4 to 5 and similarly, 5 to 6. Node 6 completes the connection to E. In completing the connection, a test is made to determine it E is busy or is prepared to accept the connection. 2. Data Transfer: Information can now be transmitted from A through network to E. The data may be analog or digital, depending on the nature of the network. The path is A-4 link, internal switching through 5,5-6 channel, and internal switching through 6, 6-E link, Generally, the connection is fullduplex. 3. Circuit Disconnect: After some period of data transfer, the connection is terminated, usually by the action of one of the two stations. Signals must be propagated to nodes 4,5 and 6 to de-allocate the dedicated resources.

9. Describe and explain for general architectural components for public telecommunication network. (8marks) Solution: Four generic architectural components 1. Subscribers: The devices that attach to the network. (e g. telephone) 2. Local loop: The link between the subseriber and the network, also referred to as the subscriber loop. Almost all local loop is in a range a few kilometers to a few tens of kilometers. 3. Exchanges: The switching canters in the network, which is directly supports subscribers is known as an end office. An end office supports many thousands of subscribers in localized area. 4. Trunks: The branches between exchanges. Trunks carry multiple voice frequency circuits using either FDM or synchronous TDM. Earlier, these were referred to as carrier systems.

Telephone

End o o o o o

Office o o o o o

Long-Distance Office

Long-Distance Office

Subscriber Loop

o o o o o o o o o o

o o o o o o o o o o

o o o o o o o o o o

o o o o o o o o o o

End Office

o o o o o Connecting Trunk Intercity Trunk

o o o o o

Digital PBX

Telephone

Figure: Public- Circuit- Switching network

10. What are the signaling functions and describe.(16marks) Solution: Signaling Functions 1. Audible communication with the subscriber, including dial tone, ringing tone, busy signal and so on. 2. Transmission of the number dialed to switching office, that will attempt to complete a connection. 3. Transmission of information between switches indicating that a call cannot be completed. 4. Transmission of information between switches indicating that a call has ended and that the path can be disconnected. 5. A signal to make a telephone ring. 6. Transmission of information used for billing purposes. 7. Transmission of information giving the status of equipment or trunks in the network. This information may be used for routing and maintenance purposes. 8. Transmission of information used in diagnosing and isolating system failures. 9. Control of special equipment such as satellite channel equipment.

Signaling can also be classified functionally as supervisory, address, call-information, and network management. (1) Supervisory control signal The term supervisory is generally used to refer to control function, that have a binary character C true/false; on (off) , such as request for service, answer, alerting, and return to idle; They deal with the availability of the called subscriber and of the need network resources. (2) Address control signals Address signals identify a subscriber, and it is generated by a calling subscriber when dialing a telephone number. The resulting address may be propagated through the network to support the routing function and to locate and ring the called subscribers phone. (3) Call-information control signals - provide information to the subscriber about the status of a call. - are audible tones that can be heard by the caller or operator with the proper Phone set. (4) Network management signal - is used for maintenance, troubleshooting, and overall operator of the network. -may be in the form of message, such as a list of preplanned routes being sent to a station to update its routing tables. 11. How many types of routing techniques in circuit-switched network? Explain them.(16marks)

Solution: Two types: (1) Alternate Routing (2) Adaptive Routing (1) Alternate Routing The essence of alternate-routing scheme is that possible routes to be used between two end offices are predefined. It is the responsibility of the originating switch to select the appropriate route for each call. Each switch is given a set of pre-planned routes for each destination, in order of preference C i.e, a direct link connection between two switches. If this trunk is unavailable, then the second choice is to be tired, and so on. The routing sequence are based on historical traffic patterns and designed to optimize the use of network resources. There are two types of Alternate-Routing Scheme. (a) Fixed-alternate Routing If there is only one routing scheme defined for each source-destination pair, the scheme is known as a fixedalternate-routing scheme. (b) Dynamic Alternate-routing A different set of pre-planned routes is used for different time periods. The routing decision is based both on current traffic status and historical traffic patterns. (2) Adaptive Routing An adaptive-routing scheme is designed to enable switches to react to changing traffic patterns on the network. Such schemes require greater management overhead, as the switches must exchange information to learn of network conditions. Dynamic traffic Management (DTM) is a routing capability. DTM uses a central controller to find the best alternate route choices depending on congestion in the network. The central controller collects the status data from each switch in the network every 10 seconds to determine preferred alternate routes. Each

call is first attempted on the direct path, if any exits, between source and destination switches. If the call is blocked, it is attempted on a two-link alternate-path.

12. Explain the elements of a circuit-switched node.(16marks)

Elements of a circuit-switch node are: (1) digital switch (2) network interface element (3) control unit (1) Digital switch The function of the digital switch is to provide a transparent signal path between any pair of attached devices, and to connect directly between them by using full-duplex transmission. (2) Network-Interface Element The network-interface elements the functions and hardware needed to connect digital device, such as data processing devices and digital telephone, to the network. Analog telephone can also be attached if the network interface contains the logic for converting to digital signals. It provide the links for constructing multiple-node networks. (3) Control unit The control unit performs three general tasks. First, it establishes connections. To establish the connection, the control unit must handle and acknowledge the request, determine it the switch. Second, the control unit must maintain the connection. Third, the control unit must tear down the connection.

Control unit

0 0 0 0 0 0 0 0 0 0 0 0 0 0 Network Interface

Full-duplex lines To attached devices

Digital Switch

FIGURE

Elements of a circuit switch note

13. State and explain cross-bar switch limitation.(8marks)

Input Lines

Output Lines

FIGURE

Space-division switch

Figure shows a simple crossbar matrix with 20 full-duplex I/O lines. The matrix has 10 inputs and 10 outputs, each station attaches to the matrix via one input and one output line. Interconnection is possible between any two lines by enabling the appropriate crosspoint. Crossbar switch limitations The number of crosspoints grows with the square of the number of attached stations. This is costly for a large switch. The lost of crosspoint prevents connection between the two devices whose lines intersect at that crosspoint. The crosspoints are inefficiently utilized, even when all of the attached devices are active, only a small fraction of the crosspoints are engaged.

CHAPTER (9) PACKET SWITCHING


14. Show the advantages of packet switching over circuit switching.(8marks) Solution: Advantages of Packet-switching Line efficiency is greater, as a single node-to-node link, can be dynamically shared by many packets over time. The packets are queued up an transmitted as rapidly as possible over the link. A packet switching network can perform data-ra15te conversion. Two stations of different data rates can exchange packets because each connects to its node at its proper data rate. When traffic becomes heavy on a packet-switching network, packets are still accepted, but delivery delay increases.

Priorities can be used. Thus, if a node has a number of packets queued for transmission , it can transmit the higher-priority packets first. Because these packets will less delay than lower-priority packets.

15. Draw timing diagram for circuit-switch |& packet switching and describing and describe three types of delay. (8 marks)
Propagation Processing delay delay Call request packet

Call request signal

3 3

pkt 1 Call accept packet Call accept signal pkt 1 pkt 2 pkt 3 pkt 1 pkt 2 pkt 3 pkt 1 pkt 2 pkt 3 pkt 1 pkt 2 Acknowledgement signal pkt 3 pkt 1 pkt 2 pkt 3 Acknowledgement packet

User Data

pkt 2 pkt 3

Link

Link

Link

FIGURE

Event timing for circuit-switching and packet switching

In figure , there types of delay are occurred; (1) Propagation delay: The time it takes a signal to propagate from one node to the next. This time is generally negligible. (2) Transmission Time: The time it takes for a transmitter to send out a block of data. (3) Node delay: The time it takes for a node to perform the necessary processing as it switches data. For circuit-switching, There is a processing delay at each node during the call request but is not needed the call-accept because the connection is already set-up. For Virtual-circuit packet switching, the processing delay at each node in both call request and call accept packet. Because this packet is queued at each node and must wait its turn for retransmission, although the route is established. Datagram packet switching does not require a call setup. It will be faster than the above two switching techniques in short messages but the processing time may be longer than virtual-circuit packets in long messages.

16. Using diagram, show the effect of packet size on transmission time.(8marks) 1 Data 1 Data Data 2 Data 1 2 3 4 5 Data 2 Data Data 2 X a b Data 1 1 2 3 4 1 2 3

4 5 Y

(c ) 5 packet message X Data a b Y

(b ) 2 packet message

(a ) 1 packet message

1 1 1

10

10

10

( d ) 10- packet message

Header Figure : Effect of packet size on transmission time

17. Compare the different communication switching techniques by using tables.(16marks) Solution: Comparison of communication switching techniques

Circuit switching

Dedicated transmission path Transmission of packets Continuous transmission of data Fast enough for interactive Fast enough for interactive Packets may be stored until Messages are not stored delivered The path is established for entire conversation Call setup delay; negligible transmission delay Busy signal if called party busy Overload may block call setup; no delay for established calls Electromechanical or computerized switching nodes User responsible for message loss protection Usually no speed for or code conversion Fixed bandwidth transmission No overhead bits after call setup

Datagram packet switching No dedicated path

Virtual-circuit packet switching No dedicated path Transmission of packets Fast enough for interactive Packets stored until delivered Route established for entire conversation Call setup delay; packet transmission delay Sender notified of connection denial Overload may block call setup; increases packet delay Small switching nodes

Route established for each packet Packet transmission delay

Sender may be notified if packet not delivered Overload increases packet delay: Small switching nodes

Network may be responsible for individual packets Speed and code conversion Dynamic use of bandwidth Overhead bits in each message

Network may be responsible for packet sequences Speed and code conversion Dynamic use of bandwidth Overhead bits in each packet

18. Draw the diagrams of External and Internal virtual circuit and diagram.(8marks) Solution:
1. 3 1. 3 A 2. 3 2. 2 2. 1 1. 2 1. 1 1. 2 1. 1 B

Packetswitched network
2. 3 2. 2 2. 1 C

(a) External vertical circuit. A logical connection is setup between two stations. Packets are labeled with a vertical circuit number and a sequence number. Packets arrive in sequence.
B. 1 B. 3 A C. 3 C. 2 C. 1 B. 2 B. 1 B. 3 B. 2 B

Packetswitched network
C. 2 C. 1 C. 3 C

(b) External datagram. Each packet is transmitted independently. Packets are labeled with the destination address and may arrive out of sequence. B
VC # 1

3 6 C

1
VC # 2

(c)Internal virtual circuit: A route for packets between two stations is defined and labeled. All packet for the virtual circuit follow the same route and arrive in sequence. B 2 1 2 A 1 1 2 3 6 5 C

3 4

(d) Internal datagram: Each packet is treated independly by the network. Packets are labeled with the destination address and may arrive at the destination node out of sequence. FIGURE External and Internal virtual circuits and diagram.

19.

Explain fixed Routing and draw the table for central routing directory for a given packet-switched
8 5

2 2 3 1 1 7 4 2 2

3 6 3 3 8 5 3 1 1 1 1 4 2 5 6

FIGURE Example packed-switched network network.(16marks) Fixed Routing For Fixed Routing, a route is selected for each source-destination pair of nodes in the network. The routes are fixed, with the exception that they might change if there is movement in the topology of the network. Thus, the link costs used in designing routes could be based on expected traffic or capacity. Figure shows how fixed routing might be implemented. A certain routing matrix is created at a network control center. The matrix shows, for each source-destination pair of nodes, the identity of the next node on the route. At each node along a route, it is only necessary to know the identity of the next node, not the entire route. Ea With fixed routing, there is no difference between routing for data-grams and virtual circuits. Advantage: It is simplicity and it work well in a reliable network with a stable Load. Disadvantage: It has lack of flexibility and it does not react to network congestion or failures. CENTRAL ROUTING DIRETORY From Node
1 1 2 2 3 4 5 6

To Node

3 4 5 6

2 4 4 4 4

1 3 4 4 4

5 5 5 5 5

2 2 5 5 5

4 4 3 4 6

5 5 5 5 5 -

Node 1 Directory Destination 2 3 4 5 6 Next Node 2 4 4 4 4

Node 2 Directory Destination 1 2 4 5 6 Next Node 1 3 4 4 4

Node 3 Directory Destination 1 2 4 5 6 Next Node 5 5 5 5 5

Node 4 Directory Destination 1 2 3 5 6 Next Node 2 2 5 5 5

Node 5 Directory Destination 1 2 3 4 6 Next Node 4 4 3 4 6

Node 6 Directory Destination 1 2 3 4 5 Next Node 5 5 5 5 5

20. Draw the diagram of sequence of events: X.25 protocol. User System A User Network Interface User Network Interface User System B

Network

A initiate a virtual call to B

Call Request Incoming Call B accepts the call Call Accepted Call Connected

When A is informed That the call is connected , it can begin to sent data packet

Data R=0, S=0 The packets are delivered in sequence

Data R=0 , S =1 Data R= 0, S =2 Data R=2, S =0 Data R=1, S=3

Data R=0 , S=0 Data R=0 , S =1 Data R=2, S=0 Data R=0, S=2 Receive Ready 3

Data R=2 , S=4 Data R=1, S =3 Receive Ready R=3 Data R=1 , S =4

B has no data packet With which to acknowledege packets S= 2 . it sends a control packet

Data R=5, S =1 Data R=5, S=1 Clear Request

A initiates clearing Of the virtual call

Clear Indication

Clear Confirmation Clear Comfirmation

Figure

Sequence Of events : X .25 protocol

CHAPTER (10) FRAME RELAY


21. Explain Frame Relay Protocol Architecture.(16marks) Solution: Frame relay protocol architecture Two separate planes of operation are needed in the frame-mode bearer service. Control Plane (C) The control plane for frame-mode bearer services is similar to that for common-channel signaling in circuit-switching services, in that a separate logical channel is used for control information. In the case of ISDN, control signaling is done over the D-channel, to control the establishment and termination of frame-mode virtual calls on the D, B and H channels. User Plane (U) For the actual transfer of information between end users, the user-plane protocol is LAPF C link Access Procedure for Frame-Mode Barrier Service, Only the core functions of LAPP are used for frame relay: Frame delimiting, alignment, and transparency. Frame multiplexing, demultiplexing using the address field. Inspection of the frame to ensure that it consists of an integral number of octets prior to zero-bit extraction. Inspection of the frame to ensure that it is neither too long not too short. Detection of transmission errors Congestion control functions

Control Plane Q.931/Q.933

User Plane Userselectable TE function LAPD (Q.922) LAPF core (Q.922)

User (TE) User Plane Control Plane Q.931/Q.933 LAPF control (Q.922) LAPF core (Q.922) LAPD (Q.921)

FIGURE

Network (NT) User-network interface protocol architecture.

22. Why the congestion ad voidance procedures are used? Explain two bits in the address Field are used for congestion ad voidance procedure.(8marks) Solution: Congestion avoidance procedures are used at the onset of congestion to minimize the effect on the network. The two bits are Backward explicit congestion notification (BECN) Notifies the user that congestion avoidance procedures should be initiated where applicable for traffic in the opposite direction of the received frame. The notification indicates that the frames transmitted by the user on this logical connection may encounter congested resource. Forward explicit congestion notification (FECN) Notifies the user that congestion avoidance procedures should be initiated where applicable for traffic in the same direction of the received frame. The notification indicates that this frame, on this logical connection, has encountered congested resource. 23. Draw and briefly explain the comparison of X.25 and frame relay protocol stacks.(8 marks) Solution: -User data is transmitted in frames with virtually no processing by the intermediate nodes, other than to check for errors and to route based on connection number. - The packed handling functions of X.25 operate at layer 3 of OSI model. At layer 2, LABB is used. - The processing burden on the network for X.25 considerably higher than for frame relay.

X.25 Packet level Implement by end LAPB system and network Physical Layer

(a) X.25

Implement by end system but not network LAPF control LAPF core Implement by end Physical layer system and network

(b) Frame relay Figure Comparison of X.25 and Frame Relay protocol stacks

Digital Design

IT (3013)

For

Second Semester

Sample Question

1. Write down the goals of UDM. (10 marks) 2. Draw the design flow of UDM-PD (10 marks) 3. Describe the specification of UDM-PD and discuss any four. (20-marks) 4. Write down the following specification of UDM-PD (20-marks) (a)External Block Diagram (b)Internal Block Diagram (c)Timing Estimates (d)Gate Count Estimate 5. Write down the following of specification of UDM-PD. (20-marks) (a)Package Type (b)Power consumption Target (c)Price Target (d)Test Procedure 6. (i) Describe the rules of UDM-PD design. (10-marks) (ii). A design specification should include the following (select all that apply). (10 marks) 7. What steps are contained in verification? (10 marks) 8. Express top-down design and write down any three. (20-marks) 9. Express the steps contain in verification? Write short note for these. (a)Resimulation and formal verification (b)Place and route What steps are contained in verification? (20-marks) 10. Discuss the followings ( 20-marks ) (a) Reusability (b) Place and route (c) Timing Estimate (d) Allocating resources 11. Explain Hardware Description Language and give an example of multiplication for two unsigned 4-bit number. ( 20 marks ) 12. Express top-down design with its spects. (10-marks) 13. Write down five rules of synchronous design. (10-marks) 14. Explain the race condition of problems and its solution with figure. (20-marks) 15. Explain delay dependent logic with figure. (10-marks) 16. Write down the hold time violation of problems and with figure. (20-marks) 17. Write down the glitches with diagram. (20-marks) 18. Explain gated clocking with diagram. (10 marks) 19. Explain floating nodes with diagram. (10-marks) 20. Discuss bus contention with diagram. (10-marks) 21. How many types of scan techniques and explain all of them. (20-marks) 22. Write verilog code for the following diagram (20 marks)

SIG1 SIG2

D CLK CLR

OUT

SIG1

SIG2

OUT

Fig : Asynchronous: Race condition. 23. Write verilog code for the follow figure.(fig 5.12).(20 marks)

10
D DATA GATE CLK Q OUT

11

Figure:Synchronous: logic gating 24. Write the verilog code for the following figure.(20marks)

ASYNC-IN

D S1

Q SYNC-IN D FF1

1 Q

A G1 CLK

D FF2

OUT1

CLK

CLK

B 1 G2 CLK FF3

CLK

ASYNC-IN SYNC-IN

IN B A OUT1 OUT2

Figure: Metastability- the solution 25(i). Match the model level on the left with the correct description on the right.(20 marks) (a) Algorithmic (A) Describes a design in terms of mathematical functionally (b) Architectural (B) Describes a design in terms of basic logic, such as NANDs and NORs. (c) Register transfer (C) Describes a design in terms of Level transistors and basic electronic components. (d) Gate level (D) Describes a design in terms of functional blocks. (e) Switch level (E) Describe a design in terms of Boolean logic and storage devices. (ii). Select all of the statements that are true about top-down design. (a) Allow better allocation of resources (b) Allow each small function to be simulated independently. (c) Speeds up simulations. (d) Facilitates behavioral modeling of the device. (e) Results in lower power consumption designs. (f) Allows a design to be split efficiently among the various team members. 26.Express top-down design and Write down following . (20-marks) (a)Use of Hardware Design languages (b)Written specifications 27.What is UDM and UDMPD? And then write down the goals of UDM? (20-marks) 28.Express top-down design and write down the following. (20-marks)

(a)Allocate resources (b)Reusability 29.Express top-down design and write down the following. (16-marks) (a)Verification (b)Know the Architecture 30(i). Which of the following HDL levels are considered behavioral levels? (a) Switch level (b) Algorithmic level (c) Gate level (d) Architectural level (e) Register transfer level (ii). Select all of the statements that are true about top-down design. (a) Allow better allocation of resources (b) Allow each small function to be simulated independently. (c) Speeds up simulations. (d) Facilitates behavioral modeling of the device. (e) Results in lower power consumption designs. (f) Allows a design to be split efficiently among the various team members.(10marks) 31.What is the specification of UDM-PD? Describe them. (10-marks)

Digital Design

IT (3013)

For

Second Semester

Sample Answer & Question

1. Write down the goals of UDM. The goals of universal design methodology are these: --Design a device that --Is free from manufacturing defects --Works reliably over the lifetime of the device. --Functions correctly in your system --Design this device efficiently, meaning --In the least amount of time --Using the least amount of resources, including person --Plan the design efficiently, meaning --Create a reasonable schedule as early in the process as possible --Know all necessary resources up front and allocate them as early in the process as possible. 2. Draw the design flow of UDM-PD
Write a specification Specification Review Choose chip and Tools Design Simulate Verificatio Design Review Synthesize Place and Route Simulate Formal V ifi i Final Review System Integration and Test Ship product!

(10 marks)

(10 marks)

3. Describe the specification of UDM-PD and discuss any four. (20-marks)

The specification of UDM_PD should include the following information: External block diagram showing how the chip fits into the system Internal block diagram showing each major functional section Description of the I\O pins, including, o Output drive capability o Input threshold level Timing estimates, including: o Setup and hold times for input pins o Propagation times for output pins o Clock cycle time Gate count estimate Package type Power consumption target Price target Test procedures

_ External Block Diagram The external block diagram must show how the device fits into the system. This diagram will help describe the overall functionality of the device and will be a good reference for the system designers, PC board designers, designers of other chips in the system, and software developers. _ Internal Block Diagram The internal block diagram will be the starting point for the behavioral description of the device .As the behavioral HDL code changes, these changes must be incorporated into the internal block diagram. As other factors necessitate changes in the internal block diagram, these changes can also be incorporated easily into the behavioral HDL code. _ Timing Estimates Timing estimates are needed to determine which devices, vendors, and technologies can be used. You should have a good understanding of the clock frequency required for the design and also the setup and hold time requirements of the I\O. Remember to identify all asynchronous input signals. You can then discuss metastability issue with the vendors that you are considering. _ Gate Count Estimates As you gain experience designing programmable devices, estimating gate counts will become easier. For your first few designs, talk to various vendors you are considering. They will be able to help you construct reasonable estimates and determine which of their devices are appropriate for your design.

4. Write down the following specification of UDM-PD (20-marks) (a)External Block Diagram

(b)Internal Block Diagram (c)Timing Estimates (d)Gate Count Estimate (a) External Block Diagram The external block diagram must show how the device fits into the system. This diagram will help describe the overall functionality of the device and will be a good reference for the system designers, PC board designers, designers of other chips in the system, and software developers. (b) Internal Block Diagram The internal block diagram will be the starting point for the behavioral description of the device .As the behavioral HDL code changes, these changes must be incorporated into the internal block diagram. As other factors necessitate changes in the internal block diagram, these changes can also be incorporated easily into the behavioral HDL code. (c) Timing Estimates Timing estimates are needed to determine which devices, vendors, and technologies can be used. You should have a good understanding of the clock frequency required for the design and also the setup and hold time requirements of the I\O. Remember to identify all asynchronous input signals. You can then discuss metastability issue with the vendors that you are considering. (d) Gate Count Estimates As you gain experience designing programmable devices, estimating gate counts will become easier. For your first few designs, talk to various vendors you are considering. They will be able to help you construct reasonable estimates and determine which of their devices are appropriate for your designs. 5. Write down the following of specification of UDM-PD. (20-marks) (a)Package Type (b)Power consumption Target (c)Price Target (d)Test Procedure

(a)Package Type Package type is often a very large percentage of the entire cost of an FPGA .Understand the package options offered by different vendors. Also you will need to understand the capabilities of your PC board layout designers and fabrication facilities to work with the different package types. (b)Power consumption Target Be certain you understand the variable that affect the devices s power consumption .You must also understand how the devices operation will affect overall board and system power consumption .Finally ,whoever is designing or choosing the power supply will need to know how much power, typical case and worst case, each chip in the system will require.

(c)Price Target For most projects, you will need a realistic price target. This target can help you determine the necessary tradeoffs between pin count, functionality, speed, package type, and other factors. (d)Test Procedure Test procedure must know at a very early stage of the design flow. Too often, design teams leave test procedures for the end of the design flow at which time they discover that the device cannot be tested completely or accurately. If the tests require software, the software team must begin planning the test very early, and they must have input into the hardware design so that testability is built in from the beginning. 6. (i) Describe the rules of UDM-PD design. (6-marks) The rules of UDM-PD design When designing the chip, remember to design according to the rules, These are: Use top-down design Work with the device architecture Do synchronous design Protect against metastability Avoid floating nodes Avoid bus contention

(ii). A design specification should include the following (select all that apply). (a) The name of the FPGA vendor. (b) A description of the I/O pins, including output drive capabilities and input threshold levels. (c) The estimated gate count. (d) The target power consumption. (e) Test procedures, including in-system test requirements. (f) An external block diagram showing how the FPGA fits into the system. (g) A notice that the document, once approved, cannot be changed. (h) An internal block diagram showing each major functional section. (i) Timing estimates, including setup and hold times for input pins, propagation times for output pins, and the clock cycle time. (j) The target price. (k) The package type. (iii)Here is the design flow with each phase in the correct order. (c)Write a specification (e) Specification review (g) Choose device and tools (k) Design (h) Simulate (j) Design review (l) Synthesis (i) Place and route

(f) Resimulation (d) Final review (b) System integration and test (a) Ship product 7. What steps are contained in verification? (10 marks) Verification is a super-phase because it consists of several other phase of the design process. Which exact phases that makes up verification is open to argument, but generally verification can be broken into several phases, each of which is essential to the entire process. These steps consists of ---Simulation ---Design review ---Synthesis ---Place and route ---Formal verification 8. Express top-down design and write down any three. (20-marks) Top-Down Design Top-down design is the design methodology whereby high level functions are defined first, and the lower level implementation details are filled in later. The top level block represents the entire chip. The next lower level blocks also represents the entire chip but divided into the major function blocks of the chip. Intermediate level contains only gates and macro functions.
Behavioral

4
RTL

10 Gate

Figure. Top- down design _ Allocating Resources

Chips typically incorporate a large number of gates and a very high level of functionality. A top. down approach simplifies the design task and allows more than one engineer, when necessary, to design the chip. For example, the lead designer or the system architect may be responsible for the specification and the top-level blocks, depending on their strength, experience, and abilities. An experienced ALU designer may be responsible for the ALU block and several other blocks .A junior engineer can work on a smaller block, such as a bus controller. Each engineer can work in parallel, writing code and simulating, until it is time to integrate the pieces into a single design. No one person can slow down the entire design. _Design Partitioning If you are the only engineer designing the chip, this methodology allows you to break the design into simpler function that you can design and simulate independently from the rest of the design. A large, complex design becomes a series of independent smaller ones that are easier to design and simulate. _Reusability CPLDs and FPGAs contains so much logic that reusing any function from a previous design can save days,weeks,or months of design time. When one group has already designed a certain function, say a fast, efficient 64-bit multiplier, HDLs allow you to take the design and reuse it in your design. If you need a 64-bit multiplier, you cam simply take the designed, verified code and plop it into your design. Or you can purchase the code from a third party. But it will only fit easily into your design if you have used a top-down approach to break the design into smaller pieces, one of which is 64-bit multiplier.

9. Express the steps contain in verification? Write short note for these. (20-marks) (a)Resimulation and formal verification (b)Place and route _ What steps are contained in verification? Verification is a super-phase because it consists of several other phase of the design process. Which exact phases that makes up verification is open to argument, but generally verification can be broken into several phases, each of which is essential to the entire process. These steps consists of ---Simulation ---Design review ---Synthesis ---Place and route ---Formal verification

(a)Resimulation and formal verification At this stage, design team must check the results of synthesis to make sure that

the RTL design that was fully simulated is functionally equivalent to the gate level design that was produced after synthesis some case ,it may also be necessary to show that the configuration of the programmable device behaves identically to the RTL description. There are two ways to do this: by resimulation the lowest level design or by using formal verification. In some case, both techniques can be used for further certainty. (b)Place and route The next step is to lay out the chip, resulting in a real layout for a real chip. This involves using the vendors software tools to place various functions into the available blocks in the device and to route the blocks together. The software will figure out the bits needed to program the chip to implement the design. If you cannot successfully place the design into the device and route it you may need to tweak the design. In some cases, you will need to make radical changes, such as eliminating some functionality or using a larger device. If you have followed all of the procedures outlined in this book, the chances of a major problem at this stage, resulting in a major design change, will be minimized. Once the place and route is successful, the design team must perform timing analysis.

10. Discuss the followings ( 20-marks ) (a) Reusability (b) Place and route (c) Timing Estimate (d) Allocating resources

(a)Reusability CPLDs and FPGAs contains so much logic that reusing any function from a previous design can save days,weeks,or months of design time. When one group has already designed a certain function, say a fast, efficient 64-bit multiplier, HDLs allow you to take the design and reuse it in your design. If you need a 64-bit multiplier, you cam simply take the designed, verified code and plop it into your design. Or you can purchase the code from a third party. But it will only fit easily into your design if you have used a top-down approach to break the design into smaller pieces, one of which is 64-bit multiplier. (b)Place and route The next step is to lay out the chip, resulting in a real layout for a real chip. This involves using the vendors software tools to place various functions into the available blocks in the device and to route the blocks together. The software will figure out the bits needed to program the chip to implement the design. If you cannot successfully place the design into the device and route it you may need to tweak the design. In some cases, you will need to make radical changes, such as eliminating some functionality or using a larger device. If you have followed all of the procedures outlined in this book, the

chances of a major problem at this stage, resulting in a major design change, will be minimized. Once the place and route is successful, the design team must perform timing analysis. (c) Timing Estimates Timing estimates are needed to determine which devices, vendors, and technologies can be used. You should have a good understanding of the clock frequency required for the design and also the setup and hold time requirements of the I\O. (d) Allocating Resources Chips typically incorporate a large number of gates and a very high level of functionality. A top. down approach simplifies the design task and allows more than one engineer, when necessary, to design the chip. For example, the lead designer or the system architect may be responsible for the specification and the top-level blocks, depending on their strength, experience, and abilities. An experienced ALU designer may be responsible for the ALU block and several other blocks .A junior engineer can work on a smaller block, such as a bus controller. Each engineer can work in parallel, writing code and simulating, until it is time to integrate the pieces into a single design. No one person can slow down the entire design.

11. Explain Hardware Description Language and give an example of multiplication for two unsigned 4-bit number. ( 20 marks ) Design teams can use a hardware description language to design at any level of abstraction, from high level architectural models to low-level switch models. These levels, from least amount of detail to mist amount of detail are as follows: Behavioral models Algorithmic Architectural Structural models Register Transfer Level (RTL) Gate level Switch level No hardware implementation is implied in an algorithmic model. The algorithmic model is coded to be fast, efficient, and mathematically correct. An algorithmic model of a circuit can be simulated to test that the basic specification of the design is correct. Architectural models specify the blocks that implement the algorithms. Architectural models may be divided into blocks representing PC boards, ASICs, FPGAs, or other major hardware components of the system. Sample behavioral level HDL code always @(posedge multiply_en) begin

Product <= a*b; end Structural models consist of code that represents specific pieces of hardware. The simplest RTL code specifies register logic. Actual gates are avoided, although RTL code may use Boolean functions that can be implemented in gates. Gate level modeling consists of code that specifies gates such as NAND and NOR gates. Gate level code is often the output of a synthesis program that reads the TRL, level code that an engineer has used to design a chip and writes the gate level equivalent. This gate level code can then be optimized for placement and routing within the CPLD or FPGA. Sample RTL HDL code always @( posedge clk ) begin if ( multiply_en 1 ) begin count <= 0; product <= 0; end if (count) begin if ( b[count] ) begin product <= ( product << 1 ) + a; end else begin product <= product << 1; end count <= count 1; end end

12. Express top-down design with its spects. (10-marks) Top-Down Design Top-down design is the design methodology whereby high level functions are defined first, and the lower level implementation details are filled in later. The top level block represents the entire chip. The next lower level blocks also represents the entire chip but divided into the major function blocks of the chip. Intermediate level contains only gates and macro functions.

10

Behavioral

4
RTL

10 Gate

Figure. Top- down design

13. Write down five rules of synchronous design. (10-marks) Five Rules of Synchronous Design Five rules to define synchronous design for a single clock domain. ( A single clock domain means that all logic is clocked by a single clock signal. 1. All data is passed through combinational logic, and through delay elements, typically flip-flops, that are synchronized to a signal clock. 2. Delay is always controlled by delay elements, not combinatorial logic. 3. No signal that is generated by combinatorial logic can be fed back to the same combinatorial logic without first going through a synchronizing delay element. 4. Clocks cannot be gated; clocks must go directly to the clock inputs of the delay elements without going through any combinatorial logic. 5. Data signals must go only to combinatorial logic or data inputs of delay elements.

14. Explain the race condition of problems and its solution with figure. (20-marks) How does this logic behave? When SIG2 is low, the flip-flop is reset to a low state. On the rising edge of SIG2, the designer wants the output, OUT, to change to reflect the current state of the input, SIG1. Because we do not know the exact internal timing of the flip-flop or the routing delay of the reset input, we cannot know which signal will effectively arrive at the appropriate logic first- the clock or the reset. This is a race condition. If the clock rising edge arrives first, the output will remain low. If the

11

reset signal arrives first, the output will go high. A slight change in temperature, voltage, or process may cause a chip that works correctly to suddenly work incorrectly because the order of arrival of the two signals changes. When creating a synchronous design, or converting an asynchronous design to a synchronous one, is to draw a state diagram. The state diagram for this function is shown in Figure (a). From this diagram, it is easy to design the more reliable, synchronous solution shown in Figure (b). Here their flip-flop is reset synchronously on the rising edge of a fast clock. Ive introduced a new signal, STATE, that together with the OUT signal. This circuit performs the correct function, and as long as SIG1 and SIG2 are produced synchronously- they change only after the rising edge of CLK- there is no race condition. The synchronous design uses more logic adding delay and using up expensive die space. They may also argue that the fast clock means that this design will consume more power. The design introduces extra signals that require more routing resources, add delay and again, that consume precious die space. All of this is true. This design, however will work reliably and the previous design will not.

STATE 0 OUT 0

SIG2 & SIG1

SIG2 & SIG1

STATE 0 OUT 0

STATE 0 OUT 0

SIG2

SIG2

Figure (a) Synchronous state diagram

12

SIG2

STATE

STATE SIG1

CLK

OUT

OUT CLK

CLK

SIG1 SIG2 OUT Figure (b) Synchronous No race condition

15. Explain delay dependent logic with figure. (10-marks) Figure (a) shows an asynchronous circuit used to create a pulse. The pulse width depends very explicitly on the delay of the individual logic gates. If the semiconductor process used to manufacture the chip should change, making the delay shorter, the pulse width will shorten also, to the point where the logic that it feeds may not recognize it at all. A synchronous version of a pulse generator is shown in Figure(b). This pulse depends only on the clock period. As our rule number 2 of synchronous design states,

13

delay must always be controlled by delay elements. Changes to the semiconductor process will not cause any significant change in the pulse width for this design.
A1 A2 A3

A A3 Z
Pulse width

Figure (a) Asynchronous : Delay dependent logic Z A 0 0

CLK

CLK A Z Figure (b) Synchronous: Delay independent logic

14

16. Write down the hold time violation of problems and with figure. (20-marks) Hold Time Violations Figure(a) shows an asynchronous circuit with a hold time violation. Hold time violations occur when data changes around the same time as the clock edge; it is uncertain which value will be registered by the clock the value of the data input right before the clock edge or the value right after the clock edge. It all depends on the internal characteristics of the flip-flop. This can also result in met stability. The circuit in figure (b) fixes this problem by putting both flip-flop on the same clock and using a flip-flop with an enable input. A pulse generator creates a palse, signal Dp3,by ANDing signal D3 and a signal D3d,which is D3 delay by a signal clock cycle. The pulse D3p enables the flip-flop for one clock cycle. The pulse generator also turns out to be very useful for synchronous design, when you want to clock data into a flip-flop after a particular event.

CLK

D2

0 0
D1

D1

0 0

D2

CLK

D3

D4

Hold time violation

Figure (a) Asynchronous: Hold time violation

15

D2

D
D3 D1 D3p

D4

ENA

D3d CLK

CLK CLK

CLK

D1

D2

D3

D3d

D3p

D4

Figure (b) Synchronous: No hold time violation 17. Write down the glitches with diagram. (20-marks) A glitch can occur due to small delays in a circuit, such as that shown in Figure. The output would be high no matter what the value of the select input, One should be able to change the select input from how to high and back to low again and still get a high value out. In practice, trough, the multiplexer produces a glitch when switching the select input. This is because of the internal design of the multiplexer, as shown in Figure. Due to the delay of the inverter on the select input, there is a short time when signals SEL and SELn are both low. Thus neither input is selected, casing the output to go low. Synchronizing this output by sending it through a flip-flop, as shown in Figure (b), ensure that this glitch will not appear on the output and will not affect logic further down stream. As long as the timing calculation have been performed correctly, the entire design is synchronous, and the device is operated below the maximum clock frequency for the design, glitches such as this one will settle before the next clock edge.

16

CLK SEL

00
SELn

Z 01

01

SEL

SELn

Z
glitch

Figure Asynchronous

CLK
SEL
SELn 0 0

00 Z 01

01
CLK

SEL

SELn

Zp Z

Figure (b) Synchronous : No glitch

18. Explain gated clocking with diagram. (10 marks) Figure (a) shows as an example of gated clocking. This violates the fourth and fifth rules of synchronous design This kind of clock gating will produce problems that will particularly bad in FPGAs, because the GATE signals can easily be delayed so that the clock signals rise before the GATE signals can prevent it.

17

The correct way to enable and disable outputs is not buy putting logic on the clock input, as shown in Figure(b). In this synchronous design, the flip-flop is always being clocked directly by the CLK signal. The GATE input controls the mux on the input, to determine whether the new data gets clocked in or the old data gets clocked back in.

DATA

OUT

GATE CLK

Figure (a) Asynchronous Clock gating

10

DATA

11

GATE

OUT

CLK

Figure (b) Synchronous Logic gating 19. Explain floating nodes with diagram. (10-marks) Floating nodes are internal nodes of a circuit that are not driven to a logic 0 or logic 1 If signals SEL_A and SEL_B are both not asserted, signal OUT will float to an unknown level. Downstream logic may interpret OUT a login 1 or logic 0, or the floating signal may create a metastable state. In particular, any CMOS circuit that uses signal OUT as an input will use up power because CMOS dissipates power when the input is in 18

the threshold region. The signal OUT will typically float somewhere in the threshold region. If downstream logic is not using this signal, the signal can bounce up and down, causing noise and inducing noise in surrounding signals. Two solutions to the floating node problem are shown in figure (b).At the top, signal OUT is pulled up using an internal pull-up resistor. This simple fix ensures that when both signals are not asserted, OUT will be pulled to a good logic level. The pull up represented in the picture may be an active pull up circuit that can be faster and more power conservative. The other solution is to make sure that something is driving at all times. A third select signal is created that drives the OUT signal to a good level when neither of the other normal select signals are asserted.
SEL_A A SEL_B B OUT

Figure (a) Floating nodes the problem NOTE: SEL_A and SEL_B are mutually exclusive
Pull up SEL_A A SEL_B B SEL_A A SEL_B B OUT OUT

Figure (b) Floating nodes solutions NOTE: SEL_A and SEL_B are mutually exclusive

19

20. Discuss bus contention with diagram. (10-marks) Bus contention Bus contention occurs when two outputs drive the same signal at the same time as shown in fig(b).This reduce the reliability of the chip because it has multiple drivers fighting each other to drive a common output. If bus contention occurs regularly, even for short time, the possibility of damage to the drivers increases. One place where this can occurs, and that is ignored, is during the turn around of the bus. In a synchronous bus, when one device is driving the bus during one clock cycle and a different device is driving during the next clock cycle, there is a short time when both devices may be driving the bus, as shown in fig(a). To avoid contention problems, the designer must ensure that both drivers cannot be asserted simultaneously. This can be accomplished by inserting additional logic, as shown in fig (c).The logic for each buffer enable has been modified so that a buffer is not turned on until its select line is asserted and all other select lines have been de.asserted.Due to routing delays, some contention may still occurs, but this circuit has reduced it significantly. The best solution may be to find better implementations. Other solutions involve designing the system so that there is always a clock cycle where nothing is driving the bus.

21. How many types of scan techniques and explain all of them. (20-marks) Scan Techniques Scan techniques sample the internal nodes of the chip serially so that they can be observed externally. The scan enable input (SE) is low; the normal data input gets clocked into the flip-flop. In san mode, through the scan enable input is high, causing the scan data (SD) to get clocked into the flip-flop. There are two main scan techniques, full scan and boundary scan. Full scan involves creating scan chain from every flip-flop in the design.Boundry scan involves using only flip-flops that are connected to I\O pins in the scan chains.

20

D SD

10 11 D 0 0

SE
CLK

Figure (a) Scan flip-flop


IN1
SCAN_IN SCAN

D SD SE

OUT1

CLK

IN2

D SD

OUT2

SCAN

SE

CLK

Figure(b) Scan Chain _ Full scan When performing full scan, the entire chip is put into the scan mode, and the scan enable inputs to the scan flip-flop are asserted. Testers can examine the state of each flip-flop in the design. This technique of scanning patterns into and out of the the chip is used for finding physical defects in ASICs after production. Because FPGAs are not tested after production, expect manufacture, the use of scan is restricted to functional testing of FPGAs, if it is used at all. During debugging, if the chip malfunction, it can be halted, put into the scan mode, and the state of each flip-flop can be read via the scan. These bits can be loaded into a simulation of

21

the design to help figure out what went wrong. The simulation data can be scanned back into the chip to put the chip into a know starting state. The major problem with using this kind of technique for functional testing is that scanning requires a lot of software development. Each flip-flop bit must be stored, and the software must know what to do with it. If the state is to be loaded into a simulators, there must be software to convert the state information to the simulators format and back again. If states are scanned into the chip, one must be careful not to scan in illegal states. There are other considerations, such as what to do with the clock and what to do with the rest of the system while the chip is being scanned. Avoiding these problems require not only a certain level of sophistication in the software, may also require extra hardware. _ Boundary Scan Boundary scan is somewhat easier to implement and does not to add as much logic to the design. Boundary scan reads only nodes around the boundary of the chip, not internal node. Limiting the scan to boundary nodes avoids internal contentionproblems, but not contention problems with the rest of the system .Boundary scan is useful for testing the rest of your system, because testers can toggles the chip outputs and observe the effect on the rest of the system.Boundary scan can be used to check for defective solder joints or other physical connections between the chip and the printed circuit board or between the chip and other chips in the system. The Institute of Electrical and Electronic Engineer (IEEE) has created a standard for boundary scan called JTAG, or IEEE 1149.1.It covers pin definitions and signaling. 22. Write verilog code for the following diagram (20 marks)
SIG1 SIG2 D CLK CLR OUT

SIG1

SIG2

OUT

Fig : Asynchronous: Race condition. 22

//how to synthesize it into a synchronous circuit // /* * * * * * * * * * * * * / //DEFINES //TOP MODULE module arace( sig 1, sig 2, out); //PARAMETERS //INPUTS input sig1; input sig2; //OUTPUTS output out; //INOUTS //SIGNAL DECLARATIONS wire sig1; wire sig2; reg out; //ASSIGN STATEMENTS //MAIN CODE //Reset condition always @ (negedge sig2)out<=0; //Clocked condition//how to synthesize it into a synchronous circuit // /* * * * * * * * * * * * * / //DEFINES //TOP MODULE always @ (posedge sig2) out<=sig1; endmodule //arace module arace( sig 1, sig 2, out); //PARAMETERS //INPUTS input sig1; input sig2; //OUTPUTS output out; //INOUTS //SIGNAL DECLARATIONS wire sig1; wire sig2; reg out;

23

//ASSIGN STATEMENTS //MAIN CODE endmodule //arace always @ (posedge sig2) out<=sig1;

23. Write verilog code for the follow figure.(fig 5.12).(20 marks)

10
D DATA GATE CLK Q OUT

11

Figure:Synchronous: logic gating //CODE TYPE : RTL // /* * * * * * * * * * * * * */ //MODULE : not gated clock // //FILE NAME : not_gated.v //VERSION : 1.0 //DATE : June 1,2002 //AUTHOR : Bob Zeidman , Zeidman Consulting // //DESCRIPTION : This module defines a circuit without a //gated clock . This is an enable flip-flop. // /* * * * * * * * * * * * * * */ //DEFINES //TOP MODULE module not_gated( clk, data, gat//CODE TYPE : RTL // /* * * * * * * * * * * * * */ //MODULE : not gated clock

24

// //FILE NAME : not_gated.v //VERSION : 1.0 //DATE : June 1,2002 //AUTHOR : Bob Zeidman , Zeidman Consulting // //DESCRIPTION : This module defines a circuit without a //gated clock . This is an enable flip-flop. // /* * * * * * * * * * * * * * */ //DEFINES //TOP MODULE module not_gated( clk, data, e, out); //PARAMETERS //DEFINES //TOP MODULE module less-meta( clk; async_in, out1, out2); //PARAMETERS //INPUTS input clk; input async_in; //OUTPUTS output out1; output out2; //INOUTS //SIGNAL DECLARATIONS wire clk; wire async_in; reg in; reg out1; reg out2; //ASSIGN STATEMENTS //MAIN CODE // clocked condition always @ (posedge clk) begin sync_in < = async_in;

25

in <= sync_in; out1< = in; out2<= in; end endmodule

24. Write the verilog code for the following figure.(20marks)

ASYNC-IN

D S1

Q SYNC-IN D FF1

1 Q

A G1 CLK

D FF2

OUT1

CLK

CLK

B 1 G2 CLK FF3

CLK

ASYNC-IN SYNC-IN

IN B A OUT1 OUT2

Figure: Metastability- the solution // //DESCRIPTIO/* * * * * * * * * * * * */ //MODULE : less metastable circuit // //FILE NAME: less_meta.v 26

//VERSION : 1.0 //DATE : June1,2002 //AUTHOR : Bob Zeidman, Zeidman Consulting // //CODE TYPE : RTL // //DESCRIPTION : This module defines a circuit that an asynchronous input. It uses a synchronizing flip-flop to lessen the chance of //metastability. // //* * * * * * * * * * * * * * * */ //ASSIGN STATEMENTS assign d3p=d3 & ~d3d; //MAIN CODE //Clocked condition always @ (posedge clk) begin d3< = d1; d3d< = d3; if (d3p) d4<=d2; end endmodule //no-hold N : This module/* * * * * * * * * * * * */ //MODULE : less metastable circuit // //FILE NAME: less_meta.v //VERSION : 1.0 //DATE : June1,2002 //AUTHOR : Bob Zeidman, Zeidman Consulting // //CODE TYPE : RTL // //DESCRIPTION : This module defines a circuit that an asynchronous input. It uses a synchronizing flip-flop to lessen the chance of //metastability. // //* * * * * * * * * * * * * * * */ //ASSIGN STATEMENTS assign d3p=d3 & ~d3d; //MAIN CODE //Clocked condition always @ (posedge clk) begin d3< = d1; d3d< = d3; if (d3p) d4<=d2; end endmodule //no-hold

27

defines a circuit that can /* * * * * * * * * * * * */ //MODULE : less metastable circuit // //FILE NAME: less_meta.v //VERSION : 1.0 //DATE : June1,2002 //AUTHOR : Bob Zeidman, Zeidman Consulting // //CODE TYPE : RTL // //DESCRIPTION : This module defines a circuit that an asynchronous input. It uses a synchronizing flip-flop to lessen the chance of //metastability. // //* * * * * * * * * * * * * * * */ //ASSIGN STATEMENTS assign d3p=d3 & ~d3d; //MAIN CODE //Clocked condition always @ (posedge clk) begin d3< = d1; d3d< = d3; if (d3p) d4<=d2; end endmodule //no-hold still potentially go metastable //due to an asynchronous input. It uses a synchronizing flipflop to lessen the chance of //metastability. // //* * * * * * * * * * * * * * * */ //ASSIGN STATEMENTS assign d3p=d3 & ~d3d; //MAIN CODE //Clocked condition always @ (posedge clk) begin d3< = d1; d3d< = d3; if (d3p) d4<=d2; end endmodule //no-hold 25(i). Match the model level on the left with the correct description on the right.(10 marks) (a) Algorithmic (A) Describes a design in terms of mathematical functionally (b) Architectural (B) Describes a design in terms of basic logic, such as NANDs and NORs.

28

(c) Register transfer Level (d) Gate level (e) Switch level

(C) Describes a design in terms of transistors and basic electronic components. (D) Describes a design in terms of functional blocks. (E) Describe a design in terms of Boolean logic and storage devices.

(a) Algorithmic

(A) Describes a design in terms of mathematical functionally (D) Describes a design in terms of functional blocks.

(b) Architectural

( c )Register transfer (E) Describe a design in terms of Boolean Level logic and storage devices (ii). Select all of the statements that are true about top-down design. (a) Allow better allocation of resources (b) Allow each small function to be simulated independently. (c) Speeds up simulations. (d) Facilitates behavioral modeling of the device. (e) Results in lower power consumption designs. (f) Allows a design to be split efficiently among the various team members.

(a) Allow better allocation of resources (b) Allow each small function to be simulated independently. (c) Speeds up simulations. (d) Facilitates behavioral modeling of the device. (f) Allows a design to be split efficiently among the various team members. 26.Express top-down design and Write down following . (20-marks) (a)Use of Hardware Design languages (b)Written specifications Top-Down Design Top-down design is the design methodology whereby high level functions are defined first, and the lower level implementation details are filled in later. The top level block represents the entire chip. The next lower level blocks also represents the entire chip but divided into the major function blocks of the chip. Intermediate level contains only gates and macro functions.

29

Behavioral

4
RTL

10 Gate

Figure. Top-Down design (a)Use of Hardware Design languages Top-down design methodology lands itself particular well to using HDLs,the accepted method of designing complex CPLDs and FPGAs .Each block in the design corresponds to the code for a self-contained module. The top-level block corresponds to the behavioral models that comprise the chip. The intermediate levels correspond to the RTL models that will become input to the synthesis process. The lowest level of the hierarchy corresponds to gate level code which is output from the synthesis software and which directly represents logic structures within the chip. (b)Written specifications The specification must include general aspects of the design, including the major functional blocks. The highest blocks of top-down design are behavioral level models that correspond to the major functional blocks described in the specification .Using a topdown design approach, the specification becomes a starting point for the actual HDL code. Specification change can immediately be turned into HDL design change, and design change can be quickly and easily translated back to the specification, keeping the specification accurate and up to date. 27.What is UDM and UDMPD? And then write down the goals of UDM? (20-marks) _What is UDM and UDM-PD? It would have to be one methodology that applied universally to large and small companies in any industry. Rather than being a method that describes very specific steps,

30

it would need to a methodology that could be generally applied to different design. We called this methodology the Universal Design Methology. As technology changed, the methodology was adopted. The different types of devices required slightly different methodologies. ASICs and printed circuit boards required slightly different methodologies than FPGAs and CPLDs. The methodology described here is specifically for programmable devices and call it UDM-PD. _ Write down the goals of UDM. The goals of universal design methodology are these: --Design a device that --Is free from manufacturing defects --Works reliably over the lifetime of the device. --Functions correctly in your system --Design this device efficiently, meaning 28.Express top-down design and write down the following. (20-marks) (a)Allocate resources (b)Reusability Top-Down Design Top-down design is the design methodology whereby high level functions are defined first, and the lower level implementation details are filled in later. The top level block represents the entire chip. The next lower level blocks also represents the entire chip but divided into the major function blocks of the chip. Intermediate level contains only gates and macro functions.

31

Behavioral

4
RTL

10 Gate

Figure:Top-Down design (a) Allocating Resources Chips typically incorporate a large number of gates and a very high level of functionality. A top. down approach simplifies the design task and allows more than one engineer, when necessary, to design the chip. For example, the lead designer or the system architect may be responsible for the specification and the top-level blocks, depending on their strength, experience, and abilities. An experienced ALU designer may be responsible for the ALU block and several other blocks .A junior engineer can work on a smaller block, such as a bus controller. Each engineer can work in parallel, writing code and simulating, until it is time to integrate the pieces into a single design. No one person can slow down the entire design. (b) Reusability CPLDs and FPGAs contains so much logic that reusing any function from a previous design can save days,weeks,or months of design time. When one group has already designed a certain function, say a fast, efficient 64-bit multiplier, HDLs allow you to take the design and reuse it in your design. If you need a 64-bit multiplier, you cam simply take the designed, verified code and plop it into your design. Or you can purchase the code from a third party. But it will only fit easily into your design if you have used a top-down approach to break the design into smaller pieces, one of which is 64-bit multiplier.

32

29.Express top-down design and write down the following. (16-marks) (a)Verification (b)Know the Architecture Top-Down Design Top-down design is the design methodology whereby high level functions are defined first, and the lower level implementation details are filled in later. The top level block represents the entire chip. The next lower level blocks also represents the entire chip but divided into the major function blocks of the chip. Intermediate level contains only gates and macro function
Behavioral

4
RTL

10 Gate

Figure:Top-Down design (a)Verification Top-down design is one important means for improving verification. A topdown design approach allows each module to be simulated independently from the rest of the design. This is important for complex designs where an entire design can take weeks to simulate and days to debug. By using a top-down approach, design teams can efficiently perform behavioral, RTL, and gate level simulation and use the results to verify functionality at each lave of design. Top down design facilitates these good design practices: Use of hardware design languages Writing accurate and up-to-date specifications Allocation of resources for the design task Simplification and easy partitioning of the design task Flexibility in experimenting with different designs and optimizing the design Reusing previous designs

33

Floor planning Improved the verification and less time spent on verification

(b)Know the Architecture Look at the particular architecture for the CPLDs or FPGAs that you are using to determine which logic devices fit best into it. Many FPGA and CPLD vendors include specialized logic functions in their devices. For example, vendors may offer a device with a built-in digital signal (DSP).This device will not be useful, and is the wrong choice, if your design does not use a DSP.On the other hand, if you are implementing signal processing functions, you should make sure you use this DSP function as much as possible throughout the design. The vendor will be able to offer advice about their device architecture and how to efficiently utilize it. 30(i). Which of the following HDL levels are considered behavioral levels? (a) Switch level (b) Algorithmic level (c) Gate level (d) Architectural level (e) Register transfer level (b) Algorithmic level (d) Architectural level

(ii). Select all of the statements that are true about top-down design. (a) Allow better allocation of resources (b) Allow each small function to be simulated independently. (c) Speeds up simulations. (d) Facilitates behavioral modeling of the device. (e) Results in lower power consumption designs. (f) Allows a design to be split efficiently among the various team members.

(a) Allow better allocation of resources (b) Allow each small function to be simulated independently. (c) Speeds up simulations. (d) Facilitates behavioral modeling of the device. (f) Allows a design to be split efficiently among the various team members 31.What is the specification of UDM-PD? Describe them. (8-marks) The specification of UDM_PD should include the following information: External block diagram showing how the chip fits into the system Internal block diagram showing each major functional section Description of the I\O pins, including,

34

o Output drive capability o Input threshold level Timing estimates, including: o Setup and hold times for input pins o Propagation times for output pins o Clock cycle time Gate count estimate Package type Power consumption target Price target

35

Data Structure

IT 3015

For

Second Semester

Sample Question

1. Difference between two types of genealogical charts. 2. Define the following terms (i) degree (ii) leaf (or) terminal nodes (iii) siblings (iv) children (v) parent (vi) ancestors (vii) level (viii) height (or) depth 3.

(4marks) (16 marks)

Write out each node stands for the item of information for following is tree (16 marks)

A B

I (1) degree of C (2) Leaf (or) terminal modes (3) non-terminal modes (4) children of A (5) parent of G (6) grandparent of J (7) sibling (8) defined the level for each mode (9) depth (or) height

4. Define the binary tree, skewed and complete binary tree with example. (6 marks)

5. Draw the internal memory representation of the given binary tree using (a) List representation (b)Linked representation (10 marks) A B

6. Draw the internal memory representation of given binary tree using (a)List left child-right sibling representation (b)List representation (8 marks) A B

C G

7. For the binary trees using array representation (8 marks) (a) B A (b) B A

8. Given the binary tree, it follows that the height of a complete binary tree with n nodes is [log2(n)] Prove your answer. 1

9. Write out the inorder, preorder, postorder and level-order traversals for the binary tree. (16 marks) A A (a) (b) B B C

10. Write out the norder preorder and postorder for the binary tree with arithmetic expression. (8 marks) + J

* / H

11. (a) What are the differences between tree and binary tree. (b) Write a code segment for level-order traversal for binary tree. (c) Draw the internal memory representation of binary tree of following binary tree using left child-right sibling representation. (16 marks) A

12. (a) Here the prefix form of the expression is as (+ * * / A B C D E). Convert this expression to binary tree. (b) Here the code segments for preorder for binary tree. 1. void Tree :: preorder() 2. { preorder (root); 3. } 4. void Tree :: preorder ( Tree Node * current Node) 5. { if ( Current Hode) { 6. cout << CurrentHodedata; 7. preorder (CurrentHodeLeftchild); 8. preorder (CurrentHodeRightchild); 9. } 10. } Trace the code segment for Preorder using binary tree that build above question(a). (16 marks) 13. (a) Here the postfix form of the expression is as (AB / C * D * E +). Convert this expression to binary tree. (b) Here the code segment for postorder for binary tree. 1. void Tree :: postorder() 2. { postorder (root); 3. } 4. void Tree :: postorder (TreeNode * CurrentNode) 5. { if ( CurrentNode) { 6. postorder (CurrentNodeleftchild); 7. postorder ( CurrentNodeRightchild); 8. cout << CurrentNodedata; 9. } 10. }

Trace the code segment for postorder using binary tree that build above Question(a). (16 marks) 14. (a) Here the infix form of the expression is as (A/b * C * D + E). Convert this expression to binary tree. (b) Here the code segment for inorder for binary tree. 1. void Tree :: inorder () 2. { inorder (root); 3. } 4. void Tree :: (TreeNode * CurrentNode) 5. { if (CurrentNode) { 6. inorder (CurrentNode leftchild); 7. cout << CurrentNodedata; 8. inorder (CurrentNodeRightChild); 9. } 10. } Trace the code segment for inorder using binary tree that build above Question(a). (16 marks) 15. List the terminal nodes, the nonterminal nodes and the level of each node for following binary tree. . The terminal nodes = The nonterminal nodes = The level of A = The level of B = The level of C and D = The level of E = 16. What is the maximum number of nodes in a k-array tree of heigh h? Prove your answer. (6 marks) 17. Draw the internal memory representation of the binary tree using (a) sequential (b) linked representation. (10 marks) 18. Write out the inorder, preorder, postorder and level- order traversals for the following binary tree. (8 marks)

19. Write a nonrecursive version of function postorder for the following code segment for postorder traversal of a binary tree. 1. void Tree :: postorder() 2. { postorder (root); 3. } 4. void Tree :: postorder (TreeNode * CurrentNode) 5. { if ( CurrentNode) { 6. postorder ( CurrentNodeLeftChild); 7. postorder ( CurrentNodeRightchild); 8. cout << CurrentNodedata; 9. } 10. }

20. Write a nonrecursive version of function preorder for the following code segments for preorder traversals of a binary tree. (8 marks) 1. void Tree :: preorder() 2. { preorder (root); 3. } 4. void Tree :: preorder (TreeNode * CurrentNode) 5. { if ( CurrentNode) { 6. cout << CurrentNode data; 7. preorder ( CurrentNodeLeftChild); 8. preorder ( CurrentNodeRightchild); 9. } 10. }

21. Write a nonrecursive version of function inorder for the following code segment for inorder traversal of a binary tree. (8 marks)

1. void Tree :: preorder() 2. { inorder (root); 3. } 4. void Tree :: inorder (TreeNode * CurrentNode) 5. { if ( CurrentNode) { 6. inorder ( CurrentNodeLeftChild); 7. cout << CurrentNode data; 8. inorder ( CurrentNodeRightchild); 9. } 10. }

22. Define the following definitions. i) ii) iii) iv) Eulerian wake Graph Undirected graph Directed graph

(8 Marks)

23. Define the following definitions.

(8 Marks)

i) Maximum numbers of edges in any n-vertex for undirected graph? ii) Maximum number of edges in nay n-vertex for directed graph? iii) If di is the degree of vertex i in a graph G with a vertices and e edges, the number of edges is e? iv) The adjacency matrix for an undirected graph the degree of nay vertex i is?

24. Define the following terms. i) Sub graph

(8 Marks)

ii) iii) iv) v)

Path Length Cycle Simple path

25. What are the differences between connected components and strongly connected component? (4 Marks)

26. Define the following terms for given graphs. (a) 1 0 (b) 0

(16 Marks)

i) Path= ii) Simple path= iii) Length= iv) Cycle= v) In-degree of vertex 1= vi) Adjacent of vertex 2 = vii) Incident of vertex 0 = viii) Degree of vertex 1 =

27. Does the following multigraph have an Eulerian walk? If so, find one. (4 Marks)

28. Show that the adjacency-matrix, adjacency-list and adjacency-multilist representation for the graph. (16 Marks)

3 2

29. For the following digraph obtain. a) b) c) d) e) Its in-degree and out-degree of each vertex Its adjacency-matrix Its adjacency-list representation Its adjacency-multilist representation Its strongly connected components 0 4 1 2 5

(16 Marks)

30. Is the directed graph for given strongly connected list all the simple paths.(8 Marks) 0 3 2

31. (a) Define the spanning trees.

(16 Marks)

(b) Draw how to modify the following graph applies depth-first and breadth-first spanning trees. List the vertices in order they would be visited. 0 1 3 7 4 5 8 2 6

32. What are the differences between biconnected components and a biconnected graph? 33. (a) Write a code segments for Kruskals builds a minimum-cost spanning tree. (b) To construct minimum-cost spanningtee for the graph G. Using Kruskals algorithm. 0

10 5 25 4 24

28 14 6 18 12 1 16 2

22

Data Structure

IT (3015)

For

Second Semester

Sample Answer & Question

1. Difference between two types of genealogical charts. 2. Define the following terms (i) degree (ii) leaf (or) terminal nodes (iii) siblings (iv) children (v) parent (vi) ancestors (vii) level (viii) height (or) depth 3.

(4marks) (16 marks)

Write out each node stands for the item of information for following is tree (16 marks)

A B

I (1) degree of C (2) Leaf (or) terminal modes (3) non-terminal modes (4) children of A (5) parent of G (6) grandparent of J (7) sibling (8) defined the level for each mode (9) depth (or) height

4. Define the binary tree, skewed and complete binary tree with example. (6 marks)

5. Draw the internal memory representation of the given binary tree using (a) List representation (b)Linked representation (10 marks) A B

6. Draw the internal memory representation of given binary tree using (a)List left child-right sibling representation (b)List representation (8 marks) A B

C G

7. For the binary trees using array representation (8 marks) (a) B A (b) B A

8. Given the binary tree, it follows that the height of a complete binary tree with n nodes is [log2(n)] Prove your answer. 1

9. Write out the inorder, preorder, postorder and level-order traversals for the binary tree. (16 marks) A A (a) (b) B B C

10. Write out the norder preorder and postorder for the binary tree with arithmetic expression. (8 marks) + J

* / H

11. (a) What are the differences between tree and binary tree. (b) Write a code segment for level-order traversal for binary tree. (c) Draw the internal memory representation of binary tree of following binary tree using left child-right sibling representation. (16 marks) A

12. (a) Here the prefix form of the expression is as (+ * * / A B C D E). Convert this expression to binary tree. (b) Here the code segments for preorder for binary tree. 1. void Tree :: preorder() 2. { preorder (root); 3. } 4. void Tree :: preorder ( Tree Node * current Node) 5. { if ( Current Hode) { 6. cout << CurrentHodedata; 7. preorder (CurrentHodeLeftchild); 8. preorder (CurrentHodeRightchild); 9. } 10. } Trace the code segment for Preorder using binary tree that build above question(a). (16 marks) 13. (a) Here the postfix form of the expression is as (AB / C * D * E +). Convert this expression to binary tree. (b) Here the code segment for postorder for binary tree. 1. void Tree :: postorder() 2. { postorder (root); 3. } 4. void Tree :: postorder (TreeNode * CurrentNode) 5. { if ( CurrentNode) { 6. postorder (CurrentNodeleftchild); 7. postorder ( CurrentNodeRightchild); 8. cout << CurrentNodedata; 9. } 10. }

Trace the code segment for postorder using binary tree that build above Question(a). (16 marks) 14. (a) Here the infix form of the expression is as (A/b * C * D + E). Convert this expression to binary tree. (b) Here the code segment for inorder for binary tree. 1. void Tree :: inorder () 2. { inorder (root); 3. } 4. void Tree :: (TreeNode * CurrentNode) 5. { if (CurrentNode) { 6. inorder (CurrentNode leftchild); 7. cout << CurrentNodedata; 8. inorder (CurrentNodeRightChild); 9. } 10. } Trace the code segment for inorder using binary tree that build above Question(a). (16 marks) 15. List the terminal nodes, the nonterminal nodes and the level of each node for following binary tree. . The terminal nodes = The nonterminal nodes = The level of A = The level of B = The level of C and D = The level of E = 16. What is the maximum number of nodes in a k-array tree of heigh h? Prove your answer. (6 marks) 17. Draw the internal memory representation of the binary tree using (a) sequential (b) linked representation. (10 marks) 18. Write out the inorder, preorder, postorder and level- order traversals for the following binary tree. (8 marks)

19. Write a nonrecursive version of function postorder for the following code segment for postorder traversal of a binary tree. 1. void Tree :: postorder() 2. { postorder (root); 3. } 4. void Tree :: postorder (TreeNode * CurrentNode) 5. { if ( CurrentNode) { 6. postorder ( CurrentNodeLeftChild); 7. postorder ( CurrentNodeRightchild); 8. cout << CurrentNodedata; 9. } 10. }

20. Write a nonrecursive version of function preorder for the following code segments for preorder traversals of a binary tree. (8 marks) 1. void Tree :: preorder() 2. { preorder (root); 3. } 4. void Tree :: preorder (TreeNode * CurrentNode) 5. { if ( CurrentNode) { 6. cout << CurrentNode data; 7. preorder ( CurrentNodeLeftChild); 8. preorder ( CurrentNodeRightchild); 9. } 10. }

21. Define the following definitions. i) ii) iii) iv) Eulerian wake Graph Undirected graph Directed graph

(8 Marks)

22. Define the following definitions.

(8 Marks)

i) Maximum numbers of edges in any n-vertex for undirected graph? ii) Maximum number of edges in nay n-vertex for directed graph? iii) If di is the degree of vertex i in a graph G with a vertices and e edges, the number of edges is e? iv) The adjacency matrix for an undirected graph the degree of nay vertex i is?

23. Define the following terms. i) ii) iii) iv) v) Sub graph Path Length Cycle Simple path

(8 Marks)

24. What are the differences between connected components and strongly connected component? (4 Marks) 25. Define the following terms for given graphs. (a) 1 0 (b) 0 (16 Marks)

i) Path= ii) Simple path= iii) Length= iv) Cycle= v) In-degree of vertex 1= vi) Adjacent of vertex 2 = vii) Incident of vertex 0 = viii) Degree of vertex 1 =

26. Does the following multigraph have an Eulerian walk? If so, find one. (4 Marks) 0 3

27. Show that the adjacency-matrix, adjacency-list and adjacency-multilist representation for the graph. (16 Marks)

3 2

28. For the following digraph obtain. a) b) c) d) e) Its in-degree and out-degree of each vertex Its adjacency-matrix Its adjacency-list representation Its adjacency-multilist representation Its strongly connected components 0 4 1 2 5

(16 Marks)

29. Is the directed graph for given strongly connected list all the simple paths.(8 Marks) 0 3 2

30. (a) Define the spanning trees.

(16 Marks)

(b) Draw how to modify the following graph applies depth-first and breadth-first spanning trees. List the vertices in order they would be visited. 0 1 3 7 4 5 8 2 6

31. What are the differences between biconnected components and a biconnected graph? 32. (a) Write a code segments for Kruskals builds a minimum-cost spanning tree. (b) To construct minimum-cost spanningtee for the graph G. Using Kruskals algorithm. 0

10 5 25 4 24

28 14 6 18 12 1 16 2

22

Q1 The pedigree chart is normallly two-way branching, though this does not allow for inbreeding. The lineal chart is a chart of desendants rather tham ancestors, and each item can produce sevral other. Q2 (i)

degree

The number of subtrees of a node is called its degree. degree gero are called leaf or terminal nodes.

(ii)

Leaf (or) terminal nodes =

(iii) (iv)

Siblings Childrem

= =

Childrem of the same parent are said to be siblings. The roots of a subtrees of a node x are the childrem of x. = x is the parent of its cildrem.

(v) (vi)

Parent Ancestors =

The ancestors of a node are all the nodes along the path from the root to that node. The level of a node is defined by letting the root be at level one.

(vii)

Level

(viii)

Height (or) Depth = The height (or) depth of a tree is defined to bethe manimum level of any node in the tree.

Q3 Write out the following questions for given binary tree.

(1) degree of c (2) leaf (or) terminal (3) non terminal nodes (4) childrem of A (5) parent of G (6) grandparent of J (7) sibling (8) define the level (9) depth (or) height Q4 The binary tree

=3 = D, E, F, G, I, J = A, B, C, H = B, C, D =C =C = B, C, D, F, G, H, I, J =4 =4

Skewed Complete binary tree

A binary tree is a finite set of node that either is empty (or) consist of a root and two disjoint binary trees called the left subtree and right subtree. Skewed to the left, and there is a corresponding tree that skews to the right. A complete binary tree that all terminal node are on adacent levels.

Q5 (a) List representation

(b) Linked representation

Q6 (a) Left child right sibing representation

(b) List representation

Q7 (a) Left child-right sibling representation

(b) List representation

Q8

The height (or) depth of a complete binary binary tree with n nodes is [ log2 (n+1) ] Prove depth (or) height = Log2 (n+1) Log (7+1) Log2 8 Log2 23 3 Log2 2 3 n=7, depth (or) height = = = = =
Q9 (a)

(b)

Q10

Write out

(i) (ii)

inorder preorder

= = =

F/G*H-I +J
+-*/FGHIJ

(iii) postorder

FG/H*I-J+

Q11

(a) A tree is a finite set of one (or) more roder such that (i) There is a specially designated node called the woot. (ii) The remaining nodes are partitioned into n > o disjoint sets T1...., Tn, where each of these sets is a tree. T1,....,Tn are called the subtrees of that the rood. (b) A binary tree is a finite set of nodes that either is empty (or) consists of a root and two disjoint binary trees called the left subtree and the right subtree. (c) Using left child - right sibling representation

Q12 (a)The prefin form ( +

* / ABCDE ) convert to binary tree.

(b) A code segment for level - order traversal binary tree. 1. 2. 3. 4. 5. 6. 7. 8. Void Tree :: Level Order ( ) { Queue < Tree Node * > q ; Tree Node * Current Node = root ; While ( Current Node ) { Cout << Current Node data << endl ; if (Current NodeLeftchild)q.Add(CurrentNode Leftchild) ; if (Current Node rightchild) q.Add (Current Noderightchild) ; Current Node = * q . Delete (Current Node) ;

(c)Trace the node segment for preorder + Cout '+' Driver 1 * Cout ' * ' 2 * Cout ' * ' 3. / Cout ' / ' 4. A Cout ' A ' 5. O

6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. ( + *

O B O O C O O D O O E O O

Cout ' B '

Cout ' C '

Cout ' D '

Cout ' E '

* / ABCDE ) A B / C * D * E+ )convert the binary

Q13(a)The postfix form ( tree.

Trace the node segment for postorder. Call of postorder value in Current Node Action Driver 1 2 3 4 5 6 4 7 8 9 7 3 + * * / A O O A B O O B / 10 C 11 O 12 O 10 C 2 * 13 D 14 O 15 O 13 D 1 * 16 E 17 O 18 O 16 E Driver +

Cout ' C ' Cout ' * '

Cout ' A '

Cout ' D ' Cout ' * '

Cout ' B ' Cout ' / '

Cout ' E ' Cout ' + '

(AB/C*D*E+)

Q14(a)The infin form ( A / B * C * D + E )convert to binary tree.

(b) Trace the code segment for inorder Call of inorder Value in Current Nate Driver + 1 * 2 * 3 / 4 A 5 O 4 A 6 O 3 / 7 B 8 O 7 B 9 O 2 * 10 C 11 O 10 C 12 O

Action

Cout << ' A Cout << ' / '

Cout << ' B ' Cout << ' * '

Cout << ' C '

1 13 14 13 15 Driver 16 17 16 18

* D O D O + E O E O

Cout << ' * '

Cout << ' D Cout << ' +

Cout << ' E '

Q15

(i) (ii) (iii) (iv) (v) (vi)

The terminal nodes The nonterminal nodes The level of A The level of B The level of C The level of E

= E,D = A, B, C =1 =2 =3 =4

Q16 Height (or) Depth Max no:of nodes Eg/ k=3, k=2, = h (or) k = 2k - 1 , k > 1 = 23-1 = 7 = 22-1 = 3

Q17

(a)

Sequential representation

(b)

Linked representation

Q18

Write out list. (i) inorder (ii) preorder (iii) postorder (iv) level order

= = = =

8, 4, 9, 2, 10, 11, 1, 12, 6, 13, 3, 14, 7, 15 1, 2, 4, 8, 9, 5, 10, 11, 3, 6, 12, 13, 7, 14, 15 8, 9, 4, 10, 11, 5, 2, 3, 1, 12, 13, 6, 14, 15, 7 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

Q19 Nonrecursive Postorder (Answer) Void Tree :: Non Recpostorder

{
stack < Tree Node > s ; Tree Node * Current Node = root ; while (True)

{
while (Current Node)

{
s-add (Current Node) ; Current Node=Current Nodeleftchild ;

if ( ! S. is Empty ( ) )

{
Current Node =Current Noderightchild ; Current Node=* s.del (Current Node); Cout << Current Nodedata ;

}
else break ;

} }
Q20. Nonrecursive preorder (Answer) Void Tree :: Non Rec preorder { stack < Tree * >s ; Tree Node * Current Node = root ; while (True) { while (Current Node) { Cout << Current Nodedata ; s, add (Current Node) ; Current Node = Current Nodeleftchild ; } ef (! s, is Empty ( ) ) { Current Node=* s.del (Current Node) ; Current Node=Current Noderightchild ; } else break ; } }

Q21.

(i) Eulerian walk = Euler showed that there is a walk starting at any vertex, going through each edge exactly once and terminating at the start vertex iff the degree of each vertex is even. A walk that does this is called Eulerian walk.

(ii) Graph = A graph , G, consists of two sets, V and E, V is a finite , nonempty set vertices.E is a set of pairs of vertices; these pairs are called edges. (iii) Directed graph = A directed graph each edge is represented by a directed pair < u,v>; u is the tail and v the head of the edge. (iv) Undirected graph = An undirected graph the pair of vertices representing any edge is unordered. Q 22. (i) Maximum number of edges in any n-vertex for undirected graph. = n (n-1) / 2 (ii) Maximum number of edges in any n-vertex for directed graph. = n (n-1) (iii) If di is the degree of vertex i in a graph G with a n vertices and e edges,

(iv) The adjacency matrix for an undirected graph the degree of any vertex i is-

Q.23 (i) Subgraph = A subgraph of G is a graph G such that V(G) V Z(G) and E(G) E(G). (ii) A path = A path from vertex u to vertex v in graph G is a sequence of vertices u, i1 , i2 , , ik , v such that (u ,i1),( i1,i2), , (ik, v ) are edges in E(G). (iii) The length = The length of a path is the number of edges on it.

(iv) A simple path = A simple path is a path in which all vertices except poosibly th first and last are distinct. (v) A cycle = a cycle is a simple path in which the first and last vertices are the same. Q.24. A connected component Graph G contains no other subgraph that is both connected and property contains H. Graph G has two components , H1 and H2 H1 H2

A strongly connected component A strongly connected component is a maximul subgraph that is strongly connected. Graph G has two strongly connected components.

Q.25.

(a)

= (0,1)(1,2) (2,3) = 0,1 0,1,2 0,1,2,3 0,2 0,2,1 0,2,3 0,2,3,1 0,3 0,3,1 0,3,2,1 (iii) length =3 (iv) cycle = 0,1,3,2,0 (v) in-degree of vertex 1 = 3 (vi) adgcent of vertex 2 = 0,1,3 (vii) incident of vertex 0 = (0,1) (0,2) (0,3) (ix) degree of vertex 1 = 3 (b)

(i) Path (ii) simple path

Path = (0,1) (1,0) Simple path = 0,1 0,1,0 0,1,2 1,0 1,0,1 1,0,1,2 Length =2 Cycle = 0,1,0 In-degree of vertex 1 = 1 Adgcent of vertex 2 = 1 Incident of vertex 0 = (0,1) (1,0) Degree of vertex 1 = 2

Q.26

The multigraph has an Eulerian walie. Each vertex has even edges. The edges are (0,1) (0,2) (0,3) (2,3) (1,0)

Q27.
0 1

(a) The adjacency matrix

(b) The adjacency List

(c) The adjacency- multilist

The lists are vertex 0 : N0 Vertex 1 : N0 Vertex 2 : N2 Vertex 3 : N1

N1 N2 N3 N4

28.
0 4 1 2 5

(a)

The in-degree of vertex The in-degree of vertex The in-degree of vertex The in-degree of vertex The in-degree of vertex The in-degree of vertex The out-degree of vertex The out-degree of vertex The out-degree of vertex The out-degree of vertex The out-degree of vertex The out-degree of vertex

0= 1= 2= 3= 4= 5= 0= 1= 2= 3= 4= 5=

3 2 1 1 2 2 0 2 1 3 1 3

(b)

adjacency matrix

(c )

adjacency list represenatation Head nodes Datalink

(d) adjacency multilist representation

The lists are vertex 0 : vertex1: vertex2 : vertex3: vertex4: vertex5:

N0 N0 N2 N1 N5 N3

N1 N3 N4 N7 N8

N5 N9

N6 N10

(e) it does not has strongly connected components. 29.

The graph does not have strongly connected . <0 , 1, > < 0 , 1,2 > < 0 , 3> <0,3 > <0,3,2>

30 (a) Any tree consisting soley of edges in G and including all verteces in graph is called a spanning tree (b) The list of DFS (0) spanning tree 0,1,3,7,4,8,5,2.6

The list of DFS (0) spanning tree

0,1,2,3,4.5.6.7.8

31 (a)

biconnected component

A biconnected component of a connected graph G is a maximal biconnected Subgraph H of G . By maximal, we mean that G contains no other subgraph that is both Biconnected and properly contains H. biconnected graph A biconnected graph is a connected graph that has no articulation point..

(b)

Kruskals algorithm

1. T = ; 2.while (( T contain less than n-1 edges)&&( E not empty)){ 3. choose an edge (v,w) from E of lowest cost; 4. delete (v,w) from E. 5. if ((v,w) does not create a cycle in T ) add (v,w) to T; 6. else discard (v,w); 7. } 8. if (T contain fewer than n-1 edges) cout<<no spanning tree<<endl;

(c)

Database Management System

IT 3016

for

Second Semester

Sample Question

1. Define the characteristics of a good program. (10 marks) 2. Describe the Modular advantages. (10) marks 3. Draw layout of a decision table and decision table example.(10)marks 4. A business has decided to encourage early payment on its invoice introducing the following payment procedures for its regular customers 10% discount if the invoice is settled within 7 days. 7% discount if the invoice is settled within 14 days. 5% discount if the invoice is settled within 30 days. Other cases for discount must be referred to the manager. Construct a decision table for implementing the above procedure. (10 marks) 5. Write the pseudo code equivalent of the computations shown by the flowchart. Start

accept n count1 countcount+1

n mod count=0 Yes n = count Yes Display Yes

No Display No

Stop (10 marks) 6. Explain the types of files. (10) marks 7. Write the algorithm of merging two sorted files .(10)marks 8.Write the algorithm for sequential file updating.(20)marks

9. Daily sales are stored in two sale files. They include item no and sale quality. They are sorted in item no order. Master stock file contains item no, item name, on hand and is sorted in ascending order with item no. Write an algorithm to generate new master stock file with updated on hand quantity. (20 marks) Sale 1 file Item no 1 3 Sale 2 file Item no Sale-quantity Sale quantity 10 20

Master stock file Item no 1 2 3 New master stock file Item-no 1 2 3

Item name A B C

On-hand 100 50 75

Item-name A B C

On-hand 75 45 55

10. A

daily

sale file contains following fields field type width 3 20 5

Field name Item no Item name Sale amount

numeric character numeric

All records are sorted in ascending order on item no An item may be sold one or more . Generate a blat with total sale amount for each item. (20 marks) 11. Describe the logical Database Design. 12. Explain the degree of a relationship. 13.(a) What is entity relationship model. (20-marks) (20 marks)

field . sale file

13.(b) Draw E-R diagram for Customer, Order, and Product System. (20 marks) 14. Supplier Table S# S1 S2 S3 S4 P# P1 P2 P3 P4 P5 SNAME Smith Jones Black clark PNMAE Nut Bolt Screw Screw Can STATUS 20 10 30 20 COLOR Red Green Blue Red Blue CITY London Paris Paris london WEIGHT 12.0 17.0 17.0 14.0 12.0 CITY London Paris Rome London Paris Part Table

By using the above relational tables, write SQL statements for the following queries. (i) Get all combinations of supplier and part information such that the supplier and part in question are located in the same city. (ii) Get supplier numbers for suppliers in Paris with status >20. (iii) Delete supplier S1 (15 marks)

15. DEPT (DEP#, MGR#, DBUGET) EMP (EMP#, ENAME#, DEPT#, SALARY, TOWN) JOB (DEPT#, EMP#, JOBTITLE) By using above relational tables, write SQL statements for queries. 1. Get all employee who live in Town T1, 2. Get employee name who live in Town T3 and salary greater than 50000. 3. Get all details of job. 4. Get employee name whose jobtitle is J2. 5. Get employee number and jobtitles where the jobtitle has an n as second letter. (20marks) 16. DEPT (DEP#, MGR#, DBUGET) EMP (EMP#, ENAME#, DEPT#, SALARY, TOWN) JOB (DEPT#, EMP#, JOBTITLE) 1. Change the Department number for Department D8 to D9. 2. Get dept numbers that spend dbuget less than 1,000,000. 3. Get employee name who work under manager M1.

4. Get manager number whose managers the jobtitle J2 and J3. 5. Get the department number and employee name whose salary is greater than 1500 and save the result in the database table NEW. (20 marks) 17. S (S#, SNAME, STATUS, CITY) P (P#, PNAME, COLOR, WEIGHT, CITY) J (J#, JNAME, CITY) SP (S#, P#, QTY) SPJ (S#, P#, J#, QTY) 1. Get supplier numbers for suppliers in Paris with status greater than 20. 2. Get color and city for nonParis parts with weight greater than ten. 3. Get all supplier number, part number and project number such that the indicated supplier, par and project are all collocated. 4. Get parts number and part name for parts in weight descending order. 5. Get the total quantity of part P1 supplied by supplierS1. (20 marks) 18. S (S#, SNAME, STATUS, CITY) P (P#, PNAME, COLOR, WEIGHT, CITY) J (J#, JNAME, CITY) SP (S#, P#, QTY) SPJ (S#, P#, J#, QTY) 1. Get part number for parts supplied to some project in an average quantity of more than 320. 2. Get part number for parts supply by a supplier in London to a project in London. 3. Get project numbers for projects using at least one part available from supplier S1. 4. Get project number and cities where the city as an O as the second letter of its name. 5. Delete all shipments for supplier in London. (20 marks) 19. S (S#, SNAME, STATUS, CITY) P (P#, PNAME, COLOR, WEIGHT, CITY) J (J#, JNAME, CITY) SP (S#, P#, QTY) SPJ (S#, P#, J#, QTY) 1. 2. 3. 4. 5. Insert a new shipment with supplier number S20, part number P20 and quantity 1000. Change the name of supplier S2 to Mary, decrease its status by 5 and set its city to New York. Add supplier S7 (Rose, status 25) who live in Yangon. Get the part number of parts whose quantity is in the range 300 to 750 inclusive. Get the supplier number and total quantity supplied of the part and save the result in the database. (20 marks)

20. Explain function dependency. 21. Explain briefly about 2NF.

(20 marks) (10 marks)

Database Management System

IT 3016

for

Second Semester

Sample Answer & Question

1. Define A

the characteristics

of a good program. (10 marks)

Good Program what mean to do, and and

A good program has the characteristics show below: 1. Accuracy - The program must do what it is supposed to do, the criteria laid down in its specification. 2 .Reliability- The program must always do what never crush. is supposed

3. Efficiency- The program must use the available stored space resources in such a way that the systems speed is not wasted.

4. Robustness-The program should cope with invalid data without stopping with no indication as to the cause and without creating errors. 5. Usability- The program must be easy to use and well documents. 6.Maintainbility- The program must be easy to amend, having good structing and documentation. 7.The code in the program must be well laid out comments. 2. Describe the Modular advantages.(10) marks Modular Advantages (a) Contain standard produces throughout the program. (b) The checking of conditions and error situations are undivided . (c) Testing of individual modules. (d) Amendments to single modules. (e) Create a library of often used routines. (f) Easy to find in the documentation and consistent. and explained with

3. Draw layout of a decision table and decision table example.(10)marks

Decision Table Decision table is a table that shows the various actions to be taken for different combinations of conditions. It is suited for a procedure with a large number of related decisions. Condition Stub Action Stub Condition Entries Action Entries

Fig: Layout of a decision table Condition entries show whether the condition is true or false. Action entries indicate whether the actions take place or not. The most common / - ) for actions and Y convention is to use a cross and a dash ( * and N for conditions. The condition stub show: all possible conditions and action stub show all possible actions.

1 It is raining. I have to go out. Y Y

2 Y N

3 N Y

4 N N

Put on raincoat. Leave raincoat in closet. Go outside.

X X

X -

X X

X -

Fig: Decision table example

4. A business has decided to encourage early payment on its invoice introducing the following payment procedures for its regular customers 10% discount if the invoice is settled within 7 days. 7% discount if the invoice is settled within 14 days. 5% discount if the invoice is settled within 30 days. Other cases for discount must be referred to the manager. Construct a decision table for implementing the above procedure. (10 marks) Solution: 1 The voice is settled within 7days. The voice is settled within 14 days. The voice is settled within 30 days. 10% discount 7% discount 5% discount Y Y Y 2 Y Y N 3 Y N Y 4 Y N N 5 N Y Y 6 N Y N 7 N N Y 8 N N N

X X

X -

X X

X -

X X X -

5. Write the pseudo code equivalent of the computations shown by the flowchart.

Start

accept n count1 countcount+1

n mod count=0 Yes n = count Yes Display Yes

No Display No

Stop Solution: begin accept n count1 repeat countcount+1 until n mod count=0 if n=count then display Yes; else display No; endif end

6. Explain the types of files. (10) marks

The file types to be described are: -serial file -sequential file -indexed sequential file -Relative or direct access files (i) Serial File Each record is written after the last record in the current file. Records in a serial file are sequenced in the order in which the data were generated. Examples include memory dumps, archival files and record. (ii)Sequential File This file is sorted in the order of one of the record files. Records can be arranged in sequence of one or more key fields. (iii) Indexed Sequential File Indexed sequential file organization uses two files. As the file is created an index is set up. The index contains the key field from each record. (iv)Relative or direct access file These files must be on direct access storage device. A record key can be used for converting to a unique record location. To use this technique space is allocated to all the expected records to be stored and each record has a unique address. The disadvantage of this method is that space must be allocated to all expected records and in actual usage there may be many records slots not used. The key conversion also relies on the record key being numeric and thus direct addressing is not suitable for all applications. Indirect addressing can allow more efficient use of disk space and cope with alphanumeric keys. The technique is called hashing. Direct access files are used in on-line applications such flight reservations system where speed of access is crucial.

7. Write the algorithm of merging two sorted files .(10)marks Algorithm of merging two sorted filesBegin open first file; open second file; open third file; read first file; read second file; repeat if key of first file < = key of second

file

then write first record into third file; read first file; else write second record into third file; read second file; until end of first file or end of second file; while not end of first file do write first record into third file; read first file; endo; while not end of second file. do write second record into third file; read second file; endo; close first file; close second file; close third file; end.

8.Write the algorithm for sequential file updating.(20)marks Alogrithm for sequential file updating begin open master file; open transaction file; open new master file; read master file; read transaction file; while not end of master file and not of transaction file do if transaction key < master key then process unmatched transaction; else if transaction key > master key then process unmatched master; else process match; endif; endo; while not end of transaction file do

process unmatched transaction; endo; while not end of master file do process unmatched master; endo; close master file; close transaction file; close new master file; end. Unmatched transaction file begin if type = I then write transaction record into new master file; else if type= D then display delete error ; else display amendment error ; endif; read transaction file ; end; Unmatched master file begin write master record into new master file; read master file; end; Match begin files

if type= A then write amended record into new master file; read master file; read transaction file; else if type = I then display insect error ; read transaction file; else read transaction file; read master file; endif; end.

9. Daily sales are stored in two sale files. They include item no and sale quality. They are sorted in item no order. Master stock file contains item no, item name, on hand and is sorted in ascending order with item no. Write an algorithm to generate new master stock file with updated on hand quantity.(20 marks) Sale 1 file Item no 1 3 Master stock file Item no 1 2 3 Sale quantity 10 20 Item name A B C On-hand 100 50 75 Sale 2 file Item no Sale-quantity

New master stock file Item-no Item-name On-hand 1 A 75 2 B 45 3 C 55 begin open sale 1 file; open sale 2 file; open total sale file; open master stock file; open new master stock file; read 1st record from sale1; read 2nd record from sale2; repeat if item no of sale 1=item no of sale2 then item no of tempitem no of sale 1; quantity of temp quantity of sale1+ quantity of sale2; write temp record to total sale; read next record from sale1; read next record from sale2; else if item no of sale1< item no of sale 2 then write sale 1 record to total sale; read next record from sale 1; else write sale 2 record to total sale; read next record from sale2;

until end of sale 1 or end of sale2 if end of sale1 then repeat write sale 2 record to total sale; read next record from sale2; until end of sale2; else repeat write sale 2 record to total sale; read next record from sale1; until end of sale 1; read 1st record from total sale; read 1st record from master stock file; repeat if item no of total sale= item no of master stock file then item no of temp item no of master stock file; item name of temp item name of master stock file; on hand of temp on hand of master stock file+ quantity of total sale; write total sale record to new master stock file; read next record from master total sale record; read next record from master stock file; else write master stock file to new master stock file; read next record from master stock file; until end of total sale or master stock file; close sale 1 file; close sale 2 file; close total sale file; close master stock file; close new master stock file; end. 10. A daily sale file contains following fields field type width 3 20 5

Field name Item no Item name Sale amount

numeric character numeric

All records are sorted in

ascending

order

on

item

no

field .

An item may with total sale Ans:

be sold one or more . Generate amount for each item. (20 marks)

blat

sale

file

begin open daily sale file; open total sale file; read a record from the daily sale file; While not end of daily sale file do temp.itemno item no of daily sale file; temp. item name item name of daily sale file; temp. sale amount sale amount of daily sale file; read next record from daily sale file; while (tempitemno = itemno of daily sale file ) AND not end of daily sale file do temp . sale amount temp.sale amount + sale amount of daily sale file; read next record from daily sale file; endo; write temp record to total sale file; endo; close daily sale file; close total sale file; end.

Database Management System Chapter (3) PART (2)


Q (11) Describe the logical Database Design. [20-marks] This is the process of transforming the conceptual model into logical database model. There are four types logical database model in use today. (i) relational data model (ii) hierarchical data model (iii) network data model (iv) object-oriented data model (i) Relational data model In this model that represent data in the form of relation. The relational data model include three components. Data Structure (Data are organized in the form of tables) Data manipulation (SQL language or query by example are used data stored in the database). - Data integrity (Business rules are specified to maintain the integrity the data when they are a manipulated). [3-marks] (ii) Hierarchical data model Hierarchical data model was the first important to logical data model. Today, it is primarily on implemented mainframes. In this model, records are arranged a top-down structure. The parents and childs are used in describing this model. The important characteristic is that a child is related to one parent. DEPT NO Equipmen
INDENT CODE NUMBER

DNAME

LOCATE Employe e ENAME YEAR

EMP NO

Dependent skill CODE SNAME YEAR

(iii) Network data model There is no difference between the parent and child record type. In the figure, any record type may be associated with both the employee and project record type. Department

Department Employee

Department Project

Department Department

Department skill

DEPT-EMO,DEPT-PROJ,PROJ-EMP

(iv) Object oriented data model Most future the database management system will be based on object or will incorporated object oriented functionality. The enable user to create generic all purpose components that can be reused in multiple applications. Object---are abstraction from the real world entity that exhibit state and behavior. The state of an object is expressed as the values of the attribute of the object. The behavior at an object is expressed as a set of method that operates on its attributes. Attribute This is the property of object that interest to the organization. Method Method defines the behavior of an object. Method can process data within the object class in which they are defined (concept of encapsulation). However, they can retrieve from method in another object class. A number of method categories occur methodinstance add, instance change, instance delete etc. Calculation method performs calculation on the data values encapsulated in the same object class. Monitor method-produced signal when predetermined limit are exceed in the system. [7-marks]

12. Explain the degree of a relationship. (20 marks) Solution: Degree of relationship The degree of a relationship is the number of entity types that participate in that relationship. Unary relationship (recursive relationship) It is a relationship between the instances of one entity type.

Employee

Manages

PERSON

Is Married to

Item Many to many

Has components

Figure [7-marks] Binary relationship It is a relationship between instances of two entity types. Product line CLASS
Is Assigned

Product line STUDENT S STUDENT S

contains

CLASS

Register for

Figure [7-marks] Ternary relationship It is a simultaneous relationship among instance of three entity types.
TEACHER teach

CLASS teach Figure [6-marks]

STUDEN T

Q (13) a- What is entity relationship model. The E-R model is used to construct a conceptual data model, which is a representation of the structure of a database that is independent of the software that will be used to implement the database. [5-marks]

Q (13) b- Draw E-R diagram for Customer, Order, and Product System. Solution: Name Address

Customer no

City

Total Owned

Customer

Credit limit

Places

Order no

ORDER
Order date

Qty-shipped

Places

Qty-Ordered

Product no
Description PRODUC T

United Price Qty on hand

E.R diagram
Figure [20-marks]

Q(14) Supplier Table S# S1 S2 S3 S4 P# P1 P2 P3 P4 P5 SNAME Smith Jones Black clark PNMAE Nut Bolt Screw Screw Can STATUS 20 10 30 20 COLOR Red Green Blue Red Blue CITY London Paris Paris london WEIGHT 12.0 17.0 17.0 14.0 12.0 CITY London Paris Rome London Paris Part Table

By using the above relational tables, write SQL statements for the following queries. (i) Get all combinations of supplier and part information such that the supplier and part in question are located in the same city. SELECT S*,P* FROM S,P WHERE S.CITY=P.CITY;

[5-marks]

(ii) Get supplier numbers for suppliers in Paris with status >20. SELECT S.S#,S.NAME,S.STATUS, S.CITY

FROM S WHERE CITY=PARIS AND STATUS > 20; (iii) Delete supplier S1 SELETE FROM S WHERE S# = S;

[5-marks]

[5-marks]

15. DEPT (DEP#, MGR#, DBUGET) EMP (EMP#, ENAME#, DEPT#, SALARY, TOWN) JOB (DEPT#, EMP#, JOBTITLE) By using above relational tables, write SQL statements for queries. 1. Get all employee who live in Town T1, 2. Get employee name who live in Town T3 and salary greater than 50000. 3. Get all details of job. 4. Get employee name whose jobtitle is J2. 5. Get employee number and jobtitles where the jobtitle has an n as second letter. (20marks) 1. SELECT EMP * FROM EMP WHERE TOWN = T1; 2. SELECT NAME FROM EMP WHERE TOWN T3 AND SALARY > 50000; 3. SELECT * FROM JOB; 4. SELECT NAME FROM EMP,JPB WHERE EMP.EMP# = JOB.EMP# AND JOBTITLE = J2; 5. SELECT EMP#, JOBTITLE FROM JOB WHERE JOBTITLE LIKE _n%; 16. DEPT (DEP#, MGR#, DBUGET) EMP (EMP#, ENAME#, DEPT#, SALARY, TOWN) JOB (DEPT#, EMP#, JOBTITLE) 1. Change the Department number for Department D8 to D9. 2. Get dept numbers that spend dbuget less than 1,000,000. 3. Get employee name who work under manager M1. 4. Get manager number whose managers the jobtitle J2 and J3. 5. Get the department number and employee name whose salary is greater than 1500 and save the result in the database table NEW. (20 marks) 1. UPDATE DAPT SET DEPT# = D9 WHERE DEPT# = D8; 2. SELECT DEPT# FROM DEPT WHERE DBUGET < 1,000,000; 3. SELECT ENAME FROM EMP

WHERE

4. SELECT FROM WHERE AND AND 5. CREATE (DEP# ENAME INSERT INTO NEW (DEP#, ENAME) SELECT DEP#, ENAME FROM EMP WHERE SALARY > 1500;

DEPT# IN (SELECT DEPT# FROM DEPT WHERE MGR# = M1); MGR# DEPT, JPB JPB.DEPT# = DEPT.DEP# JOB.JOBTITLE = J2 JOB.JOBTITLE = J3 TABLE NEW CHAR (6), CHAR (20));

17. S (S#, SNAME, STATUS, CITY) P (P#, PNAME, COLOR, WEIGHT, CITY) J (J#, JNAME, CITY) SP (S#, P#, QTY) SPJ (S#, P#, J#, QTY) 1. Get supplier numbers for suppliers in Paris with status greater than 20. 2. Get color and city for nonParis parts with weight greater than ten. 3. Get all supplier number, part number and project number such that the indicated supplier, par and project are all collocated. 4. Get parts number and part name for parts in weight descending order. 5. Get the total quantity of part P1 supplied by supplierS1. (20 marks)

1. SELECT FROM WHERE AND 2. SELECT FROM WHERE AND 3. SELECT FROM WHERE AND

S# S CITY = Paris STATUS > 20; COLOR, CITY P CITY ~= Paris WEIGHT > 10; S#, P#, J# S, P, J S.CITY = P.CITY P.CITY = J. CITY;

4. SELECT P#, PNAME FROM P ORDER BY WEIGHT DESC; 5. SELECT SUM(QTY) FROM SP WHERE P# = P1 AND S# = S1; 18. S (S#, SNAME, STATUS, CITY) P (P#, PNAME, COLOR, WEIGHT, CITY) J (J#, JNAME, CITY) SP (S#, P#, QTY) SPJ (S#, P#, J#, QTY) 1. Get part number for parts supplied to some project in an average quantity of more than 320. 2. Get part number for parts supply by a supplier in London to a project in London. 3. Get project numbers for projects using at least one part available from supplier S1. 4. Get project number and cities where the city as an O as the second letter of its name. 5. Delete all shipments for supplier in London. (20 marks) 1. SELECT FROM WHERE 2. SELECT FROM WHERE AND AND 3. SELECT FROM WHERE AND 4. SELECT FROM WHERE 5. DELETE FROM WHERE P# SP AVG(QTY) > 320; P# S, P, SPJ S.S# = SPJ.S# P.P# = SPJ.P# S.CITY = P.CITY = LONDON; J# SPJ S# = S1 QTY >= 1; P#, CITY P CITY LIKE _O%; SP LONDON = (SELECT CITY FROM S WHERE S.S# = SP.S#);

19. S (S#, SNAME, STATUS, CITY) P (P#, PNAME, COLOR, WEIGHT, CITY) J (J#, JNAME, CITY) SP (S#, P#, QTY) SPJ (S#, P#, J#, QTY) 1. 2. 3. 4. 5. Insert a new shipment with supplier number S20, part number P20 and quantity 1000. Change the name of supplier S2 to Mary, decrease its status by 5 and set its city to New York. Add supplier S7 (Rose, status 25) who live in Yangon. Get the part number of parts whose quantity is in the range 300 to 750 inclusive. Get the supplier number and total quantity supplied of the part and save the result in the database. (20 marks) 1. INSERT INTO SP(S#, P#, QTY) VALUES (S20,P20,1000); 2. UPDATE S SET SNAME = MARY STATUS = STATUS 5 CITY = New York WHERE S# = S2; 3. INSERT INTO S(S#, SNAME, STATUS, CITY) VALUES (S7, Rose, 25, Yangon); 4. SELECT P# FROM SP WHERE 750>QTY>300; 5. CREATE TEMP (P# CHAR(6), TOTQTY INTEGER); INSERT INTO TEMP (P#, TOTQTY) SELECT P#,SUM(QTY) FROM SP GROUP BY P#;

20. Explain briefly about 2NF. Answer

(10 marks)

A relation R is in 2NF if and only if it is in 1NF and every attribute is fully dependent on the primary key. Relations SECOND and SP are both in 2NF (the primary keys are S# and te combination (S#,P#), respectively). Relations FIRST is not in 2NF. A relation that is in first normal form and not in second can always be reduced to and equivalent collection of 2NF relations. The SECOND/SP structure still causes problems, however. Relation SP is satisfactory: as a master of fact, relation SP is now in third normal form, and we will ignore it for the remainder of this section. Relation SECOND, on the other hand, still suffers from a lack of mutual independence among its nonkey attributes. The FD diagram for SECOND is still more complex than a 3NF diagram. To be specific, the dependency of STATUS on S#, though it is functional, and indeed full, is transitive (via CITY). Each S# value determines a CITY value, and that in turn determines the STATUS value. In general, whenever the FDs R.A R.B and R.B R.C Both hold, then the transitive FD R.A R.C Also holds Transitive dependencies lead, once again, to update anomalies.

OBJECTED ORIENTED PROGRAMMING USING JAVA

IT (3025)

For

Second Semester

Sample Questions

1. Write a Java class to represent a book. A book contains the following information: title, edition, publisher and price. You should provide a constructor for the creation of book objects and a method to display the detail of a book in the following format. Title Edition Publisher Price

(8 Marks)

2. Write a java class to represent a cube. You should provide a default constructor to create a cube with side of length 5cm and a second constructor which creates a cube with a given side value. The cube should be capable of returning its surface area and its volume through its methods. In your user class, create 3 cube instances with side of length 10, 3 and 5cm respectively, and then report their respective surface areas and volume. (16 Marks) 3. Draw a class hierarchy diagram that best represents the relationship of the following classes: SecondaryStudent,, Student, PrimaryStudent, Teacher and Person. (10 Marks) 4. Write a java class to represent a rectangle with a width and height. The rectangle should be capable of returning its perimeter and area through 2 methods. Next, write a java class to represent a square by creating square as a subclass of rectangle. Write a user class and create a square instance with side 4 and reports its perimeter and area. (20 Marks) 5. Write a java class that represents and address book entry consisting of title, name and address, all of String type. Define methods for the class to update the value of each of its instance variables. For example, the name should have a setName (String newName) method. Write a user class and create and instance of entry using the default constructor and update title, name and address as Mr, John Lim and Holland Road 123 respectively. (20 Marks) 6. Write a java class that represents a clock that keeps track of time as hours, minutes and seconds. Provide a constructor method to create the clock objects with given hour, minute and second. Next, provide methods that will allow a user to set the time (i.e. change the hour, minute or second). Finally, provide a method dislayTime(int mode) to display the time of the clock, the display of which depends on the mode as supplied by the user. (20Marks) 7. Write a java class to represent a bank account. A bank account contains such information as: name of account holder, account number, current balance. The bank account class must contain static information to keep track of the number of account created. You should provide a constructor for the creation of bank account objects. The objects shall have given names, account numbers and with an initial balance of zero. You must keep track of the total number of accounts created as well. Provide the methods to deposit and withdraw from the account, these methods should report if the operations are successful and if so, report the new balance after the operations. And also provide a method to print out summary of a bank account and a class method that prints out the number of accounts created. Write also a user class and create 2 instances of the bank account class with the following information. (20 Marks) Name John Mary Account 123456 654321

Call appropriate methods to create the following output.

Name : John Account Number : 123456 Current Balance : 0.0

8. What is wrong with the following java code? public class MyClass { package com.mypackage; public MyClass() { } } 9. What is wrong with the following java code? Import java.util.*; package com.mypackage; public class MyClass { public MyClass() { } } 10. Modify the following code by making use of import statement.

(5 Marks)

(5 Marks)

(5 Marks)

package mypackage; public class MyClass { public void myMethod () { java.util.Date today = new java.util.Date (); } } 11. Suggest the package that the following classes should belong to: Dog, Table, Plate, Bed, Lion, Van, Cat, Bus, Car, Chair, Spoon. (5 Marks) 12. Write a java program that reads in 2 double values and prints their sum and product (assume user will only enter double value). (10 Marks) 13. Write a java program that reads in 2 double values and prints their sum and product such that the double values are greater then zero and numeric. Your program should prompt for re-entry if the output is invalid. (20 Marks) 14. The following is a definition of AreaCalculator class: (20 Marks) (a) Complete the readChoice( ) method that prompts the user to enter a choice to calculate area for rectangle or circle. The user will enter 1 for rectangle and 2 for circle. Read the users choice and store it in the instance variable choice. (b) Complete the readWidthHeight( ) method to prompt the user to enter the width and height of a rectangle. Read the users input and store them in the instance variables width and height respectively. (c) Complete the readRadius( ) method to prompt the user to enter the radius of a circle. Read the users input and store it in the instance variable radius. (d) Complete the computeArea( ) method, which first calls the readChoice( ).It then calls the readWidthHeight( ) method and readRadius( ) depending on the value of the instance variable choice to print the area of the shape. 15. Write a Java program that prompts the user to enter a filename, the program then reads the content of that file and display it on screen. (20 Marks)

16. Write a Java program that repeatedly prompt the user to enter positive integers ranging from 1 to 100 until the user enters 9999 to terminate the program. The program will report the average of the integers entered. (20 Marks) 17. Define an abstract base Animal that includes an abstract method sound( ) to output the type of sound the animal makes. Derive subclass for Dog and Cat. Implements the sound( ) method for these subclasses. Test the class by creating instances of Dog and Cat class an Animal and invoke the sound( ) method. (20 Marks) 18. Define an AnimalList class that can store an arbitrary collection of objects of subclasses of the Animal class. Your AnimalList class should contain methods to add, remove Animal object from the list as well as returning the Animal object at a given index position (Consider using the Vector class in Java.util package for storing Animal objects. (20 Marks) 19. Fill in the blanks; are the instance variables w, x, y and z accessible from class B? (10 Marks) 20. Fill in the blanks. Are the instance variables w, x, y and z accessible from class C? (10 Marks)

OBJECTED ORIENTED PROGRAMMING

IT (3025)

For

Second Semester

Sample Answer & Questions

1. Write a Java class to represent a book. A book contains the following information: title, edition, publisher and price. You should provide a constructor for the creation of book objects and a method to display the detail of a book in the following format.

Title Edition Publisher Price class Book{ public String title; public String edition; public String publisher; public float price; public Book(String title, String edition, String publisher, float price) { this.title=title; this.edition=edition; this.publisher=publisher; this.price=price; } public String gettitle( ) { return this.title ;} public String getedition( ) { return this.edition;} public String getpublisher( ) { return this.publisher;} public float getprice( ) { return this.price;} public void BookInfo( ) { System.out.println(Title:+gettitle( )); System.out.println(Edition:+getedition( )); System.out.println(Publisher:+getpublisher( )); System.out.println(Price:+getprice( )); } }

(10 Marks)

2. Write a java class to represent a cube. You should provide a default constructor to create a cube with side of length 5cm and a second constructor which creates a cube with a given side value. The cube should be capable of returning its surface area and its volume through its methods. In your user class, create 3 cube instances with side of length 10, 3 and 5cm respectively, and then report their respective surface areas and volume. (20 Marks)

public class cube{ int length; public cube( ) { this.length=5; } public cube(int length) { this.length=length;} public int SurfaceArea( ) { return.length*length;} public int Volume( ) 2

{return length*length*length;} } class userforcube { public static void main(String [ ] args) { cube c1=new cube(10); cube c2=new cube (3); cube c3=new cube (5); System.out.println(Cube 1 SurfaceArea:+c1.SurfaceArea( )); System.out.println(Cube 1 Volume:+c1.Volume( )); System.out.println(Cube 2 SurfaceArea:+c2.SurfaceArea( )); System.out.println(Cube 2 Volume:+c2.Volume( )); System.out.println(Cube 3 SurfaceArea:+c3. SurfaceArea( )); System.out.println(Cube 3 Volume:+c3.Volume( )); } }
3. Draw a class hierarchy diagram that best represents the relationship of the following classes: SecondaryStudent,, Student, PrimaryStudent, Teacher and Person. (10 Marks)

Person

Superclass

Subclasses Student Teacher

Primary Student

Secondary Student

4. Write a java class to represent a rectangle with a width and height. The rectangle should be capable of returning its perimeter and area through 2 methods. Next, write a java class to represent a square by creating square as a subclass of rectangle. Write a user class and create a square instance with side 4 and reports its perimeter and area. (20 Marks) public class rectangle{ private int width; private int height; public rectangle(int width,int height) { this.width=width; this.height=height; public int perimeter( ) { return (length+height)*2;} public int area( ) {return width*length;}

} class square extends rectangle{ public square (int side) {super(side,side);} } public static void main(String args [ ]) {square myrectangle=new square( ); System.out.println(Perimeter+myrectangle.perimeter( )); System.out.println(Area:+myrectangle.area( )); } } 5. Write a java class that represents and address book entry consisting of title, name and address, all of String type. Define methods for the class to update the value of each of its instance variables. For example, the name should have a setName (String newName) method. Write a user class and create and instance of entry using the default constructor and update title, name and address as Mr, John Lim and Holland Road 123 respectively. (20 Marks) class AddressBook{ private String title; private String name; private String address; publice AddressBook( ){ } public void setName(String name) { this.name=name; } Public void setTitle(String title) { this.title=title; } Public void setAddress(String add) { This.address=add; } } class userClass{ public static void main(String [ ]args) { AddressBook p1= new AddressBook(); p1.setTitle(Mr.); p1.setName(John Lim); p1.setAddress(Holland Road 123); } } 6. Write a java class that represents a clock that keeps track of time as hours, minutes and seconds. Provide a constructor method to create the clock objects with given hour, minute and second. Next, provide methods that will allow a user to set the time (i.e. change the hour, minute or second). Finally, provide a method dislayTime(int mode) to display the time of the clock, the display of which depends on the mode as supplied by the user. (20Marks) public class clock { int hours,minutes,seconds; public clock(int h,int m,int s)

{ this.hours=h; this.minutes=m; this.seconds=s; } public void setHours(int hr) { this.hours=hr; } public void setMinutes(int min) { this.minutes=min; } public void setSeconds (int sec) { this.seconds=sec; } public void displayTime(int mode) { String period=p.m; if (seconds>=60) {seconds-=60;minutes+=1; } if (minutes>=60) {minutes-=60;hours+=1; } if (mode= =1) {if(hours>=24)hours-=24; System.out.println(hours+:+minutes+;+seconds); } if (mode= =2) { if (hours>=12) {hours-=12;period=a.m;} System.out.println(hours+:+minutes+:+period); } } } 7. Write a java class to represent a bank account. A bank account contains such information as: name of account holder, account number, current balance. The bank account class must contain static information to keep track of the number of account created. You should provide a constructor for the creation of bank account objects. The objects shall have given names, account numbers and with an initial balance of zero. You must keep track of the total number of accounts created as well. Provide the methods to deposit and withdraw from the account, these methods should report if the operations are successful and if so, report the new balance after the operations. And also provide a method to print out summary of a bank account and a class method that prints out the number of accounts created. Write also a user class and create 2 instances of the bank account class with the following information. (20 Marks) Name John Mary Account 123456 654321

Call appropriate methods to create the following output.

Name : John Account Number : 123456 Current Balance : 0.0 5

public class BankAccount{ private String hoderName; private int accountNumber; private float currentBalance; static int totalNoOfAccount=0; public BankAccount(String name,int accountNo) {this.holderName=name; this.accountNumber=accountNo; this.currentBalance=0.0; } public void Deposit(float amount) { if (amount>0){ currentBalance=current.Balance+amount; System.out.println(DepositSuccessful); System.out.println(this.holderName+now Balance is :+currentBalance); } else{ System.out.println(Deposit unsuccessful); } } public toString( ){ System.out.println(Name:+ this.holderName); System.out.println(AccountNumber:+ this.accountNumber); System.out.println(Current Balance:+this.currentBalance); } public static void getTotalAccount( ){ System.out.println(Total Number of Accounts created+ totalNoOfAccount): } } public class BankUser{ public static void main(String [ ]args) { BankAccount account1=new BankAccount(John,123456); account1.toString( ); BankAccount.totalNoOfAccount++; BankAccount account2=new BankAccount(John,654321); account2.toString( ); BankAccount.totalNoOfAccount++; account1.Deposit(100); account1.Withdraw(150); account1.Withdraw(50); account1.Withdraw(50); account1.toString( ); account2.Deposit(200); account2.Withdraw(150); account2.toString( ); BankAccount.getTotalAccount( ); } }

8. What is wrong with the following java code? public class MyClass { package com.mypackage; public MyClass() { } } Correct Program package com.mypackage; public class MyClass{ public MyClass( ) { } } 9. What is wrong with the following java code? Import java.util.*; package com.mypackage; public class MyClass { public MyClass() { } } Correct program package com. mypackage; import java.util.*; public class MyClass{ public MyClass( ) { } } 10. Modify the following code by making use of import statement. package mypackage; public class MyClass { public void myMethod () { java.util.Date today = new java.util.Date (); } } Correct program package mypackage; import java.util.Date; public class MyClass{

(5 Marks)

(5 Marks)

(5 Marks)

public void myMethod ( ) { Date today =new Date ( );} } 11. Suggest the package that the following classes should belong to: Dog, Table, Plate, Bed, Lion, Van, Cat, Bus, Car, Chair, Spoon. Classes Dog,Lion,Cat Table,Chair,Bed,Plate,Spoon Van,Car,Bus Package Package animal; Package furniture; Package motorvehical;

(5 Marks)

12. Write a java program that reads in 2 double values and prints their sum and product (assume user will only enter double value). (10 Marks) class SumProduct{ public static void main(String args[ ]){ BufferReader br=new BufferReader(new InputStreamReader(System.in)); System.out.println(Enter a number.); double num1=Double.parseDouble(br.readLine( )); double num2=Double.parseDouble(br.readLine( )); System.out.println(Sum of two numbers:+(num1+num2)); System.out.println(Product of two numbers:+(num1*num2)); } } 13. Write a java program that reads in 2 double values and prints their sum and product such that the double values a greater then zero and numeric. Your program should prompt for re-entry if the output is invalid. (20 Marks) class SumProduct{ public static void main(String args[ ]){ double num1=ReadInNumber( ); double num2=ReadInNumber( ); System.out.println(Sum of two numbers:+(num1+num2)); System.out.println(Product of two numbers:+(num1*num2)); } public static double ReadInNumber( ){ BufferReader br=new BufferReader(new InputStreamReader(System.in)); do{ System.out.println(Enter a number.); double.num=Double.parseDouble(br.readLine( )); if(num<=0) System.out.println(Please reenter number again); }while(num<=0); return num; } }

14. The following is a definition of AreaCalculator class: (20 Marks) (a) Complete the readChoice( ) method that prompts the user to enter a choice to calculate area for rectangle or circle. The user will enter 1 for rectangle and 2 for circle. Read the users choice and store it in the instance variable choice. (b) Complete the readWidthHeight( ) method to prompt the user to enter the width and height of a rectangle. Read the users input and store them in the instance variables width and height respectively. (c) Complete the readRadius( ) method to prompt the user to enter the radius of a circle. Read the users input and store it in the instance variable radius. (d) Complete the computeArea( ) method, which first calls the readChoice( ).It then calls the readWidthHeight( ) method and readRadius( ) depending on the value of the instance variable choice to print the area of the shape. import java.io.*; class AreaCalculator{ int choice; double width, height, radius; BufferReader br=new BufferReader(new InputStreamReader(System.in)); double calculateRectangleArea( ) { return width*height; } double calculateCircleArea( ) { return 3.14*radius*radius; } void readChoice ( ) throws IOException { System.out.println(Please enter 1 for Rectangle.2 for Circle); choice=Integer.parseInt(input.readLine( )); } void read WidthHeight( ) throws IOException { System.out.println(Please enter width>>); width=Double.parseDouble(input.readLine( )); System.out.print(Please enter height>>); height=Double.parseDoble(input.readLine( )); } void readRadius( ) throws IOException{ System.out.print(Please enter radius>>); radius=Double.parseDouble(input.readLine( )); } void computerArea( ) throws IOExpection { readChoice( ); if(choice= =1) { read WidthHeight( ); System.out.println(Area of Rectangle=+calculateRectangleArea( )); } if(choice= =2) { readRadius( ); System.out.println(Area of Circle=+ calculateCircleArea( )); } } public static void main(String [ ] argv) throws IOException{ AreaCalculator ac=new AreaCalculator( );

ac.computeArea( ); } } 15. Write a Java program that prompts the user to enter a filename, the program then reads the content of that file and display it on screen. (20 Marks) import java.io.*; class PrintFile{ public static void main (String [ ] args)throws IOException{ BufferedReader input=new BufferedReader(new InputStreamReader(system.in)); System.out.println(Enter File Name.); String filename=input.readLine( ); BufferedReader br=new BufferedReader(new FileReader(filename)); String s; while ((s=br.readLine( ))!=null) { System.out.println(s);} br.close( ); } } 16. Write a Java program that repeatedly prompt the user to enter positive integers ranging from 1 to 100 until the user enters 9999 to terminate the program. The program will report the average of the integers entered. (20 Marks) Class Positive Public static void main(String [ ]args){ long sum=0: int count=0:int num; do{ num=ReadInNumber( ); if(num!=9999){ sum+=num: count++; } }while(num!=9999); System.out.println(Average of all positive numbers:+(sum/count)); } public static int ReadInNumber( ){ BufferedReader br=new BufferedReader(new InputSreamReader(System.in)); System.out.print(Enter a number); try{ int num=Integer.parseIn(br.readLine( )); }catch (NumberFormatExpection e); Num=0 Sysem.out.println(Invalid Input); } if(num>=0\\num<101&&num!=9999 System.out.println(Please enter number again); }while ((num<=0\\num>101&&!=9999)); Return num;

10

} }

17. Define an abstract base Animal that includes an abstract method sound( ) to output the type of sound the animal makes. Derive subclass for Dog and Cat. Implements the sound( ) method for these subclasses. Test the class by creating instances of Dog and Cat class an Animal and invoke the sound( ) method. (20 Marks) abstract class Animal { public abstract string sound ( );} Class Dog extends Animal{ Pravite String name ; publicDogs (String name) {this.name=name;} Public String Sound( ) { return Hoh Hoh;} public String tostring( ) { return this.name;} } class Cat extends Animal{ private String name; public Cat (String name) { this.name=name;} Public String Sound( ) { return Nyan Nyan;} public String tostring( ) { return this.name;} } class AnimalSound{ public static void main(string [ ]args) {Dog=new Dog(dog1); getSound(dog); Cat cat1=new Cat(cat1); getSound(cat); } public getSound(Animal animal){ String sound =animal.Sound( ); System.out.println(sound); } } 18. Define an AnimalList class that can store an arbitrary collection of objects of subclasses of the Animal class. Your AnimalList class should contain methods to add, remove Animal object from the list as well as returning the Animal object at a given index position (Consider using the Vector class in Java.util package for storing Animal objects.

11

(20 Marks) Import java.util.*; class AnimalList{ private Vector animalist; public AnimalList( ) { animalist=new Vector( );} public void add(Animal animal) {animalist.addelement(animal);} public Animal remove (int idx) { return Animal Animalist.remove(idx);} public static void main(String[ ]args) {AnimalList list=new AnimalList( ); Dog dog1=new Dog(dog1); Dog dog2=new Dog(dog2); list.add(dog1); list add(dog2); Cat cat1=new Cat(Cat1); Cat cat1=new Cat(Cat2); list.add(cat1); list.add(cat2); Animal animal list.remove(0); System.out.println(animal tosring ( )); System.out.println(animal Sound ( )); animal list.remove(0); System.out.println(animal tosring ( )); System.out.println(animal Sound ( )); animal list.remove(0); System.out.println(animal tosring ( )); System.out.println(animal Sound ( )); } }

19. Fill in the blanks; are the instance variables w, x, y and z accessible from class B? (10 Marks)

12

Same Package

public class A int w; private int x; protected int y; public int z;

public class B extend A ( ( ( ( True False True True ) ) ) )

20. Fill in the blanks. Are the instance variables w, x, y and z accessible from class C? (10 Marks) Same Package

public class A int w; private int x; protected int y; public int z; ( ( ( (

public class C True False True True ) ) ) )

13

Computer Graphics and Image Processing

IT 3014

for

Second Semester

Sample Question

1. Set up the program segment that plots three data set with three different line types : solid , dashed and dotted line .(20 marks) 2. Discuss detail how the thick lines are plotted. (20 marks) 3. What is the color lookup table .Describe the advantages of this table .(10 marks) 4. Implement the line type function by modifying Bresenhams line drawing algorithm to display either solid , dashed , or dotted lines .(20 marks). 5. Suppose a system with an 8-inch by 10 inch video screen that can display 100 pixels per inch . If a color lookup table with 64 positions is used with this system what is the smallest possible size (in bytes ) for the frame buffer ?(10 marks) 6. Implement the line type function with a midpoint algorithm to display either solid ,dashed or dotted lines.(20 marks) 7. Set up a program segment that plots the three data sets with three different line colors and types : solid , dashed and dotted line . These three data sets are monthly data for year 1960, 1970 and 1980 and read from the respective file .(20 marks) 8. Consider an RGB raster system that has a 512-by-512 frame buffer with a 20 bits per pixel and a color lookup table with 24 bits per pixel. ( a) How many distinct gray levels can be displayed with this system ? (b) How many distinct colors (including gray levels ) can be displayed ? ( c ) How many colors can be displayed at anyone time ? ( d ) What is the total memory size ? ( e ) Explain two methods for reducing memory size while maintaining the same color capabilities .(10 marks) 9.Define and implement a function for controlling the line type ( solid, dashed , dotted ) of displayed ellipses . (20 marks) 10.What means the term aliasing ? And briefly discuss on the antialising methods . (20 marks) 11.Show that the composition of two rotations is additive by concatenating the matrix representations for R ( 1) and R ( 2) to obtain R ( 1) . R (1) = R (1+ 1 ) (20 marks) 12. Discuss how and object can be rotated about a specified pivot point ( xr , yr ). (20 marks) 13. Illustrate and explain the transformation sequence for scaling an object with respect to a specified fixed position using the sealing matrix , S ( sx ,sy ). (10 marks) 14. Write a procedure that transforms a polygon by using translation,rotation and scaling (20 marks) 15. Show that transformation matrix for a reflection about the line y = x ,is equivalent to a reflection relative to the x- axis followed by a counterclockwise rotation of 90. (20 marks) 16. Show that transformation matrix for a reflection about the line y= -x , is equivalent to a reflection relative to the y-axis followed by a counterclockwise rotation of 90. (20 marks) 17. Set up procedure for implementing a block transfer of a rectangular area of a frame buffer, using one function to read the area into an array and another

function to copy the array into the designated transfer area. (20 marks) 18. Implement the Cohen Sutherland line clipping algorithm. (20 marks) 19. Write a procedure that demonstrates the cohen-sutherland line-clipping algorithm.Codes for each points are stored as bytes and processed using bit manipulations. (20 marks) 20. Write a procedure to implement the liang Barsky line clipping algorithm. (20 marks) 21. Set up a detailed algorithm for the Nicholl-Lee-Nicholl approach to the line clipping for any input of line endpoints. (20 marks) 22. Compare the number of arithmetic operations in NLN algorithm to both the Cohen-Sutherland and the Liang-Barsky line clipping algorithms for several different line orientations relative a clipping window. (20 marks)

Computer Graphics

IT 3026

for

Second Semester

Sample Answer & Question

1. Set up the program segment that plots three data set with three different line types : solid , dashed and dotted line .(20 marks) Answer # include < stdio.h > # include graphics . h #define MARGIN-WIDTH 0.05 WINDOW-WIDTH int radius (char * infile ,float * data ) { int fileError= False; FILE * fp; int month; if ( ( fp= fopen (infile , r) )= = NULL); fileError = TRUE; else { for (month=0;month<12; month++) fscanf ( fp , %f , &data [month]); } fclose (fp); return (file Error); } void chartData (float * data , plineType Line Type ) { wcpt2 pts [12], float month Width = (WINDOW-WIDTH-2 * MARGIN-WIDTH); int i; for (i=0;i< 12;i ++ ) { pts [i].x = MARGIN-WIDTH + i * monthWidth * 0.5 *monthWidth ; pts [i].y =data [i] ; } pSetlineType (line Type ); pPolyLine (12,pts ); } int main (int argc, char ** argv) { long window ID = open Graphics (* argv, WINDOW-WIDTH,WINDOW-HEIGHT), float data [12]; set Background (WHITE); set Color (BLUE); read Data ( ../ data/ data 1960,.data); chartData (data ,SOLID);

read Data(../data/data 1970,.data); chart Data (data, DOTTED); sleep(10); closeGraphics (windowID); } 2. Discuss detail how the thick lines are plotted .(20 marks) Answer Implementation of line width options depends on the capabilities of the output device. A heavy line on a video monitor could be displayed as adjacent parallel lines , while a pen plotter might require pen changes . This value is then used by line drawing algorithms to control the thickness of lines generated with subsequent output primitive commands. Setline width Scale Factor (lw) Line width parameter lw is assigned a positive number to indicate the relative width of the line to be displayed. For lines with slope magnitude less than 1, we can modify a line drawing routine to display thick line by plotting a vertical spans of pixels at each x position along the line . We calculate the corresponding y coordinate and plot pixels with screen coordinates (x,y) and (x,y+1). For lines with slope magnitude greater than 1, we can plot thick lines with horizontal spans. Although thick lines are generated quickly by plotting horizontal or vertical pixels spans, the displayed width of a line is dependent on its slope. Another problem with implementing width option using horizontal or vertical pixel spans is that the method produces lines whose ends are horizontal or vertical regardless of the slope of the line. One kind of line cap is the butt cap obtained by adjusting the end positions of the component parallel lines. So that the thick line is displayed with squares ends that are perpendicular to the line path. Another line cap is the round cap obtained by adding a filled semicircle to each butt cap. The circular arcs are centered on the line endpoints and have a diameter equal to the line thickness. A miter joint is accomplished by extending the outer boundaries of each of the two lines until they meet. A round join is produced by capping the connection between the two segments with a circular boundary whose diameter is equal to the line width. And a bevel join is generated by displaying the line segments with butt caps and filling in the triangular gap where the segments meet.

3. What is the color lookup table .Describe the advantages of this table .(10 marks) Answer A possible scheme for storing color values in a color lookup tables (or video lookup table), where frame-buffer values are now used as indicates into the color table. Use of a color table can provide a reasonable number of simultaneous colors without requiring large frame buffers. A user to be able to experiment easily with different color combinations in a design, scene, or graph without changing the attribute settings for the graph ics data structure. Visualization applications can store values for some physical quantity, such as energy, in the frame buffer and use a lookup table to tryout various color encoding without changing the pixel value color tables are a convenient means for setting cole thresholds. Thresholds can be set to the same color. 4. Implement the line type function by modifying Bresenhams line drawing algorithm to display either solid , dashed , or dotted lines .(20 marks). # include <stdio.h> # include graphics.h # define MARGIN-WIDTH 0.05*WINDOW-WIDTH void lineBres (int xa,int ya ,int xb,int yb) { int dx= abs (xa-xb),dy=abs(ya-yb); int p=2* dy-dx;

int twoDy=2*dy,twoD 2*(dy-dx); int x,y, xEnd; if (xa.xb) { x=xb; y=yb; xEnd =xa; } else { x=xa; y=ya; xEnd=xb; } setPixel (x,y); while (x<xEnd) { x+ +; if (p<0) p+ =twoDy; else { y+ +; p+ =two DyDx; } setPixel(x,y); } } int main (int argc, char ** argv) { long window ID= openGraphics (argv,WINDOW-WIDTH,WINDOW-HEIGH float data [12]; setBackground (WHITE); setColor (Blue); readData (../data/ data 1960,xa,ya,xb,yb,SOLID); readData (../data/data 1970, xa,ya,xb,yb, DASHED); readData (../data/data 1980,xa,ya,xb,yb,DOTTED); sleep (10); close Graphics (windowID); } 5. Suppose a system with an 8-inch by 10 inch video screen that can display 100 pixels per inch . If a color lookup table with 64 positions is used with this system , what is the smallest possible size (in bytes ) for the frame buffer ?(10 marks) Answer . Screen size 8inch by 10inch Display 100 pixels \inch So pixel of screen = 8*100*10*100

=8*105 pixels each pixel can reference 64 table position so each entry in this table uses 18 bit The smallest possible size for the frame is = 8*105*18 =18*105 bytes =1.8 Mbytes #

6. Implement the line type function with a midpoint algorithm to display either solid ,dashed or dotted lines.(20 marks) Answer #include <stdio.h> #include graphics.h #define MARGIN-WINDTH 0.05 . WINDOW-WIDTH void circleMidpoint (int xcenter, int ycenter, int radius ) { int x=0; int y=radius ; int p=1-radius; void circlePlotPoints( int , int, int, int); circlePlotPoints (xcenter,ycenter,x,y); while (x<y) { x+ +; if (p<0) p+2*x+1; else { y - -; p + =2*(x-y)+1; } circlePlotPoints (xcenter,ycenter,x,y); } } void circlePlotPoints(int xcenter, int ycenter, intx,inty); { setPixel(x center +x, ycenter=y); setPixel(xcenter x, ycenter+y); setPixel (xcenter+x, ycenter-y); setPixel (xcenter x, ycenter-y); setPixel (xcenter +y, ycenter+x); setPixel (xcenter y, ycenter+x); setPixel (xcenter +y, ycenter-x); setPixel (xcenter y, ycenter x); } int main (int argc, char* * argv)

{ long window ID= openGraphics (argv, WINDOW-WIDTH, WINDOW-HEIGHT) float data [12]; set Background (WHITE); setColor (BLUE); read Data (../data / data 1960,xcenter,ycenter, radius , SOLID); read Data (../data/data 1970,xcenter,ycenter, radius ,DASHED); readData (../data/data 1980, xcenter,ycenter,radius,DOTTED); sleep(10); closeGraphics( windowID); } 7. Set up a program segment that plots the three data sets with three different line colors and types : solid , dashed and dotted line . These three data sets are monthly data for year 1960, 1970 and 1980 and read from the respective file .(20 marks) Answer # include < stdio.h > # include graphics . h #define MARGIN-WIDTH 0.05 WINDOW-WIDTH int radius (char * infile ,float * data ) { int fileError= False; FILE * fp; int month; if ( ( fp= fopen (infile , r) )= = NULL; fileError = TRUE; else { for (month=0;month<12; month++) fscanf ( fp , %F , &data [month]); fclose (fp); } return (file Error); } void chartData (float * data , plineType Line Type ) { wcpt2 pts [12], float month Width = (WINDOW-WIDTH-2 * MARGIN-WIDTH) int i; for (i=0;i< 12;i ++ ) { pts [i].x = MARGIN-WIDTH + i * monthWidth + 0.5 *monthWidth ; pts [i].y =data [i] ; } pSetlineType (line Type ); pPolyLine (12,pts ); }

int main (int argc, char ** argv) { long window ID = open Graphics (* argv, WINDOW-WIDTH,WINDOW-HEIGHT), float data [12]; set Background (WHITE); set Color (BLUE); read Data ( ../ data/ data 1960,.data); chartData (data ,SOLID); read Data(../data/data 1970,.data); chart Data (data.DOTTED); sleep(10); closeGraphics (windowID); } 8. Consider an RGB raster system that has a 512-by-512 frame buffer with a 20 bits per pixel and a color lookup table with 24 bits per pixel. ( a) How many distinct gray levels can be displayed with this system ? (b) How many distinct colors (including gray levels ) can be displayed ? ( c ) How many colors can be displayed at anyone time ? ( d ) What is the total memory size ? ( e ) Explain two methods for reducing memory size while maintaining the same color capabilities .(10 marks) Answer Frame buffer 512 by 512 with 20 bits /pixels color lookup table 24 bit per pixel. (a) (b) (c) (d) (e) 220 =1M distinct gray levels can be displayed with this system. 224=16M distinct colors gray levels can be displayed . Three colors can be displayed at anyone time. Total memory sizes = 512* 512*24 = 0.7 M bytes . When multiple output devices are available at an installation , the same colortable interface may be used for all monitors . A color table for a monochrome monitor can be set up using a rage of RGB value with the display intensity. Intensity =0.5 [min(r, s, b) + max(r, y, b)] of

9.Define and implement a function for controlling the line type ( solid, dashed , dotted ) displayed ellipses . (20 marks) Answer #include <stdio.h> #include graphics.h #define MARGIN-WIDTH 0.05*WINDOW-WIDTH #define ROUND (a) ((int) (a+0.5)) void ellipse Midpoint (int xCenter , int yCenter , int Rx ,int Ry) { int Rx2 =Rx*Rx; int Ry2 =Ry*Ry; int twoRx2=2*Rx2 int twoRy2=2*Ry2 int p;

int x=0; int y=Ry; int px=0; int py= twoRx2*y; void ellipsePlotPoints (int,int,int,int); ellipsePlotpoints(xCenter,yCenter,x,y); p=ROUND (Ry2-(Rx2*Ry)+(0.25*Rx2)); while (px<py) { x++ ; px + = twoRy2; if (p<0) p+ = Ry2+px; else { y--; py-= twoRx2; p += Ry2 +px-py; } ellipsePlotPoints (xCenter, yCenter,x,y); } p=ROUND (Ry2*(x+0.5)*(x+0.5)+Rx2*(y-1)-Rx2*Ry2 while (y>0) y--; py-= twoRx2; if (p>0) p+= Rx2-py; else { x ++; px +=twoRy2; p+ =Rx2-py+px; } ellipsePlotPoints (xCenter,yCenter ,x,y); } } int main (int argc,char**argv) { long window ID= openGraphics (*argv,WINDOW-WIDTH, WINDOW HEIGHT)FLOAT DATA [12]; setBackground (WHITE); setColor (BLUE); readData(../data/data 1960 ,xcenter ,ycenter,Rx,Ry,SOLID); read Data(../data/data 1970,xcenter,ycenter,Rx,Ry,DASHED); readData(../data/data 1980 ,xcenter,ycenter,Rx,Ry,DOTTED); sleep (10); closeGraphics(window ID); }

10.What means the term aliasing ? And briefly discuss on the antialising methods . . What means the terms aliaring.And briefly discuss on the antiallising methods. (20 marks) Answer Display primitives generated by the raster algorithms have a jagged, or stairstep appearance because the sampling inter pixel positions.The distortion of information due to low frequency sampling (undersampling) is called aliasing. A stzightforward antialiasing) method is to increase sampling rate by treating the screen as if it were covered with a finer grid than is actually availavle .Then multiple sample points can be used across this finer grid to determine an appropriate intensity level for each screen pixel. This technique of sampling object characteristic at a high resolution and displaying the result at a lower resolution is called supersampling (or postfiltreing, since the general method involves computing intensities at subpixel grid position , then combining the results to obtain the pixel intensities). Displayed pixel positions are spots of light covering a finite area of the screen, and not infinitesimal mathematical points. In the line and fill-area algorithms the intensity of each pixel is mathematical points. In the line and fill-area algorithms the intensity of each pixel is determined by the location of a single point on the object boundary .By supersampling, intensity information is obtained from multiple points that contribute to the overall intensity of a pixel. An alternative to supersampling is to determined pixel intersity by calculating the areas of overlaps of each pixel with the object to be displayed, Antialiasing by computing overlap area is referred to as area sampling (or prefiltering since the intensity of the pixel as a whole is determined without calculating subpixel intensities ). Pixel overlap areas are obtained by determined where object boundaries intersect individual pixel boundaries. Raster objects can also be antialiased by shifting the displayed location of pixel areas. This technique,called pixel phasing , is applied by micropositioning the electron beam in relation to object geometry. 11.Show that the composition of two rotations is additive by concatenating the matrix representations for R ( 1) and R ( 2) to obtain R ( 1) . R (1) = R (1+ 1 )(20 marks) Answer A two dimentional rotation is applied to an object by repositioning it along a circular path in the xy plane.To generate a rotarion , we specify a rotation angle and the position (xr,xy)of the rotation point (or pivote point ) about which the object is to be rotate Fig (5.3). Positive values for the rotations angle define counterclockwise rotations about the pivote point , as in Fig 5.3, and negative values rotate objects in the clockwise direction. This transformation can also be describe as a rotation about a rotation axis. We first determine the transformation equations for rotation of a point position when the pivot point is at the coordinate orgin. X =rcos (+ q) = rcos cos - rsin sin Y= rsin (+) =rcos sin+rsin cos The original coordinates of the point in the polor coordinates are X= r cos , y=rsin

_ x =x cos -ysin y= xsin + ycos P=R.P cos -sin Sin cos

R=

R( 1+ 2) =R1+R2 12. Discuss how and object can be rotated about a specified pivot point ( xr , yr ). (20 marks) Answer A two dimentional rotation is applied to an object by repositioning it along a circular path in the xy plane .Togenerate a rotation , specify a rotation angle q and the position (xr,xy) of the rotation point (or pivot point) about which the object is to be rotated. Positive values of the rotation angle define counterclockwise rotations about the pivot point and the negative values rotate object in the clockwise direction. This transformation can be described as a rotation about a rotation axis that is perpendicular to the xy plane and passes through the pivot point. First consider the rotation of a point position P when the pivot point is at the coordinate origin. The angular and coordinate relationships of the original and transformed point positions are shown in figure below. Using standard trigonometric identities, the coordinates can be expressde in terms of angle and as, X= r cos (+)= rcos cos rsin sin y=r sin ( + )=r cos sin + rsin cos The original coordinates of the point in polar coordinste are X=r cos , y=rsin hen x =xcos -ysin y= xsin +ycos Rotation of a point about an arbitary poisition is illustrated in the above fijgure. Using the trigonometric relatioonships the transformation equations for rotation of a pisition (xr, xy): X= xr + (x-x r) cos -(y-yr) sin y=yr+ (x-xr)sin + (y-yr) cos Rotations are rigid body transformations that moves objects without deformations. Every point on an object is rotated through the same angle. Astraight line segment is rotated by appling the rotarion equatiogs to each of line endpoints and redrawing the line beween the new end points. Polygons are rotate by displaying each vertex through the specified rotation angle and regenerating the polygon using the new vertices. Curved lines are rotated by repositioning the defining points and redrawing the curve. Acircle of ellipse , in instance can be rotated about a noncentre axis by moving center position through the arc

that subtends the specified rotation angle . An ellipse can be rotated about its center coordinates by totating the major and major axes. 13. Illustrate and explain the transformation sequence for scaling an object with respect to a specified fixed position using the sealing matrix , S ( sx ,sy ).(10 marks) Answer . To produce scaling with respect to a selected fixed position (xf, yf) using a scaling function that can only scale relative to the coordinate orgin. 1. Translate object so that the fixed piont coordinates with the coordinates origin. 2. Scale the object with respect to the coordinate origin. 3. Use the inverse translation of step 1 to return origin the object to its original position . Concatenating the matrices for these operations produce the required scaling matrix.

[
or

][

][

][

T ( xf,yf ) .S(sx,sy),T ( -xf, -yf) = S ( xf, yf, sx, sy )

Fig. A transformation sequence for scaling an object with respect to a specified fixed position using the scaling matrix S ( Sx, Sy ) transformation 14. Write a procedure that transforms a polygon by using translation,rotation and scaling (20 marks)

Answer

. Figure.A polygon (a) is transformed into ( b ) by the composite operations # include <math.h> #include graphics.h typedef float Matrix 3*3 [3] [3]; Matrix3*3 the Matrix 3*3[3] [3]; Void matrix3*3 Set Identify (Matrix3*3 m) { int I, j; for (i=0; i< 3; I + +) for (j= 0; j,3; j-+} m[i] [j] ={i= =j}; } /* Multiples matrix a times b, putting result in b*} void matrix 3*3 PreMultiply {Matrix3*3 a,Matrix 3*3 b} { int r, c; Matrix3*3 tmp; For (r=0; r<3; r+ +) For (c=0;c<3;c+ +) Tmp [r] [c] = a[r] [0] * b[0][c]+ a[r][1] * b[1][c] +a[r][2] * b[2][c]; For (r=0; r< 3; r+ +) For (c=0; c<3; c+ +) B[r][c]= tmp[r][c]; }

void translate 2 (int tx,intty) { Matrix 3*3 m; Matrix 3*3 SetIdentity (m); M[0][2] =tx; M[1][2]=ty; Matrix3*3PreMultiply (m,the Matrix); } void scale 2 (float 3x,float sy,wcpt2 refpt) { Matrix3*3 m; Matrix3*3SetIdentity (m); M[0][0] =sx;

M[0][2]=(1-sx)*refpt.x; M[1][1]=sy; M[1][2]=(1-sy)*refpt.y; Matrix3*3PreMultiply(m,the Matrix); } void rotate 2(float 2, wcpt2 refpt) { Matrix 3*3 m; Matrix 3*3 SetIdentity {m}; A=OtoRadions (a); M[0][0]=cosf(a); M[0][1]= -sinf(a); M[0][2]= refpt.x*(1-cosf(a)) +refpt.y*sin (a); M[1][0] = sinf-(a); M[1][1]=cosf-(a); Matrix3*3 PreMultiply (m, the Matrix); } void transformpoints 2 (int npts,wcpt6 2*pts) { int k; float tmp; for (k=0; k<npts; k+-) { tmp= the Matrix [0][0]*Pts[k].x+ theMatrix[0][1]* pts [k].y+theMatrix[0][2]; pts[k].y+theMatrix[1][0] * pts[k].x+ theMatrix[1][1]* pts[k].y+ theMatrix[1][2]; pts[k].x=tmp; } }

void main (int argc.char** argv) { wcpt2 pts[3] ={50.0,50.0, 150.0,50,100.0,150.0}; long window ID=openGraphics (*argv,200,350}; set Background (WHITE); set Color(BLUE); PfillArea (3,pts); Matrix3*3SetIdentity (theMatrix); Scale 2 (0.5,0.5, refpt); Rotate 2(90.0,refpt); Translate2 (0,150); Transformpionts 2(3,pts); pfillArea (3.pts); sleep(10); closeGraphics(WINDOW ID);

15. Show that transformation matrix for a reflection about the line y = x ,is equivalent to a reflection relative to the x- axis followed by a counterclockwise rotation of 90. (20 marks) Answer Reflection about the line y=0 the x- axis is accomplished with the transformeation matrix.

[ [ [ ][

] ][ ][ ] ]

The counterclockwise rotation of 90. is accomplished with the transformation matrix.

For the translation sequence 1.Reflection relative to x-axis 2.Counterclockwise rotation of 90. the transformation matrix is obtained with the concatenation

The resultant transformation matrix is equal to the that for the reflection about the line y=x , which is :

16. Show that transformation matrix for a reflection about the line y= -x , is equivalent to a reflection relative to the y-axis followed by a counterclockwise rotation of 90. (20 marks) Answer Reflection about the y axis flips x coordinates while keeping y coordinates the same.The matrix for this transformation is

]
The counterclockwise rotation of 90. is accomplished with the transformation matrix

[ [ [ ] [

] [ ] [ ]

] ]

For the translation sequence (1). Reflection relative to y axis (2). Counterclockwise rotation of 90. The transformation matrix is obtained with the concatenation

The resultant transformation matrix is equal to the that for the reflection about the line y= x which is:

17. Set up procedure for implementing a block transfer of a rectangular area of a frame buffer, using one function to read the area into an array and another function to copy the array into the designated transfer area. (20 marks) Answer Raster function that manipulate rectangular pixel array are generally referred to as raster ops. Moving a block of pixels from one location to another is also called a block transfer of pixel values . On a bilevel system , this operation is called a bitBit (bit block transfer).The term pixBit is sometimes used for block transfers on multilevel systems (multiple bit per pixel ). Figure illustrates translation performed as a block transfer of a raster area . We accomplish this translation by first reading pixel intensities from a specified rectangular area of a raster into an array , then we copy the array back into the raster at the new location . The original object could be erased by filling its rectangular area with the background intensity. Typical raster functions often provided in graphics packets are:

Copy move a pixel block from one raster area to another Read save a pixel block in a designated array Write- transfer a pixel array to a position in the frame buffer

Rotation an array of pixel values. The original array orientation is in (a), the array orientation after a 90. .counterclockwise rotation is shown in (b), and the array orientation after 180. rotation is shown in (c).

Fig

A raster rotation for a rectangular block of pixels is accomplished by mapping the destination pixel areas onto the rotated block. Rotation in 90. degree increment are easily accomplished with block transfrers. We can rotate an rotate an object an object 90. counterclockwise by first reversing the pixel values in each row of the array , then we interchange rows and colums. A180. rotation is obtained by reversing the order of the elements in each row of the array , then reversing the order of the rows. For array rotations that are not multiples of 90. , we must perform more computations. 18. Implement the Cohen Sutherland line clipping algorithm.(20 marks) Answer The method speeds up the processing of line segments by performing initial tests that reduce the number of intersections that must be calculated. Every line and point in a pic5ture is assigned a four-digit binary code. Regions are set up in reference to the boundaries as shown in fig . Each bit position in the region code is used to indicate one of the four relative coordinate positions of the point with respect to the clip window to the left, right ,top or bottom. Bit 1:left

Bit 2:right Bit 3: below Bit 4: above Avalue of 1 in any bit position indicates that point is in that relative position; otherwise , the bit position is set 0. Bit 1 is set to 1 if x<x wmin. Region code bit values can be determined with the following two steps: (1) Calculate differences between endpoint coordinates and dipping boundaries.(2) Use the resultant sign bit of each difference calculation to set the corresponding value in the region code. Bit 1 is the sign bit of x-xwmin ; bit 2 is the sign bit of x wmin x; bit 3 is the sign bit of y-ywmin
We begin the clipping process for a line by comparing an outside endpoint to a clipping boundary to determine how much of the line can be discarded.Then the remaining part of the

line is checked against the other boundaries; and we continue until either the line is totally discarded or a section is found inside the window. Intersection points with a clipping boundary can be calculated using the slopeintercept form of the line equation, For a line with endpioint coordinate (x1 ,y1) And (x2,y2) , they coordinate of the intersection point with a vertical boundary can be obtained with the calculation Y= y1+ m(x-x1) Where the x value is set either to xwmin to xwmax
x=x1+y-y1 with y set either to ywmin to ywmax.

1001 0001

1000 0000 window

1010 0010

0101

0100

0110

Figure. Binary region codes assigned to line endpoints according to relative position with respect to the clipping rectangle. 19. Write a procedure that demonstrates the cohen-sutherland line-clipping algorithm.Codes for each points are stored as bytes and processed using bit manipulations. (20 marks) #define ROUND(a) ( (int)(0.0.5)) #define LEFT.EDGE 0*1 #define RIGHT.EDGE 0*2 #define BOTTOM.EDGE 0*4 #define TOP.EDGE 0*8 #define INSIDE (a) (!a) #define REJECT (a,b)(a&b) #define ACCEPT (a,b) (!(a/b))

usigned char encode (wcpt 2pt, dcpt winmin,dcpt winmax) { usigned char encode=0*00; if (pt.x<winmin.x) code= code/LEFT-EDGE; if (pt x>winmax x) code=code\RIGHT-EDGE; if (pt.y<winmin.y) code=code \ BOTTOM-EDGE; if (pt.y>winmax.y) code=code\TOP-EDGE; return (code); } void swapts (wcpt2*p1,wcpt2*p2) { wcpt2 tmp; tmp=*p1; *p1=*p2; *p2=tmp; } unsigned char tmp; tmp=*c1; *c1=*c2; *c2=tmp; } void clipline (dcpt winmin,dcptmax;wcpt2p1,wcpt2p2) { unsigned char code 1,code2; int done =FALSE,draw=FALSE; float m; while (!done) { code 1=encode (p1,winmin ,winmax); code2=encode (p2,winmin,winmax); if (ACCEPT(code1, code2)) { done =TRUE; draw=TRUE; } else if (REJECT(code1,code2)) done =TRUE; else { swap Pts (&p1,&p2); swapCodes (&code1,&code2); } if (p2.x!=p1.x) m=(p2.y-p1.y)/(p2.x-p1.x);

if (code1 & LEFT-EDGE) { p1.y+=(winminx-p1.x)*m; p1.x+=winmin.x; } else if (code1&RIGHT-EDGE) { p1.y+=(winmax.x-pl.x)*m; p1.x=winmax.x; } else if (code1& BOTTOM-EDGE) { if (p2.x!= p1.x) p1.x+=(winmin.y-p1.y)/m; p1.y=winminy; } else if (p2.x!= p1.x) p1.x+= (winmin.y-p1.y)/m; p1.y=winmin.y; } else if (code1&TOP-EDGE) { p1.x+= (winmax.y-p1.y)/m; p1.y=winmax.y; } } } if (draw) line DDA (ROUND(p1.x),ROUND(p1.y),ROUND(p2.x), ROUND (p2.y)); } 20. Write a procedure to implement the liang Barsky line clipping algorithm. (20 marks) Answer #include graphics.h #define ROUND(a) ((int)(2+0.5)) int clipTest (float p,float q,float * u1,float*u2) { float r; int retVal=TRUE; if (p<0.0){ r=p/q; if(r<*U2)

retVal= FALSE; else if (r>*Ul) *U1=r; } else if (p>0.0); { r=p/q; if (r<*U1) retVal= FALSE; else if (r<*U2) *U2=r; } else if (q<0.0) retVal=FALSE; return (ret Val); } void clipline (dcpt winmin,dcpt winmax,wcpt2p1,wcpt2 p2) { float u1=0.0, u2=1.0,p2.x-p1.x,dy; if (clip Test(-dx,p1.x-winmin.x,&u1,&u2)) if (clip Test (dx,winmax.x-p1.x,&u1,u2)) { dy=p2.y-p1.y; if (clip Test(-dy,p1.y-winmin.y,&u1,&u2)) { dy=p2.y-p1.y; if (clip Test (-dy,wimmax.y-p1.y,&u1,&u2)) { if (u2<1.0) { p2.x=p1.x+u2*dx; p2.y=p1.y+u2*dy; } if (u>0.0) { p1.x+= u1*dx; p1.y+=u1*dy; } line DDA(ROUND (p1.x),ROUND(p1.y),ROUND(p2.x),ROUND(p2.y); } } } 21. Set up a detailed algorithm for the Nicholl-Lee-Nicholl approach to the line clipping for any input of line endpoints. (20 marks)

Answer For a line with endpoints P1 and P2 ,first determine the position of P1 for the nine possible regions relative to the clipping rectangle. Only the three regions shown in figure 1 need be consider. If p1 lies in any of the other six regions , move it to one of the three regions in figure-1 using a symmetry transformation. P1 in Corner Region

Fig -1.Three possible positions for a line endpoint p1create some new regions in the plane , depending on the location of P1. Boundaries of the new regions are half-infinite line segments that start at the position of P1 and pass through the window corners If P1 is inside the clip window and P2 is outside, set the four regions shown in figure-2. The intersection with the appropriate window boundary is then carried out, depending on which one of the four regions (l,T,R or B) cotains P2 , of course , if both P1 P2 are inside the clipping rectangular, save the entire line. For the third case, when P1 is to the left and above clip window, use the clipping window, use the clipping regions in Fig-4. If P2 is in one of the three regions.T,L,TR, TB,LR or LB, this determines a unique clip window edge. An x intersection position on the left window boundary x with u=(xL-x1)/(x2x1) so that the y-intersection position y=y1+y2-y1 ( xL-x1) x2-x1

22. Compare the number of arithmetic operations in NLN algorithm to both the Cohen-Sutherland and the Liang-Barsky line clipping algorithms for several different line orientations relative a clipping window. (20 marks) Answer Compared to both the Cohen-Suther-Land and the Liang-Barsky algorithms, the Nicholl-Lee-Nicholl algorithm performs fewer comparisons and divisions. The trade-off is that the NLN algorithm can only be applied to two-dimensional clipping, whereas both the Liang-Barsky and the Cohen-Sutherland methods are easily extended to threedimensional scenes. For a line with endpoints P1 and P2 we first determine the position of point P1 for the nine possible regions relative to the clipping rectangle. Only the three regions shown in fig. If P1 lines in any one of the other six regions, we can move it to one of the three regions in fig using a symmetry transformation. We determine the position of P2 relative to T1, we create some new regions in the plane, depending on the location of P1. Boundaries of the new regions are half-infinite line segments that start at the position of P1 and pass through the window corners. If P1 is in the region to the left of the window, we set up the four regions,L,LT,LR and LB. These four regions determine a unique boundary for the line segment. For the third case, when P1 is to the left and above the clip window, we use the clipping regions, in this case, we have the two possibilities shown, depending on the position of P1 relative to the top left corner of the window, If P2 is one of the regions T,L,TR,TB,LR or LB, this determines a unique clip-window edge for the intersection calculations, To determine the region in which P2 is located, we compare the slop of the line to the slop of the boundaries of clip regions, For example, if P1 is left of the clipping rectangle, Then P2 is in region LT if

También podría gustarte