Anda di halaman 1dari 101

GE6151 Computer Programming Question Bank

UNIT I - INTRODUCTION PART A (2 MARKS) 1. Define computers? A computer is a programmable machine or device that performs pre-defined or programmed computations or controls operations that are expressible in numerical or logical terms at high speed and with great accuracy. (Or) Computer is a fast operating electronic device, which automatically accepts and store input data, processes them and produces results under the direction of step by step program. 2. What are the basic operations of Computer? It accepts data or instructions by way of input . It stores data. It can process data as required by the user. It gives results in the form of output. It controls all operations inside a computer. 3. What are the characteristics of computers? (JAN 2009) Speed Accuracy. Automation. Endurance. Versatility. Storage. Cost Reduction. 4. How will you classify computer systems? (JAN2009) Based on physical size, performance and application areas, we can generally divide computers into four major categories: Micro computer Mini Computer

GE6151 Computer Programming Question Bank

Mainframe computer and Super Computer 5. Expand ENIVAC, ABC, EDVAC, EDSAC and UNIVAC. (JAN2010) ENIAC ABC EDVAC EDSAC UNIVAC - Electronic Numerical Integrator and Calculator. - Atanasoff and Berry Computer. - Electronic Discrete Variable Automatic Calculator. - Electronic Delay Storage Automatic Calculator. - UNIversal Automatic Computer.

6. What are the components of the computer systems? Basic components of the computer system are Input Unit, Central Processing Unit, Secondary Storage Unit and Output Unit. 7. What is an ALU? Arithmetic logic unit, the part of a computer that performs all arithmetic computations, such as addition and multiplication, and all logical operations such s comparison operations. The ALU is one component of the CPU (central processing unit). 8. What are the functions in the input unit? An input device is a device that is used to input data or information into a computer. Some examples of input devices include: Keyboards. Computer Light Pen. Digitizer. Touchpad. 9. What are the functions in the output unit? In computers, a unit which delivers information from the computer to an external device or from internal storage to external storage. Speakers. Printer. Headphone mice.

GE6151 Computer Programming Question Bank

10. Define Mainframe computer? Mainframes are computers used mainly by large organizations for critical applications, typically bulk data processing such as census, industry and consumer statistics, enterprise resource planning, and financial processing. The term probably had originated from the early mainframes, as they were housed in enormous, room-sized metal boxes or frames. 11. Define super computer? The fastest type of computer. Supercomputers are very expensive and are employed for specialized applications that require immense amounts of mathematical calculations. For example, weather forecasting requires a supercomputer. Other uses of supercomputers include animated graphics, fluid dynamic calculations, nuclear energy research, and petroleum exploration. 12. What is a volatile and non-volatile memory? Volatile memory: also known as volatile storage is computer memory that requires power to maintain the stored information, unlike non-volatile memory which does not require a maintained power supply. It has been less popularly known as temporary memory. Non-volatile memory: nonvolatile memory, NVM or non-volatile storage, is computer memory that can retain the stored information even when not powered.

13. Write the binary and octal equivalent of hexadecimal number 7BD? (APR2009) Binary Equivalent of 7BD = (0111 1011 1101)2 Octal Equivalent of 7BD = (011 110 111 101) = (3675)8 14. Convert binary number 100110 into its octal equivalent? (JAN2009) Octal equivalent of 100110 = (100 110) = (46)8 15. What are registers? (JAN2009) A special, high-speed storage area within the CPU. All data must be represented in a register before it can be processed.

GE6151 Computer Programming Question Bank

For example, if two numbers are to be multiplied, both numbers must be in registers, and the result is also placed in a register. 16. Differentiate analog and digital computers? (JAN2010) Analog Computer Digital Computer Process measured data Process discrete data Analog computers are not precise, Digital computers are more precise Processing speed is low . Processing speed is high. Less accuracy . More accuracy.

17. Find the decimal equivalent of hexadecimal number 4D.C8 (JAN2010) 4D.C8 = 4 X 161 + 13 X 162 + 12 X 16-1 + 8 X 16-2 = 64 + 13 +0.75 + 0.03125 = (77.78)2 18. Convert hexadecimal number into binary equivalent of EBC (JAN2010) Binary equivalent of EBC = (1110 1011 1100)2 19. What is algorithm? (JAN2009) Algorithm means the logic of a program. It is a step-by-step description of how to arrive at a solution of a given problem. 20. What are the steps to solve the problem in a computer system? Problem must be analyzed thoroughly. Solution method is broken down into a sequence of small tasks. Based on this analysis, an algorithm must be prepared to solve the problem. The algorithm is expressed in a precise notation. This notation is known as Computer Program. The Computer program is fed to the computer. The instruction in the program executes one after another and outputs the expected result. 21. What are the characteristics of an algorithm? In algorithms each and every instruction should be precise. In algorithms each and every instruction should be unambiguous.

GE6151 Computer Programming Question Bank

The instructions in an algorithm should not be repeated infinitely. Ensure that the algorithm will ultimately terminate. The algorithm should be written in sequence. It looks like normal English. 22. What is Flowchart? A Flowchart is a pictorial representation of an algorithm. It is often used by programmer as a program planning tool for organizing a sequence of step necessary to solve a problem by a computer. 23. What is the need of Flowchart symbols? Each symbol of different shapes denotes different shapes denote different types of instructions. The program logic through flowcharts is made easier through the use of symbol that has standardized planning. 24. What is pseudo code? Pseudo means imitation of false and code refers to the instruction written in the programming language. Pseudo code is programming analysis tool that is used for planning program logic.

25. Draw the flowchart to find the maximum among three numbers (JAN2009) PART B 16 MARKS 1. Explain the various Generations of Computers in detail. (16) The Zeroth Generation The term Zeroth generation is used to refer to the period of development of computing, which predated the commercial production and sale of computer equipment. The period might be dated as extending from the mid-1800s. In particular, this period witnessed the emergence of the first electronics digital computers on the ABC, since it was the first to fully implement the idea of the stored program and serial execution of instructions. The development of EDVAC set the stage for the evolution of commercial computing and operating system software. The hardware component technology of this period was electronic vacuum tubes. The actual operation of these early computers took place without be benefit of an operating system.

GE6151 Computer Programming Question Bank

Early programs were written in machine language and each contained code for initiating operation of the computer itself. This system was clearly inefficient and depended on the varying competencies of the individual programmer as operators. The First Generation, 1951-1956

The first generation marked the beginning of commercial computing. The first generation was characterized by high-speed vacuum tube as the active component technology. Operation continued without the benefit of an operating system for a time. The mode was called "closed shop" and was characterized by the appearance of hired operators who would select the job to be run, initial program load the system, run the users program, and then select another job, and so forth. Programs began to be written in higher level, procedure-oriented languages, and thus the operators routine expanded. The operator now selected a job, ran the translation program to assemble or compile the source program, and combined the translated object program along with any existing library programs that the program might need for input to the linking program, loaded and ran the composite linked program, and then handled the next job in a similar fashion. Application programs were run one at a time, and were translated with absolute computer addresses The Second Generation, 1956-1964 The second generation of computer hardware was most notably characterized by transistors replacing vacuum tubes as the hardware component technology. In addition, some very important changes in hardware and software architectures occurred during this period. For the most part, computer systems remained card and tape-oriented systems. Significant use of random access devices, that is, disks, did not appear until towards the end of the second generation. Program processing was, for the most part, provided by large centralized computers operated under mono-programmed batch processing operating systems.

The most significant innovations addressed the problem of excessive central processor delay due to waiting for input/output operations. Recall that programs were executed by processing the machine instructions in a strictly sequential order. As a result, the CPU, with its high speed electronic component, was often forced to wait for completion of I/O operations which involved mechanical devices (card

GE6151 Computer Programming Question Bank

readers and tape drives) that were order of magnitude slower.

These hardware developments led to enhancements of the operating system. I/O and data channel communication and control became functions of the operating system, both to relieve the application programmer from the difficult details of I/O programming and to protect the integrity of the system to provide improved service to users by segmenting jobs and running shorter jobs first (during "prime time") and relegating longer jobs to lower priority or night time runs. System libraries became more widely available and more comprehensive as new utilities and application software components were available to programmers.

The second generation was a period of intense operating system development. Also it was the period for sequential batch processing. Researchers began to experiment with multiprogramming and multiprocessing. The Third Generation, 1964-1979 The third generation officially began in April 1964 with IBMs announcement of its System/360 family of computers. Hardware technology began to use integrated circuits (ICs) which yielded

significant advantages in both speed and economy. Operating System development continued with the introduction and widespread adoption of multiprogramming. This marked first by the appearance of more sophisticated I/O buffering in the form of spooling operating systems. These systems worked by introducing two new systems programs, a system reader to move input jobs from cards to disk, and a system writer to move job output from disk to printer, tape, or cards. The spooling operating system in fact had multiprogramming since more than one program was resident in main storage at the same time. Later this basic idea of multiprogramming was extended to include more than one active user program in memory at time. To accommodate this extension, both the scheduler and the dispatcher were enhanced. In addition, memory management became more sophisticated in order to assure that the program code for each job or at least that part of the code being executed was resident in main storage. Users shared not only the system hardware but also its software resources and file system disk space.

The third generation was an exciting time, indeed, for the development of both computer hardware and the accompanying operating system. During this period, the topic of operating systems became, in reality,

GE6151 Computer Programming Question Bank

a major element of the discipline of computing. The Fourth Generation, 1979 - Present

The fourth generation is characterized by the appearance of the personal computer and the workstation. Miniaturization of electronic circuits and components continued and Large Scale Integration (LSI), the component technology of the third generation, was replaced by Very Large Scale Integration (VLSI), which characterizes the fourth generation. However, improvements in hardware miniaturization and technology have evolved so fast that we now have inexpensive workstation-class computer capable of supporting multiprogramming and time-sharing. Hence the operating systems that supports todays personal computers and workstations look much like those which were available for the minicomputers of the third generation. Examples are Microsofts DOS for IBM -compatible personal computers and UNIX for workstation. However, many of these desktop computers are now connected as networked or distributed systems. Computers in a networked system each have their operating system augmented with communication capabilities that enable users to remotely log into any system on the network and transfer information among machines that are connected to the network. The machines that make up distributed system operate as a virtual single processor system from the users point of view; a central operating system controls and makes transparent the location in the system of the particular processor or processors and file systems that are handling any given program. 2. Explain the various Classifications of Computers (16) CLASSIFICATION OF COMPUTERS

There are four classifications of digital computer systems: super-computer, mainframe computer, minicomputer, and microcomputer. Super-computers are very fast and powerful machines. Their internal architecture enables them to run at the speed of tens of MIPS (Million Instructions per Second). Super-computers are very expensive and for this reason are generally not used for CAD applications. Examples of super-computers are: Cray and CDC Cyber 205 Mainframe computers are built for general computing, directly serving the needs of business and

GE6151 Computer Programming Question Bank

