Tuesday, October 7, 2008

OPERATING SYSTEMS



Operating System Interview Questions



What’s OPERATING SYSTEM?
An Operating System, or OS, is a software program that enables the computer hardware to communicate and operate with the computer software. Without a computer Operating System, a computer would be useless.

OPERATING SYSTEM TYPES
As computers have progressed and developed so have the types of operating systems. Below is a basic list of the different types of operating systems and a few examples of Operating Systems that fall into each of the categories. Many computer Operating Systems will fall into more than one of the below categories.

GUI - Short for Graphical User Interface, a GUI Operating System contains graphics and icons and is commonly navigated by using a computer mouse. See our GUI dictionary definition for a complete definition. Below are some examples of GUI Operating Systems.

System 7.x
Windows 98
Windows CE

Multi-user - A multi-user Operating System allows for multiple users to use the same computer at the same time and/or different times. See our multi-user dictionary definition for a complete definition for a complete definition. Below are some examples of multi-user Operating Systems.

Linux
Unix
Windows 2000
Windows XP
Mac OS X

Multiprocessing - An Operating System capable of supporting and utilizing more than one computer processor. Below are some examples of multiprocessing Operating Systems.

Linux
Unix
Windows 2000
Windows XP
Mac OS X

Multitasking - An Operating system that is capable of allowing multiple software processes to run at the same time. Below are some examples of multitasking Operating Systems.

Unix
Windows 2000
Windows XP
Mac OS X

Multithreading - Operating systems that allow different parts of a software program to run concurrently. Operating systems that would fall into this category are:

Linux
Unix
Windows 2000
Windows XP
Mac OS X

What are the basic functions of an operating system?

- Operating system controls and coordinates the use of the hardware among the various applications programs for various uses. Operating system acts as resource allocator and manager. Since there are many possibly conflicting requests for resources the operating system must decide which requests are allocated resources to operating the computer system efficiently and fairly. Also operating system is control program which controls the user programs to prevent errors and improper use of the computer. It is especially concerned with the operation and control of I/O devices.

Why paging is used?
-Paging is solution to external fragmentation problem which is to permit the logical address space of a process to be noncontiguous, thus allowing a process to be allocating physical memory wherever the latter is available.

While running DOS on a PC, which command would be used to duplicate the entire diskette?
diskcopy

What resources are used when a thread created? How do they differ from those when a process is created?
When a thread is created the threads does not require any new resources to execute the thread shares the resources like memory of the process to which they belong to. The benefit of code sharing is that it allows an application to have several different threads of activity all within the same address space. Whereas if a new process creation is very heavyweight because it always requires new address space to be created and even if they share the memory then the inter process communication is expensive when compared to the communication between the threads.

What is virtual memory?
Virtual memory is hardware technique where the system appears to have more memory that it actually does. This is done by time-sharing, the physical memory and storage parts of the memory one disk when they are not actively being used.

What is Throughput, Turnaround time, waiting time and Response time?
Throughput – number of processes that complete their execution per time unit. Turnaround time – amount of time to execute a particular process. Waiting time – amount of time a process has been waiting in the ready queue. Response time – amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment).





What is the state of the processor, when a process is waiting for some event to occur?
Waiting state

What is the important aspect of a real-time system or Mission Critical Systems?
A real time operating system has well defined fixed time constraints. Process must be done within the defined constraints or the system will fail. An example is the operating system for a flight control computer or an advanced jet airplane. Often used as a control device in a dedicated application such as controlling scientific experiments, medical imaging systems, industrial control systems, and some display systems. Real-Time systems may be either hard or soft real-time. Hard real-time: Secondary storage limited or absent, data stored in short term memory, or read-only memory (ROM), Conflicts with time-sharing systems, not supported by general-purpose operating systems. Soft real-time: Limited utility in industrial control of robotics, Useful in applications (multimedia, virtual reality) requiring advanced operating-system features.

What is the difference between Hard and Soft real-time systems?
- A hard real-time system guarantees that critical tasks complete on time. This goal requires that all delays in the system be bounded from the retrieval of the stored data to the time that it takes the operating system to finish any request made of it. A soft real time system where a critical real-time task gets priority over other tasks and retains that priority until it completes. As in hard real time systems kernel delays need to be bounded

What is the cause of thrashing? How does the system detect thrashing?
Once it detects thrashing, what can the system do to eliminate this problem? - Thrashing is caused by under allocation of the minimum number of pages required by a process, forcing it to continuously page fault. The system can detect thrashing by evaluating the level of CPU utilization as compared to the level of multiprogramming. It can be eliminated by reducing the level of multiprogramming.

What is multi tasking, multi programming, multi threading?
Multi programming: Multiprogramming is the technique of running several programs at a time using timesharing. It allows a computer to do several things at the same time. Multiprogramming creates logical parallelism. The concept of multiprogramming is that the operating system keeps several jobs in memory simultaneously. The operating system selects a job from the job pool and starts executing a job, when that job needs to wait for any i/o operations the CPU is switched to another job. So the main idea here is that the CPU is never idle. Multi tasking: Multitasking is the logical extension of multiprogramming .The concept of multitasking is quite similar to multiprogramming but difference is that the switching between jobs occurs so frequently that the users can interact with each program while it is running. This concept is also known as time-sharing systems. A time-shared operating system uses CPU scheduling and multiprogramming to provide each user with a small portion of time-shared system. Multi threading: An application typically is implemented as a separate process with several threads of control. In some situations a single application may be required to perform several similar tasks for example a web server accepts client requests for web pages, images, sound, and so forth. A busy web server may have several of clients concurrently accessing it. If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time. The amount of time that a client might have to wait for its request to be serviced could be enormous. So it is efficient to have one process that contains multiple threads to serve the same purpose. This approach would multithread the web-server process, the server would create a separate thread that would listen for client requests when a request was made rather than creating another process it would create another thread to service the request. To get the advantages like responsiveness, Resource sharing economy and utilization of multiprocessor architectures multithreading concept can be used.

