Vous êtes sur la page 1sur 80

Question Bank of CPU

SHORT QUESTIONS
Q. 1 Define Computer

Ans.

A computer is an electronic data processing machine which accepts data from the
outside world in the form of an input and manipulates, calculates, computes on the
basic of a set of instructions supplied and stored in the memory and gives the
required or desired result in the form of an output to the user. To put in a simple
language, a computer is an information processing machine.

Q. 2 Define Hardware

Ans. The physical parts of a computer are called the hardware. In other words, the
units that are visible and units which one can touch and feel are known as the
computer hardware.
Q. 3 Define Software

Ans. Software refers to the set of specific instructions that give directions to a computer
to perform certain specific or desired operations. In other words, software is
another component of a computer system which helps the user to utilize the
various capabilities of a computer system for a specific purpose.
Q. 4

Define Firmware

Ans.

Firmware often refers to a sequence of instructions (software) that its


substituted for hardware.

Q. 5

Define Analog Computer

Ans.

An analog computer is an electric system which recognizes data as continuous


measurements of physical quantities, such as pressure, voltage or temperature
along a continuous scale. The output of an analog computer will be usually in the
form of language readings or graphs.

Q. 6 Define Digital Computer

Ans.

A Digital computer is a combination of electronic devices, designed to manipulate


physical quantities of information that are represented in a digital format. In other
words, a digital computer represents data in terms of discrete numbers and
processes data using the standard arithmetic operations.

Q. 7 What is a hybrid computer ?

Ans.

Computer which performs operations based on both analog and digital


principles in called as a hybrid computer. In other words, a computer system
that has capabilities, behavior, functions and principles of operation of both
analog and digital computer is called a hybrid computer.
1

Q. 8 Give full form of SSI, MSI, LSI, VLSI, ULSI.

Ans. SSI

- Small Scale integrated Circuits

MSI

- Medium Scale Integrated Circuits

LSI

- Large Scale integrated Circuits

VLSI

- Very Large Scale Integrated Circuits

ULSI

- Ultra Large Scale Integrated Circuits

Q. 9 What is RAM ?

Ans.

Stand for random-access memory form of primary storage for holding


temporary data and instruction volatile : Programs and data are erased when
the power is disrupted.

Q. 10 Explain ROM in brief

Ans.

Stands for read-only memory form of primary storage for holding permanent data
and instructions permanent : program and data rename intact even when power is
off other forms of ROM PROM - Programmable ROM EPROM Erasable
PROM.

Q. 11 What is a Cache Memory ?

Ans. Cache memory, also called in high-speed buffer, is a portion of primary


storage used to speed the processing operations of the computer. Cache memory
serves as a working buffer or temporary area to store both instructions and data
that must be accessed, often by the program being executed.
Q. 12 Define Bus.

Ans.

In microcomputers, the term bus refers to the paths between the components of a
computer. There are two main buses in a computer, the data bus and the address
bus.

Q. 13 Define Data Bus


Ans.

The data bus is an electrical path that connects the CPU, memory, and the other
hardware devices on the motherboard. Actually, the bus is group of parallel wires.

Q. 14 Define Address Bus


Ans.

The address bus is a set of wires similar to the data bus that connects the CPU and
RAM and carries the memory addresses.

Q. 15 Define subroutines
Ans.

Subroutines are the smallest items of software normally provided by a


manufacturer. These are usually routines devised to perform large numbers of
routine calculations e.g.,tax calculations multiplications and division (if these
functions are not supported by hardware) editing of data for input and output

Q. 16 Define Flowchart
Ans.

A flowchart is a graphical representation of a program flow or an algorithm of a


problem, to be solved by a computer. It is an aid to solve a complex problem
2

easily and efficiently.


Q. 17 Define Static Variables
Ans.

A static can only be accessed from the function in which it was declared, like
a local variable. The static variable is not destroyed on exit from the function,
instead its value is preserved, and becomes available again when the function is
next called.

Q.18 Define Token


Ans.

In a C source program, the basic element recognized by the compiler is the


"token". It is smallest part which does not break down further.

Q.19 What are identifiers ?


Ans. "Identifiers" or "symbols" are the names you use for variables, types, functions
and labels in your program. Identifier names must differ in spelling and case
from any keywords.
Q.20 Define Escape sequence
Ans.

Character combinations consisting of a backslash (\) followed by a Setter or by a


combination of digits are called "escape sequences".

Q.21 Define Simple IF statement.


Ans.

The simplest form of the control statement is the If statement. It is very


frequently used in decision making and allowing the flow of program
execution.

Q.22 Define If ELSE Statement.


Ans.

The if else is actually just on extension of the general format of if statement. If


the result of the condition is true, then program statement 1 is executed,
otherwise program statement 2 will be executed.

Q.23 Define nested IF ELSE.


Ans.

The if statement may itself contain another if statement is known as nested if


statement.

Q.24 What is a looping structure.


Ans. When user (programmer) initialize, increment a counter variable and check
(test) it value at an appropriate place in the program by repeated task such
structure is known as looping structure.
Q.25 Define Entry Control loop.
Ans.

In this loop user first checks the condition & if the condition becomes true it
will execute the body of loop.

Q.26 Define Exit Control loop


Ans.

In this loop first body of loop is executed then it checks the condition until itbecomes true.

Q. 27 Define array
3

Ans. Array is a group of elements which have same data types. An array is a collection of
variables of the same type.
Q. 28 Define String
Ans,

String is a collection or group of character array.

Q. 29 What is gets() ?
Ans.

gets() function is used to read(get) a string into program.

Q. 30 What is puts() ?
Ans.

puts() function is used to write(put) a string into program.

Q. 31 What is getchar( ) ?
Ans. getchar() function is used to read(get) a character into program.
Q. 32 What is putchar( ) ?
Ans. putchar() function is used to write(put) a character into program.
Q. 33 What is strcat() function used for ?
Ans. Strcat() function is used to concatenate more than one string into'.single one and
returns a single string from given input strings.
Q. 34 What is strcmpf ) function used for ?
Ans. strcmp() function is used two compare between.two strings ad returns either T or F
because of it compare the ASCII vajue of Two strings.
Q. 35 What is strlen( ) function used for ?
Ans.

When user want to find the length of string at that time use strlen( ) function.

Question Bank of CPU


Q. 36 What is strcpy( ) function used for ?
Ans.

Strcpyf ) function assign one string value to other string va!ue in short it copy
the data from one string to another siring.

Q. 37 What is strrev( ) function used for ?


Ans.

Strrev() function is used to print a string in reverse order.

Q. 38 Define recursion
Ans.

Recursion is the process where a functions is called itself but stack frame will
be-out of limit because function call will be infinite times. So a termination
condition is mandatory to a recursion.

Q. 39 Define Pointer
Ans.

Pointer is nothing but a variable that contains the address of another variable in
memory.

Q. 40 Define Structure
Ans. A structure is a collection of variable under a single name. These variables canbe
of different types, and each has a name which is used to select it from the
structure. A structure is a convenient way of grouping^everal pieces of related
information together.
Q. 41 Define Clars
Ans.

Class is a user defined data type which has data and method both and it is
used to generate object from it.

Q. 42 Define Data Abstraction.


Ans.

Abstraction refers to give the general view. We are representing thing without
going into the background details. Class contains the abstract data members
such as size, weight, height and function to operate on it.

Q. 43 Define Data Encapsulation.


Ans. Wrapping up (pac.king) of data and functions into a single unit called class is
known as The data encapsulation.
Q. 44 Define Data Hiding
Ans.

Data members can't be accessed outside class in which it is declared. This


fundamental is known as the data hiding.

Q. 45 Define Inheritance
Ans. Inheritance is the process by which object of one class acquire the properties and
method of another class. This is based on the hierarchical classification.
Inheritance provides the facility of reusability.

Q. 46 Define polymorphism
Ans.

Polymorphism is a Greek word and its meant is to take more than one form. An
operations show different behavior in different condition. The behaviour is used on
the data type of variable and number of arguments. For example following
function calls are different in terms of number of arguments. sum(int a, int b, int
c) sum(int.a, ind b) The above fundamental is known as the Function Overloading.

Q. 47 Define Operator Overloading


Ans.

We can perform Operator Overloading is one in which operator is used for multiple
operations, for example '+' is a operator that is used for arithmetic operation the same
operator we can use for the concatation of string and add two structure elements.

Q. 48 Define Dynamic Binding


Ans.

Binding means linking of two functions. There are two types of binding technique:
one is compile time binding in which linking is performed during the time of
compilation. It is also known as early binding.

Q. 49 Define Late Binding


Ans.

Technique of binding is dynamic binding in which linking of function is performed


during the execution when function is called. It is also known as the late binding.

Q. 50 Define Keywords
Ans.

In C++ program certain words have fixed mean for compiler and cannot be used for
other purpose in program. These fixed words are known as keywords.

Q. 51 Define Polymorphism
Ans.

The polymorphism can be.defined as : "One Interface, multiple methods."

Q. 52 What is a virtual function ?


Ans.

Virtual function is example of runtime polymorphism. In virtual function we


have pointer of base class, which can point to either base class object or derive class
object depending of address of object assigned to pointer variable.
When we use the same function name in both the base and derived classes, the
function in base class is declared as virtual using the keyword virtual before the
function declaration.

FREQUENTLY ASKED QUESTIONS


1. Define Computer
2. State the difference between hardware & software.
3. What is a firmware ?
4. State the advantage of computer.
5. Explain classification of computer.
6. Write a shortnote on Hybrid Computer.
7. Define (1) Mini Computer (2) Micro Computer (3) Main Frame
(4) Super Computer (5) Analog Computer (6) Digital Computer.
8. Explain Basic structure of C.
9. Explain the difference between RAM/ROM.
10. What is Cache Memory ?
11. Explain classification of memory with a neat diagram.
12. State types of ROM.
13. What are the points be considered while buying a SMPS ?
14. What do you mean by BUS. Explain different types of BUS.
15. What are trigraph character ? How are they useful ?
16. State all types of operators.
17. Explain scope of variables.
18. What is a token in C ?
19. Explain Data Types in Detail.
20. Disr . juish break &. continue.
21. What is a looping structure ? Types of looping structure ?
22. Differenciate while and Do while.
23. What ia string ? Which are operations on string ?
24. Explain (a) getcharf )