engineering. Although these computing systems are a step below super-computers, they are still very fast and will process information at about 10 MIPS. Mainframe computing systems are located in a centralized computing center with 20-100+ workstations. This type of computer is still very expensive and is not readily found in architectural/interior design offices. Minicomputers were developed in the 1960's resulting from advances in microchip technology. Smaller and less expensive than mainframe computers, minicomputers run at several MIPS and can support 5-20 users. CAD usage throughout the 1960's used minicomputers due to their low cost and high performance. Examples of minicomputers are: DEC PDP, VAX 11. Microcomputers were invented in the 1970's and were generally used for home computing and dedicated data processing workstations. Advances in technology have improved microcomputer capabilities, resulting in the explosive growth of personal computers in industry. In the 1980's many medium and small design firms were finally introduced to CAD as a direct result of the low cost and availability of microcomputers. Examples are: IBM, Compaq, Dell, Gateway, and Apple Macintosh.

The average computer user today uses a microcomputer. These types of computers include PC's, laptops, notebooks, and hand-held computers such as Palm Pilots. Larger computers fall into a mini-or mainframe category. A mini-computer is 3-25 times faster than a micro. It is physically larger and has a greater storage capacity.

A mainframe is a larger type of computer and is typically 10-100 times faster than the micro. These computers require a controlled environment both for temperature and humidity. Both the mini and mainframe computers will support more workstations than will a micro. They also cost a great deal more than the micro running into several hundred thousand dollars for the mainframes. Processors The term processor is a sub-system of a data processing system which processes received information after it has been encoded into data by the input sub-system. These data are then processed by the processing sub-system before being sent to the output sub-system where they are decoded back into

GE6151 Computer Programming Question Bank

information. However, in common parlance processor is usually referred to the microprocessor, the brains of the modern day computers.

There are two main types of processors: CISC and RISC. CISC: A Complex Instruction Set Computer (CISC) is a microprocessor Instruction Set Architecture (ISA) in which each instruction can indicate several low-level operations, such as a load from memory, an arithmetic operation, and a memory store, all in a single instruction. The term was coined in contrast to Reduced Instruction Set Computer (RISC).

Examples of CISC processors are the VAX, PDP-11, Motorola 68000 family and the Intel x86/Pentium CPUs. RISC: Reduced Instruction Set Computing (RISC), is a microprocessor CPU design philosophy that favors a smaller and simpler set of instructions that all take about the same amount of time to execute. Most types of modern microprocessors are RISCs, for instance ARM, DEC Alpha, SPARC, MIPS, and PowerPC. The microprocessor contains the CPU which is made up of three components--the control unit supervises all that is going on in the computer, the arithmetic/logic unit which performs the math and comparison operation, and temporary memory. Because of the progress in developing better microprocessors, computers are continually evolving into faster and better units. Notebooks A laptop computer (also known as notebook computer) is a small mobile personal computer, usually weighing around from 1 to 3 kilograms (2 to 7 pounds). Notebooks smaller than an A4 sheet of paper and weighing around 1 kg are sometimes called sub-notebooks and those weighing around 5 kg a desk note (desktop/notebook). Computers larger than PDAs but smaller than notebooks are also sometimes called "palmtops". Laptops usually run on batteries. Notebook Processor:

GE6151 Computer Programming Question Bank

A notebook processor is a CPU optimized for notebook computers. All computing devices require a CPU. One of the main characteristics differentiating notebook processors from other CPUs is low-power consumption.

The notebook processor is becoming an increasing important market segment in the semiconductor industry. Notebook computers are an increasingly popular format of the broader category of mobile computers. The objective of a notebook computer is to provide the performance and functionality of a desktop computer in a portable size and weight. Wireless networking and low power consumption are primary consideration in the choice of a notebook processor. Integrated Components

Unlike a desktop computer, a notebook has most of the components built-in or integrated into the computer. For desktop systems, determining which computer to buy is generally not based on what type of keyboard or mouse that is available. If you don't like the keyboard or mouse, you can always purchase something else. However, in the case of a notebook computer, the size of the keyboard or type of pointing device may be something that you need to consider unless you intend to use a regular mouse or full-sized keyboard. There are some notebooks that have a keyboard that expands when the notebook is opened which is a nice feature if you find the normal keyboard to be too small. Pointing devices vary from a touch pad to a stick within the keyboard to a roller or track-ball. Most notebooks have the video, sound, and speakers integrated into the computer and some notebooks even have a digital camera built-in which is very handy for video conferencing.

3. Briefly explain the basic Organization of computers with neat sketch. (16) BASIC COMPUTER ORGANIZATION: Introduction to CPU CPU Operation The fundamental operation of most CPUs - To execute a sequence of stored instructions called a program. The program is represented by a series of numbers that are kept in some kind of computer memory.

There are four steps that nearly all CPUs use in their operation: fetch, decode, execute, and write back. Fetch: o Retrieving an instruction from program memory. o The location in program memory is determined by a program counter (PC)

o After an instruction is fetched, the PC is incremented by the length of the instruction word in terms of memory units. Decode : o The instruction is broken up into parts that have significance to other portions of the CPU.

o The way in which the numerical instruction value is interpreted is defined by the CPU's instruction set architecture (ISA). o Opcode, indicates which operation to perform. o The remaining parts of the number usually provide information required for that instruction, such as operands for an addition operation.

o Such operands may be given as a constant value or as a place to locate a value: a register or a memory address, as determined by some addressing mode. Execute :

o During this step, various portions of the CPU are connected so they can perform the desired operation.

o If, for instance, an addition operation was requested, an arithmetic logic unit (ALU) will be connected to a set of inputs and a set of outputs. o The inputs provide the numbers to be added, and the outputs will contain the final sum.

o If the addition operation produces a result too large for the CPU to handle, an arithmetic overflow flag in a flags register may also be set. Write back : o Simply "writes back" the results of the execute step to some form of memory.

o Very often the results are written to some internal CPU register for quick access by subsequent instructions.

o In other cases results may be written to slower, but cheaper and larger, main memory.

o Some types of instructions manipulate the program counter rather than directly produce result data. Input Devices Anything that feeds the data into the computer. This data can be in alpha-numeric form which needs to be keyed-in or in its very basic natural form i.e. hear, smell, touch, see; taste & the sixth sense feel? Typical input devices are: 1. Keyboard 2. Mouse 3. Joystick 4. Digitizing Tablet 5. Touch Sensitive Screen 6. Light Pen 7. Space Mouse 8. Camera 9. Magnetic Ink Character 10. Reader Recognition (MICR) 11. Image Scanner 12. Bar Codes 13. Magnetic Reader 14. Smart Cards 15. Voice Data Entry 16. Sound Capture 17. Video Capture The Keyboard is the standard data input and operator control device for a computer. It consists of the standard QWERTY layout with a numeric keypad and additional function keys for control purposes. (OMR)

The Mouse is a popular input device. You move it across the desk and its movement is shown on the screen by a marker known as a 'cursor'. You will need to click the buttons at the top of the mouse to select an option. .The joystick is a rotary lever. Similar to an aircraft's control stick, it enables you to move within the screen's environment, and is widely used in the computer games industry. The Space mouse is different from a normal mouse as it has an X axis, a Y axis and a Z axis. It can be used for developing and moving around 3-D environments. The Optical Mark Reader (OMR) can read information in the form of numbers or letters and put it into the computer. The marks have to be precisely located as in multiple choice test papers. Scanners allow information such as a photo or text to be input into a computer. Scanners are usually either A4 size (flatbed), or hand-held to scan a much smaller area. If text is to be scanned, you would use an Optical Character Recognition (OCR) program to recognize the printed text and then convert it to a digital text file that can be accessed using a computer. Output Devices

Output devices display information in a way that you can you can understand. The most common output device is a monitor. It looks a lot a like a TV and houses the computer screen. The monitor allows you to 'see' what you and the computer are doing together. Types of Output Device

Printing: Sound : Visual :

Plotter, Printer Speakers Monitor

A Printer is another common part of a computer system. It takes what you see on the computer screen and prints it on paper. There are two types of printers; Impact Printers and Non-Impact Printers. Speakers are output devices that allow you to hear sound from your computer. Computer speakers are just like stereo speakers. There are usually two of them and they come in various sizes.

Memory or Primary Storage Purpose of Storage The fundamental components of a general-purpose computer are arithmetic and logic unit, control circuitry, storage space, and input/output devices. If storage was removed, the device we had would be a simple calculator instead of a computer. The ability to store instructions that form a computer program, and the information that the instructions manipulate is what makes stored program architecture computers versatile. Primary storage, or internal memory, is computer memory that is accessible to the central processing unit of a computer without the use of computer's input/output channels Primary storage, also known as main storage or memory, is the main area in a computer in which data is stored for quick access by the computer's processor.

Primary Storage

Primary storage is directly connected to the central processing unit of the computer. It must be present for the CPU to function correctly, just as in a biological analogy the lungs must be present (for oxygen storage) for the heart to function (to pump and oxygenate the blood). As shown in the diagram, primary storage typically consists of three kinds of storage: Main memory

It contains the programs that are currently being run and the data the programs are operating on. The arithmetic and logic unit can very quickly transfer information between a processor register and locations in main storage, also known as a "memory addresses". In modern computers, electronic solid-state random access memory is used for main storage, and is directly connected to the CPU via a "memory bus" and a "data bus". Cache memory

It is a special type of internal memory used by many central processing units to increase their performance or "throughput". Some of the information in the main memory is duplicated in the cache memory, which is slightly slower but of much greater capacity than the processor registers, and faster but much smaller than main memory.

4. Explain the various memory storage systems. (16) Memory or Primary Storage Purpose of Storage

The fundamental components of a general-purpose computer are arithmetic and logic unit, control circuitry, storage space, and input/output devices. If storage was removed, the device we had would be a simple calculator instead of a computer. The ability to store instructions that form a computer program, and the information that the instructions manipulate is what makes stored program architecture computers versatile.

Primary storage, or internal memory, is computer memory that is accessible to the central processing unit of a computer without the use of computer's input/output channels

Primary storage, also known as main storage or memory, is the main area in a computer in which data is stored for quick access by the computer's processor. Primary Storage

Primary storage is directly connected to the central processing unit of the computer. It must be present for the CPU to function correctly, just as in a biological analogy the lungs must be present (for oxygen storage) for the heart to function (to pump and oxygenate the blood). As shown in the diagram, primary storage typically consists of three kinds of storage: Processors Register

It is the internal to the central processing unit. Registers contain information that the arithmetic and logic unit needs to carry out the current instruction. They are technically the fastest of all forms of computer storage. Main memory It contains the programs that are currently being run and the data the programs are operating on. The arithmetic and logic unit can very quickly transfer information between a processor register and locations in main storage, also known as a "memory addresses". In modern computers, electronic solid-state random access memory is used for main storage, and is directly connected to the CPU via a "memory bus" and a "data bus".

Cache memory

It is a special type of internal memory used by many central processing units to increase their performance or "throughput". Some of the information in the main memory is duplicated in the cache memory, which is slightly slower but of much greater capacity than the processor registers, and faster but much smaller than main memory. Memory Memory is often used as a shorter synonym for Random Access Memory (RAM). This kind of memory is located on one or more microchips that are physically close to the microprocessor in your computer. Most desktop and notebook computers sold today include at least 512 megabytes of RAM (which is really the minimum to be able to install an operating system). They are upgradeable, so you can add more when your computer runs really slowly.

The more RAM you have, the less frequently the computer has to access instructions and data from the more slowly accessed hard disk form of storage. Memory should be distinguished from storage, or the physical medium that holds the much larger amounts of data that won't fit into RAM and may not be immediately needed there.