What is hard disk and what is its purpose?
Hard disk is the secondary storage device, which holds the data in bulk, and it holds the data on the magnetic medium of the disk. Hard disks have a hard platter that holds the magnetic medium, the magnetic medium can be easily erased and rewritten, and a typical desktop machine will have a hard disk with a capacity of between 10 and 40 gigabytes. Data is stored onto the disk in the form of files.

What is fragmentation? Different types of fragmentation?

- Fragmentation occurs in a dynamic memory allocation system when many of the free blocks are too small to satisfy any request. External Fragmentation: External Fragmentation happens when a dynamic memory allocation algorithm allocates some memory and a small piece is left over that cannot be effectively used. If too much external fragmentation occurs, the amount of usable memory is drastically reduced. Total memory space exists to satisfy a request, but it is not contiguous. Internal Fragmentation: Internal fragmentation is the space wasted inside of allocated memory blocks because of restriction on the allowed sizes of allocated blocks. Allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being used

What is DRAM? In which form does it store data?
- DRAM is not the best, but it’s cheap, does the job, and is available almost everywhere you look. DRAM data resides in a cell made of a capacitor and a transistor. The capacitor tends to lose data unless it’s recharged every couple of milliseconds, and this recharging tends to slow down the performance of DRAM compared to speedier RAM types.

What is Dispatcher?
- Dispatcher module gives control of the CPU to the process selected by the short-term scheduler; this involves: Switching context, Switching to user mode, Jumping to the proper location in the user program to restart that program, dispatch latency – time it takes for the dispatcher to stop one process and start another running.

What is CPU Scheduler?
- Selects from among the processes in memory that are ready to execute, and allocates the CPU to one of them. CPU scheduling decisions may take place when a process: 1.Switches from running to waiting state. 2.Switches from running to ready state. 3.Switches from waiting to ready. 4.Terminates. Scheduling under 1 and 4 is non-preemptive. All other scheduling is preemptive.

What is Context Switch?
- Switching the CPU to another process requires saving the state of the old process and loading the saved state for the new process. This task is known as a context switch. Context-switch time is pure overhead, because the system does no useful work while switching. Its speed varies from machine to machine, depending on the memory speed, the number of registers which must be copied, the existed of special instructions(such as a single instruction to load or store all registers).

What is cache memory?
- Cache memory is random access memory (RAM) that a computer microprocessor can access more quickly than it can access regular RAM. As the microprocessor processes data, it looks first in the cache memory and if it finds the data there (from a previous reading of data), it does not have to do the more time-consuming reading of data from larger memory.

What is a Safe State and what is its use in deadlock avoidance?
- When a process requests an available resource, system must decide if immediate allocation leaves the system in a safe state. System is in safe state if there exists a safe sequence of all processes. Deadlock Avoidance: ensure that a system will never enter an unsafe state.

What is a Real-Time System?
- A real time process is a process that must respond to the events within a certain time period. A real time operating system is an operating system that can run real time processes successfully





Following are a few basic questions that cover the essentials of OS:

1. Explain the concept of Reentrancy.
It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack.
Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure.

2. Explain Belady’s Anomaly.
Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process’ virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated to the process. This is Belady’s Anomaly. This is true for certain page reference patterns.

3. What is a binary semaphore? What is its use?
A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrent processes.

4. What is thrashing?
It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults.

5. List the Coffman’s conditions that lead to a deadlock.

  • Mutual Exclusion: Only one process may use a critical resource at a time.

  • Hold & Wait: A process may be allocated some resources while waiting for others.

  • No Pre-emption: No resource can be forcible removed from a process holding it.

  • Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.

6. What are short-, long- and medium-term scheduling?
Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process.
Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-management criteria.
Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption.

7. What are turnaround time and response time?
Turnaround time is the interval between the submission of a job and its completion. Response time is the interval between submission of a request, and the first response to that request.

8. What are the typical elements of a process image?

  • User data: Modifiable part of user space. May include program data, user stack area, and programs that may be modified.

  • User program: The instructions to be executed.

  • System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls.

  • Process control Block (PCB): Info needed by the OS to control processes.

9. What is the Translation Lookaside Buffer (TLB)?
In a cached system, the base addresses of the last few referenced pages is maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtual memory reference causes 2 physical memory accesses– one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physical memory access in cases of TLB-hit.

10. What is the resident set and working set of a process?
Resident set is that portion of the process image that is actually in real-memory at a particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.)

11. When is a system in safe state?
The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock.

12. What is cycle stealing?
We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle.

13. What is meant by arm-stickiness?
If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, C-SCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones.

14. What are the stipulations of C2 level security?
C2 level security provides for:

  • Discretionary Access Control

  • Identification and Authentication

  • Auditing

  • Resource reuse

15. What is busy waiting?
The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion.