(b) putchar( )

25. Explain string handling function.

(c) gets()

(d) puts( ).

Short Questions
26

What is a functions ?

27

Write a short note on call by value & call by reference.

28

What is recussion ? Explain it with example.

29

What is a pointer ?

30

Differenciate arrays fit pointers.

31

What is a structure ?

32

Differenciate structure & arrays ?

33

What are the features of object oriented programming ?

34

What are benefits of OOPs ?

35

Explain structure of C++ program.

36

What is a token ?

37

Define Keyword.

38

Explain basic data types of C++.

39

What are user defined data types ? Explain with example.

40

What are derived datatypes ? Explain with example.

41

What are free store operators ?

42

Explain expression & their types.

43

Explain entry control loop & exit control loop.

44

What is prototyping ?

45

What are inline functions ?

46

Explain function overloading

47

How to make outside function inline ?

48

What is a friend function ? What are its special characteristics.

40

What is a virtual function ? Explain in detail

50

Explain Flash Memory.

X X X

GTU-Dec.2008 Paper with Answers


Q. 1

Explain Basic Structure of C Program

Ans.

A C Program may conain one or more sections shown in Figure

Documentation Section
Link Section
Definition Section
Global Declaration Section
main( )

Function Section

Declaration Part
Executable Part

Subprogram Section

(User-defined functions)
The documentation section consists of a set of comment lines giving the name of the program,
the author and other details which the programmer would like to use later, The link section
provides instructions to the compiler to link functions from the system library. The definition
section defines all symbolic constants.
There are some variables that are used in more than one function. Such variables are called
global variables and are declared in the global declaration that is outside of al! the functions.
Every C program must have one main() function section. This section contains two parts,
declaration part and executable part. The declaration part declares all the variables used in the
executable part. There is at least one statement in the executable part. These two parts must
appear between the opening and the closing braces. The program execution begins at the
opening brace and ends at the closing brace. The closing brace of the main function section is
the logical end of the program. All statement in the declaration and executable part end with a
semicolon.
The subprogram section contains all the user-defined functions that are called in the main
function. User-defined functions are generally placed immediately after the main function,
although they may appear in any order.
All sections, except the main function section may be absent when they are not required.

Q. 2
Ans.

Explain token in C
In a passage of text, individual words and punctuation marks are calk tofcens.1 Similarly, in a
C program the smallest individual units are known as C tokens. C has! six types of tokens as
shown in figure. C programs are written using these tokens and! the syntax of the language
C TOKENS

Q. 3
Ans.

Give a Switch case example.


we write a menu driven program for simple calculator using switch.
# include <stdio.h>
# include <conio.h>
# include <process.h>
Void main I)
I
int a, b, c, choice;
clrscr();
printf("\n Enter the value of A");
scanf("%d",asa);
printf("\n Enter the value of B");
scanf("%d">&b);
printf("\n 1.Addition \n 2.subraction \n 3.Multipication 4.exit');
printf("\n Enter the choice");
scanf("%d" ,&choice);
Switch (choice)
{

case 1:
c=a+b;
bre
ak;
case 1:
c=a-b;
break;
case 3:
c=a*b;
break;
case 4: exit(O);
default :
printf("\n Invalid choice");
break;
printf("\n Answer is C %d",c);
getch();

OUTPUT
Enter the value of A 12
Enter the value of B 13
1 .Addition 2. subtraction
3.multipication 4. exit
Enter your choice 1 Answer is
C 25

Q. 4 Explain Basic units of Computer.


Ans.

As shown in Figure 2.1, a computer system consists of four parts :


Hardware, also known simply as the computer Software, also known as
Programs Data, which the system converts into information People, also known
as users The term hardware refers to the part of the computer you can touch. It
consists of interconnected electronic devices that control everything the
computer does. When most people talk about a computer, they mean
hardware. The term software refers to set of electronic instructions that tell the
hardware what to do. These set of instructions are also known as programs, and
each of them has a specific purpose. For example, you will probably use a word
processing program to enter, edit, and format text documents, such as letters,
memos, and reports, Word Perfect and Microsoft Word are two popular word
processing programs.

Data refers to the raw facts the computer can manipulate data can consist of
letters numbers, sounds, or images. However, no matter what kind of data is
entered into a. computer, the computer converts it into numbers. Consequently,
computerized data is digital, meaning it has been reduced to digits, or numbers.
Within the computer, data is organized into files.

Fig. The Computer System


Computer file is simply a set of data or program instructions that has been given a name.
A file containing data is often called a document. .Although many people think of documents
simply as text, a computer document can include many kinds of data. For example, a computer
document can be a text file (such as a letter), a group of numbers (such as a budget), or a video
clip (which includes images and sounds). Programs are organized into files as well, but because
programs are not considered as data, these are not document files.
The last part of the computer system is the person who uses the computer. In discussion
about computers, people are u sally referred to as users.

Q. 5

Explain Type conversions in detail.


Ans. C permits mixing of constants and variables of different types in an expression, but
during evaluation it address to very strict rules of type conversion. We know that the
computer considers one operator at a time, involving two operands. If the operands are of
different types, the lower' type is automatically converted to the higher' type before the
operation proceeds. The result is of the higher type. A typical type conversion process is
illustrated in Figure.

Q. 6

Differentiate Break V/S Continue

Q.7 Explain goto statement

Ans.

GOTO STATEMENT :
Definition : it is useful for unconditional transfer of control to the named label.
Syntax:
goto identifier ;

A statement label is meaningful only to a goto statement; in any other context, a


labeled statement is executed without regard to the label.
A jump-statement must reside in the same function and can appear before only
one statement in the same function. The set of identifier names following a goto
has its own name space so the names do not interfere with other identifiers.
Labels cannot be redeclared.
It is good programming style to use the break, continue, and return statement in
preference to goto whenever possible. Since the break statement only exits from one
level of the loop, a goto may be necessary for exiting a loop from within a deeply
nested loop.

Q. 8

Difference between H/W and S/W

The main parts of a computer hardware are the storage devices, the input devices, the
output devices and the Central Processing Unit (CPU).
Software
Software refers to the set of specific instructions that give directions to a computer to
perform certain specific or desired operations. In other words, a software is another
component of a computer system which helps the user to utilize the various capabilities
of a computer system for a specific purpose. Some examples of the software are the
following.

>
>

Programming languages (BASIC, C, Pascal, C++, etc.)


Loader and Linker

>
>
>
>

Editor
Compiler
Assembler
Operating systems

In general, software can be classified into two types: systems software and applications
software.

Q. 9
Ans.

State and explain the Advantage of Computer


The advantages of selecting and using computers and how and why computers
have become an important tool in the modern world are summarized and given in follow
liv points.

1)

Speed
One the main reasons for using computers in the modern world is the speed. There is no
doubt that computers are extremely fast, accurate and can store a large amount of data
and can execute a long sequence of instructions automatically, h is only because of
computers that certain activities and operations can be accomplished in todays world.
Some of the examples for such activities are weather forecasting, control of industrial
operations, traffic and spacecraft control, reservations of tickets, etc. Without u;computers, it is rather very difficult to take accurate decisions, predict the shortfall or]
excess of the production and carry out day-to-day managerial activities and functions)
associated with the social, financial, technological and other areas.

2)

Storage

Computer units can store and process vast amount of information in very little
space. Also any information can be located, copied, deleted, browsed, navigated, modifier!
and displayed swiftly at the touch of a few keys. The above facility is unique to computer^
only.

3)

Diligence and maintenance

Unlike human beings, computers do not get tired. They are only a few movable (mechanical)
parts and hence computers arc not susceptible to wear and tear and require frequent repairs. Hence it is
the best tool or machine for performing repeated jobs and operations without any actual limit.

4)

Accuracy

Computers are many times more accurate than human beings. Once programmed long sequences
of operations can be performed without human assistance and the necessary answers can be produced
and hence complex mathematical, scientific a engineering problems can be solved very quickly and
accurately. A large amount of and information can be entered, stored and manipulated in computer
systems for taking logical decisions.

Q. 10 Explain Memory Classification with a neat diagram


Ans.
As mentioned earlier, memory can be classified into two groups : prime (systecj or
main) memory and storage memory. The R/WM and ROM are examples of primJ memory; this is the
memory the microprocessor uses in executing and storing programs This memory should be able to
respond fast enough to keep up with the execution speef of the microprocessor. Therefore, it should be
random access memory, meaning lha
the microprocessor should be able to access information from any register with the same speed
(independent of its place in the chip}. The size of a memory chip is specified in terms of bits. For
example, a 1 K memory chip means it can store 1 K (1022} bits {not bytes). On the other hand, memory
in a system such as a PC is specified in bytes. For example, 2M memory in a PC means it has 2
megabytes of memory. The other group is the storage memory, such as magnetic disks and tapes (see
Figure 2.16). This memory is used to store programs and results after the completion of program
execution. Information stored in these memories is nonvolatile, meaning information remains intact
even if the system is turned off. The microprocessor cannot directly execute or process programs stored
in these devices; programs need to be copied into theR/W prime memory first. Therefore, the size of the
prime memory, suchas512Kor SM (megabytes), determines how large a program the system can
process. The size of the storage memory is unlimited; when one disk or tape is full, the next one can be
used.
Figure 2.6 shows two groups in storage memory: secondary storage and backup storage. The
secondary storage is similar to what you put on a shelf in your study, and the backup is similar to what
you store in your attic. The secondary' storage and the backup storage include devices such as disks,
magnetic tapes, magnetic bubble memory, and charged-coupled devices, as shown in Figure 2.16. The
primary features of these devices are high capacity, low cost, and slow access. A disk is similar to a
record; the access to the stored information in the disk is semi random. The remaining devices shown in
Figure 2.16 are serial, meaning if information is stored in the middle of the tape, it can be accessed after
running half the tape.

