Sie sind auf Seite 1von 35

# Strictly Based on Latest Syllabus Issued by CBSE

## for 2015 Examination

Sample
Question
Papers
solutions
Computer Science
(Based on C++)

Class

OSWAAL BOOKS
Oswaal House 1/11, Sahitya Kunj, M.G. Road, AGRA-282002
Ph.: 0562-2857671, 2527781, Fax : 0562-2854582, 2527784
email : contact@oswaalbooks.com, website : www.oswaalbooks.com

11

Sam pl
e Que s tion Pape r6
1. (a) PUP11andAPPLEIIaretwoexamplesoffourthgenerationcomputers.
[1 mark]
backuppurposes.Typically,dataiswrittentoopticalmedia,suchasCDsandDVDs.
[1 mark]
(c) Inputunitsaredeviceswecanusetogiveinstructions,communicatewithorsenddatatoacomputer.
E.g. keyboard, mouse, barcode scanner, microphone etc.
[1 mark]
(d) Bitisasinglebinarydigitthatcanhaveeithervalue0or1.
[2 marks]
1byte=8bits.
1nibble=4bits.
2. (a) ISCII Indian Standard Code for Information Interchange
[1 mark]
(b) Theformulaforexpressingrealnumbersis:
[1 mark]
1|(1)^S*2^(E127)*(1+F)
where:
Sisthesignbitandso0isunderstoodaspositive(1^0=1).
calculation.
(c) These number systems refer to the number of symbols used to represent numbers. In the decimal
system,weusetendifferentsymbols:0,1,2,3,4,5,6,7,8,and9.
[1 mark]
[1 mark]
(d) (i)
(EB4A)16 =14*163+11*162+4*161+10*160
=57344+2816+64+10
=(60234)10
(ii)
(2C9)16 =2*162 +12*161 +9*160
[1 mark]
=512+192+9
=(713)10
[2 marks]
Data Register

## 1. Dataregisterscanbeassignedtoavarietyof 1. Address registers contain main memory

addresses of data and instructions or they
functions by the programmer. They can be
contain a portion ofthe address thatis used
used with any machine instruction that
performs operations on data.
2. Dataregistersareusedtostoreintermediate 2. Memory address registers are used to store
data values and result when any arithmetic
memory locations.
operation is performed. The registers are
allocatedtothevariablesaccordingtothetype
ofthe operation.
3. (a) Procedural language is a type of computer programming language that specifies a series of wellstructuredstepsandprocedureswithinitsprogrammingcontexttocomposeaprogram.Itcontainsa
[1 mark]
(b) (i) Datamembers:
[2 marks]
Classesusetheconceptofabstractionandaredefinedasalistofabstractattributessuchassize,
weight,andcostandusesfunctionstooperateontheseattributes.Theattributesaresometimes
calledasdatamembersbecausetheyholdinformation.
E.g.:inta,b;//a,baredatamembers
(ii) ObjectMemberfunctions:
Thefunctionsthatoperate onthesedataarecalledas methodsormemberfunctions.
E.g.:Voidgetdata();//memberfunction

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

(c) An enumerated datatype is a user-defined datatype, which provides a way for attaching names to
numbers,therebyincreasingcomprehensibilityofthecode.Thesyntaxofanenumstatementis:
enumshape{circle,square,triangle}
enumcolor{red, blue,green,yellow}
[2 marks]
same functionname tocreate functionsthat perform a variety ofdifferent tasks.
[2 marks]
//Declarations
//Function calls
(e) (i) Since C++ allows us to create hierarchy-related objects, we can build special object-oriented
libraries,whichcanbeusedlaterbymanyprogrammers.
[1 mark]
(ii) C++programsareeasilymaintainableandexpandable.
[1 mark]
(iii) CpartofC++givesthelanguagetheabilitytogetclosetothemachine-leveldetails. [1 mark]
(iv) Extremelyfast, worksverywellfor GUIprogrammingon a computer.
[1 mark]
4. (a) Character setis a setof valid charactersthat a language canrecognise.A characterrepresents any
letter,digitoranyotherspecialcharacter.TheC++hasthefollowingcharacterset:
[2 marks]
Letters:AZ,a-z
Digits:09
Whitespaces:Horizontaltab(>),Blankspace,Carriagereturn(<)Newline,formfeed
(b) (i) A token is a group of characters that logically belong together. The programmer can write a
program by using tokens.
[1 mark]
(ii) C++usesthefollowingtypesoftokens:keywords,identifiers,literals,punctuatorsandoperators.
[1 mark]
[4=2marks]
(c) (i) (a2+b2)=sqrt(pow(a,2)+pow(b,2))
(ii) 2y.2ey+4y=2y*pow(e,2*y)+4*y
(iii) p+q/(r+s)2=p+q/pow((r+s),2)
(iv) b24ac=pow(b,2)4*a*c
(d) aisacharacterliteral.Itsoftypechar.aisastringliteral.Itsoftypeconstchar[2],andrefers
toanarrayof2charswithvaluesaand\0.Inmost,butnotall,contexts,areferencetoawillbe
implicitlyconvertedtoapointertothefirstcharacterofthestring.
[3 marks]
Both
cout<< a;
and
cout<<a;
happentoproducethesameoutput,butfordifferentreasons.Thefirstprintsasinglecharactervalue.
The second successively prints all the characters of the string (except for the terminating \0)
whichhappenstobethesinglecharactera.
(e) (i) Onlyalphabeticcharacters,digitsandunderscorearepermitted.
[3 marks]
(iii) Theuppercaseandlowercaselettersaredistinct.
5. (a) Do-whileloopisnotapretestloop.
[1 mark]
(b) (i) Aswitchstatementisgenerallybesttousewhenyouhavemorethantwoconditionalexpressions
basedonasinglevariableofnumerictype.Theswitchstatementisaconstructthatisusedwhen
manyconditionsarebeingtestedfor.
[1 mark]
(ii) Whentherearemanyconditions,itbecomestoodifficultandcomplicatedtousetheifandelseif
constructs.Nested if/elsestatementsarise whenthereare multiplealternativepaths ofexecution
basedonsomeconditionthatisbeingtestedfor.
[1 mark]

Solutions |

(c) #include<iostream.h>
#include<conio.h>
intmain()
{
inti=0,ua=0,ub=0,uc=0,fail=0;
while(i<=5)
{
switch (i++)
{
case1:
case2:++ua;
case3:
case4:++ub;
case5:++uc;
default:++fail;
}
}
cout<<\nua=<<ua<<\t<<ub=<<ub<<endl;
cout<<\nuc=<<uc<<\t<<fail=<<fail;
getch ( );
return 0;
}
Ans.
ua=2
ub=4
uc=5
fail=6

[3 marks]

(d)

[3 marks]

## (e) Algorithm : Calculate Simple Interest

Step1:inputP,N,R
Step2:SI=(P*N*R)/100
Step3:PrintSimpleInterest=SI
Step4:[EndofAlgorithm]
Stop
Flowchart :