Storage devices include hard disks, floppy disks, CDROMs, and tape backup systems. The terms auxiliary storage, auxiliary memory, and secondary memory have also been used for this kind of data repository.

RAM is temporary memory and is erased when you turn off your computer, so remember to save your work to a permanent form of storage space like those mentioned above before exiting programs or turning off your computer. TYPES OF RAM: There are two types of RAM used in PCs - Dynamic and Static RAM. Dynamic RAM (DRAM): The information stored in Dynamic RAM has to be refreshed after every few milliseconds otherwise it will get erased. DRAM has higher storage capacity and is cheaper than Stati c RAM.

Static RAM (SRAM): The information stored in Static RAM need not be refreshed, but it remains stable as long as power supply is provided. SRAM is costlier but has higher speed than DRAM. Additional kinds of integrated and quickly accessible memory are Read Only Memory (ROM), Programmable ROM (PROM), and Erasable Programmable ROM (EPROM). These are used to keep special programs and data, such as the BIOS, that need to be in your computer all the time. ROM is "built-in" computer memory containing data that normally can only be read, not written to (hence the name read only).

ROM contains the programming that allows your computer to be "booted up" or regenerated each time you turn it on. Unlike a computer's random access memory (RAM), the data in ROM is not lost when the computer power is turned off. The ROM is sustained by a small long life battery in your computer called the CMOS battery. If you ever do the hardware setup procedure with your computer, you effectively will be writing to ROM. It is non volatile, but not suited to storage of large quantities of data because it is expensive to produce. Typically, ROM must also be completely erased before it can be rewritten, PROM (Programmable Read Only Memory)

A variation of the ROM chip is programmable read only memory. PROM can be programmed to record information using a facility known as PROM-programmer. However once the chip has been programmed the recorded information cannot be changed, i.e. the PROM becomes a ROM and the information can only be read. EPROM (Erasable Programmable Read Only Memory) As the name suggests the Erasable Programmable Read Only Memory, information can be erased and the chip programmed a new to record different information using a special PROM-Programmer. When EPROM is in use information can only be read and the information remains on the chip until it is erased. Hard Disks

Your computer uses two types of memory: primary memory which is stored on chips located on the motherboard, and secondary memory that is stored in the hard drive. Primary memory holds all of the essential memory that tells your computer how to be a computer. Secondary memory holds the information that you store in the computer.

Inside the hard disk drive case you will find circular disks that are made from polished steel. On the disks, there are many tracks or cylinders. Within the hard drive, an electronic reading/writing device called the head passes back and forth over the cylinders, reading information from the disk or writing information to it. Hard drives spin at 3600 or more rpm (Revolutions Per Minute) - that means that in one minute, the hard drive spins around over 7200 times! Optical Storage

Compact Disk Read-Only Memory (CD-ROM) CD-Recordable (CD-R)/CD-Rewritable (CD-RW) Digital Video Disk Read-Only Memory (DVD-ROM) DVD Recordable (DVD-R/DVD Rewritable (DVD-RW) Photo CD

Optical Storage Devices Data is stored on a reflective surface so it can be read by a beam of laser light. Two Kinds of Optical Storage Devices CD-ROM (compact disk read-only memory)

DVD-ROM (digital video disk read-only memory)

Compact Disks

Instead of electromagnetism, CDs use pits (microscopic indentations) and lands (flat surfaces) to store information much the same way floppies and hard disks use magnetic and non-magnetic storage. Inside the CD-Rom is a laser that reflects light off of the surface of the disk to an electric eye. The pattern of reflected light (pit) and no reflected light (land) creates a code that represents data.

CDs usually store about 650MB. This is quite a bit more than the 1.44MB that a floppy disk stores. A DVD or Digital Video Disk holds even more information than a CD, because the DVD can store information on two levels, in smaller pits or sometimes on both sides. Recordable Optical Technologies

CD-Recordable (CD-R) CD-Rewritable (CD-RW) PhotoCD DVD-Recordable (DVD-R) DVD-RAM

CD ROM - Compact Disc Read Only Memory.

Unlike magnetic storage device which store data on multiple concentric tracks, all CD formats store data on one physical track, which spirals continuously from the center to the outer edge of the recording area. Data resides on the thin aluminum substrate immediately beneath the label.

The data on the CD is recorded as a series of microscopic pits and lands physically embossed on an aluminum substrate. Optical drives use a low power laser to read data from those discs without physical contact between the head and the disc which contributes to the high reliability and permanence of storage device.

To write the data on a CD a higher power laser are used to record the data on a CD. It creates the pits and land on aluminum substrate. The data is stored permanently on the disc. These types of discs are called as WORM (Write Once Read Many). Data written to CD cannot subsequently be deleted or overwritten which can be classified as advantage or disadvantage depending upon the requirement of the user. However if the CD is partially filled then the more data can be added to it later on till it is full. CDs are usually cheap and cost effective in terms of storage capacity and transferring the data. The CDs were further developed where the data could be deleted and re written. These types of CDs are called as CD Rewritable. These types of discs can be used by deleting the data and making the space for new data. These CDs can be written and rewritten at least 1000 times.

5. Explain the basic function of CPU. (16) FUNCTIONS OF CPU: Process Management The CPU executes a large number of programs. While its main concern is the execution of user programs, the CPU is also needed for other system activities. These activities are called processes. A process is a program in execution. Typically, a batch job is a process. A time-shared user program is a process. A system task, such as spooling, is also a process. For now, a process may be considered as a job or a timeshared program, but the concept is actually more general.

In general, a process will need certain resources such as CPU time, memory, files, I/O devices, etc., to accomplish its task. These resources are given to the process when it is created. In addition to the various physical and logical resources that a process obtains when it is created, some initialization data (input) may be passed along.

We emphasize that a program by itself is not a process; a program is a passive entity. It is known that two processes may be associated with the same program; they are nevertheless considered two separate execution sequences.

The operating system is responsible for the following activities in connection with processes managed. The creation and deletion of both user and system processes

The suspension and resumption of processes.

The provision of mechanisms for process synchronization

The provision of mechanisms for deadlock handling. Memory Management

Memory is central to the operation of a modern computer system. Memory is a large array of words or bytes, each with its own address. Interaction is achieved through a sequence of reads or writes of specific memory address. The CPU fetches from and stores in memory. In order for a program to be executed it must be mapped to absolute addresses and loaded in to memory.

In order to improve both the utilization of CPU and the speed of the computer's response to its users, several processes must be kept in memory.

The operating system is responsible for the following activities in connection with memory management. Keep track of which parts of memory are currently being used and by whom.

Decide which processes are to be loaded into memory when memory space becomes available. Allocate and de-allocate memory space as needed. Secondary Storage Management The main purpose of a computer system is to execute programs. These programs, together with the data they access, must be in main memory during execution. Since the main memory is too small to permanently accommodate all data and program, the computer system must provide secondary storage to backup main memory. Most modem computer systems use disks as the primary on-line storage of information, of both programs and data.

Most programs, like compilers, assemblers, sort routines, editors, formatters, and so on, are stored on the disk until loaded into memory, and then use the disk as both the source and destination of their processing. Hence the proper management of disk storage is of central importance to a computer system.

There are few alternatives. Magnetic tape systems are generally too slow. In addition, they are limited to sequential access. Thus tapes are more suited for storing infrequently used files, where speed is not a primary concern.

The operating system is responsible for the following activities in connection with disk management Free space management Storage allocation Disk schedling. Input Output System One of the purposes of an operating system is to hide the peculiarities of specific hardware devices from the user. For example, in UNIX, the peculiarities of Input/Output devices are hidden from the bulk of the operating system itself by the INPUT/OUTPUT system. The Input/Output system consists of:

A buffer caching system A general device driver code Drivers for specific hardware devices. 6. Define Flow. Mention the guide lines to be followed to draw a flow chart. List out the Advantage and disadvantages (16)

A flowchart is a schematic representation of an algorithm or a stepwise process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts are used in designing or documenting a process or program.[

A flow chart, or flow diagram, is a graphical representation of a process or system that details the sequencing of steps required to create output.

A flowchart is a picture of the separate steps of a process in sequential order. GUIDELINES FOR DRAWING A FLOWCHART

Flowcharts are usually drawn using some standard symbols; however, some special symbols can also be developed when required. Some standard symbols, which are frequently required for flowcharting many computer programs. Start or end of the program Computational steps or processing function of a program Input or output operation Decision making and branching Connector or joining of two parts of program

Flowchart Symbols The following are some guidelines in flowcharting:

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

b. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart.

c. The usual direction of the flow of a procedure or system is from left to right or top to bottom. d. Only one flow line should come out from a process symbol.

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

f.

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

g. Write within standard symbols briefly. As necessary, you can use the annotation symbol to describe data or computational steps more clearly. h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication. i. Ensure that the flowchart has a logical start and finish.

j.

It is useful to test the validity of the flowchart by passing through it with a simple test data.

Advantages Logic Flowcharts are easy to understand. They provide a graphical representation of actions to be taken. Logic Flowcharts are well suited for representing logic where there is intermingling among many actions. Disadvantages Logic Flowcharts may encourage the use of GoTo statements leading to software design that is unstructured with logic that is difficult to decipher.Without an automated tool, it is time-consuming to maintain Logic Flowcharts.

Logic Flowcharts may be used during detailed logic design to specify a module. However, the presence of decision boxes may encourage the use of GoTo statements, resulting in software that is not structured. For this reason, Logic Flowcharts may be better used during Structural LIMITATIONS OF USING FLOWCHARTS

1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy.

2. Alterations and Modifications: If alterations are required the flowchart may require redrawing completely.

3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.

4. The essentials of what is done can easily be lost in the technical details of how it is done.

UNIT-II 2 MARKS
1. Define Compilation process. Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. 2. What do you meant by linking? Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned. 3. Define Constants in C. Mention the types. The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. The constants are treated just like regular variables except that their values cannot be modified after their definition. 4. What are the different data types available in C? There are four basic data types available in C. 1. int 2. float 3. char 4. double 5. What is meant by Enumerated data type. Enumerated data is a user defined data type in C language.

Enumerated data type variables can only assume values which have been previously declared.
Example : enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };

6. What are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their intended purpose. 7. What do you mean by variables in C? A variable is a data name used for storing a data value. Can be assigned different values at different times during program execution. Can be chosen by programmer in a meaningful way so as to reflect its function in the program Some examples are: Sum 8. Difference between Local and Global variable in C. Local These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called. Global These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.

9. What are Operators? Mention their types in C.


An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides following type of operators: Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators 10. What is the difference between = and == operator? Where = is an assignment operator and == is a relational operator. Example: while (i=5) is an infinite loop because it is a non zero value and while (i==5) is true only when i=5.

11. What is type casting? Type casting is the process of converting the value of an expression to a particular data type. Example: int x,y; c = (float) x/y; where a and y are defined as integers. Then the result of x/y is converted into float. 12.What is the difference between ++a and a++? ++a means do the increment before the operation (pre increment) a++ means do the increment after the operation (post increment) Example: a=5; x=a++; /* assign x=5*/ y=a; /*now y assigns y=6*/ x=++a; /*assigns x=7*/ 3.Distinguish between while..do and do..while statement in C. (JAN 2009) While (i) Executes the statements within the while block if only the condition is true. (ii) The condition is checked at the starting of the loop 14.Mention the various Decisions making statement available in C. Statement if statement if...else statement Description An if statement consists of a boolean expression followed by one or more statements. An if statement can be followed by an optional else statement, which executes when the boolean expression is false nested if statements You can use one if or else if statement inside another if or else if statement(s). switch statement A switch statement allows a variable to be tested for equality against a list of values. You can use one swicth statement inside another switch statement(s). nested switch statements DO..while (i) Executes the statements within thwhile block at least once. (ii) The condition is checked at the end of the loop

15.What do you meant by conditional or ternary operator?

? : If Condition is true ? Then value X : Otherwise value Y


16. What is the use of sizeof() operator in C. Sizeof operator is used to return the size of an variable. Example :sizeof(a), Where a integer, will return 4. 17. Define Looping in C .

A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages
18. What are the types of looping statements available in C

C programming language provides following types of loop to handle looping requirements. Click the following links to check their detail.
Loop Type while loop Description Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

for loop do...while loop nested loops Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. Like a while statement, except that it tests the condition at the end of the loop body You loop. can use one or more loop inside any

ano

19. What are the types of I/O statements available in C? There are two types of I/O statements available in C. Formatted I/O Statements Unformatted I/O Statements 20. Write short notes about main ( ) function in C program. (MAY 2009) Every C program must have main ( ) function. All functions in C, has to end with ( ) parenthesis. It is a starting point of all C programs.

The program execution starts from the opening brace { and ends with closing brace }, within which executable part of the program exists. 21. Define delimiters in C. Delimiters Use : Colon ; Semicolon ( ) Parenthesis [ ] Square Bracket { } Curly Brace # Hash , Comma 22. Why header files are included in C programming? This section is used to include the function definitions used in the program. Each header file has h extension and include using # include directive at the beginning of a program. 23.What is the output of the programs given below? main() { float a; int x=6, y=4; a=x\y; printf(Value of a=%f, a); } Output: 1. 1.500000 main() { float a; int x=6, y=4; a=(float) x\y; printf(Value of a=%f,a); } Output:

24.What is the difference between scanf() and gets() function?

In scanf() when there is a blank was typed, the scanf() assumes that it is an end. gets() assumes the enter key as end. That is gets() gets a new line (\n) terminated string of characters from the keyboard and replaces the \n with \0. 25.What are the Escape Sequences present in C \n - New Line \b - Backspace \t - Form feed \ - Single quote \\ - Backspace \t - Tab \r - Carriage return \a - Alert \ - Double quotes 26.What is the difference between if and while statement? If (i) It is a conditional statement (ii) If the condition is true, it executes some statements. (iii) If the condition is false the control is (iii) If the condition is false then it stops transferred to the next statement of the loop. the execution the statements. While (i) It is a loop control statement (ii) Executes the statements within the while block if the condition is true.

27.Differentiate between formatted and unformatted you input and output functions? Formatted I/P functions: These functions allow us to supply the input in a fixed format and let us obtain the output in the specified form. Formatted output converts the internal binary representation of the data to ASCII characters which are written to the output file. Unformatted I/O functions: There are several standard library functions available under this category-those that can deal with a string of characters. Unformatted Input/Output is the most basic form of input/output. Unformatted input/output transfers the internal binary representation of the data directly between memory and the file.

UNIT II (16 Marks) 1. Define C language. Mention the basic structure of C programs with explanation. (16) C programs are essentially constructed in the following manner, as a number of well defined sections. /* HEADER SECTION */ /* Contains name, author, revision number*/ /* INCLUDE SECTION /* contains #include statements */ */ */

/* CONSTANTS AND TYPES SECTION /* contains types and #defines */ /* GLOBAL VARIABLES SECTION /* any global variables declared here */ /* FUNCTIONS SECTION /* user defined functions /* main() SECTION int main() { ----} */ */ */

*/

A Simple Program The following program is written in the C programming language. #include <stdio.h> Void main() { printf(Programming in C is easy.\n); }

INITIALISING DATA VARIABLES AT DECLARATION TIME In C, variables may be initialized with a value when they are declared. Consider the following declaration, which declares an integer variable count which is initialized to 10. int count = 10; SIMPLE ASSIGNMENT OF VALUES TO VARIABLES The = operator is used to assign values to data variables. Consider the following statement, which assigns the value 32 an integer variable count, and the letter A to the character variable letter count = 32; letter = A Variable Formatters %d decimal integer %c character %s string or character array %f float %e double HEADER FILES Header files contain definitions of functions and variables which can be incorporated into any C program by using the pre-processor #include statement. Standard header files are provided with each compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading of variables. To use any of the standard functions, the appropriate header file should be included. This is done at the beginning of the C source file. For example, to use the function printf() in a program, the line #include <stdio.h> should be at the beginning of the source file, because the definition for printf() is found in the file stdio.h All header files have the extension .h and generally reside in the /include subdirectory.

#include <stdio.h> #include mydecls.h The use of angle brackets <> informs the compiler to search the compilers include directory for the specified file. The use of the double quotes around the filename inform the compiler to search in the current directory for the specified file. 2. Discuss about the various data types in C. (MAY 2009) The four basic data types are a. INTEGER These are whole numbers, both positive and negative. Unsigned integers (positive values only) are supported. In addition, there are short and long integers. The keyword used to define integers is,

int An example of an integer value is 32. An example of declaring an integer variable called sum is, int sum; sum = 20; b. FLOATING POINT These are numbers which contain fractional parts, both positive and negative. The keyword used to define float variables is, float An example of a float value is 34.12. An example of declaring a float variable called money is, float money;

money = 0.12; c. DOUBLE These are exponentional numbers, both positive and negative. The keyword used to define double variables is, double An example of a double value is 3.0E2. An example of declaring a double variable called big is, double big;

big = 312E+7; d. CHARACTER These are single characters. The keyword used to define character variables is,char An example of a character value is the letter A. An example of declaring a character variable called letter is, char letter; letter = A; Note the assignment of the character A to the variable letter is done by enclosing the value in single quotes. Example: #include < stdio.h > main() { int sum; float char money; letter;

double pi;

sum = 10; letter = A; pi = 2.01E6;

/* assign integer value */

money = 2.21; /* assign float value */ /* assign character value */ /* assign a double value */

printf(value of sum = %d\n, sum ); printf(value of money = %f\n, money ); printf(value of letter = %c\n, letter ); printf(value of pi = %e\n, pi ); } Sample program output value of sum = 10 value of money = 2.210000 value of letter = A value of pi = 2.010000e+06 3. What are Operators? Explain the various operators available in C. (16) An ex pr e ss io n is a sequence of operators and operands that specifies computation of a value, or that designates an object or a function, or that generates side effects, or that performs a combination thereof. ARITHMETIC OPERATORS: The symbols of the arithmetic operators are:Operation Operator Comment Multiply Divide Addition Subtraction Increment Decrement Modulus
/ +
-