Figure 2.16 shown that the prime (system) memory is divided into two main groups Read/Write
memory (R/WM) and Read-Only memory (ROM); each group includes several different

types of memory, as discussed below,


Q. 11 Short note on EPROM
Ans. This memory stores a bit by charging the floating gate of an FET. Information is stored by
using an EPROM programmer, which applies high voltages to charge the gale. All the
information can be erased by exposing the chip to ultraviolet light through its quartz
window, and the chipcan be re programmed. Because the chip can be reused many times,
this memory is ideally suited for product development, experimental projects, and college
laboratories. The disadvantages of EPROM are (1) it must be taken out of j the circuit to
earse it, (2) the entire chip must be erased, and (3) the erasing process takes 15 to 20
minutes.

Q. 12 Short note on EE-PROM


Ans. This memory is functionally similar to EPROM, except that information can be altered by
using electrical signals at the register level rather than erasing all the information. This has
an advantage in field and remote control applications. In' microprocessor systems, software
update is common occurrence. If EE-PROMs are used in the systems, they can be updated
from a central computer by using a remote link via telephone lines. Similarly, in a process
control where timing information needs to be changed, it can be changed by sending
electrical signals from a central place. This memory also includes a Chip Erase mode,
whereby the entire chip can be erased in 10 ms vs. 15 to 20 min. to erase an EPROM.
However, this memory is expensive compared) to EPORM or flash memory (described in
the next paragraph).
Q. 13 Explain Flash Memory
Ans. This is a variation of EE-PROM that is becoming popular. The major difference i between
the flash memory and EE-PROM is in the erasure procedure: the EE-PROM: can be erased
at register level, but the flash memory must be erased either in its entirety or at the sector
(block) level. These memory chips can be erased and programmed at least a million times.
The power supply requirement for programming these chips was] around 12 v, but now
chips are available that can be programmed using a power supply as low as 1.8 V.
Therefore, this memory is ideally suited for Jow-power systems.
In a micro processor-based product, programs are generally written in ROM, and data that
are likely to vary are stored in R/WM. For example, in a microprocessor-controlled

Question Bank of CPU

19

oven, programs that run the oven are permanently stored in ROM, and data such
as baking period, starting time, and temperature are entered in R/W memory
through the keyboard. On the other hand, when microcomputers are used for
developing software or for learning purpose, programs are first written in R/W
memory, and then stored on a storage memory such as a cassette tape or floppy
disk.
Q. 14 Explain CRT

Ans.

The monochromatic CRTs used for graphics displays are essentially the same
as those used in biack and white home television sets- Figure 3.31 illustrates
the basic operation of a CRT.

A beam of electrons (cathode rays) emitted by an electron gun, passes through


focussing and deflection systems that direct the beam towards specific positions
on the phosphor coated screen. The screen phosphor coating is organised into a grid
of dots called pixels (picture elements). The phosphor then emits a small spot of
light at each position contacted by the electron beam. Beacuse the light emitted by
the phosphor feeds very rapidly some method is needed for maintaining the
screen picture.

One way to keep the phosphor glowing is to redraw the picture repeatedly by
quickly directing the electron beam back over the same points. This type of display
is called a refresh CRT. Refresh rate is typically 60 per second for raster displays.
As refresh rate decreases, flickers develop because the eye can no longer integrate
the individual light impulses coming from a pixel. The refresh rate above which the
picture stops flickering and fuses into steady state is called Critical Fusion
Frequency.

20

Long Questions

Q. 15 What is a Static variable?


Ans. Another class of local variable is the static type. A static can only be accessed
from the function in which it was declared, like a local variable. The static
variable is not destroyed on exit from the function; instead its value is preserved,
and becomes available again when the function is next called. Static variables are
declared as local variables, but the declaration is preceded by the word static.
Q. 16 Explain scope of Variable in C
Ans. The scope of variable determines over what parts of the program a variable is
actually available for use. Lifetime refers to the period during which a variable
retains a given value during execution of a program.
Example of Local and global variables :
int b =99;
main()
{
int a =10;
printf('a=%d b=%d",a,b);
f1();
}
void f1()
{
int a= 100;
printf('a=%d b=%d",a,b);
getch();
}
OUTPUT
a=10
b=99
a=100
b=99
Description : here in main the scope of variable a is logical to function main(),then
when we move to function fl(),the scope of variable a is ended and new value of a is set
to 100.

Storage class

Visibility

Lifetime

Auto

Only in that function

Until the end of that


function or block.

Static

or block where it is
declared
Only in that function

None

Entire file

Entire program

Global

(global variable)
Q. 17

Ans.

Explain Data types in C


A C language programmer has to tell the system before-hand, the type of numbers or
characters he is using in his program. These are data types.

Primary Data types :


All C Compilers accept the following fundamental data types or primary datatypes
Sr No

Name

I.
2.
3.

Integer
Character
Floating Point

4.

Double precision floating point

5.

Void

Declaration Name
int
char
float
double
void

Integer Data type :


Integers are whole numbers with a machine dependent range of values, A good programming
language as to support the programmer by giving a control on a range of numbers and storage
space. C has 3 classes of integer storage namely short int, int and long int. Alt of these data
types have signed and unsigned forms. A short int requires half the space than normal integer
values. Unsigned numbers are always positive and consume all the bits for the magnitude of
the number. The long and unsigned integers are used to declare a longer range of values.

Float Data type :


Floating point number represents a real number with 6 digits precision. Floating point
numbers are denoted by the keyword float. When the accuracy of the floating point
number is insufficient, we can use the double to define the number. The double is same as
float but with longer precision. To extend the precision further we can use long I
double which consumes 80 bits of memory space.
Character Data Type :
A single character can be defined as a defined as a character type of data. Characters]
are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be
explicitly applied to char. While unsigned characters have values between 0 and 255,
signed characters have values from -128 to 127.
Void Data Type :
Using void data type, we can specify the type of a function. It is a good practice to avoid]
functions that does not return any values to the calling function
Range and keyword of Data Type
User defined type declaration. Declaration of Storage Class, auto, static, extern, registerJ
Denning Symbolic Constants, Declaring Variable as Constant and Volatile Variable

User - Defined Data Type


In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables.
Q. 18 Explain simple IF
Ans. Definition: The simplest form of the control statement is the If statement. It is very
frequently used in decision making and allowing the flow of program execution.
The If structure has the following syntax
If (Condition)
statement;