[4 marks]

Start

Input P, N, R

## Calculate Interest = P*N*R/100

Print Interest

Stop

6. (a) Thestrcpy()functionisdesignedtoworkexclusivelywithstrings.Itcopieseachbyteofthesource
stringto thedestinationstringand stopswhentheterminating nullcharacter(\0) has beenreached.
Ontheotherhand,thememcpy()functionisdesignedtoworkwithanytypeofdata. [1 mark]
(b) Anyfunctionprototypes,andtypedefinitionsthatcanbeexportedfromasourcecodefileareputin
a header file. From the point of view of the main application, these functions are external. The
thisitwouldjustreportanundefinedfunctionerror.
[2 marks]
1. Formatted input/output functions
2.Fileoperationfunctions
3. Character input/output functions
4.Errorhandlingfunctions
(c) /*Programto countthenumberofwordsin a string*/
[3 marks]
# include<iostream.h>
# include<conio.h>
# include<stdio.h>
#defineclrscr();
intmain()
{
clrscr( );
char str[80];
intwords=0;
cout<<Enterastring:;
gets (str);
for(inti=0;str[i]!=\0';i++)
{
if(str[i]==)
words++;//Checkingforspaces
}
cout<<The number of words =<<words+1<<endl;
getch ( );
return 0;
}

Solutions |

(d)

7. (a)

(b)

(c)

Output:
Enterastring:Ilovemyfamily
The number of words = 4
1. Power Function - pow(x,y) :
(+1+)[2marks]
Power function pow(x,y) has two parameters
pow(x,y) returnsvalue oftype double
pow(x,y)calculatesx tothepowerofy: pow(2,3)=8.0
xandy calledparameters(orarguments) offunctionpow
2. SquareRootFunctionsqrt(x):
Squarerootfunctionsqrt(x) hasonlyoneparameter
sqrt(x)returnsvalueoftypedouble
sqrt(x)calculatesnon-negativesquarerootofx,forx>=0.0:sqrt(2.25)=1.5
3. FloorFunction-floor(x):
Floorfunctionfloor(x)hasonlyoneparameter
floor(x)returnsvalueoftypedouble
floor(x)calculateslargestwholenumbernotgreaterthanx:floor(48.79)=48.0
When an overloaded function or overloaded operator is called, the compiler chooses the function
declarationwiththebestmatchonallargumentsfromallthefunctiondeclarationsthatarevisible.A
[1 mark]
Anexactmatch
No match or
An ambiguous match
The:(scoperesolution)operatorisusedtoqualifyhiddennamessothatyoucanstillusethem.You
canusetheunaryscopeoperatorifanamespacescopeorglobalscopenameishiddenbyanexplicit
declarationofthesamenameinablockorclass.
[2 marks]
Scope resolution operator is used to uncover the hidden variables. It also allows access to global
versionofvariables.
E.g.,
# include<iostream.h>
intm=10;//globalvariablem
voidmain()
{
intm=20;//localvariablem
cout<<m =<<m<<\n;
cout<<::m=<<::m<<\n;
}
output:
20
10(::maccessglobalm)
Thecallbyvaluemethodofpassingargumentstoafunctioncopiestheactualvalueofanargument
into the formal parameter of the function. In this case, changes made to the parameter inside the
function have no effect on the argument.
[2 marks]
Example:
#include<iostream.h>
voidchangeValue(intvalue);
intmain()
{
intvalue=5;
changeValue(value);
cout<<Thevalueis:<<value<<.<<endl;
return 0;
}
voidchangeValue(intvalue)
{

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

value=6;
}
//Thisdoesntchangethevaluefrom5to6.5isoutput.
(d) /*To print the computer science marksof 40 students in descending order */
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
intmain()
{
int number[40];
inti,j,a,n=40;
cout<<Enter thecomputersciencemarksof40 students<<endl;
for(i=0;i<n;++i)
cin>>number[i];

[3 marks]

/*sortingbegins...*/
for(i=0;i<n;++i)
{
for(j=i+1;j<n;++j)
{
if(number[i]<number[j])
{
a=number[i];
number[i] = number[j];
number[j]=a;
}
}
}
cout<<Themarksarrangedindescendingorderaregivenbelow<<endl;
for(i=0;i<n;++i)
{
cout<<number[i]<<endl;
}
getch ( );
return 0;
}
(e) /*TofindthesumofthediagonalsofasquarematrixA*/
#include <iostream.h>
#include<conio.h>
intmain()
{
intA[5][5],row,col ;
inti,j,d1=0,d2=0;
cout<<Enterno.ofrowsandcolumns(max 5):<<endl;
cin>>row>>col ;
cout<<Entertheelementsofmatrix:<<endl;
if (row==col)
{
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)

[4 marks]

Solutions |

cin>>A[i][j];
}
for(i=0,j=col-1;i<row||j>=0;i++,j)
{
d1=d1+A[i][i];
d2=d2+A[i][j];
}
cout<<\nThesumoffirstdiagonalelements:<<d1<<endl;
cout<<\nThesumofseconddiagonalelements:<<d2<<endl;
}
else
{
cout<<RowsandColumnsarenotequal!!<<endl;
}
getch( );
return 0;
}

Output:
Enterno. ofrowsandcolumns (max 5):
33
Entertheelementsofmatrix:
123
456
789
Thesumoffirstdiagonalelements:15
Thesumofseconddiagonalelements:15
l

Sam pl
e Que s tion Pape r7
1. (a) ROM stands for Read-Only Memory. ROM is typically used to refer to a chip in a computer that
contains permanently stored data.
[1 mark]
(b) Input devices: keyboard, scanner, mouse
[1 mark]
Outputdevices:printer,monitor,speaker
(c) ENIACElectronicNumericalIntegratorAndComputer
[1 mark]
(d) Systemsoftwareisatypeofcomputerprogramthatisdesignedtorunacomputershardwareand
applicationprograms.Ifwethinkofthecomputersystemasalayeredmodel,thesystemsoftware
istheinterfacebetweenthehardwareanduserapplications.
[1 mark]
The operatingsystem (OS) isthe best-knownexample of systemsoftware. The OSmanages all
the other programsin a computer.
[1 mark]
2. (a) Exampleof CISCinstructionsetarchitecture isSystem/360.
[1 mark]
(b) MDRMemoryDataRegister
[1 mark]
baseof16.
[2 marks]
Itusessixteendistinctsymbols,mostoftenthesymbols09torepresentvalueszerotonine,and
A,B,C,D,E,F(oralternativelyaf)torepresentvaluestentofifteen.
(d)

0.275*2 =0.550(0)

[2 marks]

0.550*2 =1.100(1)
0.100*2 =0.200(0)
0.200*2 =0.400(0)
0.400*2 =0.800(0)
0.800*2 =1.600(1)
Hence,

(0.275)10 =(0.010001)2