16. Explain the popular multiprocessor thread-scheduling strategies.

  • Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.

  • Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.

  • Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.

  • Dynamic scheduling: The number of thread in a program can be altered during the course of execution.

17. When does the condition ‘rendezvous’ arise?
In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered.

18. What is a trap and trapdoor?
Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition.

19. What are local and global page replacements?
Local replacement means that an incoming page is brought in only to the relevant process’ address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only.

20. Define latency, transfer and seek time with respect to disk I/O.
Seek time is the time required to move the disk arm to the required track. Rotational delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time.

21. Describe the Buddy system of memory allocation.
Free memory is maintained in linked lists, each of equal sized blocks. Any such block is of size 2^k. When some memory is required by a process, the block size of next higher order is chosen, and broken into two. Note that the two such pieces differ in address only in their kth bit. Such pieces are called buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined, and put into the original free-block linked-list.

22. What is time-stamping?
It is a technique proposed by Lamport, used to order events in a distributed system without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system ‘i’ in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system ‘j’ sets its counter Cj to 1 more than the maximum of its current value and the incoming time-stamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds….(a) if Ti

23. How are the wait/signal operations for monitor different from those for semaphores?
If a process in a monitor signal and no task is waiting on the condition variable, the signal is lost. So this allows easier program design. Whereas in semaphores, every operation affects the value of the semaphore, so the wait and signal operations should be perfectly balanced in the program.

24. In the context of memory management, what are placement and replacement algorithms?
Placement algorithms determine where in available real-memory to load a program. Common methods are first-fit, next-fit, best-fit. Replacement algorithms are used when memory is full, and one process (or part of a process) needs to be swapped out to accommodate a new program. The replacement algorithm determines which are the partitions to be swapped out.

25. In loading programs into memory, what is the difference between load-time dynamic linking and run-time dynamic linking?
For load-time dynamic linking: Load module to be loaded is read into memory. Any reference to a target external module causes that module to be loaded and the references are updated to a relative address from the start base address of the application module.
With run-time dynamic loading: Some of the linking is postponed until actual reference during execution. Then the correct module is loaded and linked.

26. What are demand- and pre-paging?
With demand paging, a page is brought into memory only when a location on that page is actually referenced during execution. With pre-paging, pages other than the one demanded by a page fault are brought in. The selection of such pages is done based on common access patterns, especially for secondary memory devices.

27. Paging a memory management function, while multiprogramming a processor management function, are the two interdependent?
Yes.

28. What is page cannibalizing?
Page swapping or page replacements are called page cannibalizing.

29. What has triggered the need for multitasking in PCs?

  • Increased speed and memory capacity of microprocessors together with the support fir virtual memory and

  • Growth of client server computing

30. What are the four layers that Windows NT have in order to achieve independence?

  • Hardware abstraction layer

  • Kernel

  • Subsystems

  • System Services.

31. What is SMP?
To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor.

32. What are the key object oriented concepts used by Windows NT?

  • Encapsulation

  • Object class and instance

33. Is Windows NT a full blown object oriented operating system? Give reasons.
No Windows NT is not so, because its not implemented in object oriented language and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities .

34. What is a drawback of MVT?
It does not have the features like

  • ability to support multiple processors

  • virtual storage

  • source level debugging

35. What is process spawning?
When the OS at the explicit request of another process creates a process, this action is called process spawning.

36. How many jobs can be run concurrently on MVT?
15 jobs

37. List out some reasons for process termination.

  • Normal completion

  • Time limit exceeded

  • Memory unavailable

  • Bounds violation

  • Protection error

  • Arithmetic error

  • Time overrun

  • I/O failure

  • Invalid instruction

  • Privileged instruction

  • Data misuse

  • Operator or OS intervention

  • Parent termination.

38. What are the reasons for process suspension?

  • swapping

  • interactive user request

  • timing

  • parent process request

39. What is process migration?

It is the transfer of sufficient amount of the state of process from one machine to the target machine

40. What is mutant?

In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of ownership.

41. What is an idle thread?

The special thread a dispatcher will execute when no ready thread is found.

42. What is FtDisk?

It is a fault tolerance disk driver for Windows NT.

43. What are the possible threads a thread can have?

  • Ready

  • Standby

  • Running

  • Waiting

  • Transition

  • Terminated.

44. What are rings in Windows NT?
Windows NT uses protection mechanism called rings provides by the process to implement separation between the user mode and kernel mode.

45. What is Executive in Windows NT?
In Windows NT, executive refers to the operating system code that runs in kernel mode.

46. What are the sub-components of I/O manager in Windows NT?

  • Network redirector/ Server

  • Cache manager.

  • File systems

  • Network driver

  • Device driver

47. What are DDks? Name an operating system that includes this feature.
DDks are device driver kits, which are equivalent to SDKs for writing device drivers. Windows NT includes DDks.

48. What level of security does Windows NT meets?
C2 level security.



COMPUTER NETWORKS

COMPUTER NETWORKING QUESTIONS for freshers!!!!
1. What are the two types of transmission technology available?
(i) Broadcast and (ii) point-to-point
2. What is subnet?
A generic term for section of a large networks usually separated by a bridge or router.