Description: The statement is any valid C' language statement and the condition
is any valid C' language expression, frequently logical operators are used in the
condition statement. The condition part should not end with a semicolon, since
the condition and statement should be put together as a single statement. The
command says if the condition is true then perform the following statement or If
the condition is fake the computer skips the statement and moves on to the next
instruction in the program.
Example : Program for even number.
Ans :
# include <stdio.h> //Include the stdio.h file
void main () // start of the program
{
int numbers; // declare the variables

printf ("Enter A Number: :"); / / message to the user


scanf ("%d", &number);
// read the number from standard input
if (number %2== 0)
// check whether the number is a negative number
printf ("The Enter Number is EVEN %d \n", number);
// print the value
}
OUTPUT
Enter A Number: 12
The Number is Even 12
Q. 19 Explain IF-ELSE statement
Ans. Definition: if else is actually just on extension of the general format of if
statement. If the result of the condition is true, then program statement 1 is
executed, otherwise program statement 2 win be executed. If any case either
program statement 1 is executed or program statement 2 is executed but not both
when writing programs this else statement is so frequently required that almost all
programming languages provide a special construct to handle this situation.
Syntax:
If(Condition)
{
True Block;
}
Else
{
False Block
}
Example : Program for even number and Odd Number.
Ans :
# include <stdio.h> //Include the stdio.h file
void main () // start of the program
{
int numbers; // declare the variables
printf ("Enter A Number: :"); // message to the user
scanf ("%d", &number); // read the number from standard input
if (number %2= = 0)
// check whether the number is a negative number
{
printf ("The Enter Number is EVEN %d \n", number);
/ / print the True block value
}
else
{

printf ("The Enter Number is ODD %d \n", number);


/ / print the false block value H}
OUTPUT
Enter A Number : 12
The Number is Even 12
Enter A Number : 13
The Number is Odd 12

Q. 20 Explain IF-ELSE ladder


Ans.

The elseif ladder statement is used to carry out a logical test and then take one of
many possible actions depending on the evaluation of the condition(i.e whether the
outcome is true or false. Syntax : The syntax for else if ladder as under :

If (expression)
Statement;
else if (expression)
Statement;
else if (expression)
Statement;
else if (expression)
Statement;

else

Statement;
Description:
(1)
(1)
(2)
(2)

The expression must be placed in parenthesis as shown


In this form, the statement will be executed only if the expression has true
value.
If the expression has a false then tbc control will be transferred to next condition
and so on.
If all the conditions are evaluated false then else block will be executed.

Q. 21 Explain Switch Statement

Ans.

Definition: some times in C Program we face more than one alternative choices
for different operations. So the program becomes difficult for reading and
executing. For this occurrence c provide the multi way decision statement
known as switch. The switch statement check(test) the value of a given choice
variable or expression against a list of case values and when it match a logical
block which associated with that case is executed. Syntax : switch (variable
or expression)

case value -1:


Block -1
break;
case value -2:
Block
break;

default:

default block
break;
Statement x;
Syntax Description ;
(1)
The expression or variable is either integer or character value,
(2)
Value -1 ,value -2 are called as case labels.
(3)
Each of this label value is unique in switch.
(1)
block -I, block -II are statement (logic of the block) contain 0 or more
statements.
(4)
Case is always ended with . ( Colon)
(2)
When the switch statement is executed then the value of the variable or
expression compares with block of statements and if it found it executes
the block of the statement.
(3)
break statement at the end of each block which represent end of a
particular block.
(8|
When value is not with any block of the switch case it will execute the
default statement. Default is an optional case.

Q. 22 Explain GOTO Statement ,


GOTO STATEMENT :
Definition : it is useful for unconditional transfer of control to the named label.
Syntax :
goto identifier ;
A statement label is meaningful only to a goto statement; in any other context, a labeled
statement is executed without regard to the label.
A jujnp-stqtement must reside in the same function and can appear before only one
statement in the same function. The set of identifier names following a goto has its own
name space so the names do not interfere "with other identifiers. Labels cannot be
redeclared.
It is good progr a mining style to use the break, continue, and return statement in
preference to goto whenever possible. Since the break statement only exits from one
level of the loop, a goto may be necessary for exiting a loop from within a deeply nested
loop.
Q. 23 Explain Entry Control LOOP
Ans.
Definition : when user (programmer) initialize .increment a counter variable
and check (test) it value at an appropriate place in the program by repeated task
such structure is known as looping structure. The general syntax of while loop
as under:
Syntax :
while ( test - condition)
(Body Of The Loop

!
Statement X;
Syntax Description :
(1)
It is known as "Entry Control Loop".
(2)
In this loop first user can check the condition and if the condition become true
it will execute the body of the loop.
(3)
If condition becomes false control goes to statement X.
(4)
In this loop condition is checkjtest) until it becomes false.

Q. 24 Explain Exit Control Loop

Ans.

Definition : when user(programmer) initialize ,increment a counter variable


and check (test) it value at an appropriate place in the program by repeated
task such structure is known as looping structure. The general syntax of do
while loop as under:

Syntax : do
{
Body Of The Loop
}

while

(test

condition);
Statement X;
Syntax Description:

(1)
(2)
(3)
(4)

It is known as "Exit Control Loop".


In this loop first body of the loop is executed then after check the condition until
the condition become true.
If condition becomes false control goes to statement X.
In this loop condition is check(test) at last

Q. 25
Explain String Handling Function.
Ans. STRING HANDLING FUNCTIONS
Whenever user want to perform different string manipulation operations "C" provides
the way to perform the different String Handling functions :
1.
strcat()
2.
strcmp()
3.
strlen()
4.
strcpy()
5.
strrev()
strcat : String Concatenate Function

strcat function is used to concatenate more than one string into single one and returns
a single string from given input strings.

Question Bank of CPU


Q. 26

29

Differentiate While V/S Do While

Ans.

while
it is called as entry control loop
because of Condition is tested at
the entry time
Loop even may not be executed
a single rime

do while
It is called as entry control loop
because of Condition is tested at exit
time.
Loop always at least executed for
one time.

Example

Example

int a = 1
while(a<5)
{
printf("\n a=%d",a);
a++;
}
printf(\nbye);
OUTPUT
1

2
345
bye

int a =10
do
{

printf(a=%d",a);
a++;
} while(a<10);
printf(\nbye);
OUTPUT

10
bye

Q. 27 Explain Call by Value & Call by Reference

Ans.

In call by value, the actual parameter "n" is independent of the formal parameter "x".
When a function (such as "changeit()") is called, the value of "n" is determined and is stored
in "x". Any subsequent changes to "x" do not affect "n".
Call-by-value evaluation is the most common evaluation strategy, used in
languages as far-ranging as C and Scheme. In call-by-value, the argument expression is
evaluated, and the resulting value is bound to the corresponding variable in the
function (usually by capture-avoiding substitution or by copying the value into a new
memory region). If the function or procedure is able to assign values to its parameters,
only the local copy is assigned that is, anything passed into a function call is unchanged in
the caller's scope when the function returns.
Call-by-value is not a single evaluation strategy, but rather the family of evaluation strategies
in which a function's argument is evaluated before being passed to

the function. While many programming languages (such as Kiffel and Java) that use call-byvalue evaluate function arguments left-to-right, some evaluate functions and their arguments
right-to-left, and others (such as Scheme, OCaml and C) leave the order unspecified (though
they generally guarantee sequential consistency
The arguments passed to function can be of two types namely
1.
Values passed
2.
Address passed

The first type refers to call by value and the second type refers to cal! by reference.
Example : -1

main()
!

int
x=50,
y=70;
interchange(x.y);
printfTx=%d y=%d",x,y);

interchange(xl.yl)
int x 1 ,y 1;
j
int zl;
zl=xl;
xl=yl;

yl=zl;
printf("xl=%d yl=%d",xl,yl);
!
Here the value to function interchange is passed by value.
Example - H
main()
i
i

int x=50, y=70; interchange(&x,&y);


printf("x=%d y=%d",x,y);

interchange (x 1 ,y 1)
int*xl,*yl;
{
int z\;
zl=*xl;

*xl=*yl;
*yl=zl;
printf("*x=%d ^y=%d',

Here the function is called by reference. In other words address is passed by using
symbol & and the value is accessed by using symbol *.
The main difference between them can-be seen by analyzing the output of Example - I
and Example - II.
The output of Example -I that is call by value is

xl=70yl=50
x=50 y=70 But the output of Example-II that is call
by reference is
*x=70 *y-50
x=70 y=50

Q. 28 What is Recursion ? Explain with example.


Ans.
Recursion is the process where a function is called itself but stack frame will be out of
limit because function cali will be infinite times. So a termination condition is
mandatory to a recursion.

In C, Recursion can be divided into two types:


(a) Run- Time Recursion: Normal as in C
(b) Compile- Time Recursion: By using Template
recursion a function call itself in a simple manner and by termination condition it terminates.

This process called 'Winding' and when it returns to caller that is called tin-Winding'.
Termination condition also known as Base condition, -.mple: Factorial calculation by linear
recursion

Run-Time
int Fact(long n)

Version

32

Long Questions

if(0>n) return -1;


if(0 == n) return
1; else

!
return ( n* Fact(n-l));

Winding Process:
Function called Function return
Fact(6) 6*Fact(5)
Fact(5) 5*Fact(4)
Fact(4)
4*Fact(3)
Pact(3)
3* Fact(2)
Fact(2)
2* Fact(l)
Fact(l)
1* Fact(O)
Terminating Point
Fact(O)
1
Unwinding Process
Fact(l) Fact(2) Fact(3) Fact(4) Fact(5) Fact(6)

Q. 29 Explain of C++ Program


Ans. STRUCTURE OF C++ PROGRAM

Include Statements
Class Declaration
Class function definition
Main program

Fig. Structure of C++ program


In C++ program first we are writing include preprocessor statements to include various
header (library) file. After include statement there is class declaration. In class declaration
we are defining class, its member variable and declaration for the member function.
After class declaration there is class member function definition in which we are writing

the definition of various class member function. At last there is main program, which
start the execution of program and create the object of class. The general structure of
C++ program can be shown in Fig.3.
Generally in C++ program class declaration, class member function definition and main
program is written in three separate files.
Class declaration file and class member.

function definition file is included into the


main program to link all of them. This
structure is known as the client-server
architecture. In client-server architecture
we have client requests for service to server
and server provides service to client. One
client can get service from more than one
server and similarly one server can
provides the service to multiple clients.
Same fundamental is used at here. Class
is act as server and program acts as client.
Main program (Client) can use more than
one class (berver) similarly one class
(server) can be used for more than one program (client).

34

Long Questions

Q. 30 Explain types of Primary Data Type.

Ans. In C++ language primary data types are mainly four: int (Integer value), float
(single precision value), double {double precision value), char (Character value). There
are also some other data types but it is combination of all these four data types such as
long int, long float, unsigned int, etc.

Integers are whole numbers. Integer data type variable can be declared as
int
variablename
In 16-bit machine the size of integer type variable is 2 bytes that means it can store
the value from-2LS to (2'5)-l i.e. from -32,768 to +32,767. In 32-bit machine the size of
integer type variable is 4 bytes that means it can store the value from -2 31 to (231)-1 i.e.
from -2,14,74,83,648 to +2,14,74,83,647. Integer data type also can be divided into
different sub type.
a.
Signed Integer :
Signed integer is a number, which contains either positive or negative sign.
Signed integer variable can be declared using
signed
int
uariablename

By default integer is signed type of variable.


b.

Unsigned Integer :
The unsigned integer has not posses the size so you cannot represent sign with
this number. But it provides the facility to store higher value using same number
of bytes. In 16-bit machine the size of unsigned integer is 2 bytes but it can
store the value from 0 to 65,535.
unsigned
int
variablename

Question Bank of CPU


c.

35

Long Integer :
If you have to store higher value than the given range then there is use of long
integer. In Jong integer for 16-bit machine there is use of 4 bytes so we can
represent the value from -2,14,74,83,648 to +2,14,74,83,647.
long

int

uariablename

Unsigned long integer can represent the value from 0 to 4,294,967,295.


unsigned

long ,

int

uariablename

d.

Short Integer :
It occupies only 2 byte In 16-bit machine. That means your can represent the
number from -32,768 to 32,767.
short int
uariablename
Float Data type Float variable can contain any rea! number. It represents the value with single precision.
In 16-bit machine the size of float variable is 4 bytes. We can represent the value from
3.4E-38 to 3.4E+38 by using float variable. Float variable cannot be have any signed or
unsigned characteristic. We cannot use signed and unsigned format for the float variable.
Double Data type ;
Double data type is used to declare the variable for any real number but it represents
the value with double precision. In 16-bit machine the size of double variable is 8 bytes.
We can represent the value from 1.7E-308 to 1.7E+308 h\ using the double data type.
There is also another data type long doubic in which 10 bytes are required in memory.
The range for the long double variable is 3.4E-4932 to 1.1E+4932 We cannot use
signed and unsigned format for the float variable. Character Data type :
A single character can be defined as a character (char) data type. The size of the variable
declared as char is 1 byte. We can use two kind of character variable :
a.
Signed character :
Whenever you not specify any qualifier by default character variable is signed
character. We can represent the value from -128 to +127 by using singed character
b.
Unsigned character:
Whenever you declare the character as the unsigned character type you can
represent the value form 0 to 255
We can also represent the *void' as the primary data type. Variable of type Void' doesn't
hold any value but it is mainly used for the return value and in pointer. In C void is
not a primary data type.

Long Questions
Q. 31 Explain Virtual Functions
Ans. Virtual function is example of runtime polymorphism. In virtual function we
have pointer of base class, which can point to either base class obje-n or derive class
object depending of address oi object assigned to painter variable.
When we use the same function name in both the base and derived classes, the
function in base class is declared as urrtual using the keyword virtual before the
function declaration. class Base
! public :

void baseGwnf ) [
cout "It is base class own Function \n";

void sirnFun( ) ]
cout "It is simple function in base class\n B ;

virtual void virFun( } j


cout "It is virtual function is base class\n;

class Derive : public Base J


public :
void deriveOwn( ) |
cout "H is derive class own function\n;
}

void simFunt ) ]
cout "It is simple function in derive ctass\n";

void virFunf ) {
.cout "It is version of virtual function ir
derive class\n";

37
void main( ) {
Base *p; Base b;
Derive d;
p = &b;
// Pointer points to base class
p -;> baseOwnf );
// Call from base class
p -? simFunl I;
// Call from base class
p > virFun( );
// Call from 'base class
p = otd;
// Pointer points to derive class
p -> deriveOwn(); // Cannot call. Give
// compilation error. p
-> simFunf );
// Call from base class
// because it is not inrtual
p -> virFun( };
// Call from derive class
ij

Rules for Virtual function :


1. The virtual function must be member of some class. 2
It cannot be static function.
3. It can only accessed by pointer variable but not by simple object
variable.
4. It can be a friend of another class.
5
It must be defined in base class although it is not used in base class.
It is not necessary to define the virtual function in derive class.
6. Virtual function defined in base class and derive class have same
number of arguments, same type of argument, and same return type
otherwise it is considered as function overloading by compiler.
7. We cannot have virtual constructor but we have virtual destructor.
8. Pointe of base class can point to object of derive class but vice-a-versa
is not true.

Q. 32 List all Operator In C and explain them.


Ans. Operators are used with operands to build expressions. An operator computes
new values out of old ones. An expression consists of variables, constants, and
operators combined to perform some useful computation. For example the following
is an expression containing two operands and one operator.

38

Long Questions

c= a+b
The following list of operators is probably not complete but does highlight the common
operators and a few of the outrageous ones....
(1)
Arithmetic Operator
(2)
Relational Operator
(3)
Logical Operator
(4)
Assignment Operator
(5)
Conditional Operator or Ternary Operator
(6)
Increment(++) - Or -Decrement Operator()
(7)
Size of Operator
(8)
Comma Operator
(9)
Bitwise Operator
ARITHMETIC OPERATOR :
The basic operators for performing arithmetic are the same in many computer languages:

The - operator can be used in two ways: to subtract two numbers (as in a - b), or to negate
one number (as in -a + b or a t -b).
When applied to integers, the division operator / discards any remainder, so 1 / 2 is 0 and
7 / 4 is 1. But when either operand is a floating-point quantity (type float or double), the
division operator yields a floating-point result, with a potentially nonzero fractional part.
So 1 / 2.0 is 0.5, and 7.0 / 4.0 is 1.75. The modulus operator % gives you the remainder
when two integers are divided.
1 % 2 is I; 7 % 4 is 3. (The modulus operator can only be applied to integers.)
An additional arithmetic operation you might be wondering about is
exponentiation. Some languages have an exponentiation operator (typically ' or **), but C
doesn't. (To square or cube a number, just multiply it by itself.) Multiplication, division,
and modulus all have higher precedence than addition

and subtraction. The term "precedence" refers to how "tightly" operators bind to their
operands (that is, to the things they operate on). In mathematics, multiplication has
higher precedence than addition, so 1 + 2 * 3 is 7, not 9. In other words, 1 + 2 * 3 is
equivalent to 1 + (2 * 3). C is the same way. All of these operators "group" from left to
right, which means that when two or more of them have the same precedence and
participate next to each other in an expression, the evaluation conceptually proceeds
from left to right. For example, 1 - 2 - 3 is equivalent to (I - 2) - 3 and gives -4, not +2.
("Grouping" is sometimes called associativity, although the term is used somewhat
differently in programming than it is in mathematics. Not all C operators group from left
to right; a few group from right to left.)
Whenever the default precedence or associativity doesn't give you the grouping you want,
you can always use explicit parentheses. For example, if you wanted to add 1 to 2 and
then multiply the result by 3, you could write (1 + 2) * 3.
Q. 33 What are the Limitation of Computer ?

Ans. With the formation of powerful features of a computer, it may seem that the
solution to any problem in this world is possible with the help of computers, but it
is not so. Although computers possess several superhuman advantages, they do
not have the thinking capacity or the cornmonsense. They do not understand
anything and so they do not have brains. This is becuase computer is merely a
combination of electronic circuits in which bits of information and data travel with
lightning speed. In other words, computers lack the intelligence and common sense
of human beings. It does not have the sense of feel, touch, smell, sight and hearing.
One can sum up the following as the limitations of a computer.
Computers cannot operate or function by itself without the assistance
of human beings.
It cannot identify any problem of the world on tts own that requires a
solution.
It cannot identify the input/output needed to solve a problem.
It cannot identify and collect the data needed to produce any desired
output.
It cannot design or develop its own software that is necessary to
transform any data into a desired output.
Computers cannot interpret and use information that is stored in a
computer.

X X X

1*1 2*1 3*2*1 4*3*2*1


5*4*3*2*1 6*5*4*3*2*1

Continue Statement:

The continue statement skips the remaining statements in the body of the loop, and continues
with the next iteration of the loop.

Example: Write your own program that reads integers given by keyboard and applies
following rule above them: if the given number is smaller than zero, program should print
error message and stop reading numbers. If the given number is bigger than 100, it should be
skipped and program should rfad another number. All other numbers should be red and
printed. Program must stop reading numbers when 0 or error shows up.

ffinclude <stdio.h>
void main() {
int x; do{
printf ("Input number :\n"];
scanf(a%d", &x ); if (x < 0) {
printf("Not allowed value\n");
break;
/* escapes the loop */ 1
I

if (x > 100) i
print!("Skipping the value\n");
continue; /* jumps to second
iteration */

printf ("Given number is : %d", x);


while (x != 0);

iii).Explain Following String Manipulation Functions.

05

Strcmp(),strlen(),strcat(),strstr(J,strchr().
ANS:
I

Strcmp():

Syntax:
^include <string.h>
int strcmp' const char *strl, const char *str2 );
Description:
The function strcmpQ compares strl and str2, then returns:
Return value

Explanation

less than 0
equal to 0*
greater than 0

strl is less than str2


s*rl is equal to str2
strl is greater than str2

strlenf)

Syntax:
strlen( char *str );
Description:
The strlenQ function returns the length of str (determined by the number of
characters before null termination).
strcat():

Syntax:
char *strcat( char *strl, const char *str2 };
Description:
The strcatQ function concatenates str2 onto the end of strl, and returns strl,
strstr(): Syntax:
char *strstr( const char *strl, const char *str2 );
Description:

The function strstrO returns a pointer to the first occurrence of str2 in strl, or NULL
if no match is found.
strchr():
Syntax-char *strchr( const char
*str, int ch ); Description:

The function strchrQ returns a pointer to the first occurence of ch in str, or NULL
if ch is not found.
OR
Q-3 Do as Direct

i)

Draw Flow chart to do the sum of 10


elements read from user.

05

ii)

List out Operators used in C Language and


explain any Four with Example
Ans:

1)
2)
3}
4)
5)
6)
7]
Ex