Value of Sum before Value of sum after 4 4 4 4 4 4 4


8 2 6 2 5 3 1

sum = sum * 2; sum = sum / 2; sum = sum + 2; sum = sum -2; ++sum; --sum; sum = sum % 3;

++

-%

Example: #include <stdio.h> main() { int sum 50; float modulus; modulus = sum % 10; printf("The %% of %d by 10 is %f\n", sum, modulus); } * PRE/POST INCREMENT/DECREMENT OPERATORS PRE means do the operation first followed by any assignment operation. POST means do the operation after any assignment operation. Consider the following statements ++count; count++; /* PRE Increment, means add one to count */ /* POST Increment, means add one to count */

THE RELATIONAL OPERATORS These allow the comparison of two or more variables. n equal to !=not equal <less than <=less than or equal to >greater than >=greater than or equal to Example: #include <stdio.h> main() /* Program introduces the for statement, counts to ten */ { int count; for( count = 1; count <= 10; count = count + 1 ) printf("%d ", ount ); printf("\n"); } LOGICAL (AND, NOT, OR, EOR) Combining more than one condition

These allow the testing of more than one condition as part of selection statements. The symbols are

LOGICAL AND && Logical and requires all conditions to evaluate as TRUE (non-zero). LOGICAL OR || Logical or will be executed if any ONE of the conditions is TRUE (non-zero). LOGICAL NOT ! logical not negates (changes from TRUE to FALSE, vsvs) a condition.

LOGICAL EOR ^ Logical error will be executed if either condition is TRUE, but NOT if they are all true.

THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR This conditional expression operator takes THREE operators. The two symbols used to denote this operator are the ? and the :. The first operand is placed before the ?, the second operand between the ? and the :, and the third after the :. The general format is, condition ? expression1 : expression2

If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression2 is evaluated and its result becomes the result of the operation. An example will help, s = ( x < 0 ) ? -1 : x * x; If x is less than zero then s = -1 If x is greater than zero then s = x * x

BIT OPERATIONS C has the advantage of direct bit manipulation and the operations available are,

Operation AND OR Exclusive OR 1's Complement Left Shift

Operator Comment
&
|
^

sum = sum & 2; sum = sum | 2; sum = sum ^ 2; sum = ~sum; sum = sum << 2;

~
<<

Value of Sum before Value of sum after


4 4 4 4 4 0 6 6 -5

16
>>

Right Shift Example:

sum = sum >> 2;

/* Example program illustrating << and >> */ #include <stdio.h> main() { int n1 = 10, n2 = 20, i = 0; i = n2 << 4; /* n2 shifted left four times */ printf("%d\n", i); i = n1 >> 5; /* n1 shifted right five times */ printf("%d\n", i); } 4. Explain in detail about managing the Input Output Operations. (16) Printf (): printf() is actually a function (procedure) in C that is used for printing variables and text. Where text appears in double quotes "", it is printed without modification. There are some exceptions however. This has to do with the \ and % characters. These characters are modifier's, and for the present the \ followed by the n character represents a newline character.

Example: #include <stdio.h> main() { printf("Programming in is easy.\n"); printf("And so is Pascal.\n"); } O/P: Programming in C is easy. And so is Pascal. Scanf (): Scanf () is a function in C which allows the programmer to accept input from a keyboard. Example: #include <stdio.h> main() { int number; /* program which introduces keyboard input */

printf("Type in a number \n"); scanf("%d", &number); printf("The number you typed was %d\n", number); } ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD Getchar, Putchar getchar() gets a single character from the keyboard, and putchar() writes a single character from the keyboard. Example: The following program illustrates this: #include <stdio.h> main() { int i; int ch; for( i = 1; i<= 5; ++i ) { ch = getchar(); putchar(ch); } } The program reads five characters (one for each iteration of the for loop) from the keyboard. Note that getchar() gets a single character from the keyboard, and putchar() writes a single character (in this case, ch) to the console screen

. 5. Explain the various decision making mechanism in C. (16) IF STATEMENTS The if statements allows branching (decision making) depending upon the value or state of variables. This allows statements to be executed or skipped, depending upon decisions. The basic format is,