3. (a) ThefollowingarethebasicconceptsofOOPs:
[1 mark]
Classes,Objects,Dataabstractionandencapsulation,Polymorphism,Inheritance,MessagePassing,
andDynamicBinding.
thatisusedtocreate(orderive)anotherclassiscalledthebaseclass.
[2 marks]
Derived Class :A class that was created based on a previously existing class (i.e., base class).A
derived class inherits all of the member variables and methods of the base class from which it is
derived.
Forexample,abaseclassfurniturecanhavetwoderivedclassestableandchair.Thederived
classestableandchairinheritallofthemembervariablesandmethodsofthebaseclassfurniture.
(c) Alow-levelprogramminglanguageisaprogramminglanguagethatprovideslittleornoabstraction
from a computers instruction set architecture.
[2 marks]
Low-levellanguagescanbeconvertedintomachinecodewithoutusingacompilerorinterpreter,
andthe resultingcode runsdirectly onthe processor.

Solutions |

(d)

[2 marks]

(e) Namespaces are used in C++ programming language to create a separate region for a group of
variables,functionsandclasses.Namespacesareneededbecausetherecanbemanyfunctions,variables
forclassesinoneprogramandtheycanconflictwiththeexistingnamesofvariables,functionsand
classes. C++ uses namespaceto avoid the conflicts.
[4 marks]
Theconceptisshownusingthefollowingdiagram:
Standard
Namespace

User Defined
Namespace

variables

variables

functions

functions

classes

classes

variables
functions
classes

## Thefollowingaresomereasonsdueto whicha conflictcanoccur:

BetweenUserdefinedvariables/functions/classesandbuiltinLibraryvariables/functions/classes
(e.g.sqrt( ),abs( )etc.)
Betweentheseparatelyincludedlibraryandbuiltinlibrary
Betweenthevariables/functions/classesoftheoneseparatelyincludedlibraryandthesameofthe
otherseparatelyincludedlibrary
InC++languagethekeywordnamespacehastobeincludedforcreatingnamespaces.
namespace
{
members of namespace;
}
4. (a) Thelogicaloperatorsareusedtohelpincreatingatestexpressionthatcontrolsprogramflow.This
valuewhenevaluated.
[2marks]

10

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

fortrueor0forfalse.
TherearethreecommonlogicaloperatorsthatgiveaBooleanvaluebymanipulatingotherBoolean
operand(s).
TheC++programminglanguageoperatorswiththeirmeaningsare:
C++Operator

(b)

(c)

(d)

(e)

Meaning

&&

Logicaland

||

Logicalor

Logicalnot

Anexampleis:
6>4&&2<=14
1&&1
or
true&&true
Thefinalevaluationoftheexpressionis:1meaningtrue.
a=3,b=6,c=4,d=2.
[2 marks]
(((a+b)>c)&&((b-c)<d||(b+d)>=(a+c)))
=(((3+2)>4)&&((6-4)<2||(6+2)>=(3+4)))
=((5>4)&&(2<2||8>=7))
=1&&(0||1)
=1&&1
=1(True)
Constantsrefertofixedvaluesthattheprogrammaynotalterandtheyarecalledliterals.
[2 marks]
Constantsaretreatedjustlikeregularvariablesexceptthattheirvaluescannotbemodifiedafter
theirdefinition.
DefiningConstants:
TherearetwowaysinC++todefineconstants:
Using #define preprocessor.
Using const keyword.
Example:
#defineLENGTH10
constintWIDTH=5;
C++allowsthechar,int,anddoubledatatypestohavemodifiersprecedingthem.
[3 marks]
Amodifierisusedtoalterthemeaningofthebasetypesothatitmorepreciselyfitstheneedsof
various situations.
Thedatatypemodifiersarelistedas:
osigned
ounsigned
olong
o short
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For
example,unsignedlongint.
Example:
unsignedinty;
shortunsignedintj;
/*Programtofindareaandperimeteroftriangle:giventhreesides*/
[4 marks]
#include<iostream.h>
#include<conio.h>

Solutions |

5. (a)
(b)

(c)

(d)

11

#include<math.h>
intmain()
{
float a,b,c,s,area,perimeter;
clrscr ( );
cout<<\nEnterthethreesidesofthetriangle:;
cin>>a>>b>>c;
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
perimeter=a+b+c;
cout<<Area=<<area<<endl;
cout<<Perimeter=<<perimeter<<endl;
getch ( );
return 0;
}
Output:
Enterthethreesidesofthetriangle:1048
Area=15.1987
Perimeter=22
A compoundstatement consists ofzero ormore statements enclosedin curly braces({ }).
[1 mark]
/*Programtofindthelargestofany3numbers*/
[2 marks]
#include<iostream>
#include<conio.h>
using namespace std;
intmain()
{
int a,b,c,greatest;
cout<<Enterthreenumbers:;
cin>>a>>b>>c;
greatest=(a>b&&a>c)?a:(b>c)?b:c;
cout<<Largestnumber is<<greatest;
getch ( );
return 0;
}
Output:
Enterthreenumbers:385
Largestnumberis8
if(a<b)
[2 marks]
n=a;
else
n=b;
The jump statementsunconditionally transfers program control within a program / function.
[3 marks]
(i) goto statement
(ii) break statement
(iii) continue statement
(i) Thegotostatement:gotoallowstomakeajumptoanotherpointintheprogram.
goto p;
p:pisknownaslabel.Itisauserdefinedidentifier.Aftertheexecutionofgotostatement,the
controltransferstothelineafterlabelp.
(ii) Thebreakstatement:Thebreakstatement,whenexecutedina switchstructure,providesan
immediate exit from the switch structure. When the break statement executes in a loop, it
immediatelyexitsfromtheloop.

12

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

(iii) Thecontinuestatement:Thecontinuestatementisusedinloopsandcausesaprogramtoskip
therestofthebodyoftheloop.
while(condition)
{
Statement 1;
If (condition)
continue;
statement;
}
Thecontinuestatementskipsrestoftheloopbodyandstartsanewiteration.
(e) Algorithm :
[4 marks]
1. Assignfib=0,i=0,j=1,k=0
2. Gettheno.oftermsuptowhichuwanttogeneratetheFibonaccino,i.e.,N.
4. Assignthevalueofktoji.e.j=k
5. Assignthevalueoffibtoki.e.k=fib
6. WritethevalueoffibtogetnextFibonaccinumberintheseries.
7. incrementiwith1i.e.i=i+1andrepeatstep3,4,5,6withthelastvalueofi=N(Nistheno.of
terms which we want to generate Fibonacci no. series.)
8. Stop

Start
i=0
j=1
k=0
fib = 0

i<N?

No
end

Output
"Fibonacci(i) = fib"

Output carriage
return and linefeed
fib = j + k
j=k
k = fib
i=i+1

Solutions |

13