05

Arithmetic operator
Logica1 operator
Assignment operator
Relational operator
Conditional operator
Bit-wise operator
Special operator
planations:

Arithmetic Operator

+
/
*

Addition
Subtraction
Division
Multiplication

modulo
Decrement (post and pre)
++
Increment (post and pre)
Arithmetic cperator are used for arithmetic operation.
Assignment

These all perform an arithmetic operation on the lvalue and assign the result to the
lvalue.
Here is the full set.
*=
Multiply /=
Divide.
%=
Modulus.
+=
add.
Subtract. =
left
shift.
=
Right
shift.
&=
Bitwise AND.
bitwise exclusive OR (XOR).
1=
bitwise inclusive OR.

104______________________________GTU Dec. OS Paper with Answer


Logical/Relational

==
Equal to !=
Not equal to
>
<
>
=

Logical AND | |
Logical OR !
Logical KOT These
operators are used for Logical and Relational operation.
Bitwise

&
AND (Binary operator)
|
inclusive OR exclusive
OR
shift left.

shift ri^ht.
one's complement These operators are
used for Bitwise operation
III).

what do you mean by constant in C language?


Explain types of constants in detail.

Ans:

Constants
A constant value is the one which does not change during the execution of a
program. C supports several types of constants.
1. Integer Constants

2. Real Constants
3. Single Character Constants
4. String Constants

04

Question Bank of CPU

105

Integer Constants An integer constant is a sequence of digits. There are 3 types of


integers namely decimal integer, octal integers and hexadecimal integer.
Integers consists of a set of digits 0 to 9 preceded by an optional + or - sign.
Spaces, commas and non digit characters are not permitted between digits. Example
for valid decimal integer constants are
123
-3100
Octal Integers constant consists of any combination of digits from 0 through 7 with a
0 at the beginning. Some examples of octal integers are
O26
O
O676

Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets


from A to F or a to f The alphabets A to F refers to 10 to 15 in decimal digits. Example
of valid hexadecimal integers are

0X2
f

OX8C
Single Character Constants

A Single Character constant represent a single character which is enclosed in a pair of


quotation symbols.
Example for character constants are '5'
All character constants have an equivalent integer value which are called ASCII
Values.
String Constants

106

GTU Dec. OS Paper with Answer

A string constant is a set of characters enclosed in double quotation marks. The


characters in a string constant sequence may be a alphabet, number, special character
and blank space. Example of string constants are "1234" 'God Bless"
Backslash Character Constants [Escape Sequences]

Backslash charactei constants are special characters used in output functions. Although
they contain two characters they represent only one character. Given below is the,
table of escape sequence and their meanings.

Constant

Meaning

*\'

.Audible Alert (Bell)

'\v

. Backspace

'\F

. Formfeed

'\n'

.New Line

.Carriage Return

'\t'

.Horizontal tab

'\v

.Vertical Tab

.Single Quote

t\ r

.Double Quote

'\?'

.Question Mark

'\V

.Back Slash

'\0'

.Null

Question Bank of CPU

] 07