3. Difference between the communication and transmission.
Transmission is a physical movement of information and concern issues like bit polarity, synchronization, clock etc.Communication means the meaning full exchange of information between two communication media.
4. What are the possible ways of data exchange?
(i) Simplex (ii) Half-duplex (iii) Full-duplex.
5. What is SAP?
Series of interface points that allow other computers to communicate with the other layers of network protocol stack.
6. What do you meant by “triple X” in Networks?
The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between the PAD and the network, called X.29. Together, these three recommendations are often called “triple X”
7. What is frame relay, in which layer it comes?
Frame relay is a packet switching technology. It will operate in the data link layer.
8. What is terminal emulation, in which layer it comes?
Telnet is also called as terminal emulation. It belongs to application layer.
9. What is Beaconing?
The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.
10. What is redirector?
Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer.
11. What is NETBIOS and NETBEUI?
NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications.
NETBEUI is Net BIOS extended user interface. A transport protocol designed by Microsoft and IBM for the use on small subnets.
12. What is RAID?
A method for providing fault tolerance by using multiple hard disk drives.
13. What is passive topology?
When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus.
14. What is Brouter?
Hybrid devices that combine the features of both bridges and routers.
15. What is cladding?
A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable.
16. What is point-to-point protocol
A communications protocol used to connect computers to remote networking services including Internet service providers.
17. How Gateway is different from Routers?
A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats
18. What is attenuation?
The degeneration of a signal over distance on a network cable is called attenuation.
19. What is MAC address?
The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique.
20. Difference between bit rate and baud rate.
Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits.
baud rate = bit rate / N
where N is no-of-bits represented by each signal shift.

21. What is Bandwidth?
Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth.
22. What are the types of Transmission media?
Signals are usually transmitted over some transmission media that are broadly classified in to two categories.
a) Guided Media:
These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light.
b) Unguided Media:
This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony.

23. What is Project 802?
It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN
Protocols.
It consists of the following:
 802.1 is an internetworking standard for compatibility of different LANs and Man’s across protocols.
 802.2 Logical link control (LLC) is the upper sub layer of the data link layer, which is non-architecture-specific, that is, remains the same for all IEEE-defined LANs.
 Media access control (MAC) is the lower sub layer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).
 802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.
24. What is Protocol Data Unit?
The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U - frame).
25. What are the different type of networking / internetworking devices?
Repeater:
Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link.
Bridges:
These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipient and control congestion.
Routers:
They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission.
Gateways:
They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model.
26. What is ICMP?
ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages.
27.What are the data units at different layers of the TCP / IP protocol suite?
The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media.

28. What is difference between ARP and RARP?
The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver.
The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address.

29. What is the minimum and maximum length of the header in the TCP segment and IP datagram?
The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes

30. What is the range of addresses in the classes of Internet addresses?
Class A 0.0.0.0 - 127.255.255.255
Class B 128.0.0.0 - 191.255.255.255
Class C 192.0.0.0 - 223.255.255.255
Class D 224.0.0.0 - 239.255.255.255
Class E 240.0.0.0 – 247.255.255.255



1. What are the two types of transmission technology available?
(i) Broadcast and (ii) point-to-point
2. What is subnet?
A generic term for section of a large networks usually separated by a bridge or router.
3. Difference between the communication and transmission.
Transmission is a physical movement of information and concern issues like bit polarity, synchronisation, clock etc.
Communication means the meaning full exchange of information between two communication media.
4. What are the possible ways of data exchange?
(i) Simplex (ii) Half-duplex (iii) Full-duplex.
5. What is SAP?
Series of interface points that allow other computers to communicate with the other layers of network protocol stack.
6. What do you meant by “triple X” in Networks?
The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called “triple X”
7. What is frame relay, in which layer it comes?
Frame relay is a packet switching technology. It will operate in the data link layer.
8. What is terminal emulation, in which layer it comes?
Telnet is also called as terminal emulation. It belongs to application layer.
9. What is Beaconing?
The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.
10. What is redirector?
Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer.
11. What is NETBIOS and NETBEUI?
NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications.
NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets.
12. What is RAID?
A method for providing fault tolerance by using multiple hard disk drives.
13. What is passive topology?
When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus.
14. What is Brouter?
Hybrid devices that combine the features of both bridges and routers.
15. What is cladding?
A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable.
16. What is point-to-point protocol
A communications protocol used to connect computers to remote networking services including Internet service providers.
17. How Gateway is different from Routers?
A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats
18. What is attenuation?
The degeneration of a signal over distance on a network cable is called attenuation.
19. What is MAC address?
The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique.
20. Difference between bit rate and baud rate.
Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits.
baud rate = bit rate / N
where N is no-of-bits represented by each signal shift.