[1 mark]
(b) 1. Theclassisreusable
[2 marks]
2. The users of the class know what member functions the class provides, how to call them and
what return types to expect
3. The users do not know how the class member functions are implemented.
(c) Anyfunctionprototypes,andtypedefinitionsthatcanbeexportedfromasourcecodefileareputin
[3 marks]
below.
intsum(inta,intb)
{
return(a+b);
}
filewithnamesum.hinINCLUDEorBINfolder.
#include<iostream.h>
#include<conio.h>
intmain()
{
inta,b,s;
clrscr( );
cout<<Enterthevalueofaandb:<<endl;
cin>>a>>b;
s = sum(a,b);
cout << sum= << S;
getch( );
return 0;
}
(d) # include<iostream.h>
[4 marks]
# include<conio.h>
//checkgivencharacterisalphabets,digitoranyothercharacter
intmain()
{
chara;
cout<<Enteracharacter:\n;
cin>>a;
if(((a>=A)&&(a<=Z))||((a>=a)&&(a<=z)))
cout<<YouenteredanAlphabet\n;
elseif(a>=0&&a<=9')
else

14

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

cout<<Youenterednonalphanumericcharacter\n;
getch( );
return 0;
}
7. (a) Thesearevalidcode thecompilerunderstands,buttheydonotdo whattheprogrammer,intended.
[1 mark]
(b) Accessspecifiersdefinestheaccessrightsforthestatementsorfunctionsthatfollowsituntilanother
accessspecifierortilltheendofaclass.Thethreetypesofaccessspecifiersareprivate,public,
protected.
[2 marks]
The members declared as private can be accessed only within the same class and not from
outside the class.
The members declared as public are accessible within the class as well as from outside the
class.
The members declared as protected cannot be accessed from outside the class, but can be
accessed from a derived class. This is used when inheritaance is applied to the members of a
class.
(c) Predefined functions are functions that are built into C++ Language to perform some standard
operations.
[2 marks]
The functions that are stand alone used for general purposes and that are not depended on any
classesarestoredintheStandardFunctionLibrary.
PredefinedfunctionsintheStandardFunctionLibraryarelistedbasedondifferentcategories.
(d) (i) Anintegerarrayof50elements
[3 marks]
AnArray,foregAcontains50integerelementsfromA[0]toA[49]

0
(ii)

49

Astringvariablethatcanhold20characters.
The individual characters that make up the string are stored in the elements of the array.The
stringisterminatedbyanullcharacter.
Fore.g.,stringapple:

19

(iii) A2dimensionalarraytostore3x4matrix
Second Superscript
E.g., Mat[2][3]
Second Superscript

FirstSuperscipt

Mat[0][0]

Mat[0][1]

Mat[1][2]

Mat[0][3]

Mat[1][0]

Mat[1][1]

Mat[1][2]

Mat[2][2]

Mat[2][0]

Mat[2][1]

Mat[2][2]

Mat[2][3]

(e) /*Input10numbersinanarrayandfindthesumoftheelements*/
#include<iostream.h>
#include<conio.h>
#define clrscr();
intmain(){
int sum,counter;
intA[10];
cout<<Enter10numbers\n;

[4 marks]

Solutions |

15

sum=0;
counter = 0;
while(counter<10){
cin>>A[counter];
sum = sum +A[counter];
counter =counter + 1;
}
cout<<sumofarrayelementsis<<sum;
getch ( );
return 0;
}
Output:
Enter10 numbers
12345678910
Sumofarrayelementsis55
l

Sam pl
e Que s tion Pape r8
1. (a) A driver is a software or a firmware that control hardware. Often it connects an operating system
with specific hardware devices. For example, there are drivers for every card and disk in your
computer.
[1 mark]
(b) Firmwaremakesapartofthecomputerrun.Softwareissomethingthatmakestheparttodosomething.
Example:firmwaremakestheCDdrivework,butthesoftwaremakesitburn.
[1 mark]
(c) Dataisthenamegiventobasicfactsandentitiessuchasnamesandnumbers.
[1 mark]
pointoftime.ThisabilityoftheOSiscalledmultiprogramming.
[2 marks]
[1 mark]
(b) Computers use a fixed number of bits to represent an integer.The commonly-used bit-lengths for
integersare8-bit,16-bit,32-bitor64-bit.Besidesbit-lengths,therearetworepresentationschemes
forintegers:UnsignedIntegers andSignedIntegers.
[1 mark]
(c) Theoctalnumeralsystem,isthebase-8numbersystem,andusesthedigits0to7.Octalnumeralscan
thebinaryrepresentationfordecimal74is1001010,whichcanbegroupedinto(00)1001010so
theoctalrepresentationis112.
[1+1=2marks]
Intheoctalsystemeachplaceisapowerofeight.Forexample:
1128 =182+181+280
(d)
0.2758 =2.2=2+0.2
[ 2 marks]
0.28 =1.6=1+0.6
0.68 =4.8=4+0.8
0.88 =6.4=6+0.4
Hence,
(0.275)10 =(0.2146)8
3. (a) .cppisthefileextentionforaC++program.
[1 mark]
(b) Inheritanceistheinclusionofbehaviour(i.e.methods)andstate(i.e.variables)ofabaseclassina
derivedclasssothattheyareaccessibleinthatderivedclass.ThekeybenefitofInheritanceisthatit
provides the formal mechanism for code reuse.
[2 marks]
Encapsulationrefers to keeping all the related members (variables and methods) together in an
object.Specifyingmembersasprivatecanhidethevariablesandmethods.Objectsshouldhidetheir
inner workings from the outside view.
(c)
Start

Decision 1

False

True

Decision 2

Sequence

Stop

False

[2 marks]

Solutions |

(d) Differencebetweencinandgets()
cin

17

[2 marks]
gets( )

1. Itcanbeusedtotakeinputofavalueofany 1. Itcanbeusedtotakeinputofastring.
datatype.
2. Ittakesthewhitespacei.e.,a blank,a tab, 2. Itdoesnottakethewhitespacei.e.,ablank,
oranewlinecharacterasastringterminator.
a tab, or a new line character, as a string
terminator.
(e) DifferencebetweenArrayandStructure
Array
1. Array elements are homogeneous.
2. Arrayallocatesstaticmemoryandusesindex
/ subscript for accessing elements of the
array.
3. Arrayisapointertothefirstelementofit.
4. Array element access takes less time in
comparison with structures.
E.g.,
intA[20];
char name[80];
float mat[5][5];

[4 marks]
Structure

1. Structureelementsareofdifferentdatatype.
2. Structures allocate dynamic memory and
uses (.) operator for accessing the member
of a structure.
3. Structureisnota pointer.
4. Structures take more time to be accessed.
struct STUDENT
{
introllno,age;
char name[80];
float marks;
};

4. (a) BitwiseoperatorsareAND,OR,XORandNOTusedtomanipulatedataatthebitlevelbyshiftingor
[2marks]
testingbits.
ThefollowingisthelistofbitwiseoperatorsinC++.
~
BitwiseNOT
&&
BitwiseAND
||
BitwiseOR
^
XOR
<<
BitwiseShiftLeft
>>
BitwiseShiftRight
(b) Theprocessinwhichonepre-definedtypeofexpressionisconvertedintoanothertypeiscalledtype
conversion. There are twotypes of conversion in C++.
[2 marks]
1. Implicit conversion
2.Explicitconversion
Implicit conversion
Datatypecanbemixedintheexpression.Forexample
doublea;
intb=5;
floatc=8.5;
a=b*c;
Explicitconversion
totalPay=static_cast<double>(salary)+bonus;
(c) #includedirective
[4 marks]
GlobalDeclarations
return-type main( )
{
Statements
}

18

(d)

(e)

5. (a)
(b)

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

Example:
#include<iostream.h>
intmain()
{
cout<<HelloWorld!;
return 0;
}
(i) Ifinputis2000:outputis400
(ii) Ifinputis1000:outputis400
(iii) Ifinputis500:outputis200
/*Programtocalculatevolume,surfacearea andspacediagonalofacuboid*/
#include<iostream.h>
#include<conio.h>
#include<math.h>
#define clrscr();
intmain()
{
clrscr ( );
floatwidth,length,height;
floatsurfacearea, volume,space_diagonal;
cout<<Entervalueofwidth,length&heightofthecuboid:\n;
cin>>width>>length>>height;
surfacearea=2*(width*length+length*height+height*width);
volume=width*length*height;
space_diagonal=sqrt(width*width+length*length+height*height);
cout<<Surfaceareaofcuboidis:<<surfacearea;
cout<<\nVolumeofcuboidis:<<volume;
cout<<\nSpacediagonalofcuboidis:<<space_diagonal;
getch ( );
return 0;
}
Output:
Entervalueofwidth,length&heightofthecuboid:
536
Surfaceareaofcuboidis:126
Volumeofcuboidis:90
Spacediagonalofcuboidis:8.3666
Thefinalvalueofxis10.
#include<iostream.h>
#include<conio.h>
#define clrscr();
intmain()
{
clrscr( );
intage;
cout<<\nEnteryourage:;
cin>>age;
if(age>=18)
else
cout<<\nYouareaMinor!;
getch( );
return 0;
}

[3 marks]

[3 marks]

[1 mark]
[2 marks]

Solutions |

19

Output1:
Enteryourage:34
Output2:
Enteryourage:3
YouareaMinor!
(c) #include<iostream.h>
[4=2marks]
#include<conio.h>
intmain()
{
while(W>60)//()missing
{
R=W-50;
switch(W)
{
case20:cout<<lower range<<endl; // keyword case missing
case40:cout<<higher range<<endl;
}
}
getch ( );
return 0;
}
(d) cinobject:
[3 marks]
cin can be used to input a value entered by the user from the keyboard. However, the extraction
operator>>isalsorequiredtogetthetypedvaluefromcinandstoreitinthememorylocation.
Letus considerthefollowing programsegment:
int marks;
cin>> marks;
cout object:
coutisusedtoprintmessageonscreeninconjunctionwiththeinsertionoperator<<
cout<<HelloWorld;
(e) Algorithm:Findthelargestoftwonumbers
[4 marks]
Step1.inputnumbersA,B
Step2.Checkif(A>B)
Step3.IftrueprintAisgreaterthanB
Step4.ElseIf(B>A)
Step5.PrintBisgreaterthanA
Step6.PrintAandBareequal.
Step7.[EndofAlgorithm]

20

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

Stop
Flowchart:

Start
Input A, B

A>B

T
Print A is greater
than B

B >A

T
Print A is greater
than B

Print A and B
are equal

Start

6. (a) The execution of a program can be stopped at any point with exit ( ) and a status code can be
informedtothecallingprogram.
[1 mark]
(b) Syntax:intisalpha(intcharacter);
[2 marks]
BasedontheASCIIvalueofthecharacteritwilldetermineifitisanalphabeticalcharacterornot.
Example:
//Programacceptsa userinput,andcheckstoseeifitisanalphabetornot
# include <cctype.h>
#include<iostream.h>
intmain()
{
clrscr ( );
char d;
cout<<Enteracharacter,number,orpunctionsign:;
cin>>d;
if(isalpha(d))
{
cout<<Youenteredanalphabeticalcharacter.;
}
return 0;
}
[3 marks]
(i)
AbsoluteValueFunctions
(ii) NearestInteger,AbsoluteValue,andRemainderFunctions
(iii) ExponentialandLogarithmicFunctions
(iv) Power Functions
(v) Trigonometric Functions
(vi) Hyperbolic Functions
[2 marks]
(d) (i)
(X+3)1/3 pow((X+3),(1/3))
(ii)
2(P/q)2/(r3) 2* pow((P/q),2)/(r3)
(iii)
Z=tanx Z=tan(x)

Solutions |

7. (a)
(b)

(c)

(d)

21

(iv)
W=log(v) W=log(v)
(v)
y=abexsinx y= a*pow(b,(e*x))*sin(x)
(vi) y=(sin(x)cos(x)) y= sqrt((sin(x)cos(x))
(vii)
log(a+b)log(ab) log(a+b)log(a*b)
(viii)
w=x+y w=x+y
[1 mark]
The storage class of a variable determines which parts of a program can accessit and how long it
staysinexistence.Thestorageclasscanbeclassifiedas
[2 marks]
Automatic
Register
Static
External
Outputforthegivencodeis:
[2 marks]
c
ca
cal
cali
calif
califo
califor
californ
californi
california
[3 marks]
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<iomanip>
/*using namespace std;
using std::setw;*/
intmain()
{
//anarraywith3rowsand4columns.
inti=3,j=4;
intA[i][j];
clrscr();
//outputeacharrayelementsvalue
for(inti=0;i<3;i++)
{
cout<<Entertherowelements<<endl;
for(intj=0;j<4;j++)
{
cin>>A[i][j];
}
}
cout<<Matrix<<endl;
for(inti=0;i<3;i++)
{
for(intj=0;j<4;j++)
cout<<setw(4)<<A[i][j];
cout<<endl;
}
getch ( );

22

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

return 0;
}
Output :
Entertherowelements
2
2
2
2
Entertherowelements
1
2
3
4
Entertherowelements
2
4
6
8
Matrix:

2
1
2
(e) (i)
(ii)
(iii)
(iv)

2
2
4

2
3
6

2
4
8

intP[4]={1,4,7,10};
intQ[5]={3,9,2,1,5};
float X[7] = {3,2,4,7,3,6,1.5}
char N[7] = {S,a,n,j,a,y,\0}

[4 marks]

Solutions |

23

Sam pl
e Que s tion Pape r9
1. (a) Randomaccess memory (RAM) is a form of computer data storage.
[1 mark]
near the visible light spectrum as part of the process of reading or writing data to or from optical
discs. Some drives can only read from discs, but recent drives are commonly both readers and
recorders, also calledburners or writers.
[1 mark]
(c) In1642aFrenchmancalledBlaisePascalinventedthefirstmechanicalcalculator.
[1 mark]
ItwasfirstcalledtheArithmeticMachine,thenPascalsCalculatorandlaterPascaline.
(d) Graphics software or image editing software is a program or collection of programs that enable a
person to manipulate visual images on a computer. CurrentlyAdobe Photoshop is one of the most
used and best-known graphics programs.
[2 marks]
2. (a) TRTemporaryRegister
[1 mark]
(b)

10.1000

[1 mark]

(c) Usingthefollowingsubtractionrules:
00
10
11
101

024 =0
023 =0
022 =0
121 =0.5
020=0
121=2

Ans.

=2.5
[2 marks]

=0
=1
=0
=1

11010.100

26.500

10110.011

22.375

00100.001

4.125

(100.001)2=(4.125)10
(d) (i)(327)8
(i)

(ii)(135)8
(327)8

[2 marks]

=382+381 +780
=(223)10

(ii)

(135)8 =182+381+580
=(93)10

3. (a) Theconditionaloperator(?)evaluatesanexpression,returningonevalueifthatexpressionevaluates
[1 mark]
condition?result1:result2

24

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

(b)

[2 marks]
CompilationprocessinC++
Source Code
Preprocessor

Compiler
Assembly Code
Assembler
Libraries

Object Code
Executable Code

(c) Theif..elseifstatementisanextensionoftheifelseconditionalbranchingstatement.Whenthe
expression in the if condition is false another if else construct is used to execute a set of
statements based onan expression. This belongsto Control Structures.
[2 marks]
Syntax:
if (expression)
{ Statements }
elseif(expression)
{ Statements }
elseif(expression)
{ Statements }
(d) Message Passing is sending and receiving of information by the objects same as people exchange
information. This helps in building systems that simulate real life. Following are the basic steps in
message passing .
[2 marks]
Creatingclassesthatdefineobjectsanditsbehavior.
Creatingobjectsfromclassdefinitions
Establishing communication among objects.
InOOPs,MessagePassinginvolvesspecifyingthenameofobjects,thenameofthefunction,andthe
informationtobesent.
(e) ObjectOrientedProgramminggroupsrelateddataandfunctionstogetherinaclass,generallymaking
data private and only some functions public. Restricting access decreases coupling and increases
cohesion. OOPs is often said to incorporate three techniques: inheritance, encapsulation, and
polymorphism.
[4 marks]
Encapsulation
Encapsulationisgroupingdataandfunctionstogetherandkeepingtheirimplementationdetailsprivate.
Greatlyrestrictingaccesstofunctionsanddatareducescoupling,whichincreasestheabilitytocreate
large programs.
Inheritance
Inheritance means that a new class can be defined in terms of an existing class. There are three
common terminologies for the new class: the derived class, the child class, or the subclass. The
original class is the base class, the parent class, or the superclass. The new child class inherits all

Solutions |

25

Polymorphism
Polymorphismistheabilityofdifferentfunctionstobeinvokedwiththesamename.Therearetwo
forms.
with different numbers or types of parameters.
Dynamic polymorphism is much different and relies on parent classes to define virtual functions
which child classes may redefine. When this virtual member function is called for an object of the
parentclass,theexecutiondynamicallychoosestheappropriatefunctiontocalltheparentfunction
iftheobjectreallyistheparenttype,orthechildfunctioniftheobjectreallyisthechildtype.
4. (a) Alternatedatatypenamesaredefinedusingthekeywordtypedeffortheexistingdatatypes.Thisis
used to make the code more portable, as the data type can be changed using a single typedef
statement.
[2 marks]
Syntax:
typedef type newname;
(b) Characters which cannot be typed directly from keyboard, e.g., backspace, tab,
[2 marks]
carriagereturnetc arenon-graphicalcharacters.These characterscanberepresented byusinga
escapesequence. Thefollowingtable givesa listing ofcommon escapesequences.
Non - graphical

Escape Sequence

Newline

\n

Horizontal tab

\t

Null character

\0

(c) Apreprocessordirectiveisaninstructiontothecomplieritself.Apartofcompilercalledpreprocessor
deals with these directives, before real compilation process. # is used as preprocessor directive in
C++.
[3 marks]
#defineisapreprocessordirectivetodefineamacroinaC++program.Macrosprovideamechanism
fortokenreplacementwithorwithoutasetofformal,functionlineparameters.Forexample:
#definePIE3.1416
#defineAVG(A,B,C)(A+B+C)/3

(d)

(e) (i)
(ii)
(iii)
(iv)
(v)

[3 marks]

DATE-RECInvalidvariablename.Hypen()cannotbeused.
DATE_7_77Validvariablename.
A2BOZ9Validvariablename.
_antValidvariablename.
PROG13Validvariablename.

26

5. (a)
(b)

(c)

(d)
(e)

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

(vi) net_amtValidvariablename.
(vii) 29_abInvalidvariablename.Variablenamecannotstartwithanumber.
(viii) breakInvalidvariablename.Variablenamecannotuseareservedkeyword.
Theloopexecutes 5times.
[1 mark]
#include<iostream.h>
[2marks]
intmain()
{
intX,Y;
cin>>X;
for(Y=0;Y<10;Y++)
//lower casef forfor
If (X==Y)
//missing()
cout<<Y+X;
else
cout<<Y;
//coutuses<<andnot>>
return 0;
}
Itisamemberfunctionofclasswiththefollowinguniquefeatures:
[3 marks]
Ithassamenameasthenameoftheclasstheybelongto.
Ithas noreturn type.
Itisdefinedinpublicvisibilitymode.
Itisautomaticallycalled&executedwhenanobjectisdeclared/created.
Singlelevelinheritance,multilevelinheritance,hierarchicalinheritance,multipleinheritanceandhybrid
inheritance.
[2 marks]
Findthesmallestofthreenumbers
[4 marks]
Algorithm

FlowChart
Start

Step1:inputnumberA,B,C
Input A, B, C

Step2:small=A
Step3:Checkif(B<small)

Small = A

Step4:Iftruesmall=B
Step5:If(C<small)

B < Small

Step6:Iftruesmall=C
F

Step7:printsmall
Step8:[EndofAlgorithm]
Stop

C < Small
T
F
Small = C

Print Small

Stop

Small = B

Solutions |

27

[1mark]
6. (a) Aclasswithnoinstances(noobjects)isknownasabstractclass.
(b) Brackets[]
Openingandclosingbracketsindicatesingleandmultidimensionalarraysubscript.
Parentheses () Opening and closing brackets indicate functions calls, function parameters for
grouping expressions etc.
Braces{}
Openingandclosingbracesindicatethestartandendofa compoundstatement.
Semicolon ;
Itisusedasa statementterminator.
[2 marks]
(c)

Function

Meaning

isdigit(c)

ItreturnsTrueifcisa digit(0through9)otherwiseFalse.

isalnum(c)

(either uppercase or lowercase) otherwise False.

islower(c)

ItreturnsTrueifCisalowercaseletterotherwiseFalse.

isupper(c)

ItreturnsTrueifCisanuppercaseletterotherwiseFalse.

toupper(c)

tolower(c)

## It converts c to lowercase letter.

[3 marks]
(d) (i)
Y=toascii(X);
[4 marks]
(ii) Name1=Name;
(iii) W=abs(U-V);
(iv) y=sin(x);
(v) atof(name);
(vi) toupper(Ch);
(vii) Y=strlen(X);
(viii) s3 = strcat(s2,s1);
[1mark]
7. (a) getch( ), putch( ).
(b) voidswap(int*px,int*py)/*interchange*pxand*py*/
[2 marks]
{
inttemp;
temp= *px;
*px=*py;
*py = temp;
}
(c)
1
1
3
4
6
10
10
20
15
35
21
56
28
84
36
20
45
165
55
220
66
286
Algorithmtoinsertakeyata[index].(weneedtoshiftothervaluesupasnecessary)
Step1:Initializethevariables:
a
arrayofvalues.
n
numberofvaluesina,a[0]..a[n-1]
maxsize maximumnumberofelementsthatcanfitina
index
positiontoinsertat
key
valuetoinsert.

28

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

Step2:Checkarraysize.Ifn<maxsizegotoStep3elseStep6.
Step3:Moveallelementsuponeposition.iisdestination.
for(inti=n;i>index;i){
a[i]=a[i-1];
}
Step4:a[index]=key;
//putvalueinvacatedposition
Step5:n++;
//updatecountofitemsina
Step6:Endofalgorithm.
Stop
(e) /*sumofeachrowandcolumnofa2darray*/
#include<iostream.h>
#include<conio.h>
#define clrscr();
intmain()
{
clrscr ( );
int i,j,n,a[5][5],b,c,x=0;
cout<<enter thenumberofrows andcolumns<<endl;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
cin>>a[i][j];
}
for(i=0;i<n;i++)/*SumOfRowsAndColumns*/
{
b=0;c=0;
for(j=0;j<n;j++)
{
b=b+a[i][j];
c=c+a[j][i];
}
++x;
cout<<sumofrow<<i+1<<is<<b<<endl;
cout<<sumofcolumn<<i+1<<is<<c<<endl;
}
getch ( );
return 0;
}

[4 marks]

Output :
enter the number of rows and columns
3
1
2
3
1
2
3
1
2
3
sumofrow1is6
sumofcolumn1is3
sumofrow2is6
sumofcolumn2is6
sumofrow3is6
sumofcolumn3is9
l

Solutions |

29

Sam pl
e Que s tion Pape r10
1. (a)
(b)
(c)
(d)

2. (a)
(b)

(c)

(d)

3. (a)
(b)

(c)

## Programis a sequenceof instructionsthata computercaninterpret andexecute.

[1 mark]
Linux,Ubuntu,Windows-XP,WindowsVistaarepopularoperatingsystems.
[1 mark]
RAIDRedundantArrayofInexpensiveDisks
[1 mark]
UnitsofComputerMemoryMeasurements:
[2 marks]
1Bit
= BinaryDigit
8Bits
= 1Byte
1024Bytes = 1KB(KiloByte)
1024KB
= 1MB(MegaByte)
1024MB
= 1GB(GigaByte)
1024GB
= 1TB(TerraByte)
1024TB
= 1PB(PetaByte)
1024PB
= 1EB(ExaByte)
1024EB
= 1ZB(ZettaByte)
Thedecimalnumbersystem,isapositionalnumeralsystememploying10asthebaseandrequiring10
differentnumerals,thedigits0,1,2,3,4,5,6,7,8,9.
[1 mark]
TheAmerican Standard Code for Information Interchange (ASCII) is a character-encoding scheme
originallybasedontheEnglishalphabetthatencodes128specifiedcharactersinto7-bitbinaryintegers.
[1 mark]
[1 mark]
(i)
(9AC3)16 =9*163+10*162+12*161+3*160
=36864+2560+192+3
=(39619)10
(ii)
(FA8)16 =15*162 +10*161+8*160
[1 mark]
=3840+160+8
=(4008)10
(i) AB+AC+BC =AB+AC
[1 mark]
AB+AC+BC =AB+AC+(A+A)BC
=AB+AC+ABC+ABC
=(AB+ABC)+(AC+ACB)
=AB+AC
(ii) A.B.C+A.B.C+A.B.C+A.B.C
[1 mark]
=AB+BC+CA
=A.B.C+A.B.C+A.B.C+A.B.C
=A.B.C+A.B.C+A.B.C+A.B.C+A.B.C+A.B.C
=(A.B.C+A.B.C)+(A.B.C+A.B.C)+(A.B.C+A.B.C)
=(A+A).B.C+(B+B).C.A+(C+C).A.B
=B.C+C.A+A.B
=AB+BC+CA
A programming paradigm is a fundamental style of computer programming, a way of building the
structure and elements of computer programs.
[1 mark]
CompilerIt is a program which converts the program written in a programming language to a
programinmachinelanguage.
[2 marks]
itanexecutableprogram.
Type casting refers to the data type conversions specified by the programmer, as opposed to the
automatic type conversions. This can be done when the compiler does not do the conversions
automatically.Typecastingcanbedonetohigherorlowerdatatype.
[2 marks]
Forexample:cout<<(float)18/5;//displays3.6,since18isconvertedtofloattype.

30

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

(d) Theconditionaloperatorforgivenproblemcanbewrittenas
y=((x<=2)?(2.4*x+3):(3*x+5)).
(e) (i) Syntacticerrorandsemanticerror

[2 marks]
[2 marks]

Syntacticerror

Semantic error

## Syntactic errors also known as compilation

errorsarecausedbyviolationofthegrammar
rules of the language. The compiler detects,
isolate these errors and terminate the source
programafterlistingtheerrors.
E.g.missingormisplaced;or}