Q-4) Do as directed
i)

What is Pointer? Write a program to do swapping


of two elements using pointers.

05
Ans:
In c a pointer is a variable that points to or references a memory location in which data
is stored. Each memory cell in the computer has an address that can be used to access
that location so a pointer variable points to a memory location we can access and
change the contents of this memory location via the pointer.
Pointer declaration:
A pointer is a variable that contains the memory location of another variable. The
syntax is as shown udow. You start by specifying the type of data stored in the location
identified by the pointer. The asterisk tells the compiler that you are creating a pointer
variable. Finally you give the name of the variable,
type * variable name
Example:
int *ptr; float
'string;
Address operator:
Once we declare a pointer variable we must point it to something we can do this by
assigning to the pointer the address of the variable you want to point as in the following
example:
ptr=&num;
Program:
include <stdio.h> void
changejint *,int*);
int main ()

i inta=2,b=5;

108

GTU Dec. 08 Paper with Answer

printfTBefore i a=%d,b=%d\n",a,b);
change(&a,&b);
printff After : a=%d,b=%d\n",a,b);
return 0;
}
void change(int *a,int *b){
*a += *b; *b = *a-*b; *a =
*a-*b; I
ii)

List out the categories of functions. Explain


any one category with example.

Ans:

Types of functions:

A function may belong to any one of the following categories:


1. Functions with no arguments and no return values.
2. Functions with arguments and no return values,

3. Functions with arguments and return values.


Functions with no arguments and no return values:

Let us consider the following program


/* Program to illustrate a function with no argument and no return values*/
tt include
rnainQ
i
staetemtnlQ;
starlineQ;

05

Question Bank of CPU

109

statement2();
starline(|;
1
/'function to print a message*/
state mentlQ

j
printf("\n Sample subprogram output");
!
state men t2Q

printf("\n Sample subprogram output two");

starlineO

int a;
for (a=l;a<60;a+-t-)

printfr\n");

In the above example there is no data transfer between the calling function and the
called function. When a function has no arguments it does not receive any data from
the calling function. Similarly when it does not return value the calling function does
not receive any data from the called function. A function that does not return any
value cannot be used in an expression it can be used only as independent statement.

Question Bank of CPU


1]
110
___________________GTU_Dec. 08 Paper with Answer
iii)

State difference between Structure and Union.

04

Ans: Union allocates the memory equal to the maximum memory required by the
member of the union but structure allocates the memory equal to th" total memory
required by the members.
In union, one block is used by all the member of the union but in case of
structure, each member has their own memory space
All the members of the structure can be accessed at once, where as in an union only
one member can be used at a time. Another important difference is in the size allocated
to a structure and an union.Structure

Union

- More memory is occupied


- All the members of structure
can be accured at once.
for e.g.: struct
example
{
int
integer;
float
floating_numbers;

- Memory allocation is less


- In union only one memory
can be used at a time.

the size allocated here is


sizeoff in t)+sizeof (float);
where as in an union
union example
!
int
integer;
floating_nuir.bers;

float

I
size allocated is the size of the highest member.
so size is=sizeof(flo;>t);
OR
Q-4) do as directed.
i) Write a program to find out sum of 6
elements of array using pointer.

05
N

^include <iostream.h>

Question Bank of CPU


Void mainQ

Int *-;ot,I,total=0;
Int x[]={10,20,30,40,50,60:;
Tot =&x{0];
For(i=0;i<=5;i++)

i
Total= total + *tot;
Tot++;

ii) What is scope, visibility and life time of variables?


Explain static variable with example.

05

The lifetime of a variable is the interval of time for which the variable exists; i.e.
the time from when it is created to when it is destroyed; duration, span, or
extent are equivalent terms for the same thing.
It is common to find confusion between scope and lifetime - thoagh they are in
cases related, they are entirely different notions: lifetime is to do'with a period
of time during the execution of a program, scope is to do with which parts of a
program text. In Java, lifetime is dynamic - you must execute the program (or
do so in a ihought experiment) in order to determine it. Scope is static
-determinate at compile time, or by reading the program text.

In the case of local variables (local to blocks or functions), and where there are
no scope-holes, lifetime and scope correspond: scope is the remainder of the
block / function after the variable definition; lifetime is the whole time that
control is in that part of the program from the definition to the end of the block
/ function.

112

GTU Dec. 08 Paper with Answer


tfinclude -=iostream.h>
class myclass

static int ';


public:

void setln*(int n) 1 i =
n;
1

int getlntQ {
return i;

int myclass::i;
// Definition of myclass::i. i is still private to myclass.

int rnain()
{ myclass object 1, object2;

object l.setlnt( 10);

cout "objectl.i: " object l.getlnt() '\n'; // displays 10 cout


"object^.i: " object2.getlnt() '\n'; // also displays 10

Question Bank of CPU

113

return 0;

iii) State the difference between entry control loop


and exit control loop.

04

In general both the while loop and do-while loop are iterative control structures
in any programming language. Both are conditional loops because these are
based on conditions (Boolean expressions). The value of Boolean expression
(true /false) determines whether the loop exits or. not. But there is a little
difference in their way of iterating. The basic difference is in the time of
checking the condition during execution of loop. !n while locp the condition
is checked at the start, if it is true then statements enclosed in the loop structure
are executed , otherwise the loop exits and control transfers to the statements
following this loop and this process continues until the condition becomes
false. Also is there a way to run a controLloop in the background so that I don't
have to enter a character to continue the loop with each entry. Initiaily I have I t
set up so that I enter "c" from a menu to enter checks, and then for each
additional entry I have to say "c" to repeat the loop for another entry. (In other
words I wouid like to just be able to enter a loop and stay there until I am done
entering the checks, and then just hit "x" or whatever to exit the loop, without
having to restart the loop with each entry.)
Q-5 Do as Directed.
1)

Explain the concept of class, object, polymorphism and inheritance.


04
A class is a programming language construct that is used as a blueprint to
create objects. This blueprint includes attributes and methods that the created objects
all share.

Usually, a class represents a person, place, or thing - it is an abstraction of a


concept within a computer program. Fundamentally, it encapsulates the state and
behavior of that which it conceptually represents. It encapsulates state through data
placeholders called member variables; it encapsulates behavior through reusable code
called methods.

114

GTU Dec. O8 Paper with Answer

Object-oriented software is all about objects. An object is a "black bos" which


receives and sends messages. A black box actually contains code (sequences of computer
instructions) and data (information which the instructions operates on). Traditionally,
code and data have been kept apart.
Polymorphism means any forms, it refers to the capability of objects to react
differently to the same method. Polymorphism can be implemented in the Java language
in the form of multiple methods having the same name. Java code uses a late-binding
technique to support polymorphism; the method to be invoked is decided at runtime.
Generally speaking, objects are defined in terms of classes. You know a lot about an
object by knowing its class. Even if you don't know what a penny-farthing is, if 1 told
you it was a bicycle, you would know that it had two wheels, handle bars, and pedals.
Object-oriented systems take this a step further and allow classes to be defined
in terms of other classes. For example, mountain bikes, racing bikes, and tandems are
all different kinds of bicycles, in object-oriented terminology, mountain bikes, racing
bikes, and tandems are all subclasses of the bicycle class, Similarly, the bicycle class
is the uperclass of mountain bikes, racing bikes, and tandems.

Hierarchy of Classes
Bicycles

Mountain Bike:

Racing Bikes

Tandem Bikes

ii) Expl ain stricture ofclasswithexample.

05

The C++ class is an extension of the C language structure. Because the only difference
between a structure and a class is that structure members have public access by
default and class members have private access by default, you can use the keywords
class or struct to define equivalent classes.
For example, in the following code fragment, the class X is equivalent to the structure
Y:
class X |

/ / private by default
int a;
public;
/ / public member function
int fQ { return a = 5; };

struct Y j

/ / public by default int


f() ! return a = 5; [;
private:
/ / private data member int
a;
i.
Ti

If you define a structure and then declare an object of that structure using the
keyword class, the members of the object are still public by default. In the following
example, mainQ ha", access to the members of obj__X even though obj_X has been
declared using an elaborated type specifier that uses the class key class:
#include ^iostream.h>

116

GTXJ Dec. O8 Paper with Answer


struct X i
int a; intb;

l;
class X obj_X;
int raainQ \ obj_X.a = 0; obj_X.b = 1; cout "Here are a and b: "
obj_X.a " " obj_X.b endl;
!
The following is the output of the above example:
Here are a and b: 0 1

ill)

What is inline function? Explain with example,


05
The point of making a function "inline" is to hint to the compiler that it is worth
making some form of extra effort to call the function faster than it would otherwise
-generally by substituting the code of the function into its caller. As well as eliminating
the need for a call and return sequence, it might allow the compiler to perform certain
optimizations between the bodies of both functions.
When the campiler inline-expands a function call, the function's code gets
inserted into the caller's code stream (conceptually similar to what happens with a
tfdefine macro). This can, depending on a zillion other things, improve performance,
because the optimizer can procedurally integrate the called code ~ optimize the called
code into the caller.
Suppose that you wish to write a function in C to compute the maximum of two
numbers. One way would be to say:
int max(irit a, int b)
\

return (a > b ? a : b);


But calling a frequently-used function can be a bit slow, and so you instead use
a macro:
#define max(a, b) ((a) > \b) ? (a) : (b)) The extra
parentheses are required to handle cases like:

Question Bank of CPU

117

maxfa = b, c = d)
This approach can -work pretty well. But it is error-prone due to the extra
parentheses and also because of side effects like:

max(a++, b++)
An alternative in C++ is to use inline functions:
inline int max^int a, int b)

return (a > b ? a : b);


If an inline function is a member function of a C++ class, there are a couple of
ways to write it:
class A {
public:
void fl) | /* stuff*/ 1

or:

// "inline" not needed

inline functionO'class A !
public:
inline vo.d f();

I;
inline void A::f()

inline function!);

main
() f
inline
function();

/* stuff*/
1

The "inline" keyword is merely a hint to the compiler or development environment.


