Question Bank of CPU C Programming
Question Bank of CPU C Programming
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.
Q. 5
Ans.
Ans.
Ans.
Ans. SSI
MSI
LSI
VLSI
ULSI
Q. 9 What is RAM ?
Ans.
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.
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.
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.
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.
Q. 16 Define Flowchart
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.
In this loop user first checks the condition & if the condition becomes true it
will execute the body of loop.
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,
Q. 29 What is gets() ?
Ans.
Q. 30 What is puts() ?
Ans.
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.
Strcpyf ) function assign one string value to other string va!ue in short it copy
the data from one string to another siring.
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.
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. 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.
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.
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. 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.
(b) putchar( )
(c) gets()
(d) puts( ).
Short Questions
26
What is a functions ?
27
28
29
What is a pointer ?
30
31
What is a structure ?
32
33
34
35
36
What is a token ?
37
Define Keyword.
38
39
40
41
42
43
44
What is prototyping ?
45
46
47
48
40
50
X X X
Ans.
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.
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
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.
Q. 5
Q. 6
Ans.
GOTO STATEMENT :
Definition : it is useful for unconditional transfer of control to the named label.
Syntax:
goto identifier ;
Q. 8
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.
>
>
>
>
>
>
Editor
Compiler
Assembler
Operating systems
In general, software can be classified into two types: systems software and applications
software.
Q. 9
Ans.
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)
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.
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
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.
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
Storage class
Visibility
Lifetime
Auto
Static
or block where it is
declared
Only in that function
None
Entire file
Entire program
Global
(global variable)
Q. 17
Ans.
Name
I.
2.
3.
Integer
Character
Floating Point
4.
5.
Void
Declaration Name
int
char
float
double
void
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
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)
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)
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.
!
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.
Ans.
Syntax : do
{
Body Of The Loop
}
while
(test
condition);
Statement X;
Syntax Description:
(1)
(2)
(3)
(4)
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.
29
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
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
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
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
!
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)
Include Statements
Class Declaration
Class function definition
Main program
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.
34
Long Questions
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
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
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
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 ;
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
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
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 */
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
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)
05
ii)
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.
==
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).
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
105
0X2
f
OX8C
Single Character Constants
106
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
*\'
'\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
] 07
Q-4) Do as directed
i)
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=#
Program:
include <stdio.h> void
changejint *,int*);
int main ()
i inta=2,b=5;
108
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)
Ans:
Types of functions:
05
109
statement2();
starline(|;
1
/'function to print a message*/
state mentlQ
j
printf("\n Sample subprogram output");
!
state men t2Q
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.
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
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>
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++;
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
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;
113
return 0;
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)
114
Hierarchy of Classes
Bicycles
Mountain Bike:
Racing Bikes
Tandem Bikes
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
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
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)
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)
or:
inline functionO'class A !
public:
inline vo.d f();
I;
inline void A::f()
inline function!);
main
() f
inline
function();
/* stuff*/
1
OR
118
Q-5 Do as Directed.
I) Give the difference between object oriented
language and procedure oriented language.
1,
Object
Oriented
programming deals with
the elemental basic parts
or building bio -ks of the
problem .
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.
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.
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.
exforsys
1
private:
class
void
test()
a=100;
b=200;
Question
Bank
of
CPU
121
mam()
exforsys e;
e.test{);
cout^The result is:"coraputefe);
//Calling of Friend Function with object as argument.
OS
Q-l.
(a)
i.e. C = A* B.
Solution:
,ij);
for(i=0;i<3;i++)
05
85
mul|i)LJ!=0;
printf("%d\t",
getchf);
1
Output:
86
(b)
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:
!
cou.t"\ n******* ****************** **"endl' cout"\n
ENTER STUDENT INFORMATION "endl:
//
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
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
!
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
};
/' Use the structure template */
struct SSN customer_ssn;
Example 2
(
char
month(2];
char day[2j; char
year[4];
!
current_date;
Example 3
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
CPU
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
:
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;
96
else
a *= factorial(a-l);
return a;
Output:
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) */
CPU
98
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
Q-3 Do as Direct
i)
05
Ans:
ii)
Ans:
04
99
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
prime =0;
break;
if{ prime )