21. What is Bandwidth?
Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth.
22. What are the types of Transmission media?
Signals are usually transmitted over some transmission media that are broadly classified in to two categories.
a) Guided Media:
These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light.
b) Unguided Media:
This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony.
23. What is Project 802?
It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN
protocols.
It consists of the following:
802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols.
802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs.
Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).
802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.
24. What is Protocol Data Unit?
The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U - frame).
25. What are the different type of networking / internetworking devices?
Repeater:
Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link.
Bridges:
These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion.
Routers:
They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission.
Gateways:
They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model.
26. What is ICMP?
ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages.
27. What are the data units at different layers of the TCP / IP protocol suite?
The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media.
28. What is difference between ARP and RARP?
The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver.
The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address.
29. What is the minimum and maximum length of the header in the TCP segment and IP datagram?
The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes.
30. What is the range of addresses in the classes of internet addresses?
Class A 0.0.0.0 - 127.255.255.255
Class B 128.0.0.0 - 191.255.255.255
Class C 192.0.0.0 - 223.255.255.255
Class D 224.0.0.0 - 239.255.255.255
Class E 240.0.0.0 - 247.255.255.255
31. What is the difference between TFTP and FTP application layer protocols?
The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP.
The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information.
32. What are major types of networks and explain?
Server-based network
Peer-to-peer network
Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources.
Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration
33. What are the important topologies for networks?
BUS topology:
In this each computer is directly connected to primary network cable in a single line.
Advantages:
Inexpensive, easy to install, simple to understand, easy to extend.
STAR topology:
In this all computers are connected using a central hub.
Advantages:
Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems.
RING topology:
In this all computers are connected in loop.
Advantages:
All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it.
34. What is mesh network?
A network in which there are multiple network links between computers to provide multiple paths for data to travel.
35. What is difference between baseband and broadband transmission?
In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously.
36. Explain 5-4-3 rule?
In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated.
37. What MAU?
In token Ring , hub is called Multistation Access Unit(MAU).
38. What is the difference between routable and non- routable protocols?
Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router
39. Why should you care about the OSI Reference Model?
It provides a framework for discussing network operations and design.
40. What is logical link control?
One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection.
41. What is virtual channel?
Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit.
42. What is virtual path?
Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path.
43. What is packet filter?
Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped.

C LANGUAGE



111) void pascal f(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
void cdecl f(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
main()
{
int i=10;
f(i++,i++,i++);
printf(” %d\n”,i);
i=10;
f(i++,i++,i++);
printf(” %d”,i);
}
Answer:
10 11 12 13
12 11 10 13
Explanation:
Pascal argument passing mechanism forces the arguments to be called from left to right. cdecl is the normal C argument passing mechanism where the arguments are passed from right to left.

112). What is the output of the program given below

main()
{
signed char i=0;
for(;i>=0;i++) ;
printf(”%d\n”,i);
}
Answer
-128
Explanation
Notice the semicolon at the end of the for loop. THe initial value of the i is set to 0. The inner loop executes to increment the value from 0 to 127 (the positive range of char) and then it rotates to the negative value of -128. The condition in the for loop fails and so comes out of the for loop. It prints the current value of i that is -128.

113) main()
{
unsigned char i=0;
for(;i>=0;i++) ;
printf(”%d\n”,i);
}
Answer
infinite loop
Explanation
The difference between the previous question and this one is that the char is declared to be unsigned. So the i++ can never yield negative value and i>=0 never becomes false so that it can come out of the for loop.

114) main()
{
char i=0;
for(;i>=0;i++) ;
printf(”%d\n”,i);

}
Answer:
Behavior is implementation dependent.
Explanation:
The detail if the char is signed/unsigned by default is implementation dependent. If the implementation treats the char to be signed by default the program will print –128 and terminate. On the other hand if it considers char to be unsigned by default, it goes to infinite loop.
Rule:
You can write programs that have implementation dependent behavior. But dont write programs that depend on such behavior.

115) Is the following statement a declaration/definition. Find what does it mean?
int (*x)[10];
Answer
Definition.
x is a pointer to array of(size 10) integers.

Apply clock-wise rule to find the meaning of this definition.

116). What is the output for the program given below

typedef enum errorType{warning, error, exception,}error;
main()
{
error g1;
g1=1;
printf(”%d”,g1);
}
Answer
Compiler error: Multiple declaration for error
Explanation
The name error is used in the two meanings. One means that it is a enumerator constant with value 1. The another use is that it is a type name (due to typedef) for enum errorType. Given a situation the compiler cannot distinguish the meaning of error to know in what sense the error is used:
error g1;
g1=error;
// which error it refers in each case?
When the compiler can distinguish between usages then it will not issue error (in pure technical terms, names can only be overloaded in different namespaces).
Note: the extra comma in the declaration,
enum errorType{warning, error, exception,}
is not an error. An extra comma is valid and is provided just for programmer’s convenience.

117) typedef struct error{int warning, error, exception;}error;
main()
{
error g1;
g1.error =1;
printf(”%d”,g1.error);
}

Answer
1
Explanation
The three usages of name errors can be distinguishable by the compiler at any instance, so valid (they are in different namespaces).
Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after . (dot) or -> (arrow) operator preceded by the variable name as in :
g1.error =1;
printf(”%d”,g1.error);
typedef struct error{int warning, error, exception;}error;
This can be used to define variables without using the preceding struct keyword as in:
error g1;
Since the compiler can perfectly distinguish between these three usages, it is perfectly legal and valid.

Note
This code is given here to just explain the concept behind. In real programming don’t use such overloading of names. It reduces the readability of the code. Possible doesn’t mean that we should use it!

118) #ifdef something
int some=0;
#endif

main()
{
int thing = 0;
printf(”%d %d\n”, some ,thing);
}

Answer:
Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation. The name something is not already known to the compiler making the declaration
int some = 0;
effectively removed from the source code.

119) #if something == 0
int some=0;
#endif

main()
{
int thing = 0;
printf(”%d %d\n”, some ,thing);
}

Answer
0 0
Explanation
This code is to show that preprocessor expressions are not the same as the ordinary expressions. If a name is not known the preprocessor treats it to be equal to zero.

120). What is the output for the following program