if( expression ) program statement; Example: if( students < 65 ) ++student_count; IF ELSE The general format for these is, if( condition 1 ) statement1; else if( condition 2 ) statement2; else if( condition 3 ) statement3; else statement4; The else clause allows action to be taken where the condition evaluates as false (zero). The following program uses an if else statement to validate the users input to be in the range 1-10. Example: #include <stdio.h> main() { int number; int valid = 0; while( valid == 0 ) { printf("Enter a number between 1 and 10 -->"); scanf("%d",&number); if( number < 1 ) { printf("Number is below 1. Please re-enter\n"); valid = 0; } else if( number > 10 ) { printf("Number is above 10. Please re-enter\n"); valid = 0; } else valid = 1; }

printf("The number is %d\n", number ); } NESTED IF ELSE /* Illustates nested if else and multiple arguments to the scanf function. */ Example: #include <stdio.h> main() { int invalid_oper ator = 0; char operator; float number1, number2, result; printf("Enter two numbers and an operator in the format\n"); printf(" number1 operator number2\n"); scanf("%f %c %f", &number1, &operator, &number2); if(operator == '*') result = number1 * number2; else if(operator == '/') result = number1 / number2; else if(operator == '+') result = number1 + number2; else if(operator == '-') result = number1 - number2; else invalid_operator = 1; if( invalid_operator != 1 ) printf("%f %c %f is %f\n", number1, operator, number2, result ); else printf("Invalid operator.\n");

6. With example explain the Branching and Looping mechanism in C (16) ITERATION, FOR LOOPS The basic format of the for statement is, for( start condition; continue condition; re-evaulation ) program statement;

Example: /* sample program using a for statement */ #include <stdio.h> main() /* Program introduces the for statement, counts to ten */ { int count; for( count = 1; count <= 10; count = count + 1 ) printf("%d ", count ); printf("\n"); } The program declares an integer variable count. The first part of the for statement for( count = 1; initialises the value of count to 1. The for loop continues whilst the condition count <= 10; evaluates as TRUE. As the variable count has just been initialised to 1, this condition is TRUE and so the program statement printf("%d ", count ); is executed, which prints the value of count to the screen, followed by a space character. Next, the remaining statement of the for is executed count = count + 1 ); which adds one to the current value of count. Control now passes back to the conditional test, count <= 10; which evaluates as true, so the program statement printf("%d ", count ); is executed. Count is incremented again, the condition re-evaluated etc, until count reaches a value of 11. When this occurs, the conditional test count <= 10; evaluates as FALSE, and the for loop terminates, and program control passes to the statement printf("\n"); which prints a newline, and then the program terminates, as there are no more statements left to execute. THE WHILE STATEMENT The while provides a mechanism for repeating C statements whilst a condition is true. Its format is,

while( condition ) program statement;

Somewhere within the body of the while loop a statement must alter the value of the condition to allow the loop to finish. Example: /* Sample program including while */ #include <stdio.h> main() { int loop = 0; while( loop <= 10 ) { printf("%d\n", loop); ++loop; } } The above program uses a while loop to repeat the statements

printf("%d\n", loop); ++loop; while the value of the variable loop is less than or equal to 10. Note how the variable upon which the while is dependant is initialised prior to the while statement (in this case the previous line), and also that the value of the variable is altered within the loop, so that eventually the conditional test will succeed and the while loop will terminate. This program is functionally equivalent to the earlier for program which counted to ten. THE DO WHILE STATEMENT The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The loop is executed as least once. Example: /* Demonstration of DO...WHILE */ #include <stdio.h> main() { int value, r_digit; printf("Enter the number to be reversed.\n"); scanf("%d", &value);

do { r_digit = value % 10; printf("%d", r_digit); value = value / 10; } while( value != 0 ); printf("\n"); } The above program reverses a number that is entered by the user. It does this by using the modulus % operator to extract the right most digits into the variable r_digit. The original number is then divided by 10, and the operation repeated whilst the number is not equal to 0. SWITCH CASE: The switch case statement is a better way of writing a program when a series of if elses occurs. The general format for this is, switch ( expression ) { case value1: program statement; program statement; break; case valuen: program statement; break; default: break; } he keyword break must be included at the end of each case statement. The default clause is optional, and is executed if the cases are not met. The right brace at the end signifies the end of the case selections. Example: #include <stdio.h> main() { int menu, numb1, numb2, total; printf("enter in two numbers -->"); scanf("%d %d", &numb1, &numb2 ); printf("enter in choice\n"); printf("1=addition\n"); printf("2=subtraction\n"); scanf("%d", &menu );

switch( menu ) { case 1: total = numb1 + numb2; break; case 2: total = numb1 numb2; break; default: printf("Invalid option selected\n"); }

if( menu == 1 ) printf("%d plus %d is %d\n", numb1, numb2, total ); else if( menu == 2 ) printf("%d minus %d is %d\n", numb1, numb2, total ); } The above program uses a switch statement to validate and select upon the users input choice, simulating a simple menu of choices. 7.C programs related to problem solving. 8..C programs related to scientific problem solving.

UNIT -III 2 MARKS


1. What is an array? An array is a group of similar data types stored under a common name. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Example: int a[10];

Here a[10] is an array with 10 values. 2. What are the main elements of an array declaration? Array name Type and Size 3. How to initialize an array?

You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array:

4. Why is it necessary to give the size of an array in an array declaration? When an array is declared, the compiler allocates a base address and reserves enough space in the memory for all the elements of the array. The size is required to allocate the required space. Thus, the size must be mentioned. 5. What is the difference between an array and pointer? Difference between arrays and pointers are as follows. Array 1.Array allocates space automatically 2.It cannot be resized.

3.It cannot be reassigned. 4.Size of(array name) gives the number of bytes occupied by the array. Pointer 1.Pointer is explicitly assigned to point to an allocated space. 2.It can be resized using realloc (). 3.Pointers can be reassigned. 4.Sezeof(pointer name) returns the number of bytes used to store the pointer variable 6. List the characteristics of Arrays. .

All elements of an array share the same name, and they are distinguished form one another with help of an element number. Any particular element of an array can be modified separately without disturbing other elements. 7. What are the types of Arrays? 1.One-Dimensional Array 2. Two-Dimensional Array 3. Multi-Dimensional Array 8. Define Strings. Strings: The group of characters, digit and symbols enclosed within quotes is called as Stirng (or) character Arrays. Strings are always terminated with \0 (NULL) character. The compiler automatically adds \0 at the end of the strings. Example: char name[]={C,O,L,L,E,G,E,E,\0};

9. Mention the various String Manipulation Functions in C.

Function & Purpose strcpy(s1, s2); Copies string s2 into string s1. strcat(s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

10. What is the use of atoi() function?

C allows us to manipulate characters the same way we do with numbers. Whenever a character constant or character variable is used in an expression, it is automatically converted into integer value by the system. For eg, if the machine uses the ASCII representation, then, x = a; printf(%d \n,x); will display the number 97 on the screen. The C library supports a function that converts a string of digits into their integer values. The function takes the form x = atoi(string) 11. What is the use of typedef?
It is used to create a new data using the existing type. Syntax: typedef data type name; Example: typedef int hours: hours hrs;/* Now, hours can be used as new datatype */ 12. What is meant by Sorting? Sorting refers to ordering data in an increasing or decreasing fashion according to some linear relationship among the data items. Sorting can be done on names, numbers and records. 13. What are the types of sorting available in C?

Insertion sort. Merge Sort. Quick Sort. Radix Sort. Heap Sort Selection sort Bubble sort 14. Define Heap Sort.

A sorting algorithm that works by first organizing the data to be sorted into a special type of binary tree called a heap. The heap itself has, by definition, the largest value at the top of the tree, so the heap sort algorithm must also reverse the order. It does this with the following steps:

1. Remove the topmost item (the largest) and replace it with the rightmost leaf. The topmost item is stored in an array. 2. Re-establish the heap. 3. Repeat steps 1 and 2 until there are no more items left in the heap.

15. Define Bubble sort. A simple but popular sorting algorithm. Bubble sorting is used frequently as a programming exercise because it is relatively easy to understand. It is not, however, particularly efficient. Other sorting algorithms, such as heap sorts, merge sorts and quick sorts, are used more often in real applications. 16. Define Searching.

Searching for data is one of the fundamental fields of computing. Often, the difference between a fast program and a slow one is the use of a good algorithm for the data set. Naturally, the use of a hash table or binary search tree will result in more efficient searching, but more often than not an array or linked list will be used. It is necessary to understand good ways of searching data structures not designed to support efficient search. 17. Mention the various types of searching techniques in C Linear search Binary search 18. What is linear search? In Linear Search the list is searched sequentially and the position is returned if the key element to be searched is available in the list, otherwise -1 is returned. The search in Linear Search starts at the beginning of an array and move to the end, testing for a match at each item. 19. What is Binary search? A binary search, also called a dichotomizing search, is a digital scheme for locating a specific object in a large set. Each object in the set is given a key. The number of keys is always a power of 2. If there are 32 items in a list, for example, they might be numbered 0 through 31 (binary 00000 through 11111). If there are, say, only 29 items, they can be numbered 0 through 28 (binary 00000 through 11100), with the numbers 29 through31 (binary 11101, 11110, and 11111) as dummy keys.

UNIT III 16 MARKS 1. Define array. Explain the array types with an example program for each type. Arrays are data structures which hold multiple variables of the same data type. Consider the case where a programmer needs to keep track of a number of people within an organization. So far, our initial attempt will be to create a specific variable for each user.

This might look like, int name1 = 101; int name2 = 232; int name3 = 231;

It becomes increasingly more difficult to keep track of this as the number of variables increase. Arrays offer a solution to this problem. An array is a multi-element box, a bit like a filing cabinet, and uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like other variables in C, must be declared before they can be used. The replacement of the above example using arrays looks like,

int names[4]; names[0] = 101; names[1] = 232; names[2] = 231; names[3] = 0;

We created an array called names, which has space for four integer variables. You may also see that we stored 0 in the last space of the array. This is a common technique used by C programmers to signify the end of an array. Arrays have the following syntax, using square brackets to access each indexed value (called an element).x[i] so that x[5] refers to the sixth element in an array called x. In C, array elements start with 0. Assigning values to array elements is done by, x[10] = g; and assigning array elements to a variable is done by, g = x[10]; In the following example, a character based array named word is declared, and each element is assigned a character. The last element is filled with a zero value, to signify the end of the character string (in C, there is no string type, so character based arrays are used to hold strings). A printf statement is then used to print out all elements of the array.

/* Introducing array's, 2 */ #include <stdio.h> main() { char word[20]; word[0] = 'H'; word[1] = 'e'; word[2] = 'l'; word[3] = 'l'; word[4] = 'o'; word[5] = 0; printf("The contents of word[] is -->%s\n", word ); } 2. Explain about multi dimensional array with example.

Multi-dimensioned arrays have two or more index values which specify the element in the array. multi[i][j];

In the above example, the first index value i specifies a row index, whilst j specifies a column index. DECLARATION int m1[10][10]; static int m2[2][2] = { {0,1}, {2,3} }; sum = m1[i][j] + m2[k][l];

NOTE the strange way that the initial values have been assigned to the two-dimensional array m2. Inside the braces are, { 0, 1 }, { 2, 3 } Remember that arrays are split up into row and columns. The first is the row, the second is the column. Looking at the initial values assigned to m2, they are,

m2[0][0] = 0 m2[0][1] = 1 m2[1][0] = 2 m2[1][1] = 3

Example: #include main() { static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} }; int row, column, sum; sum = 0; for( row = 0; row < 4; row++ ) for( column = 0; column < 3; column++ ) sum = sum + m[row][column]; printf("The total is %d\n", sum ); } 3. Explain String Array with example program. CHARACTER ARRAYS [STRINGS] Consider the following program, #include <stdio.h> main() { static char name1[] = {'H','e','l','l','o'}; static char name2[] = "Hello"; printf("%s\n", name1); printf("%s\n", name2); } The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in name2[5], whilst name1 has not. To insert a null at the end of the name1 array, the initialization can be changed to, static char name1[] = {'H','e','l','l','o','\0'}; <stdio.h>

Consider the following program, which initialises the contents of the character based array word during the program, using the function strcpy, which necessitates using the include file string.h Example: #include <stdio.h> #include main() { Char word[20]; Char word[20]; strcpy(word, "hi there." ) printf("%s\n", word ); <string.h>

4. Explain the standard string functions with example to support each type.
Strings: The group of characters, digits and symbols enclosed within quotes is called as strings or character arrays. Strings are always terminated with \0 character(NULL). Example: char name[ ] = {H,E,L,L,O}; Standard String Functions: strlen( ) strcpy( )

strncpy( ) stricmp( ) strcmp( ) strncmp( )

strcat( ) strrev( ) etc., Example:Program

/*Illustration of string- handling functions*/ #include<string.h> main() {


char s1[20],s2[20],s3[20]; int x, l1, l2, l3;

printf(Enter two string constants \n); printf(?); scanf(%s %s, s1, s2); x = strcmp(s1, s2); if(x != 0) printf(Strings are not equal \n); strcat(s1, s2);

else printf(Strings are equal \n); strcpy(s3,s1); l1 = strlen(s1); l2 = strlen(s2); l3 = strlen(s3);


printf(\ns1 = %s \t length = %d characters \n,s1, l1); printf(\ns2= %s \t length = %d characters \n,s2, l2); printf(\ns3 = %s \t length = %d characters \n,s3, l3);

} OUTPUT Enter two string constants