Semanticerrorsarelogicalerrors.Ifthereisa
semantic error in a program, it will run
successfully, in the sense that the computer
will not generate any error messages, but it
willnotdotherightthing.

(ii) Runtimeerrorandlogicalerror
Runtime error
outofbounderrorareknownasruntimeerrors.
These errors are generally go undetected by
the compiler soprograms with run-time error
will run butproduce erroneous results.

Logicalerror
Thesearethe errorsrelatedwiththe logicof
the program execution. These errors are not
detectedbythecompilerandareprimarilydue
to a poor understanding of the problem or a
lackofclarityofhierarchyofoperators.Such
errors cause incorrect result.

## 4. (a) (i) 700300>500false,henceC=50

[2 marks]
(ii) 800700>500false,henceC=50
(b) WheneveraC++programisexecuted,executionoftheprogramstartsandendsatmain().Themain
isthedriverfunctionoftheprogram.Ifitisnotpresentinaprogram,noexecutioncantakeplace.
[2 marks]
(c) returnstatementinafunctionisusedtoreturnavaluetothecallingprogram.Thereturnstatement
takesoneofthefollowingforms:
[3 marks]
return;Itdoesnotreturnanyvalueandactasaclosingbraceofthefunction.
or
return(expression);Itreturnsthevalueoftheexpressiontothecalledfunction.Afunctioncanhave
morethanonereturnstatement.This happenswhenthevaluereturnedis
based oncertain conditions.
Forexample:
if(x<=y)
return x;
else
return y;
Allfunctionsbydefaultreturninttypedata.
(d) (i) intcode=three;
[1 mark]
Cannotassignvalueasthree.Itshouldbe3.
intcode=3;
(ii) constintsize;
[1 mark]
sizeisareservedword,cannotuseasvariablename.
(iii) size=10
[1 mark]
sizeisareservedword,cannotuseasvariablenameandsemicolonmissing.
(e) Everyalgorithmshouldhavethefollowingfivecapabilitiesandqualities:
[4 marks]
1. Input:Thealgorithmshouldtakezeroormoreinput.
2. Output: Thealgorithm shouldproduce oneor moreoutputs.
3. Definiteness:Eachandeverystepofalgorithmshouldbedefinedunambiguously.
4. Effectiveness:Ahumanshould beable tocalculatethe valuesinvolvedin theprocedure ofthe
algorithmusingpaperandpencil.
5. Termination:Analgorithmmustterminateafterafinitenumberofsteps.