main()
{
int arr2D[3][3];
printf(”%d\n”, ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );
}
Answer
1
Explanation
This is due to the close relation between the arrays and pointers. N dimensional arrays are made up of (N-1) dimensional arrays.
arr2D is made up of a 3 single arrays that contains 3 integers each .

The name arr2D refers to the beginning of all the 3 arrays. *arr2D refers to the start of the first 1D array (of 3 integers) that is the same address as arr2D. So the expression (arr2D == *arr2D) is true (1).
Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value/meaning. Again arr2D[0] is the another way of telling *(arr2D + 0). So the expression (*(arr2D + 0) == arr2D[0]) is true (1).
Since both parts of the expression evaluates to true the result is true(1) and the same is printed.

121) void main()
{
if(~0 == (unsigned int)-1)
printf(“You can answer this if you know how values are represented in memory”);
}
Answer
You can answer this if you know how values are represented in memory
Explanation
~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill the space for an integer. –1 is represented in unsigned value as all 1’s and so both are equal.

122) int swap(int *a,int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
int x=10,y=20;
swap(&x,&y);
printf(”x= %d y = %d\n”,x,y);
}
Answer
x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help understand this.

123) main()
{
char *p = “ayqm”;
printf(“%c”,++*(p++));
}
Answer:
b

124) main()
{
int i=5;
printf(”%d”,++i++);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is required.

125) main()
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}
Answer:
b
Explanation:
There is no difference between the expression ++*(p++) and ++*p++. Parenthesis just works as a visual clue for the reader to see which expression is first evaluated.

126)
int aaa() {printf(“Hi”);}
int bbb(){printf(“hello”);}
iny ccc(){printf(“bye”);}

main()
{
int ( * ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}
Answer:
bye
Explanation:
int (* ptr[3])() says that ptr is an array of pointers to functions that takes no arguments and returns the type int. By the assignment ptr[0] = aaa; it means that the first function pointer in the array is initialized with the address of the function aaa. Similarly, the other two array elements also get initialized with the addresses of the functions bbb and ccc. Since ptr[2] contains the address of the function ccc, the call to the function ptr[2]() is same as calling ccc(). So it results in printing “bye”.

127)
main()
{
int i=5;
printf(“%d”,i=++i ==6);
}

Answer:
1
Explanation:
The expression can be treated as i = (++i==6), because == is of higher precedence than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the result.

128) main()
{
char p[ ]=”%d\n”;
p[1] = ‘c’;
printf(p,65);
}
Answer:
A
Explanation:
Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”. Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.

129) void ( * abc( int, void ( *def) () ) ) ();

Answer::
abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptrto a funtion which returns void. the return type of the function is void.
Explanation:
Apply the clock-wise rule to find the result.

130) main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
}
Answer:
No output
Explanation:
Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop.

131) main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}
Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination, it treats whatever the values that are in the following positions as part of the string until it randomly reaches a ‘\0’. So str1 and str2 are not the same, hence the result.

132) main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}

Answer:
Compiler Error: Lvalue required.
Explanation:
As we know that increment operators return rvalues and hence it cannot appear on the left hand side of an assignment operation.

133) void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.

134) void main()
{
static int i;
while(i<=10)
(i>2)?i++:i–;
printf(“%d”, i);
}
Answer:
32767
Explanation:
Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i–. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.

135) main()
{
int i=10,j=20;
j = i, j?(i,j)?i:j:j;
printf(”%d %d”,i,j);
}

Answer:
10 10
Explanation:
The Ternary operator ( ? : ) is equivalent for if-then-else statement. So the question can be written as:
if(i,j)
{
if(i,j)
j = i;
else
j = j;
}
else
j = j;

136) 1. const char *a;
2. char* const a;
3. char const *a;
-Differentiate the above declarations.

Answer:
1. ‘const’ applies to char * rather than ‘a’ ( pointer to a constant char )
*a=’F’ : illegal
a=”Hi” : legal

2. ‘const’ applies to ‘a’ rather than to the value of a (constant pointer to char )
*a=’F’ : legal
a=”Hi” : illegal

3. Same as 1.

137) main()
{
int i=5,j=10;
i=i&=j&&10;
printf(”%d %d”,i,j);
}

Answer:
1 10
Explanation:
The expression can be written as i=(i&=(j&&10)); The inner expression (j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.

138) main()
{
int i=4,j=7;
j = j || i++ && printf(”YOU CAN”);
printf(”%d %d”, i, j);
}

Answer:
4 1
Explanation:
The boolean expression needs to be evaluated only till the truth value of the expression is not known. j is not equal to zero itself means that the expression’s truth value is 1. Because it is followed by || and true || (anything) => true where (anything) will not be evaluated. So the remaining expression is not evaluated and so the value of i remains the same.
Similarly when && operator is involved in an expression, when any of the operands become false, the whole expression’s truth value becomes false and hence the remaining expression will not be evaluated.
false && (anything) => false where (anything) will not be evaluated.

139) main()
{
register int a=2;
printf(”Address of a = %d”,&a);
printf(”Value of a = %d”,a);
}
Answer:
Compier Error: ‘&’ on register variable
Rule to Remember:
& (address of ) operator cannot be applied on register variables.

140) main()
{
float i=1.5;
switch(i)
{
case 1: printf(”1″);
case 2: printf(”2″);
default : printf(”0″);
}
}
Answer:
Compiler Error: switch expression not integral
Explanation:
Switch statements can be applied only to integral types.