? New York Strings are not equal


s1 = New York s2 = York s3 = New York

length = 7 characters length = 4 characters length = 7 characters

Enter two string constants ? London London Strings are equal s1 = London length = 6 characters s2 = London length = 6 characters s3 = London length = 6 characters 5. Write a C program to do the matrix addition using C. C program for addition of two matrices using arrays source code. Matrix addition in c language: Example Program: #include<stdio.h> int main(){ int a[3][3],b[3][3],c[3][3],i,j; printf("Enter the First matrix->"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&a[i][j]);

printf("\nEnter the Second matrix->"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&b[i][j]); printf("\nThe First matrix is\n"); for(i=0;i<3;i++){ printf("\n"); for(j=0;j<3;j++) printf("%d\t",a[i][j]); } printf("\nThe Second matrix is\n"); for(i=0;i<3;i++){ printf("\n"); for(j=0;j<3;j++) printf("%d\t",b[i][j]); } for(i=0;i<3;i++) for(j=0;j<3;j++) c[i][j]=a[i][j]+b[i][j]; printf("\nThe Addition of two matrix is\n"); for(i=0;i<3;i++){ printf("\n"); for(j=0;j<3;j++) printf("%d\t",c[i][j]); } return } 6. Write a program for matrix multiplication in c #include<stdio.h> int main() { int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p; printf("\nEnter the row and column of first matrix"); scanf("%d %d",&m,&n); printf("\nEnter the row and column of second matrix"); 0;

scanf("%d %d",&o,&p); if(n!=o) { printf("Matrix mutiplication is not possible"); printf("\nColumn of first matrix must be same as row of second matrix"); } Else { printf("\nEnter the First matrix->"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("\nEnter the Second matrix->"); for(i=0;i<o;i++) for(j=0;j<p;j++) scanf("%d",&b[i][j]); printf("\nThe First matrix is\n"); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<n;j++){ printf("%d\t",a[i][j]); } } printf("\nThe Second matrix is\n"); for(i=0;i<o;i++){ printf("\n"); for(j=0;j<p;j++){ printf("%d\t",b[i][j]); } } for(i=0;i<m;i++) for(j=0;j<p;j++) c[i][j]=0; for(i=0;i<m;i++){ //row of first matrix for(j=0;j<p;j++){ //column of second matrix sum=0; for(k=0;k<n;k++) sum=sum+a[i][k]*b[k][j]; c[i][j]=sum;

} } } printf("\nThe multiplication of two matrix is\n"); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<p;j++){ printf("%d\t",c[i][j]); } } return } 7. Write a C program to find out transport of a matrix. Program: #include<stdio.h> int main(){ int a[10][10],b[10][10],i,j,k=0,m,n; printf("\nEnter the row and column of matrix"); scanf("%d %d",&m,&n); printf("\nEnter the First matrix->"); for(i=0;i<m;i++) for(j=0;j<n;j++ scanf("%d",&a[i][j]); printf("\nThe matrix is\n"); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<m;j++){ printf("%d\t",a[i][j]); } } for(i=0;i<m;i++) for(j=0;j<n;j++) b[i][j]=0; 0;

for(i=0;i<m;i++){ for(j=0;j<n;j++){ b[i][j]=a[j][i]; printf("\n%d",b[i][j]); } } printf("\n\nTraspose of a matrix is -> "); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<m;j++){ printf("%d\t",b[i][j]); } } return } 0;

UNIT IV 2 MARKS 1. What are functions in C?

A function is a group of statements that together perform a task. Every C program has at least one function which is main(), and all the most trivial programs can define additional functions.
2. How will define a function in C? Defining a Function:

The general form of a function definition in C programming language is as follows:


return_type function_name( parameter list ) { body of the function }

A function definition in C programming language consists of a function header and a function body. Here are all the of a function: Return Type Function Name Parameters Function Body 3. What are the steps in writing a function in a program? a) Function Declaration (Prototype declaration): Every user-defined functions has to be declared before the main().

b) Function Callings: The user-defined functions can be called inside any functions like main(),user-defined function, etc.

c) Function Definition:

4.What is the purpose of the function main()? (MAY 2009) Page 69

GE6151 Computer Programming Question Bank

The function main () invokes other functions within it. It is the first function to be called when the program starts execution. 5.Is it better to use a macro or a function?

Macros are more efficient (and faster) than function, because their corresponding code is inserted directly at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function.

However, macros are generally small and cannot handle large, complex coding constructs. In cases where large, complex constructs are to handled, functions are more suited, additionally; macros are expanded inline, which means that the code is replicated for each occurrence of a macro. 6. Distinguish between Call by value Call by reference. Call by value a) In call by value, the value of actual agreements Call by reference. a) In call by reference, the address of actual

is passed to the formal arguments and the operation argurment values is passed to formal argument is done on formal arguments. values.

b) Formal arguments values are photocopies of b) Formal arguments values are pointers to the actual arguments values. actual argument values.

c) Changes made in formal arguments valued do c) Since Address is passed, the changes made in the not affect the actual arguments values. both arguments values are permanent

7. What is meant by Recursive function? If a function calls itself again and again, then that function is called Recursive function. Example: Page 70

GE6151 Computer Programming Question Bank

void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); }

8. Write a C program for factorial using recursion function. Following is an example which calculates factorial for a given number using a recursive function:
#include <stdio.h> int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 15; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; }

When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016

9. What is dynamic memory allocation? Allocating the memory at run time is called as dynamic memory allocation. 10. What are the various dynamic memory allocation functions? malloc() - Used to allocate blocks of memory in required size of bytes. free() - Used to release previously allocated memory space. Page 71

GE6151 Computer Programming Question Bank

calloc() - Used to allocate memory space for an array of elements. realloac() - Used to modify the size of the previously allocated memory space. 11. What is a Pointer? How a variable is declared to the pointer? (MAY 2009)

Pointer is a variable which holds the address of another variable. Pointer Declaration: datatype *variable-name; Example: int *x, c=5; x=&a; 12. What are the uses of Pointers?

Pointers are used to return more than one value to the function

Pointers are more efficient in handling the data in arrays Pointers reduce the length and complexity of the program They increase the execution speed The pointers save data storage space in memory 13. What is the output of the program? main() { int i=5;j=2; junk(i,j); printf(\n %d %d,i,j); } Output: 1. 2 2. Page 72 junk(int i, int j) { i=i*j; j=i*j; }

GE6151 Computer Programming Question Bank

14. What are * and & operators means? * operator means value at the address & operator means address of 15. What is dangling pointer?

In C, a pointer may be used to hold the address of dynamically allocated memory. After this memory is freed with the free() function, the pointer itself will still contain the address of the released block. This is referred to as a dangling pointer. Using the pointer in this state is a serious programming error. Pointer should be assigned NULL after freeing memory to avoid this bug. 16. What is meant by Recursive function? If a function calls itself again and again, then that function is called Recursive function. Example: void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); }

17. Write a C program for factorial using recursion function. Following is an example which calculates factorial for a given number using a recursive function:
#include <stdio.h> int factorial(unsigned int i) { if(i <= 1) { return 1; }

Page 73

GE6151 Computer Programming Question Bank

return i * factorial(i - 1); } int main() { int i = 15; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; }

When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016

18. What is dynamic memory allocation? Allocating the memory at run time is called as dynamic memory allocation. 19. What are the various dynamic memory allocation functions? malloc() - Used to allocate blocks of memory in required size of bytes. free() - Used to release previously allocated memory space. calloc() - Used to allocate memory space for an array of elements. realloac() - Used to modify the size of the previously allocated memory space.

Page 74

GE6151 Computer Programming Question Bank

UNIT IV FUNCTIONS AND POINTERS 16 Marks 1 .What is Function? Explain with example. A function in C can perform a particular task, and supports the concept of modular programming design techniques.

We have already been exposed to functions. The main body of a C program, identified by the keyword main, and enclosed by the left and right braces is a function. It is called by the operating system when the program is loaded, and when terminated, returns to the operating system.