Solutions |

31

5. (a) Aflowchartisagraphicalrepresentationofdecisionsandtheresultsofthosedecisionsmappedoutin
individualshapes.
[1 mark]
(b) switch(ch)
[2 marks]
{
caseE:eastern++;
case W: western++;
case N: northern++;
case S: southern++;
default: unknown;
}
(c) Output :
[3 marks]
res1332755(Thenumberisreversed)
(d) Output :
(2+1)[3marks]
count= 5
count= 4
count= 3
count= 2
count= 1
Valueofcountisinitially5,itisprintedandthencountisdecrementedby1.
Sincecount!=0sofunctionf1iscalledagain,4isprintedandsameprocessisrepeatedtill
count=0so theaboveoutput.
(e) Fourstagesinvolvedinprogramdesignare:
(2marksforeachquestion)[4marks]
Understandingtheproblemandalgorithmdesignedfortheproblem.
Decidewhatistobegivenasinputandcorrespondingoutput.
Chooseanappropriateprogramming languageanddatastructures.
Derivetestcasesandtestexhaustivelyeachandeverymoduleoftheprogram.
Design is an important phase in software engineering.Two critical resources used in development
process areexecution time andmemory.The efficiencyof a program ismeasured in termsof these
two resources. Inefficiencies in software design can result in complexity that is costly in software
maintenance.Program efficiencycanbe improvedwithgoodprogram designanderror freecoding.
[1 mark]
(b) (i) cos ( ) <cmath.h>
[2 marks]
(ii) setw()<iomanip.h>
(iii) toupper ( ) <cctype.h>
(iv) strcpy () <string.h>
(c) Therearetwowaystodeclarestructures.Oneistofollowthestructuredefinitionwithalistofone
ormorevariablenames,asisdonehere:
[3 marks]
struct coord {
intx;
inty;
} first, second;
Thesestatementsdefinethestructuretypecoordanddeclaretwostructures,firstandsecond,oftype
coord.first andsecond areeach instancesof typecoord; firstcontains twointeger membersnamed
xandy, andsodoessecond.Thismethodofdeclaring structurescombinesthedeclaration withthe
definition.
Thesecondmethodistodeclarestructurevariablesata differentlocationinyoursourcecodefrom
thedefinition.Thefollowingstatementsalsodeclaretwoinstancesoftypecoord:
struct coord {
intx;
inty;
};
struct coord first, second;