141) main()
{
extern i;
printf(”%d\n”,i);
{
int i=20;
printf(”%d\n”,i);
}
}
Answer:
Linker Error : Unresolved external symbol i
Explanation:
The identifier i is available in the inner block and so using extern has no use in resolving it.

142) main()
{
int a=2,*f1,*f2;
f1=f2=&a;
*f2+=*f2+=a+=2.5;
printf(”\n%d %d %d”,a,*f1,*f2);
}
Answer:
16 16 16
Explanation:
f1 and f2 both refer to the same memory location a. So changes through f1 and f2 ultimately affects only the value of a.

143) main()
{
char *p=”GOOD”;
char a[ ]=”GOOD”;
printf(”\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d”, sizeof(p), sizeof(*p), strlen(p));
printf(”\n sizeof(a) = %d, strlen(a) = %d”, sizeof(a), strlen(a));
}
Answer:
sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
sizeof(a) = 5, strlen(a) = 4
Explanation:
sizeof(p) => sizeof(char*) => 2
sizeof(*p) => sizeof(char) => 1
Similarly,
sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the array and it is not the same as the sizeof the pointer variable. Here the sizeof(a) where a is the character array and the size of the array is 5 because the space necessary for the terminating NULL character should also be taken into account.

144) #define DIM( array, type) sizeof(array)/sizeof(type)
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr, int));
}
Answer:
10
Explanation:
The size of integer array of 10 elements is 10 * sizeof(int). The macro expands to sizeof(arr)/sizeof(int) => 10 * sizeof(int) / sizeof(int) => 10.

145) int DIM(int array[])
{
return sizeof(array)/sizeof(int );
}
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr));
}
Answer:
1
Explanation:
Arrays cannot be passed to functions as arguments and only the pointers can be passed. So the argument is equivalent to int * array (this is one of the very few places where [] and * usage are equivalent). The return statement becomes, sizeof(int *)/ sizeof(int) that happens to be equal in this case.



 	

main( )
{  void *vp;  char ch = ‘g’, *cp = “goofy”;  int j = 20;  vp = &ch;  printf(%c”, *(char *)vp);  vp = &j;  printf(%d”,*(int *)vp);  vp = cp;  printf(%s”,(char *)vp + 3); }

Answer:
g20fy
Explanation:
Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is ‘g’. Similarly the output from second printf is ‘20’. The third printf statement type casts it to print the string from the 4th value hence the output is ‘fy’.

52)

        main ( ) {  static char *s[ ]  = {“black”, “white”, “yellow”, “violet”};  char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;  p = ptr;  **++p;  printf(%s”,*--*++p + 3); }

Answer:
ck
Explanation:
In this problem we have an array of char pointers pointing to start of 4 strings. Then we have ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type char. p hold the initial value of ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus now value of p = s+2. In the printf statement the expression is evaluated *++p causes gets value s+1 then the pre decrement is executed and we get s+1 – 1 = s . the indirection operator now gets the value from the array of s and adds 3 to the starting address. The string is printed starting from this position. Thus, the output is ‘ck’.

53)

 main() {  int  i, n;  char *x = “girl”;  n = strlen(x);  *x = x[n];  for(i=0; i<n; ++i)    { printf(%s\n”,x); x++;    }  }

Answer:
(blank space)
irl
rl
l

Explanation:
Here a string (a pointer to char) is initialized with a value “girl”. The strlen function returns the length of the string, thus n has a value 4. The next statement assigns value at the nth location (‘\0’) to the first location. Now the string becomes “\0irl” . Now the printf statement prints the string after each iteration it increments it starting position. Loop starts from 0 to 4. The first time x[0] = ‘\0’ hence it prints nothing and pointer value is incremented. The second time it prints from x[1] i.e “irl” and the third time it prints “rl” and the last time it prints “l” and the loop terminates.
54)

        int i,j;         for(i=0;i<=10;i++)         {         j+=5;         assert(i<5);         }

Answer:
Runtime error: Abnormal program termination.
assert failed (i<5),



55)

        main()         {         int i=-1;         +i;         printf("i = %d, +i = %d \n",i,+i);         }

Answer:
i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator).

56) What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error).

57) what will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);

Answer :
a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position
of the file.

58)

        main()         {         char name[10],s[12];         scanf(" \"%[^\"]\"",s);         }         How scanf will execute?

Answer:
First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark.

59) What is the problem with the following code segment?

        while ((fgets(receiving array,50,file_ptr)) != EOF)                         ;

Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking for != NULL.

60)

        main()         {         main();         }

Answer:
Runtime error : Stack overflow.
Explanation:
main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to terminate the function call, the call stack overflows at runtime. So it terminates the program and results in an error.

61)

        main()         {         char *cptr,c;         void *vptr,v;         c=10;  v=0;         cptr=&c; vptr=&v;         printf("%c%v",c,v);         }

Answer:
Compiler error (at line number 4): size of v is Unknown.
Explanation:
You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error.

62)

        main()         {         char *str1="abcd";         char str2[]="abcd";         printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));         }

Answer:
2 5 5
Explanation:
In first sizeof, str1 is a character pointer so it gives you the size of the pointer variable. In second sizeof the name str2 indicates the name of the array whose size is 5 (including the ‘\0′ termination character). The third sizeof is similar to the second one.

63)

        main()         {         char not;         not=!2;         printf("%d",not);         }