Functions have a basic structure. Their format is ion_name r e t u r n _ d a t a _ t y p e f u n c t } { function_body ( data_type_declarations_of_arguments;

arguments, arguments

It is worth noting that a return_data_type is assumed to be type int unless otherwise specified, thus the programs we have seen so far imply that main() returns an integer to the operating system. return_data_type function_name (data_type variable_name, data_type variable_name, .. ) { function_body } Example:

Page 75

GE6151 Computer Programming Question Bank

Now lets incorporate this function into a program. /* Program illustrating a simple function call #include <stdio.h> void print_message( void ); /* ANSI C function prototype */ void print_message( void ) /* the function code */ { printf("This is a module called print_message.\n"); } main() { print_message(); } To call a function, it is only necessary to write its name. The code associated with the function name is executed at that point in the program. When the function terminates, execution begins with the statement which follows the function name. In the above program, execution begins at main(). The only statement inside the main body of the program is a call to the code of function print_message(). This code is executed, and when finished returns back to main(). */

As there is no further statement inside the main body, the program terminates by returning to the operating system. RETURNING FUNCTION RESULTS This is done by the use of the keyword return, followed by a data variable or constant value, the data type of which must match that of the declared return_data_type for the function. float add_numbers( float n1, float n2 ) { return n1 + n2; /* legal */ return 6; Page 76 /* illegal, not the same data type */

GE6151 Computer Programming Question Bank

return 6.0; }

/* legal */

Example: /* Simple multiply program using argument passing */ #include <stdio.h> int calc_result( int, int ); /* ANSI function prototype */

int calc_result( int numb1, int numb2 ) { auto int result; result = numb1 * numb2; return result; } main() { int digit1 = 10, digit2 = 30, answer = 0; answer = calc_result( digit1, digit2 ); printf("%d multiplied by %d is %d\n", digit1, digit2, answer );

2. Explain various types of functions in detail with an example program for each type. Types: Library Functions User Defined functions (a) Function Declaration returntype function-name(Parameters); Example: int square(int, int);

Page 77

GE6151 Computer Programming Question Bank

(b) Function calling function-name(actual parameters); Example: int square(a,b); (c) Function Definition: returntype function-name(formal parameters) }

Example: { local variable declaration; statement 1; statement return(value); void square(int a, int b) { printf(%d,(a*b)); } Example for Function /*program for fibonacci series using functions*/ #include<stdio.h> #include<conio.h> void main() { int n; long int i; long int fibo(int n); clrscr(); printf("Enter the limit:\n"); Page 78 2;

GE6151 Computer Programming Question Bank

scanf("%d",&n); i=fibo(n); printf("\nThe %dth Fibonacci number is %ld",n,i); getch(); }

long int fibo(int n) { int i=1; old_no=0; currnt_no=1; while(i<=n) { sum=old_no+currnt_no; old_no=currnt_no; currnt_no=sum; i++; printf("\n%d",sum); } return(sum); } old_no,currnt_no,sum,i;

3. Define Recursion in C. Explain the concept of recursion with example. RECURSION This is where a function repeatedly calls itself to perform calculations. Typical applications are games and Sorting trees and lists. Consider the calculation of 6! ( 6 factorial ) ie 6! = 6 * 5 * 4 * 3 * 2 * 1 6! = 6 * 5! 6! = 6 * ( 6 - 1 )! n! = n * ( n - 1 )! Page 79

GE6151 Computer Programming Question Bank

Example: /* example for demonstrating recursion */ #include <stdio.h> long int factorial( long int ); long int { long int result; factorial( long int n ) /* function prototype */

if( n == 0L result = else result = n * factorial( n - 1L ); return ( result ); } main() { int j; for( j = 0; j < 11; ++j ) printf("%2d! = }

) 1L;

%ld\n",

factorial(

(long)

j)

);

4. (i) Explain (i)Call by value (ii) Call by reference with example. (i) CALL BY VALUE: When the value is passed directly to the function it is called call by value. In call by value only a copy of the variable is only passed so any changes made to the variable does not reflects in the calling function. Example: #include<stdio.h>

#include<conio.h> swap(int,int); void { Page 80 main()

GE6151 Computer Programming Question Bank

int x,y;

printf("Enter two nos"); scanf("%d %d",&x,&y);

printf("\nBefore swapping : x=%d y=%d",x,y); swap(x,y); getch(); } swap(int a,int b) {

int t=a; a=b; b=t;

t;

printf("\nAfter swapping :x=%d y=%d",a,b); }

SYSTEM

OUTPUT: 12 34

Enter two nos

Before swapping :12 34 After swapping : 34 12 (ii)Call by Reference: #include <stdio.h> #include <conio.h> void swap(int*,int*); Page 81

GE6151 Computer Programming Question Bank

int main() { int x,y; printf("Enter the value of x and y \n"); scanf("%d%d",&x,&y); printf("Before swapping\nx = %d\ny = %d\n",x,y); swap(&x,&y); printf("After swapping\nx = %d\ny = %d",x,y); getch(); return } 0;

void swap (int *a, int *b) { int temp;

temp=*a; *a=*b; *b=temp; }

5. What is pointer? Explain with example. Pointers are another important feature of C language. Although they may appear a little confusing for a beginner, they are powerful tool and handy to use once they are mastered. There are a number of reasons for using pointers.

A pointer enables us to access a variable that is defined outside the function. Pointers are more efficient in handling the data tables. Pointers reduce the length and complexity of a program. They increase the execution speed. The use of a pointer array to character strings result in saving of data storage space in memory. Page 82

GE6151 Computer Programming Question Bank

UNDERSTANDING POINTERS Whenever we declare a variable, the system allocates, somewhere in the memory, an appropriate location to hold the value of the variable. Since, every byte has a unique address number, this location will have its own address number.

Consider the following statement: int quantity = 179; This statement instructs the system to find a location for the integer variable quantity and puts the value 179 in that location. Assume that the system has chosen the address location 5000 for quantity. We may represent this as shown below.

quantity

Variable

179

Value

5000

Address

Representation of a variable During execution of the program, the system always associates the name quantity with the address 5000. To access the value 179 we use either the name quantity or the address 5000. Since memory addresses are simply numbers, they can be assigned to some variables which can be stored in memory, like any other variable. Such variables that hold memory addresses are called pointers. A pointer is, therefore, nothing but a variable that contains an address which is a location of another variable in memory.

Since a pointer is a variable, its value is also stored in the memory in another location. Suppose, we Page 83

GE6151 Computer Programming Question Bank

assign the address of quantity to a variable p. The link between the variables p and quantity can be visualized as shown below. The address of p is 5048. Variable quantity p Pointer as a variable Value 179 5000 Address 5000 5048

Since the value of the variable p is the address of the variable quantity, we may access the value of quantity by using the value of p and therefore, we say that the variable p points to the variable quantity. Thus, p gets the name pointer. 6. How array elements are accessed using pointers?

Pointers can be used to manipulate two-dimensional array as well. An element in a twodimensional array can be represented by the pointer expression as follows:

*(*(a+i)+j) or *(*(p+i)+j)

The base address of the array a is &a[0][0] and starting at this address, the compiler allocates contiguous space for all the elements, row-wise. That is, the first element of the second row is placed immediately after the last element of the first row, and so on.

POINTERS IN ONE-DIMENSONAL ARRAY main ( ) { int *p, sum , i static int x[5] = {5,9,6,3,7}; i = 0; p = x; sum = 0; printf(Element Value Address \n\n); while(i < 5) { Page 84

GE6151 Computer Programming Question Bank

printf( x[%d} %d %u\n, i, *p, p); sum = sum + *p; i++, p++; } printf(\n Sum = %d \n, sum); printf(\n &x[0] = %u \n, &x[0]); printf(\n p = %u \n, p); } Output Element X[0] X[1] X[2] X[3] X[4] Sum &x[0] = 166 p Value 5 9 6 3 7 = 55 = 176 Address 166 168 170 172 174

7. How can you pass a array as a parameter in C. Give an example

Passing arrays as parameters: A program that reads elements and assign them in an array. Then, it prints the array elements out. #include <stdio.h> void get_array(int a[], int size); void prt_array(int a[], int size); #define SIZE 10 int main() { int a[SIZE]; get_array(a, prt_array(a, printf("\n"); return 0; }

SIZE); SIZE);

void get_array(int a[], int size) { int i; Page 85

GE6151 Computer Programming Question Bank

printf("Enter 10 values, after each value press enter:\n " ); for (i = 0; i < size; i++) scanf("%d", &a[i]); } void prt_array(int a[], int size) { int i; printf("Printing all values :\n"); for (i = 0; i < size; i++) printf("%d\n", a[i]); } This will produce something like: Enter 10 values, after each value press enter: 10 2 3 4 8. How can you pass a pointer as a parameter in C?. Give an example. Passing pointers as parameters:

A program that swaps integers using a function that accepts pointers to the integers to be swapped:
#include <stdio.h> void swap(int * q, int * p) { int temp = *p; *p = *q; *q = temp; } int main() { int a = 10, b = 2, x = 3, y = 5; printf("a,b,x,y: %d,%d,%d,%d\n", a, b, x, y); swap(&x, &y); swap(&a, &b); printf("a,b,x,y: %d,%d,%d,%d\n", a, b, x, y); Page 86

GE6151 Computer Programming Question Bank

} It will produces following result: a,b,x,y: 10,2,3,5 a,b,x,y: 2,10,5,

Page 87

GE6151 Computer Programming Question Bank

UNIT V 2 MARKS 1. Compare arrays and structures. Comparison of arrays and structures is as follows. Arrays Structures

An array is a collection of data items of same data A structure is a collection of data items of different type.Arrays can only be declared. There is no keyword for arrays. data types. Structures can be declared and defined. The keyword for structures is struct.

An array name represents the address of the starting A structrure name is known as tag. It is a element. Shorthand notation of the declaration. An array cannot have bit fields.

A structure may contain bit fiel

2. Compare structures and unions. Structure Every member has its own memory. The keyword used is struct. Union

All members use the same mem The keyword used is union.

All members occupy separate memory location, hence different interpretations of the Different interpretations for same memory location are not possible. Consumes more space compared to union. location are possible.

Conservation of memory is pos

Page 88

GE6151 Computer Programming Question Bank

3. Define Structure in C. C Structure is a collection of different data types which are grouped together and each element in a C structure is called member. If you want to access structure members in C, structure variable should be declared. Many structure variables can be declared for same structure and memory will be allocated for each separately. It is a best practice to initialize a structure to nu ll while declaring, if we dont assign any values to structure members. 4. What you meant by structure definition? A structure type is usually defined near to the start of a file using a typedef statement. typedef defines and names a new type, allowing its use throughout the program. typedefs usually occur just after the #define and #include statements in a file. Here is an example structure definition. typedef struct { char name[64]; char course[128]; int age; int } student; This defines a new type student variables of type student can be declared as follows. year;

student st_rec; 5. How to Declare a members in Structure? A struct in C programming language is a structured (record) type [1] that aggregates a fixed set of labeled objects, possibly of different types, into a single object. The syntax for a struct declaration in C is: Page 89

GE6151 Computer Programming Question Bank

struct tag_name { type type /* ... */ }; 6. What is meant by Union in C.? A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose. 7. How to define a union in C. To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows: union [union tag] { member definition; attribute; attribute2;

member definition;

member definition; } [one or more union variables];

8. How can you access the members of the Union? To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type.

Page 90

GE6151 Computer Programming Question Bank

9. What are the pre-processor directives?

Macro Inclusion Conditional Inclusion File Inclusion 10. What are storage classes? A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. 11. What are the storage classes available in C?

There are following storage classes which can be used in a C Program auto register static extern
12. What is register storage in storage class? Register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location). { register int } Miles;

13.What is static storage class?

Page 91

GE6151 Computer Programming Question Bank

Static is the default storage class for global variables. The two variables below (count and road) both have a static storage class. static int Count; int Road; { printf("%d\n", } Road);

14. Define Auto storage class in C. auto is the default storage class for all local variables. { int Count; auto int Month; } The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

15. Define pre-processor in C. The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool. We'll refer to the C Preprocessor as the CPP. Example:

#define Substitutes a preprocessor macro #include Inserts a particular header from another file

Page 92

GE6151 Computer Programming Question Bank

16. Define Macro in C.