Not every function can be inlined. Some typical reasons why inlining is sometimes not
done include:
- the function calls itself, that is, is recursive
- the function contains loops such as for(;;) or while ()
- the function size is too large

OR

118

GTU Dec. OS Paper with Answer

Q-5 Do as Directed.
I) Give the difference between object oriented
language and procedure oriented language.

object oriented language

procedure oriented language

1,
Object
Oriented
programming deals with
the elemental basic parts
or building bio -ks of the
problem .

1. Procedural program m ing focuses on


the steps requited lo produce the de-.ired
ou tcom e .

2. Object Orientation (OO|


in
general,
is
a
methodology for modeling
the real world or at least
the problem being solved,
by
decomposing
the
problem
into smaller
discrete
pieces
called
"Objects".

2. Procedural Programming, by contrast,


is a methodology for modeling the real
world or the .problem being solved, by
determining the steps and the order of
those steps that mustbe followed in order
to reach a desired outcome or specific
program state.

3. "Objects'1 will make up


every part of th e solution .
th at is. every part of the
program will be made from
objects. Formally, there are
technical attributes of that
must be p/esent for a
program (or a
program ming language) to
be
considered
Object
Oriented,
such
as
inheritance,
polymorphism,
encapsulation

3 . For exam pie. consider the problem:


"calculate the month end closing balance
for an account." The process is take the
starting balance, subtract all the debits
and add all the credits for the period and
then you arrive closing balance. The key
point for procedural programming is
identification and articulation of the
process or sleps that must be followed.

4.
Object
Oriented
programming
provides
tools to deal with these
objects, such as "a hook,"
in the abstract world of
writing software more
logically and naturally.

4 .Procedural provides a way of solving the


problem or a way of thin king about tlie
problem, not the language used to write
th e codp.

5.
Object
Orierted
Languages have the ben e
fit of su pportin g ke v aspect
i,f O bject Orientation in
the language itself making
il easier to im pie n en t
Object Oriented programs.

5 .The key point for procedural


programming is identification and
articulation of the pro cess or steps that
m ust be followed

04

Q u e s t i o n B an k o f C P U
9
11} Explain friend function with example.

1 ]
05

A friend function is a non member used for accessing the private members of a
class. A class can allow non-member functions and other classes to access its own
private data, by making them friends. Thus, a friend function is an ordinary function
or a member of another class.
The friend function is written as any other normal function, except the function
declaration of these functions is preceded with the keyword friend. The friend function
must have the class to which it is declared as friend passed to it in argument.
Some important p>mts to note while using friend functions in C++:

The keyword friend is placed only in the function declaration a' the friend
function and not in the function definition.

It is possible to declare a function as friend in any number of classes.


When a class is declared as a friend, the friend class has access to the
private data if the class that made this a friend.
A friend function, even though it is not a member function, would have the
rights to access the private members of the class.
It is possible to declare the friend function as either private or public.
The functior. can be invoked without the use of an object. The friend function
has its argument as objects, seen in example below.
Example of mend function.
^include

exforsys

1
private:

class

120 __ GTU Dec. OS Paper with Answer


int a,b;
public:

void

test()

a=100;

b=200;

friend int compute(exforsys el)


//Friend Function Declaration with keyword friend and with the object of
class exforsys to which it is friend passed to it

int compute,exforsys el)

//Friend Function Definition which has access to private data


return intle1 .a+e2.b)-5;

Question

Bank

of

CPU

121
mam()

exforsys e;
e.test{);
cout^The result is:"coraputefe);
//Calling of Friend Function with object as argument.

iii) What are the characteristics of constructor?


Explain hov/ to initialize the variable using constructor.

OS

Constructor Is a special Member function, which is having the Same Name as


class Name, and they are called Implictely when Object of class is created.
And Calling of Constructor Is very Important for Object Intializntion. If We are Net Specifying a Constructor then C++ Compiler provide Default
constructor
(Which Constructor Having Zero Argument List. That Mean No-Body
constructor.)
Constructor with zero arg. is called default constructor.
And Conctructor Can not be Virtual and static.
And Constructor Can be Private , Public, and Protective but genrally they
are Public.

GTU Dec. 08 Paper with Answer


GUJARAT TECHNOLOGICAL UNIVERSITY
B.E. all Sem-I Examination December 08/January 09
Computer Programming and Utilization ( 1 10003)

Q-l.
(a)

Attempt following programs in C/C++ language.


Write a program to read two matrix from the user and store the
Multiplication of two matrix in the resultant matrix.

i.e. C = A* B.
Solution:

#inc!ude< stdio. h >


#include<conio.h>
void main()
f

int aI3][3], b[3][3], mul[3][3];


int i, j, k;
clrscr();
printf("\n Enter First Matrix : \n");

printf("\n Enter value of a[%d||%d|=


scanf("%d",

,ij);

printf("\n Enter Second Matrix : \n");


for(i=0;i<3;i++)

printf("\n Enter value of b[%d]I%d]= ,ij);


scanf("%d,

for(i=0;i<3;i++)

05

Question Bank of CPU

85

mul|i)LJ!=0;

prinif("\n Multiplication of matrix is : \n");


for(i=0;i<3;i++)
I

printf("%d\t",

getchf);
1
Output:

Enter First Matrix : Enter


the value of a|0][0]= 1 Enter
the velue of a[0)|l]= 1 Enter
the value of a[0][2]= 1 Enter
the value of a|l][01= 2 Enter
the value of a(l]|l]=2 Enter
the value of a[l||21= 2 Enter
the value of a(2][0]= 3 Enter
the value of a[2]| l]= 3 Enter
the value of a[2][21= 3
Enter Second Matrix : Enter
the value of blO][0]= 1 Enter
the velue of b[0]jl]= 2 Enter
the value of b|0)[2]= 3

86

GTU Dec. O8 Paper with Answer


Enter the value of b(i ](0]= 1
Enter the value of b[l][lj= 2
Enter the value of b[l]{2|= 3
Enter the value of b[2]jO]= 1
Enter the value of b[2]fl]= 2
Enter the value of b[2]{2j= 3
Multiplication of matrix is :
3
6
9
6
12
18
9
18
27

(b)

Write a program to generate Fibonacci series of n


given numbers using function
named fibbo.
i.e. 1, 1 , 2 , 3 , . . . .
Solution:
# include <stdio.h>
# in elude <conio.h>
void fibbo(int);
void main()
I
int
n;
clrscrf);
prinlf("How many numbers do you want? : ");
scanf{"%d", &n); fibbo(n); getch(); J
void fibbo(int x)
{

int a=0,b=l,c,d=l;
printfrYour Fibonacci series is as below :\n");

while (d<=x)

i
printf{"%d, ,b);

05

Question

Bank

of

CPU

87
c = a + b;
a = b;

Output:

How many rumbers do you want? : 5


Your Fibonacci series is as below : 1.
1 , 2 , 3 , 5,
(c)

Write a C++ program which is having class named student.


It has two functions
04
named readdalaQ and writedataf). It has member elements called studlD, sludname,
studphno, studpercentage. Assume suitable data type for variable. And read th>:
data element from the user and print the same on the screen using member
functions. Solution:
#include<ioF.tream.h>
#include<conio.h>
class student
int
studlD;
char
studname[20]; long int
studphno;
float
studpercentage;
public:
void readdata(); void
writedataQ;

// MEMBER FUCTION DFFITION


void- student :: readdataj)

!
cou.t"\ n******* ****************** **"endl' cout"\n
ENTER STUDENT INFORMATION "endl:

88______________________>_____________GTU Dec. OS Paper with Answer


cout*\n**"*********i***********i*"endl;
cout"\ri Enter Student ID: ";
cinstud!D;

cout"\n Enter Student Name: ";


cmstudname;
cout-'<"\n Enter Student Phone No.: ";
cin>=>studphno;
cout"\n Enter Student Percentage: ";
cin>~-studpcrcentage;
I
i

void student :: writedata() j


cout*\n\n*********************"endl;
cout"\n STUDENT INFORMATION "endl;
cout"\n*********************"endl;
cout"\n Student ID
: "studIDendl;
cout :<"\n Student Name
: "studnameendl;
cout"\n Student Phone No. : "studphnoendl;
cout"\n Student Percentage: "studpercentageendl;

//
MAINFUCTION
void mainj) i
student
si;
clrscr();
-sl.readdata();
sl.w/itedata();
getchQ;

Output:
ENTER STUDENT INFORMATION

Student ID

:1

Student Nat.ie
: Rajesh
Student Phone No. :9527012345

Question Bank of CPU

89

Student Percentage: 60
********************!

STUDENT INFORMATION
Student ID
:1
Student Name
: Rajesh Student
Phone No. : 9527012345 Student
Percentage: 60

Q2:

Do as directed.

07

Find out the output of following C code. Assume ali the libraries has been
included a:.d code is syntactically correct.

void mainfj
{
char cAddressjSOj = "Gtu Examination";
int iX = 67584;
float fZ = 95.7658;
prin tfT%.6s VriVAddress);

printf("%7s\n",cAddress);
prindr%010d\n",iX);
printfr%10d\nViX);

printfl'%*.*f\n1',7,21fZ(;
printfrfceXn", (Z);
printff%12.4e\n, -fZ);

Output:
G t
G t
0 0

u
u
0

9
5

E
0

a
2
2
7
8

0
7

m I
0 4
0 4

n a
8
8

+ 0
E + 0

1
1

i o

Question Bank of CPU


90__________________________________GTUJJec. OS Paper with Answer
ii)
Find out the error if any in the following code and correct it and give the
output.
void main()

!
intiNo[3] = J10,20,30,40;:
char cNamej] = "exam"; char
cMidd[] =
"university";
strcpy(cName,
cMidd);
printf("%d", iNo[0|); printf ("%s",
cName};

void main{)
i
int iMo[4] = !10,20,30,40|; char
cNamejS) = "exam"; char
cMidd[l 1] =
"university";
printfr%d",
iNo[0]);
strcpy(cName, cMidd); printf
("%s", cName);

Output:

10
,
university
(b)
Attempt any two.
i)
What is structure? How do we declare and access structure variables?
Answer:
A structure is a collection of one or more variables grouped under a single
name for easy manipulation. The variables in a structure, unlike those
in an array, can be of different variable types. A structure can contain
any of C's data types, including arrays and other structures. Each variable
within a structure is called a member of the structure. The next section
shows a simple example.

07

Question

Bank

of

CPU

91
You should r.tart with simple structures. Note that the C language makes
no distinction between simple and complex structures, but it's easier to
explain structures in this way.
-> Defining and Declaring Structures
struct tag

!
structure_member(s);
I*
additional
statements may go here */ } instance;
The struct keyword is used to declare structures. A structure is a collection
of one or more variables (structure^members] that have been grouped
under a single name for easy manipulation. The variables don't have to
be of the same variable type, nor do they have to be simple variables.
Structures ;Jso can hold arrays, pointers, and other structures.
The keyword struct identifies the beginning of a structure definition. It's
followed by a tag that is the name given to the structure. Following the
tag are the structure members, enclosed in braces. An instance, the actual
declaration nf a structure, can also be defined. If you define the structure
without the instance, it's just a template that can be used later in a
program to declare structures. Here is a template's format:
struct tag
{

stmcture_member(s);
I* additional statements may go here */

};
To use the template, you use the following format:
struct tag instance;
To use this tbrmat, you must have previously declared a structure with
the given tag.
Example 1
/* Declare a structure template called SSN */
struct SSN

92

GTU Dec^ OS j*aper with Answer


int
first_three;
char dashl; int
second_two; char
dash2; int last,
four;

};
/' Use the structure template */
struct SSN customer_ssn;
Example 2

/* Declare a structure and instance together */


struct dat.j
f

(
char
month(2];
char day[2j; char
year[4];
!
current_date;
Example 3

/* Declare and initialize a structure */


struct time
!
int hours;
int minutes;
int
seconds;
}
time_of_birth = [ 8, 45, 0 };
If you're writing a graphics program, your code needs to deal with the
coordinates of points on the screen. Screen coordinates are written as
an x value, giving the horizontal position, and a y value, giving the vertical
position. You can define a structure named coord that contains both the
x and y values of a screen location as follows:

struct coo-d
int
x;
inty;

Question

Bank

of

93
The struct keyword, which identifies the beginning of a structure
definition, must be followed immediately by the structure name, or tag
(which follows the same rules as other C variable names). Within the
braces following the structure name is a list of the structure's member
variables. Yuu must give a variable type and name for each member.
The preceding statements define a structure type named coord that
contains two integer variables, x and y. They do not, however, actually
create any instances of the structure coord. In other words, they dont
declare (set aside storage for) any structures. There are two ways to
declare structures. One is to follow the structure definition with a list of
one or more variable names, as is done here:

struct coo/d i
int
x;
inty;
j first, second;
These statements define the structure type coord and declare two
structures, .Irst and second, of type coord, first and second are each
instances of type coord; first contains two integer members named x and
y, and so does second.
This method of declaring structures combines the declaration with the
definition. The second method is to declare structure variables at a
different location in your source code from the definition. The following
statements also declare two instances of type coord:
struct cooi'd

!
int x;
inty;

!;
/* Additional code may go here */
struct coo-d first, second;
-> Accessing Structure Members

Individual structure members can be used like other variables of the


same type. Structure members are accessed using the structure member

CPU

GTU Dec. 08 Paper with Answer


operator ( . } , also called the dot operator, between the structure name and
the member name. Thus, to have the structure named first refer to a
screen location that has coordinates x=50, y=100, you could write
first.x = 50;
first. y = 100;
To display, the screen locations stored in the structure second, you could
write
1

printf("%d.%d", second.x, second.y};

At this point, you might be wondering what the advantage is of using


structures rather than individual variables. One major advantage is that
you can copy information between structures of the same type with a
simple equa Jon statement. Continuing with the preceding example, the
statement
first = second; is equivalent
to this statement:
first.x = second.x;
first. y = second.y;
When your program uses complex structures with many members, this
notation can be a great time-saver. Other advantages of structures will
become apparent as you learn some advanced techniques. In genera],
you 11 find structures to be useful whenever information of different
variable types needs to be treated as a group. For example, in a mailing
list database, each entry could be a structure, and each piece of
information (name, address, city, and so on) could be a structure member.
ii)
What do you mean by recursive function? Explain with small example.
Answer:
The term recursion refers to a situation in which a function c&lls itself
either directly or indirectly. Indirect recursion occurs when one function
calls another- function that then calls the first function. C allows recursive
functions, and they can be useful in some situations.
For example, recursion can be used to calculate the factorial of a number.
The factorial of a number x is written x! and is calculated as follows:
x! = x * (x-1) * (x-2) * (x-3) * ... * (2) * 1

Question

Bank

of

CPU

95
However, you can also calculate x! like this:
x! = x* (x-l|! Going one step further, you can calculate (x-1)! using the same
procedure:
(x-1)! = {x-l) *(x-2|!
You can continue calculating recursively until you're down to a value of
1, in which case you're finished. The program in Listing 5.5 uses a
recursive function to calculate factorials. Because the program uses
unsigned integers, it's limited to an input value of 8; the factorial of 9
and larger values are outside the allowed range for integers.
Example: Using a recursive function to calculate factorials.
/* Demonstrates function recursion. Calculates the */
/* factorial of a number. */
#include <stdio.h>
int f, x;
int factorialjint a);
void mainj)
t

printff Enter an integer value between 1 and 8: ");


_scanf("%d", &x); if{ x > 8 | | x < 1)
(
printf("Only values from -1 to 8 are acceptable!");

:
else
{
f = factorial(x); printf("%u factorial equals
%u\n", x, f);
I return
0;

int factorial(ir_t a)
{
if(a==
1}
return 1;

GTU Dec. OS saper -vith Answer

96
else
a *= factorial(a-l);
return a;

Output:

Enter an integer value between 1 and 8:


6
6 factorial equals 720
ANALYSIS: The first half of this program is like many < the other
programs you have worked with so far. It starts with comme s on lines
1 and 2. On line 4, the appropriate header file is included For ic input/
output routines. Line 6 declares a couple of unsigned inte^ r values.
Line 7 is a function prototype for the factorial function. Noli :- that it
takes an unsigned int as its parameter and returns an unn ,ned int.
Lines 9 through 25 are the mainQ function. Lines 11 and ' print a
message asking for a value from 1 to 8 and then accept an enU:.- -A value.
*
- f
Lines 14 through 22 show an interesting if statement. Berai a value
greater than 8 causes a problem, this if statement checks the v. 'luc. If it's
greater than 8, an error message is printed; otherwise, the progi,. m figures
the factorial on line 20 and prints the result on line 21. When ou know
there could be a problem, such as a limit on the size of a number, add code
to detect the prohlem and prevent it.
Our recursive function, factorial!), is located on lines 27 through 36. The
value passea is assigned to a. Online 29, the value oTa ischcckC'-: If it's 1,
the program returns the value of 1. If the value isn't 1, a is sci ;qual to
itself times the value of factorial(a-l). The program calls the factorial "unction
again, but this time the value of a is (a-1). If (a-1) isn't equal to 1, l.-otorial()
is called again with ((a-l)-l), which is the same as (a-2). This process
continues until the if statement on line 29 is true. If the value of the factorial
is 3, the fac'orial is evaluated to the following:
3* (3-1) * ((3-1)-1]

Question

Bank

of

97
iii)
Explain conditional operator with small example.
Answer:
The statements
if (a > b)
z - a;
else
z = b;
compute in z the maximum of a and b. The conditional expression, written
with the ternary operator "?:". provides an alternate way to write this
and similar instructions. In the expression
fxprj ? expr2 : expr^
the expression expr; is evaluated first. If it is non-?,ero (true), then the
expression expr., is evaluated, and that is the value of the conditional
expression. Otherwise expr. is evaluated, and that is the value. Only one
of expr, and expr3 is evaluated. Thus to set z to the maximum of a and b,
z = {a > b} ? a. : b;

/* z max(a, b) */

It should be *ioted that the conditional expression is indeed an expression,


and it can be used wherever any other expression can be. If expr, and
expr, are of different types, the type of the result is determined by the
conversion rules discussed earlier in this chapter. For example, if f is a
float and n an int, then the expression
n > 0) ? f : n is of type float regardless
of whether n is positive.
Parentheses are not necessary around the first expression of a conditional
expression, since the precedence of ?: is very low, just above assignment.
They are advisable anyway, however, since they make the condition part
of the expression easier to see.
The conditional expression often leads to succinct code. For example,
this loop pnnts n elements of an array, 10 per line, with each column
separated by one blank, and with each line (including the last) terminated
by a newline.
for (i = 0; i < n; i++)
printf("%6d%c", aji], (i%10==9

| i==n-l) ? '\n': ' *);

CPU

98

GTU Dec. OS Paper with Answer

A newline is printed after every tenth element, and after the n-th All
other elements are followed by one blank. This might look tricky, but it's
more compact than the equivalent if-clse. Another good example is
printf(" You

%d items %s.\n", n, n=--O ? "" :


"s"):

Q-3 Do as Direct
i)

Draw a Flow Chart to find the maximum number


out of three given Numbers.

05

Ans:

ii)
Ans:

What is Program? Explain break ;md Continue with Example

04

A program is set of instructions and instructions are list of direction


that direct the computer to do particular task. Break statement:
It is used to exit from a loop or a switch, control passing to the first statement
beyond the loop or a switch.

Question Bank of CPU


Example:

99

program that tests if the


given number is prime
number.
#include <stdio.h>
^include <math.h>
void main() {

int

main();
statement

main()

i, n, prime=l;

break;
continue;'
statement; *Control transferred to
bottom at loop in
break statement

cotrol transferred to
top of loop in
continue statement

// prime is true

printf|"Input nazural number :*);


scanf("%d", &n);

for( i=2; i<=n-l;


iff n % i == 0 }

// also possible to state if(!(n % i))

prime =0;
break;

// prime is now false

if{ prime )

printf(''%d is prime number !\n", n);


else
printf("%d ii:n't prime number! \n", n};

Vous aimerez peut-être aussi