Answer:
0
Explanation:
! is a logical operator. In C the value 0 is considered to be the boolean value FALSE, and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non-zero value so TRUE. !TRUE is FALSE (0) so it prints 0.

64)

        #define FALSE -1         #define TRUE   1         #define NULL   0         main() {            if(NULL)                 puts("NULL");            else if(FALSE)                 puts("TRUE");            else                 puts("FALSE");            }

Answer:
TRUE
Explanation:
The input program to the compiler after processing by the preprocessor is,

        main(){                 if(0)                         puts("NULL");         else if(-1)                         puts("TRUE");         else                         puts("FALSE");                 }

Preprocessor doesn’t replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence “TRUE” is printed.

65)

        main()         {         int k=1;         printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");         }

Answer:
1==1 is TRUE
Explanation:
When two strings are placed together (or separated by white-space) they are concatenated (this is called as “stringization” operation). So the string is as if it is given as “%d==1 is %s”. The conditional operator( ?: ) evaluates to “TRUE”.

66)

        main()         {         int y;         scanf("%d",&y); // input given is 2000         if( (y%4==0 && y%100 != 0) || y%100 == 0 )              printf("%d is a leap year");         else              printf("%d is not a leap year");         }

Answer:
2000 is a leap year
Explanation:
An ordinary program to check if leap year or not.

67)

        #define max 5         #define int arr1[max]         main()         {         typedef char arr2[max];         arr1 list={0,1,2,3,4};         arr2 name="name";         printf("%d %s",list[0],name);         }

Answer:
Compiler error (in the line arr1 list = {0,1,2,3,4})
Explanation:
arr2 is declared of type array of size 5 of characters. So it can be used to declare the variable name of the type arr2. But it is not the case of arr1. Hence an error.
Rule of Thumb:
#defines are used for textual replacement whereas typedefs are used for declaring new types.

68)

        int i=10;         main()         {          extern int i;                   {              int i=20;                 {                  const volatile unsigned i=30;                  printf("%d",i);                 }               printf("%d",i);            }         printf("%d",i);         }

Answer:
30,20,10
Explanation:
‘{’ introduces new block and thus new scope. In the innermost block i is declared as,
const volatile unsigned
which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20. In the outermost block, i is declared as extern, so no storage space is allocated for it. After compilation is over the linker resolves it to global variable i (since it is the only variable visible there). So it prints i’s value as 10.

69)

        main()         {             int *j;             {              int i=10;              j=&i;              }              printf("%d",*j); }

Answer:
10
Explanation:
The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.

70)

        main()         {         int i=-1;         -i;         printf("i = %d, -i = %d \n",i,-i);         }

Answer:
i = -1, -i = 1
Explanation:
-i is executed and this execution doesn’t affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

71)

        #include main()  {    const int i=4;    float j;    j = ++i;    printf("%d  %f", i,++j);  }

Answer:
Compiler error
Explanation:
i is a constant. you cannot change the value of constant

72)

        #include main() {   int a[2][2][2] = { {10,2,3,4}, {5,6,7,8}  };   int *p,*q;   p=&a[2][2][2];   *q=***a;   printf("%d..%d",*p,*q); }

Answer:
garbagevalue..1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. now q is pointing to starting address of a.if you print *q meAnswer:it will print first element of 3D array.

73)

        #include main()   {     register i=5;     char j[]= "hello";                           printf("%s  %d",j,i); }

Answer:
hello 5
Explanation:
if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory.

74)

        main() {           int i=5,j=6,z;           printf("%d",i+++j);          }

Answer:
11
Explanation:
the expression i+++j is treated as (i++ + j)

76)

        struct aaa{ struct aaa *prev; int i; struct aaa *next; }; main() {  struct aaa abc,def,ghi,jkl;  int x=100;  abc.i=0;abc.prev=&jkl;  abc.next=&def;  def.i=1;def.prev=&abc;def.next=&ghi;  ghi.i=2;ghi.prev=&def;  ghi.next=&jkl;  jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;  x=abc.next->next->prev->next->i;  printf("%d",x); }

Answer:
2
Explanation:
above all statements form a double circular linked list;
abc.next->next->prev->next->i
this one points to “ghi” node the value of at particular node is 2.

77)

        struct point  {  int x;  int y;  }; struct point origin,*pp; main() { pp=&origin; printf("origin is(%d%d)\n",(*pp).x,(*pp).y); printf("origin is (%d%d)\n",pp->x,pp->y); }

Answer:
origin is(0,0)
origin is(0,0)
Explanation:
pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator.
Note:
Since structure point is globally declared x & y are initialized as zeroes

78)

        main() {  int i=_l_abc(10);          printf("%d\n",--i); } int _l_abc(int i) {  return(i++); }

Answer:
9
Explanation:
return(i++) it will first return i and then increments. i.e. 10 will be returned.

79)

        main() {  char *p;  int *q;  long *r;  p=q=r=0;  p++;  q++;  r++;  printf("%p...%p...%p",p,q,r); }

Answer:
0001…0002…0004
Explanation:
++ operator when applied to pointers increments address according to their corresponding data-types.

80)

        main() {  char c=' ',x,convert(z);  getc(c);  if((c>='a') && (c<='z'))  x=convert(c);  printf("%c",x); } convert(z) {   return z-32; }

Answer:
Compiler error
Explanation:
declaration of convert and format of getc() are wrong.