A macro definition is independent of block structure, and is in effect from the #define directive that defines it until either a corresponding #undef directive or the end of the compilation unit is encountered. Its format is: #define identifier replacement
Example: #define TABLE_SIZE 100 int table1[TABLE_SIZE]; int table2[TABLE_SIZE]; 17. What are conditional Inclusions in Preprocessor Directive? Conditional inclusions (#ifdef, #ifndef, #if, #endif, #else and #elif) These directives allow including or discarding part of the code of a program if a certain condition is met. #ifdef allows a section of a program to be compiled only if the macro that is specified as the parameter has been defined, no matter which its value is. For example: 1 #ifdef TABLE_SIZE 2 int table[TABLE_SIZE]; 3 #endif

18. What you meant by Source file Inclusion in Preprocessor directive? Source file inclusion (#include) This directive has also been used assiduously in other sections of this tutorial. When the preprocessor finds an #include directive it replaces it by the entire content of the specified file. There are two ways to specify a file to be included: 1 #include "file" 2 #include <file>

Page 93

GE6151 Computer Programming Question Bank

19. What is Line control? Line control (#line) When we compile a program and some error happens during the compiling process, the compiler shows an error message with references to the name of the file where the error happened and a line number, so it is easier to find the code generating the error. The #line directive allows us to control both things, the line numbers within the code files as well as the file name that we want that appears when an error takes place. Its format is:

#line number "filename"

Where number is the new line number that will be assigned to the next code line. The line numbers of successive lines will be increased one by one from this point on. UNIT V 16 MARKS 1. Define Structures. Explain structures in detail. (JAN 2009 / MAY2009) A structure is a collection of one or more variables of different data types grouped together under a single name. It contains different data types. C Structure is a collection of different data types which are grouped together and each element in a C structure is called member. If you want to access structure members in C, structure variable should be declared. Many structure variables can be declared for same structure and memory will be allocated for each separately. It is a best practice to initialize a structure to null while declaring, if we dont assign any val ues to structure members. Syntax: struct { type variable 1; Page 94 struct-name

GE6151 Computer Programming Question Bank

type variable 2; type variable n; } structure_variables;

Example program for C structure: This program is used to store and access id, name and percentage for one student. We can also store and access these data for many students using array of structures. You can check C - Array of Structures to know how to store and access these data for many students.

#include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; int { main() struct student record = {0}; //Initializing to null record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0;

Output:
Id is: 1 Name is: Raju Percentage is: 86.500000

Page 95

GE6151 Computer Programming Question Bank

2. Explain Array of structure in C. Since structures are data types that are especially useful for creating collection items, why not make a collection of them using an array? Let us now modify our above example object1.c to use an array of structures rather than individual ones. Example Program: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. Page 96 //update enemy1 position gameobjs[1].xpos = 1; gameobjs[1].ypos = 2; for (i = 0; i < 2; i++) printobj(gameobjs[i]); int i; struct object gameobjs[2]; gameobjs[0] = createobj("player1", 0, 0); gameobjs[1] = createobj("enemy1", 2, 3); void main() { void printobj(struct object obj); struct object createobj(char id[], int xpos, int ypos); struct object { char id[20]; int xpos; int ypos; }; #include <stdio.h> #include <stdlib.h>

GE6151 Computer Programming Question Bank

27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. } struct object createobj(char id[], int xpos, int ypos) { struct object newobj; strcpy(newobj.id, id); newobj.xpos = xpos; newobj.ypos = ypos; return newobj; } for (i = 0; i < 2; i++) printobj(gameobjs[i]);

We create an array of structures called gamobjs and use the createobj function to initilize it's elements. You can observer that there is not much difference between the two programs. We added an update for the enemy1's position to show how to access a structure's members when it is an element within an array. Output:

3. How can pass a structure to function in C. A structure can be passed to any function from main function or from any sub function. Structure definition will be available within the function only.

Page 97

GE6151 Computer Programming Question Bank

It wont be available to other functions unless it is passed to those functions by value or by address(reference). Else, we have to declare structure variable as global variable. That means, structure variable should be declared outside the main function. So, this structure will be visible to all the functions in a C program. Passing structure to function in C: It can be done in below 3 ways. 1. Passing structure to a function by value 2. Passing structure to a function by address(reference) 3. No need to pass a structure - Declare structure variable as global program - passing structure to function in C by value: In this program, the whole structure is passed to another function by value. It means the whole structure is passed to another function with all members and their values. So, this structure can be accessed from called function. This concept is very useful while writing very big programs in C. #include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; void func(struct student record); int main() { struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; Page 98

GE6151 Computer Programming Question Bank

func(record); return 0; } void func(struct student record) { printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); } Output: Id is: 1 Name is: Raju Percentage is: 86.500000

4. How can you insert structure with in another structure? Structures can be used as structures within structures. It is also called as 'nesting of structures'.

Syntax: struct { structure_nm <data-type> element 1; <data-type> element 2; --------------------<data-type> element n; struct { structure_nm

<data-type> element 1; <data-type> element 2; --------------------<data-type> element n; }inner_struct_var; }outer_struct_var;

Page 99

GE6151 Computer Programming Question Bank

Example Program :

Program to demonstrate nested structures.

#include <stdio.h> #include <conio.h>

struct {

stud_Res

int rno; char std[10]; struct { char subj_nm[30]; int subj_mark; }marks; }result; void { clrscr(); printf("\n\t Enter Roll Number : "); scanf("%d",&result.rno); printf("\n\t Enter Standard : "); scanf("%s",result.std); printf("\n\t Enter Subject Code : "); scanf("%s",result.marks.subj_nm); printf("\n\t Enter Marks : "); scanf("%d",&result.marks.subj_mark); printf("\n\n\t Roll Number : %d",result.rno); printf("\n\n\t Standard : %s",result.std); printf("\nSubject Code : %s",result.marks.subj_nm); 00 main() stud_Marks

GE6151 Computer Programming Question Bank

printf("\n\n\t Marks : %d",result.marks.subj_mark); getch(); } Output : Enter Roll Number : 1

Enter Standard : MCA(Sci)-I

Enter Subject Code : SUB001

Enter Marks : 63

Roll Number : 1

Standard : MCA(Sci)-I Subject Code : SUB001 Marks : 63 5. Explain the concept of pointer to structure. C structure can be accessed in 2 ways in a C program. They are, 1. Using normal structure variable 2. Using pointer variable Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to access the data using pointer variable. You have learnt how to access structure data using normal variable in C - Structure topic. So, we are showing here how to access structure data using pointer variable in below C program.

01

GE6151 Computer Programming Question Bank

Example program for C structure using pointer: In this program, record1 is normal structure variable and ptr is pointer structure variable. As you know, Dot(.) operator is used to access the data using normal structure variable and arrow(->) is used to access data using pointer variable. #include <stdio.h> #include <string.h>

struct student { int id; char name[30]; float percentage; };

int {

main()

int i; struct student record1 = {1, "Raju", 90.5}; struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n"); printf(" Id is: %d \n", ptr->id); printf(" Name is: %s \n", ptr->name); printf(" Percentage is: %f \n\n", ptr->percentage);

return 0; }

02

GE6151 Computer Programming Question Bank

Output: Records of STUDENT1: Id Name is: is: 1 Raju

Percentage is: 90.500000

6. Define Union. Explain Union in detail. (JAN 2009)

Union is a collection of variables similar to structure. The union requires bytes that are equal to number of bytes required for the largest number. Example: union { char name[20]; int rollno,m1,m2,m3,tot; student

float avg; }s1; Union of structure Union can be nested with another union. Example program:

#include <stdio.h> #include <string.h> union student { char name[20]; char subject[20]; float percentage; }; int main() { union student record1;
03

GE6151 Computer Programming Question Bank

union student record2; // assigning values to record1 union variable strcpy(record1.name, "Raju"); strcpy(record1.subject, "Maths"); record1.percentage = 86.50; printf("Union record1 values example\n"); printf(" Name : %s \n", record1.name); printf(" Subject : %s \n", record1.subject); printf(" Percentage : %f \n\n", record1.percentage); // assigning values to record2 union variable printf("Union record2 values example\n"); strcpy(record2.name, "Mani"); printf(" Name : %s \n", record2.name); strcpy(record2.subject, "Physics"); printf(" Subject : %s \n", record2.subject); record2.percentage = 99.50; printf(" Percentage : %f \n", record2.percentage); return 0; }

Output:
Union record1 values example Name : Subject : Percentage : 86.500000

Union record2 values example Name : Mani Subject : Physics Percentage : 99.500000

04

GE6151 Computer Programming Question Bank

7. What are storage classes? Explain each with example. A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. There are following storage classes which can be used in a C Program auto register static extern auto - Storage Class auto is the default storage class for all local variables. { int Count; auto int Month; } The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables. register - Storage Class register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location). { register int } Miles;

GE6151 Computer Programming Question Bank

Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implementation restrictions. static - Storage Class static is the default storage class for global variables. The two variables below (count and road) both have a static storage class. static int Count; int Road;

{ printf("%d\n", } static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in. static can also be defined within a function. If this is done the variable is initialized at run time but is not reinitialized when the function is called. This inside a function static variable retains its value during various calls. void func(void); static count=10; /* Global variable - static is the default */ Road);

main() { while { func(); } (count--)

GE6151 Computer Programming Question Bank

} void func( void ) { static i = 5; i++; printf("i is %d and count is %d\n", i, count); }

This will produce following result

i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0 8. Describe in detail about the Preprocessors in C. (MAY 2009) THE PREPROCESSOR The define statement is used to make programs more readable, and allow the inclusion of macros. Consider the following examples,

#define TRUE 1 /* Do not use a semi-colon , # must be first character on line */ #define FALSE 0 #define NULL 0 #define AND &

GE6151 Computer Programming Question Bank

#define OR | #define EQUALS == game_over = TRUE; while( list_pointer != NULL ) MACROS Macros are inline code which is substituted at compile time. The definition of a macro, which accepts an argument when referenced, #define SQUARE(x) (x)*(x) y = SQUARE(v); In this case, v is equated with x in the macro definition of square, so the variable y is assigned the square of v. The brackets in the macro definition of square are necessary for correct evaluation.

The expansion of the macro becomes y = (v) * (v); Naturally, macro definitions can also contain other macro definitions,

#define IS_LOWERCASE(x) (( (x)>='a') && ( (x) <='z') ) #define TO_UPPERCASE(x) (IS_LOWERCASE (x)?(x)-'a'+'A':(x))

while(*string) { *string = TO_UPPERCASE (*string); ++string; } CONDITIONAL COMPILATIONS These are used to direct the compiler to compile/or not compile the lines that follow

#ifdef

NULL

#define NL 10 #define SP 32

GE6151 Computer Programming Question Bank

#endif In the preceding case, the definition of NL and SP will only occur if NULL has been defined prior to the compiler encountering the #ifdef NULL statement. The scope of a definition may be limited by #undef NULL This renders the identification of NULL invalid from that point onwards in the source file. Typedef This statement is used to classify existing C data types, eg, typedef int counter; /* redefines counter as an integer */ counter j, n; /* counter now used to define j and n as integers */ typedef struct { int month, day, year; } DATE; DATE todays_date; /* same as struct date todays_date */

Anda mungkin juga menyukai