32

(d)

7. (a)
(b)
(c)

(d)

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

first.x=10;
first.y=20;
/*Programtocheckifstringispalindrome*/
[4 marls]
# include<iostream.h>
# include<conio.h>
# include<stdio.h>
intmain()
{
clrscr( );
char str[80];
cout<<Enterastring:;
gets(str);
intL,C;
for (L=0;str[L]!=\0';L++);
//Tofindlengthofthestring
for (C=0;(C<L/2) && (str[C]==str[L-C-1]);C++);
if(C==L/2)
cout<<Palindrome;
else
cout<<Notapalindrome;
getch( );
return 0;
}
Output1:
Enterastring:anna
Palindrome
Output2:
Enterastring:mark
Notapalindrome
arrow ()
[1 mark]
(i) intsum[10]Declarationforanintegerarrayofsize10.
[1 mark]
(ii) m[1]=10Assignsthevalue10tothesecondpositionofthearraym.
[1 mark]
include <iostream.h>
[2 marks]
intmain()
{
intx[5],*Y,Z[5];
for(i=0;i<5;i++)//iisnotdeclared
{
x[i]=i;
Z[i]=i+3;
Y=Z;
x=Y;//incompatibletypesinassignmentofint*toint[5]
}
return 0;
}
Missingbraces:Verycommonerrorasitiscommontoforgetaclosingbrace.Numberofopening
braces should match number of closing braces.
Undeclaredvariables:Crequiresdeclarationofvariablesbeforetheiruse.

Solutions |

33

## Forgetting the precedence of operators: Expression are evaluated according to precedence of

operators.
Mismatchofparametersinfunctioncalls:Theremaybemismatchinactualandformalparameters
infunctioncalls.
Unending and sometimes wrong loops.
(mark foreach point)[3 marks]
[4 marks]
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<iomanip>
/*#defineclrscr();
using namespace std;
using std::setw;*/
intmain()
{
intI=3,J=4;
intA[I][J], B[I][J],C[I][J];
clrscr( );
cout<<Entertheelementsoffirstarray<<endl;
for(inti=0;i<I;i++)
{
for(intj=0;j<J;j++)
{
cin>>A[i][j];
}
}
cout<<Entertherowelementsofsecondarray<<endl;
for(inti=0;i<I;i++)
{
for(intj=0;j<J;j++)
{
cin>>B[i][j];
}
}
for(inti=0;i<I;i++)
{
for(intj=0;j<J;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
cout<<SumofarrayAandB:<<endl;
for(inti=0;i<3;i++)
{
for(intj=0;j<4;j++)
cout<<setw(8)<<C[i][j];
cout<<endl;
}
getch ( );
return 0;
}

34

## Oswaal CBSE (Sample Question Papers) Computer Science, (C++) ClassXI

Output :
Entertheelementsoffirstarray
1
1
1
1
2
2
2
2
3
3
3
3
Enterthe rowelementsof secondarray
4
4
4
4
5
5
5
5
6
6
6
6
SumofarrayAandB:
5555
7777
9999