Sunteți pe pagina 1din 162

CBSE

CLASS – XII

OLD QUESTIONS
&
ANSWERS
(Source of Grasping Subject & Gaining Marks)

C++
Data Structures
Structured Query Language
Boolean Algebra
Networking & Open Source Concepts

Prepared By:

MRK

“THE FEAR OF THE


LORD
IS THE BEGINNING OF WISDOM"
CONTENTS
Unit
Chap Page Wise
Chapter Name Marks
No Number Marks
(70)
PART 1
1 C++ Revision Tour 1 12
2 Object Oriented Programming 22 0 or 2
3 Function Overloading 0 or 2
4&5 Classes and Objects & 25
6 30
Constructors & Destructors 47
6 Inheritance 51
4
7 Data File Handling 62 6
8 Pointers 76 0 or 2
9 Arrays 80 8
10 Data Structures 98 6 14
PART 2
11 Database Concepts 1 2
12 Structured Query Language 4 6 8
13 Boolean Algebra 21 8 8
14 Networking & Open Source Concepts 28 10 10

Dear Student/Reader, I have prepared this material with the good intention to make
the XIIth class computer students to understand all the important models. By practicing
this material students may get good marks. But to get full marks, one must prepare all
the syllabus prescribed by CBSE.
As I have prepared the above material through my own answers, marking
schemes from CBSE, copied material from various sources, etc, there might be some
spelling mistakes, or any other errors. So reader should read carefully. I am not
responsible for any errors that creep in this material.
**ALL THE BEST**
Your Ever….Dear….
Faculty, Friend & Well Wisher: MRK
Email: ptlspecialsolutions@gmail.com
void main()
XII COMPUTER {
char text[20], newText[20];
1. C++ REVISION TOUR gets(text);
MODEL WISE QUESTION & ANSWERS strcpy(newText,text);
Note:This material is prepared for thorough for(int i=0;i<strlen(text);i++)
practice of important models from old questions if(text[i]==‟A‟)
and thereby getting good marks and student is text[i]=text[i]+2;
advised to prepared all the syllabus given by puts(text);
CBSE. }
Ans: stdio.h, string.h
MODEL 1A: Name the types of tokens. 2 Marks
1. Write the type of C++ Operators (Arithmetic, 2. The following C++ code during compilation
Logical , Operators) from the following. reports errors as follows: (2018)
2019SP(2) Error: „ofstream‟ not declared
(i) ! (ii) != (iii) && (iv) % Error: „strupr‟ not declared
Ans: Error: „strcat‟ not declared
(i) Logical (ii) Relational (iii)Logical (iv) Arithmetic Error: „FIN‟ not declared
Write the names of the correct header files, which
2. Write the type of C++ tokesn (keywords and must be included to compile the code successfully:
user defined identifiers) from the following: void main( )
(2018) { ofstream FIN(“WISH.TXT”);
(i) else (ii) Long (iii) Queue (iv) _Count char TEXT2[ ]=”good day”;
(Note : Actually (iii) option is given wrong as char TEXT1[ ]=”John!”;
4Queue.For 4Queue – Answer will be “None”) strupr(TEXT2);
Ans) (i) else – Keyword strcat(TEXT1, TEXT2);
(ii) Long – User defined Identifier FIN<<TEXT1<<endl;
(iii) Queue – User defined Identifier }
(iv) _Count – User defined Identifier Ans:(i) fstream.h (ii) string.h
3.Write the type of C++ tokens (keywords and user 3. Anil typed the following C++ code and during
defined identifiers) from thefollowing: (2017) compilation he found three errorsas follows:
(i) new(ii) While(iii) case(iv) Num_2 (i) Function strlen should have prototype
Ans) (i) new - Keyword (ii) Undefined symbol cout
(ii) While - User defined Identifier (iii) Undefined symbol endl
(iii) case - Keyword On asking, his teacher told him to include necessary
(iv) Num_2 - User defined Identifier header files in the code.Write the names of the header
files, which Anil needs to include, for
MODEL 1B: Valid/Invalid Identifiers. 2 Marks successfulcompilation and execution of the following
code (2017)
1. Out of the following, find those identifiers, which
void main( )
can not be used for namingVariable, Constants or
{
Functions in a C++ program: 2016OD
char Txt[] = "Welcome";
Total*Tax, double, Case, My Name,
for(int C= 0; C<strlen(Txt); C++)
NeW, switch, Column31, _Amount
Txt[C] = Txt[C]+1;
A) Total*Tax,double,My Name,switch
cout<<Txt<<endl;
2. Find the correct identifiers out of the following, }
which can be used for naming Variable, Constants or Ans) string.h, iostream.h OR fstream.h
Functions in a C++program: (2015 OD) (iomanip.h also)
For, while, INT, NeW, delete, 4) Which C++ header file(s) are essentially
1stName, Add+Subtract, name1 required to be included torun/execute the following
A) For, INT, NeW, name1 C++ code : (2017MP)
MODEL 2A)Which C++ header file(s) are void main()
essentially required to be included to run/execute {
the following C++ code:1 Mark char *word1="Hello",*word2="Friends";
strcat(word1,word2);
1. Observe the following program very carefully cout<<word1;
and write the name of those header file(s), which }
are essentially needed and execute the following A)iostream.hstring.h
program successfully: 2019SP(1)

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 1 PRAISE THE LORD


5)Ronica Jose has started learning C++ and has typed 160-strlen(TEXT)<<endl;
the following program. Whenshe compiled the }
following code written by her, she discovered that she Ans: iostream.h (for cout)
needs toinclude some header files to successfully string.h (for strlen( ));
compile and execute it. Write the namesof those
10) Write the names of the header files, which is/are
header files, which are required to be included in the
essentially required to run/execute the following c++
code. (2016 OD)
code: (2011 OD)
void main()
{ void main ( )
double X,Times,Result; { char CH,Text[ ] =”+ve Attitude”;
cin>>X>>Times; for (int I=0 ; Text[I] ! =‟\0‟ ;I++)
Result=pow(X,Times); if (Text[I]== „„)
cout<<Result<<endl; cout<<end1;
} else
A) ● iostream.h (also iomanip.h) ● math.h { CH=toupper (Text [I]) ;
cout<<CH;
6) Observe the following program very carefully and }
write the nameof those header file (s), which are }
essentially needed to compileand execute the Ans: iostream.h, ctype.h
following program successfully: (2015 OD)
typedef char STRING[80]; 11) Which C++ header file(s) will be essentially
void main( ) required to be included to run/execute the following
{ STRING Txt[] = “We love Peace”; C++ code: (2010 OD)
int Count=0; void main()
while (Txt[Count]!=‟\0‟) {
if (isalpha(Txt[Count])) int Rno=24; char Name [] =” Amen Singhania”;
Txt[Count++]=‟@‟ ; cout<<setw(lO)<<Rno<<setw(20)<<Name<<endl;
else }
Txt[Count++]=‟#‟ ; Ans.iostream.h, iomanip.h
puts (Txt) ;
12) Name the header files that shall be needed for the
}
following code: (2008 OD)
A)ctype.h, stdio.h
void main( )
7) Observe the following C++ code and write the { char word[]=”Exam”;
name(s) of the header file(s), which will be essentially cout<<setw(20)<<word;
required to run it in a C++ compiler:1 }
void main( ) Ans: iostream.h, iomanip.h
{ char CH,STR[20];
13) Name the header file(s) that shall be needed for
cin>>STR;
successful compilation of the following C++ code.
CH=toupper(STR[0]);
void main( )
cout<<STR<<”start with”<<CH<<endl;
{ char Text[40];
}
strcpy(Text,”AISSCE”);
A)iostream.h and ctype.h (2014 OD)
puts(Text);
8) Observe the following C++ code and write the }
name(s) of the header file(s), which will be essentially Ans: string.h, stdio.h (2007 OD)
required to run it in a C++ compiler: 1 14) Which C++ header file(s) will be essentially
void main( ) required to be included to run /execute the following
{ int Number; C++ code: (2009-10 MP1)
cin>>Number; void main()
if (abs(Number)= = Number); { char Msg[ ]=”Sunset Gardens”;
cout<<”Positive”<<endl; for (int I=5;I<strlen(Msg);I++)
} puts(Msg);
A)iostream.h, math.h (2013 D) }
9) Which C++ header file(s) are essentially required to A) (i) string.h (ii) stdio.h
be included to run/execute the following C++ source 15) Which C++ header file(s) will be essentially
code (Note: Do not include any header file, which required to be included to run/execute the following
is/are not required): (2012) C++ code: (2011-12 MP1)
void main( ) void main( )
{ char TEXT[ ]=”SomeThing”; { int Last=25;
cout<<”Remaining SMS Chars:”<< for(int C=9;C<=Last;C++)
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 2 PRAISE THE LORD
cout<<C<<”:”<<sqrtI<<endl; (ii) scanf( ) (iii) getchar( ) (iv)clrscr( )
} Ans: (i)strcat( ) - string.h
Ans: (ii)scanf( ) - stdio.h
(i)iostream.h (for cout) (ii) math.h (for sqrt( )) (iii)getchar( ) - stdio.h
(iv)clrscr( ) - conio.h(1999)
MODEL 2b): Write the names of the header files 13)Name the header files, to which the following built in
to which the following belongs to : functions belongs to:
1 Mark (i)cos( ) (ii)setw( )(iii)toupper( ) (iv)strcpy( )
Ans: (i) cos( ) - math.h
1) Write the names of the header files to which the
(ii) setw( ) - iomanip.h
following belong: (i)puts ( ) (ii) sin ( )
(iii) toupper( ) - ctype.h
Ans (i) stdio.h (ii) math.h (2009 D)
(iv) strcpy( ) - string.h(1998)
2) Write the names of the header files to which the
14)Write the names of the header files to which the
following belong:
following belong: (2008-09 MP1)
(i) setw( ) (ii) sqrt( )
(i) strcmp() (ii) fabs()
Ans (i) iomanip.h (ii) math.h (2009 OD)
Answer: (i)string.h (ii) math.h
3 Name the header file to which the following below:
15)Write the names of the header files to which the
(i) abs( ) (ii) isupper( )
following belong: (2008-09 MP2)
Ans) (i) abs( ) - math.h, stdlib.h, complex.h
(i) frexp() (ii) isalnum()
(ii)isupper( ) - ctype.h (2006 D)
Answer:(i) math.h (ii) ctype.h
4) Name the header file to which the following belong: (i)
16) Write the names of the header files to which the
pow ( ) (ii)random( )
following belong: (2009-10 MP2)
Ans:(i) abs( ) - math.h, stdlib.h, complex.h
(i) frexp() (ii) isalnum()
(ii)random( ) - stdlib.h (2006 OD)
A) (i) math.h (ii) ctype.h
5) Name the header files to which the following belong: (i)
abs( ) (ii) strcmp( ) IMPORTANT HEADER FILES & ITS
Ans) (i) abs( ) - stdlib.h, math.h, complex.h FUNCTIONS
(ii) strcmp( ) - string.h (2005 D)
6) Name the header files to which the following belong: (i)
puts( ) (ii)isalnum( ) ctype.h isalnum( ), isalpha( ), isdigit( ), islower( ),
Ans)(i) puts( ) - stdio.h isupper( ), tolower( ), toupper( )
(ii)isalnum( ) - ctype.h (2005 OD) string.h strcat( ), strcmp( ), strcpy( ), strlent( ),
7) Write the names of the header files to which the
strchr( ), stricmp( ), strlwr( ), strew( ),
following belong:
(i) gets( ) (ii) strcmp( ) (iii)abs( ) (iv)isalnum( ) strupr( )
Ans: (i)gets( ) - stdio.h iomanip.h setw( ), setprecision( ), endl, flush( ).
(ii)strcmp( ) - string.h Stdlib.h abs( ), labs( ), free( ), random( ), atof( ),
(iii)abs( ) - math.h, stdlib.h,complex.h atoi( ), atol( ),strtol( ), strtod( ), calloc( ),
(iv)isalnum( ) - ctype.h (2004) malloc(),realloc( )
8) Name the header file, to which the following built-in
function belongs:i) strcmp( ) (ii)getc( ) iostream.h (cout,cin – these are streams available in
Ans: (i) strcmp( ) - string.h iostream.h)
(ii) getc( ) - stdio.h (2003) get( ) getline( ) read( ) write( )
put( ) open( ) close( ) flush( )
9)Name the header files of C++ to which the following seekg( ) seekp( ) tellg( ) tellp( )
functions belong: 2 bad( ) eof( ) fail( ) good( )
(i)get( ) (ii)open( )
(iii)abs( ) (iv)strcat( ) clear( )
Ans: (i)get( ) - iostream.h stdio.h printf( ) scanf( ) fflush( ) fgetc( )
(ii)open( ) - fstream.h fgetchar( ) fgets( ) fopen( ) fprintf( )
(iii)abs( ) - math.h, stdlib.h fputc( ) fputchar( ) fputs( ) fread( )
(iv)strcat( ) - string.h (2002) freopen( ) fscanf( ) fseek( ) fsetpos( )
10) Name the header file to be included for the use of the
fwrite( ) ftell( ) fwrite( ) getc( )
following built in functions:
(i)getc( ) (ii)strcat() 1 getchar( ) gets( ) getw( ) putc( )
Ans: (i)getc( ) - stdio.h putchar( ) puts( ) putw( )
(ii)strcat( ) - string.h (2001) remove( ) rename( )
11) Name the header file, to which following built in conio.h clrscr( ) getch( ) gotoxy( ) cprintf( )
function belong: 2 dos.h sound( ) nosound( ) delay( )
(i) isupper( ) ( ii)setw()
(iii)exp( ) (iv)strcmp( ) (2000) process.h exit(0)
Ans) (i) isupper( ) - ctype.h math.h acos( ) acosl( ), div( ) exp( ) ceil( )
(ii)setw( )- iomanip.h (iii)exp( ) - math.h ceill( ) fabs( ) floor( ) fmod( ) log( )
(iv)strcmp( ) - string.h pow( ) modf( ) poly( ) sqrt( )
12) Name the header file of C++ to which following
functions belong. (i)strcat( )
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 3 PRAISE THE LORD
MODEL 3a): Observe the following C++ code cout<<"Enter an Alphabet:";
very carefully and rewrite it after removing any/all cin>>CH;
syntactical errors with each correction underlined. switch(CH)
Note: Assume all required header files are already case „A‟ cout<<"Ant"; Break;
being included in the program. 2 Marks case „B‟ cout<<"Bear" ; Break;
}
1.Rewrite the following C++ code after removing Ans)
any/all Syntactical Error(s) with each correction {cout<<"Enter an Alphabet:";
underlined. 2019SP(2) char CH; // Error 1
Note: Assume all required header files are already cin>>CH;
being included in the program. switch(CH)
#define float PI 3.14 { // Error 2(i)
void main( ) case „A‟: // Error 3(i)
{ cout<<"Ant"; break; // Error 4(i)
float R=4.5,H=1.5; case „B‟ : // Error 3(ii)
A=2*PI*R*H + 2*PIpow(R,2); cout<<"Bear"; break; // Error 4(ii)
cout<<„Area=‟<<A<<endl; }// Error 2(ii)
} }
Ans: 4) Rewrite the following C++ code after removing
#define PI 3.14 //Error 1 any/all syntactical errors with eachcorrection
void main( ) underlined. Note: Assume all required header files
{ are already being included in the program. (2016)2
float R=4.5,H=1.5; #define Formula(a,b) = 2*a+b
floatA=2*PI*R*H + 2*PI*pow(R,2); //Error 2, 3 void main()
cout<<“Area=”<<A<<endl; //Error 4 {
} float X=3.2;Y=4.1;
2. Rewrite the following C++ code after removing Z=Formula(X,Y);
any/all syntactical errors with each correction cout<<‟Result=‟<<Z<<endl;
underlined. (2018) }
Note: Assume all required header files already A)
included in the program. #define Formula(a,b) 2*a+b
Typedef Count int; void main()
void main( ) {
{ Count C; float X=3.2 , Y=4.1;
Cout<<”Enter the count: “; float Z=Formula(X,Y);
cin>>C; cout<<”Result=”<<Z<<endl;
for (K=1;K<=C;K++) }
cout<<C “*” K<<endl; 5) Observe the following C++ code very carefully
} and rewrite itafter removing any/all syntactical
Ans: errors with each correctionunderlined.
typedef int Count ; //Error 1, Error 2 (2015)2 Note: Assume all required header files are
void main() already being includedin the program.
{ #Define float MaxSpeed=60.5;
Count C; void main()
int K; //OR Count K; //Error 3 {
cout<<"Enter the count:"; int MySpeed
cin>>C; char Alert=‟N‟ ;
for (K = 1; K<=C; K++) cin»MySpeed;
// OR for ( int K = 1; K<=C; K++) //Error 3 if MySpeed>MaxSpeed
// OR for ( Count K = 1; K<=C; K++) //Error 3 Alert=‟Y‟ ;
cout<< C << "*" << K <<endl; //Error 4 cout<<Alert<<endline;
// OR cout<< C * K <<endl; //Error 4 }
} A)
3) Rewrite the following C++ code after removing #define float MaxSpeed 60.5 ; //Error 1,2,3
any/all syntactical errorswith each correction void main()
underlined.Note: Assume all required header files are {
already being included in theprogram (2017) int MySpeed ; //Error 4
void main() char Alert=‟N‟;
{ cin>>MySpeed;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 4 PRAISE THE LORD
if (MySpeed>MaxSpeed) //Error 5 8) Rewrite the following program after removing
Alert=‟Y‟; the syntactical errors (if any).Underline each
cout<<Alert<< endl; //Error 6 correction. 2 (2011 OD)
} include<iostream.h>
6) Rewrite the following C++ code after removing all typedef char [80] String;
the syntax error(s), if present in the code. Make sure void main ( )
that you underline each correction done by you in the { String S= “Peace”;
code. (2014)2 int L=strlen(S) ;
Important Note: cout<<S<<„has‟<<L<<„characters‟<<end1;
-Assume that all the required header files are already }
included, which are essential to run this code. Ans: #include<string.h>
-The correctons made by you do not change the logic #include<iostream.h>
of the program. typedef char String [80];
Typedef char[80] STR; void main ( )
void main( ) {
{ String S = “Peace”;
Txt STR; int L= strlen(S) ;
gets(Txt); cout<<S<<“has”<< L <<“characters”<<end1;
cout<<Txt[0]<<‟\t‟<<Txt[2]; }
cout<<Txt<<endline; 9) Rewrite the following program after removing the
} syntax error(s) if any.Underline eachcorrection.2
#include<iostream.h> (2008 OD)
A) void main( )
Typedef char[80] STR; { One=10,Two=20;
void main( ) Callme(One;Two);
{ STR Txt; Callme(Two);
gets(Txt); }
cout<<Txt[0]<<”\t”<<Txt[2]; void Callme(int Arg1,int Arg2)
cout<<Txt<<endl; { Arg1=Arg1+Arg2;
} Count<<Arg1>>Arg2;
7) Observe the following C++ code carefully and }
rewrite the same after removing all the syntax Ans:
error(s) present in the code. Ensure that you void Callme(int Arg1,int Arg2=20);
underline each correction in the code. (2013)2 #include<iostream.h>
Important Note: void main( )
-All the desired header files are already included, { int One=10,Two=20;
which are required to run the code. Callme(One,Two); //Given ; instead of ,
-Correction should not change the logic of the Callme(Two);
program }
#define Convert (P,Q) P+2*Q; void Callme(int Arg1,int Arg2)
void main( ) {
{ Arg1=Arg1+Arg2;
Float A,B, Result; cout<<Arg1<<Arg2;
cin>>A>>B; }
Result=Convert [A,B]; 10) Rewrite the following program after removing the
cout<<”Output:”<<Result<<endline; syntactical error(s), if any.Underline each correction.2
} #include<iostream.h>
A) const int Size 5;
#define Convert(P,Q) P+2*Q void main( )
//No semicolon, and space between Covert and (P,Q) { int Array[Size];
void main( ) Array={50,40,30,20,10};
{ for(Ctr=0;Ctr<Size;Ctr++)
float A, B, Result; //keywords should be in small cout>>Array[Ctr];
case }
cin>>A>>B; Ans) (2007 OD)
Result=Convert(A,B); //(A,B) instead of [A,B] #include<iostream.h>
cout<<”Output:”<<Result<<end; const int Size=5;
//end instead of endline; void main( )
} { int Array[Size];
Array={50,40,30,20,10};
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 5 PRAISE THE LORD
for(Ctr=0;Ctr<Size;Ctr++) char membername[20];
cout<<Array[Ctr]; char membertype[]=”HIG”;
} };
11) Rewrite the following program after removing the void main( )
syntactical error(s), if any.Underline each correction { Supergym person1,person2;
#include<iostream.h> 2 (2006 OD) cin>>”Member Number: “;
void main( ) cin>>person1.membhernumber;
{ struct movie cout<<”Member Name: “;
{ char movie_name[20]; cin>>person1.membername;
char movie_type; person1.member type = “MIG”;
int ticket_cost=100; person2=person1;
}MOVIE; cin>>”Member Number;“ <<person2.membernumber;
gets(movie_name); cin<<”Member Name” <<person2.membername;
gets(movie_type); cin<<”Member Number:” <<person2.membertype;
} }
Ans: #include<iostream.h> Ans:
#include<stdio.h> #include<iostream.h>
void main( ) #include<string.h>
{ struct movie struct Supergym
{ char movie_name[20]; { int membernumber;
char movie_type; char membername[20];
int ticket_cost; char membertype[4];
//Initialization of variables inside a structure is not };
allowed. void main( )
}MOVIE; { Supergym person1,person2;
gets(MOVIE.movie_name); cin>>”Member Number: “;
cin>>MOVIE.movie_type; cin>>person1.membernumber;
//A single character cannot be read using gets cout<<”Member Name: “;
} cin>>person1.membername;
12) Rewrite the following program after removing the strcpy(person1.membertype,”MIG”);
syntactical error(s), if any.Underline each correction.2 person2=person1;
#include<iostream.h> cin>>”Member Number;”>>person2.membernumber;
cin>>”Member Name”>>person2.membername;
const int dividor 5; (2005 OD)
cin>>”Member Number:”>>person2.membertype;
void main( )
}
{ Number = 15;
14) Rewrite the following program after removing all
for(int Count=1;Count=<5;Count++,Number -= 3)
the syntax error(s) if any.
if(Number % dividor = = 0)
#include<iostream.h> (2003)2
cout<<Number / Dividor;
void main( )
cout<<endl;
{ int P[ ]={90,10,24,15};Q,Number=4;
else
Q=9;
cout<<Number + Dividor <<endl;
for[int I=Number-1;I>=0,I--]
Ans: switch(I)
#include<iostream.h>
{ case 0;
const int dividor= 5;
case 3:cout>>P[I]*Q<<endl;break;
void main( )
case 1:
{ int Number = 15;
case 2: cout<<P[I]+Q;
for(int Count=1;Count<=5;Count++,Number -= 3)
}
if(Number % dividor = = 0)
}
{ cout<<Number / Dividor;
Ans:
cout<<endl;
#include<iostream.h>
} void main( )
else
{ int P[ ]={90,10,24,15},Q,Number=4;
cout<<Number + Dividor <<endl;
Q=9;
} for(int I=Number-1;I>=0;I--)
13) Rewrite the corrected code for the following
switch(I)
program. Underline each correction if any.(2004)
{ case 0:
#include<iostream.h>
case 3:cout<<P[I]*Q<<endl; break;
structure Supergym
case 1:
{ int member number;
case 2: cout<<P[I]+Q;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 6 PRAISE THE LORD
} }
} Ans (i) Line No 5: Undefined symbol „i‟.
15)Find the syntax error(s), if any, in the following The variable „i‟ is not declared in the program.
program. (2002)2 (ii)Line No 10:Assign the value of a pointer to an
#include<iostream.h> integer variable. Ie error in x=y.
void main( ) 18)Find the syntax error(s), if any, in the following
{ int x; program: (1998)
cin>>x; include<iostream.h>
for( int y=0,y<10,y++) void main( )
cout<<x+y; { int R; W=90;
} while W>60
Ans: { R=W-50;
#include<iostream.h> switch(W)
void main( ) { 20:cout<<”LowerRange”<<endl;
{ int x; 30:cout<<”MiddleRange “<<endl;
cin>>x; 40:cout<<”HigherRange”<<endl;
for( int y=0;y<10;y++) }
cout<<x+y; }
} }
16)Will the following program execute successfully?If Ans:
not, state the reason(s) (2000) 2 (i) Line 1: It should be,
#include<stdio.h> #include<iostream.h>
void main( ) (ii) Line 4:Variables should be separated
{ int s1,s2,num; using commas.
s1=s2=0; It should be int R,W=90;
for(x=0;x<11;x++) (iii) Line 5:Test expression should be in
{ cin<<num; braces. It should be while (W>60)
if(num>0)s1+=num;else s2=/num; (iv) Line 10:It should be case 20;
} (v) Line 11:It should be case 30;
cout<<s1<<s2; (vi) Line 13:It should be case 40;
} So the corrected version of the program is as
Ans: The program will not execute successfully. follows:
Because some syntax errors are there in the program. They #include<iostream.h>
are(i)cin and cout, stream objects used but iostream.h void main( )
header file is not included in the program. { int R, W=90;
(ii)x is not declared, it should be declared as int.
while (W>60)
(iii)With cin, we should use >> instead of <<.
(iv)The shorthand operator /=, is given wrongly as =/. {R=W-50;
So the corrected program is as follows: switch(W)
#include<iostream.h> { case 20:cout<<”LowerRange”<<endl;
void main( ) case 30:cout<<”MiddleRange “<<endl;
{ int s1,s2,num; case 40:cout<<”HigherRange”<<endl;
s1=s2=0; }
for(int x=0;x<11;x++) }
{ cin>>num; }
if(num>0)s1+=num;else s2/=num; 19) Rewrite the following program after removing the
} syntactical errors (if any).
cout<<s1<<s2; Underline each correction. 2
} #include <iostream.h>
17) Find the syntax error(s), if any, in the following struct Pixels
program: (1999) { int Color,Style;}
#include<iostream.h> void ShowPoint(Pixels P)
main( ) { cout<<P.Color,P.Style<<endl;}
{ int x[5],*y,z[5]; void main()
for(i=0;i<5;i++) { Pixels Point1=(5,3);
{ x[i]=I; ShowPoint(Point1);
z[i]=i+3; Pixels Point2=Point1;
y=z; Color.Point1+=2;
x=y; ShowPoint(Point2);
} }
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 7 PRAISE THE LORD
Ans: (MP2 2009-10) }
#include <iostream.h> 2 for (C=1;C<L;C+=2)
struct Pixels if (T[C]>=‟M‟ && T[C]<=‟U‟)
{ int Color,Style; T[C]=‟@‟;
}; }
void ShowPoint(Pixels P) void main()
{ cout<<P.Color<<P.Style<<endl; { TEXT Str=”HARMONIOUS”;
} JumbleUp(Str);
void main() cout<<Str<<endl;
{ Pixels Point1={5,3}; }
ShowPoint(Point1); A) AHM@N@OIS
Pixels Point2=Point1;
3) Find. The output of the following program: 2
Point1.Color+=2;
#include <iostream.h> (2010 OD)
ShowPoint(Point2);
#include <ctype.h>
}
void MyCode (char Msg [], char CH)
MODEL 3b): Rewrite the following program after { for (int (Cnt=O;Msg[Cnt]!=‟\0‟;Cnt++)
removing the syntactical errors (if any). Underline { if (Msg[Cnt]>=‟B‟ && Msg[Cnt]<=‟G‟)
each correction (Using Class) -2 Marks Msg[Cnt]=tolower(Msg[Cnt]);
REFER CLASSES CHAPTER else if (Msg[Cnt]==‟A‟|| Msg[Cnt]==‟a‟)
MODEL 4a): Write the output of the following C++ Msg[Cnt]=CH;
program code (2 Marks). else if (Cnt%2==0)
Note: Assume all required header files are already Msg[Cnt]=toupper(Msg[Cnt]);
being included in the program (using pointers) else
REFER IN POINTERS CHAPTER Msg[Cnt]=Msg[Cnt-l];
MODEL 4b): Output(Using Class Concept)–3M }
REFER IN CLASSES CHAPTER }
void main ()
MODEL 4c): Output (Converting a string)–3M { char MyText [] =” ApEACeDriVE”;
1.Find and write the output of the following C++ MyCode(MyText,‟@‟);
program code: 2019SP(2) cout<<“NEW TEXT:”<<MyText<<endl;
typedef char STRING[80]; }
void MIXNOW(STRING S) Ans. NEW TEXT :@@e@ccddIIe
{ int Size=strlen(S);
4) Find the output of the following program:2
for(int I=0;I<Size;I+=2)
#include <iostream.h>(2009 OD)
{char WS=S[I];
#include <ctype.h>
S[I]=S[I+1];
void Secret (char Mig[ ], int N);
S[I+1]=WS;
void main ( )
}
{ char SMS[ ] = “rEPorTmE” ;
for (I=1;I<Size;I+=2)
Secret{SMS,2);
if (S[I]>=‟M‟ && S[I]<=‟U‟)
cout<<SMS<<end1;
S[I]=‟@‟;
}
}
void Secret(char Msg[ ], int N)
void main()
{ for (int C=0; Msg[C] !=‟ \0‟ ;C++)
{ STRING Word=”CBSEEXAM2019”;
if (C%2==0)
MIXNOW(Word);
Msg[C] = Msg[C]+N;
cout<<Word<<endl;
else if (isupper(Msg[C]))
}
Msg[C] = tolower(Msg[C]);
Ans: BCE@XEMA0291
else
2)Find and write the output of the following C++
Msg[C] = Msg[C]-N;
program code: (2016)
}
Note: Assume all required header files are already
Ans: teRmttoe
included in the program. 2
typedef char TEXT[80]; 5)Find the output of the following program: 3
void JumbleUp(TEXT T) #include<iostream.h> (2008 OD)
{int L=strlen(T); #include<ctype.h>
for (int C=0;C<L1;C+=2) void main( )
{ char CT=T[C]; { char Mystring[ ] = ―what@OUTPUT!‖;
T[C]=T[C+1]; for(int I=0; Mystring[I]!=‟\0‟;I++)
T[C+1]=CT; { if(!isalpha(Mystring[I]))
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 8 PRAISE THE LORD
Mystring[I]=‟*‟; else if(isupper(NAME[x]))
else if(isupper(Mystring[I])) if(x%2==0)
Mystring[I]=Mystring[I]+1; NAME[x]=tolower(NAME[x]);
else else
Mystring[I] =Mystring[I+1]; NAME[x]=NAME[x-1];
} puts(NAME);
cout<<Mystring;} Ans: INTTaNEE
Ans: hat@*PVUQVU* 9)Find the output of the following program: 2
#include <iostream.h>(MP1 2008-09)
6) Find the output of the following program 2 #include <ctype.h>
#include<iostream.h> (2005 OD) void Encrypt(char T[])
#include<string.h> { for (int i=0;T[i]!=‟\0‟;i+=2)
#include<ctype.h> if (T[i]==‟A‟ || T[i]==‟E‟)
void Change(char Msg[],int Len) T[i]=‟#‟;
{ for(int Count=0;Count<Len;Count++) else if (islower(T[i]))
{ if(islower(Msg[Count])) T[i]=toupper(T[i]);
Msg[Count] = toupper(Msg[Count]); else
else if(isupper(Msg[Count])) T[i]=‟@‟;
Msg[Count] = tolower(Msg[Count]); }
else if (isdigit(Msg[Count])) void main()
Msg[Count]=Msg[Count]+1; { char Text[]=”SaVE EartH”;
else Msg[Count] = „*‟; //The two words in the string Textare separated by
} single space
} Encrypt(Text);
void main( ) cout<<Text<<endl;
{char Message[ ]=”2005 Tests ahead”; }
int Size=strlen(Message); Answer: @a@E@E#rTH
Change(Message,Size);
cout<<Message<<endl; 10) Find the output of the following program: 2
for(int C=0,R=Size – 1; C<=Size/2;C++,R--) #include <iostream.h>(MP1 2009-10)
{ char Temp=Message[C]; void Secret(char Str[ ])
Message[C]=Message[R]; { for (int L=0;Str[L]!=‟\0‟;L++);
Message[R]=Temp; for (int C=0;C<L/2;C++)
} if (Str[C]==‟A‟ || Str[C]==‟E‟)
cout<<Message<<endl; Str[C]=‟#‟;
} else
Ans: 3116*tESTS*AHEAD {char Temp=Str[C];
DAEHA*SSTEt*6113 Str[C]=Str[L-C-1];
Str[L-C-1]=Temp;
7)Give the output of the following program }
segment(Assuming all required header files are }
included in the program): (2000) 2 void main()
char *NAME=”a ProFiLe”; { char Message[ ]=”ArabSagar”;
for(int x=0;x<strlen(NAME);x++) Secret(Message);
if(islower(NAME[x])) cout<<Message<<endl;
NAME[x]=toupper(NAME[x]); }
else if(isupper(NAME[x])) A) #agaSbarr
if(x%2!=0)
NAME[x]=tolower(NAME[x-1]); MODEL 4d): Output (Using functions)–2M
else
1) Find and write the output of the following C++
NAME[x]--;
programs code: (2018)
cout<<NAME<<endl;
Note: Assume all required header files are already
Ans: AOROoIiE
included in the program.
8) Give the output of the following program segment: void Revert(int &Num, int Last=2)
(1998) { Last = (Last%2= =0) ? Last +1 : Last – 1;
char *NAME=”IntRAneT”; for(int C=1; C<=Last; C++)
for(int x=0;x<strlen(NAME); x++) Num + = C;
if(islower(NAME[x]) }
NAME[x]=toupper(NAME[x])); void main( )
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 9 PRAISE THE LORD
{ int A=20,B=4; Indirect(Num);
Revert (A,B); }
cout<<A<<”&”<<B<<endl; void main( )
B- -; { int Number=20;
Revert(A,B); Direct(Number);
cout<<A<<”#”<<B<<endl; Indirect( );
Revert(B); cout<<”Number =”<<Number<<endl;
cout<<A<<”#”<<B<<endl; }
} Ans: 10,15,20,25,30,
Ans) 35&4 10,15,20,
38#3 Number =30
38#9 5) Write the output of the following program: (2003)
2)Write the output of the following C++ program #include<iostream.h>
code:Note: Assume all required header files are int Execute(int M)
already beingincluded in the program. (2015)2 { if(M%3==0)
void Location(int &X,int Y=4) return M*3;
{ Y+=2; else
X+=Y; return M+10;
} }
void main() void Output(int B=2)
{ int PX=l0,PY=2; { for(int T=0;T<B;T++)
Location(PY) ; cout<<Execute(T)<<”*”;
cout<<PX<<” , “<<PY<<endl ; cout<<endl;
Location(PX,PY); }
cout<<PX<<” , “<<PY<<endl ; void main( )
} { Output(4);
A) 10, 8 Output( );
20, 8 Output(3);
(3) Find the output of the following program:3 }
#include<iostream.h>(2011 OD) 6)Write the output of the following program 3
void SwitchOver(int A [ ], int N, int Split) #include<iostream.h> (2002)
{ for (int K=0 ; K<N; K++) void X(int &A,int &B)
if (K<Split) { A=A+B;
A(K]+ =K; B=A-B;
else A=A-B;
A [K]*=K; }
} void main( )
void Display (int A [ ], int N) { int a=4,b=18;
{ X(a,b);
for (int K=0 ; K<N ; K++) cout<<a<<”,”<<b;
(K%2==0)? Cout<<A[K]<<”%”:cout<<A(K]<<endl; }
} Ans: 18,4
void main ( ) 7) Give the output of the following program: (2001)
{ int H[ ]= {30,40,50,20,10,5}; #include<iostream.h>
SwitchOver (H, 6, 3); #include<conio.h>
Display (H, 6); int g=20;
} void func(int &x,int y)
Ans: 30%41 { x=x-y;
52%60 y=x*10;
40%25 cout<<x<<‟,‟<<y<<‟\n‟;
4)Find the output of the following program3 }
#include<iostream.h> (2007 OD) void main( )
void Indirect(int Temp=20) { int g=7;
{ for(int I=10;I<=Temp;I+=5) func(g,::g);
cout<<I<<”,”; cout<<g<<‟,‟<<::g<<‟\n‟;
cout<<endl; func(::g,g);
} cout<<g<<‟,‟<<::g<<‟\n‟;
void Direct(int &Num) }
{ Num+=10;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 10 PRAISE THE LORD
Ans: -13,-130 for (int L=0;L<3;L++)
-13,20 cout<<A[L]<<‟#‟;
33,330 cout<<endl;
-13,33 for (L=0;L<4;L++)
8)Write the output of the following program 3 cout<<B[L] <<‟#‟;
#include<iostream.h> (2000) cout<<endl;
int func(int &x,int y=10) for (L=0;L<2;L++)
{ if(x%y==0) return ++x;else return y- -; cout<<C[L] <<‟#‟;
} }
void main( ) Answer:
{ int p=20,q=23; 7#9#5#
q=func(p,q); 30#50#70#40#
cout<<p<<q<<endl; 2100#1200#
p=func(q); MODEL 4e): Output (Using functions &
cout<<p<<q<<endl; Structures) – 3M
q=func(p);
cout<<p<<q<<endl; (1) Find the output of the following program: 3
} #include <iostream.h> (2010 OD)
Ans: 2023 struct THREE_D
1023 { int X,Y,Z;};
1111 void MoveIn(THREE_D &T, int Step=l)
{ T.X+=Step;
9) Write the output of the following program. T.Y-=Step;
#include<iostream.h> (1999) T.Z+=Step;
static int i=100; }
void abc( ) void MoveOut(THREE_D &T, int Step=l)
{ static int i=8; { T.X-=Step;
cout<<”first =”<<I; T.Y+=Step;
} T.Z-=Step;
main( ) }
{ static int i=2; void main ()
abc( ); { THREE_D Tl={lO,20,5},T2={30,lO,40};
cout<<”second =”<<i<<endl; } MoveIn(T1);
Ans: First =8second =2 MoveOut(T2,5) ;
10) Write the output of the following program: cout<<Tl.X<<“,”<<Tl.Y<<“,”<<T1.Z<<endl;
#include<iostream.h>(1998) cout<<T2.X<<“,”<<T2.Y<<“,”<<T2.Z<<endl;
void Execute(int &X,int Y=200) MoveIn(T2,l0);
cout<<T2.X<<“,”<<T2.y<<“,”<<T2.Z<<endl;
{ int TEMP=X+Y;
}
X+=TEMP;
Ans. 11, 19, 6
if(Y!=200)
25, 15, 35
cout<<TEMP<<X<<Y<<endl;
35, 5, 45
}
2) Find the output of the following program:
void main( )
#include<iostream.h> (2005 OD)
{ int A=50,B=20;
struct Package
Execute(B);
{ int Length,Breadth,Height;
cout<<A<<B<<endl;
};
Execute(A,B);
void Occupies(Package M)
cout<<A<<B<<endl;
{ cout<<M.Length<<”x”<<M.Breadth<<”x”;
}
cout<<M.Height<<endl;
11)Find the output of the following program3
}
#include <iostream.h> (MP2 2008-09 )
void main( )
void Changethecontent(int Arr[], int Count)
{ Package P1={100,150,50},P2,P3;
{ for (int C=1;C<Count;C++)
++P1.Height;
Arr[C-1]+=Arr[C];
Occupies(P1);
}
P3=P1;
void main()
++P3.Lengh;
{ int A[ ]={3,4,5},B[ ]={10,20,30,40},C[ ] ={900,1200};
P3.Breadth++;
Changethecontent(A,3);
Occupies(P3);
Changethecontent(B,4);
P2=P3;
Changethecontent(C,2);
P2.Height+=50;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 11 PRAISE THE LORD
P2.Length--; #include <ctype.h>
Occupies(P2); typedef char str80 [80] ;
3) Give the output of the following program: void main ( )
#include<iostream.h> (2003) { char *Notes ;
struct Pixel str80 str="vR2GooD";
{ int C,R; int L=6;
}; Notes=Str;
void Display(Pixel P) while (L>=3)
{Str[L]=(isupper(Str[L])?tolower(Str[L]):
{ cout<<”col”<<P.C<<”Row”<<P.R<<endl;
toupper(Str[L]));
} cout<<Notes<<endl;
void main( ) L--;
{ Pixel X={40,50},Y,Z; Notes++;
Z=X; }
X.C+=10; }
Y=X; Ans) vR2Good
Y.R+=20; R2GoOd
Z.C-=15; 2GOOd
Display(X); gOOd
Display(Y); 3) Find the output of the following program: 2
Display(Z); #include<iostream.h> (2008OD)
} void main( )
4)Find the output of the following program: 3 { int A=5,B=10;
#include <iostream.h>(MP1 2008-09) (MP1 2009-10) for(int I=1;I<=2;I++)
struct PLAY { cout<<”Line1”<<A++<<”&”<<B-2 <<endl;
{ int Score, Bonus; cout<<”Line2”<<++B<<”&”<<A +3 <<endl;
}; }
void Calculate(PLAY &P, int N=10) }
{ P.Score++; Ans: Line15&8
P.Bonus+=N; Line211&9
} Line16&9
void main() Line212&10
{ PLAY PL={10,15};
Calculate(PL,5); 4. Find the output of the following program 2
cout<<PL.Score<<”:”<<PL.Bonus<<endl; #include<iostream.h> (2006 D)
Calculate(PL); void main( )
cout<<PL.Score<<”:”<<PL.Bonus<<endl; { long NUM=1234543;
Calculate(PL,15); int F=0,S=0;
cout<<PL.Score<<”:”<<PL.Bonus<<endl; do
} { int R=NUM % 10;
Answer: 11:20 if (R %2 != 0)
12:30 F += R;
13:45 else
S += R;
MODEL 4f): Output (Mislleneous) – 2M NUM / = 10;
1. Find and write the output of the following C++ } while (NUM>0);
program code:Note: Assume all required header files cout<<F-S;
are already included in theprogram. (2017)2 }
#define Diff(N1,N2) ((N1>N2)?N1-N2:N2-N1) Ans: 2
void main() 5)Find the output of the following program 2
{ int A,B,NUM[] = {10,23,14,54,32}; #include<iostream.h (2006 OD)
for(int CNT =4; CNT>0; CNT--) void main( )
{ A=NUM[CNT]; { long Number=7583241;
B=NUM[CNT-1]; int First = 0, Second =0;
cout<<Diff(A,B)<<'#'; do
} { int R=Number%10;
} if(R%2 ==0)
Ans) 22#40#9#13# First += R;
2.Find the output of the following program:2 else
#include <iostream.h> (2012) Second += R;
Number / = 10;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 12 PRAISE THE LORD
} while (Number > 0); Assume all the required header files are already being
cout<<First-Second; included in the code. The function random(n)
} generates an integer between o and n-1.
Ans: -2 void main( )
6) What will be the output of the following program { randomize( );
#include<iostream.h> (2004) int A[4], C;
void main( ) for (C=0;C<4;C++)
{ int var1=5,var2=10; A[C]=random(C+1) + 10;
for(int i=1,i<=2;i++) for(C=3;C>=0;C- - )
{ cout<<var1++<<‟\t‟<< - - var2<<endl; cout<<A[C]<<”@”;
cout<<var2- -<<‟\t‟<<+ + var1<<endl; }
} (i) 13@10@11@10@
} (ii)15$14$12$10$
Ans: 5 9 (iii)12@11@13@10@
9 7 (iv) 12@11@10@10@
7 7 Ans) (i) 13@10@11@10@
7 9 (iv) 12@11@10@10@
Highest value that can be assigned in the array A = 13
7)Write the output of the following program2
Lowest value that can be assigned in the array A = 10
void main( ) (2002)
{ int x=5,y=5; 3. Look at the following C++ code and find the
cout<<x- -; possible output(s) from theoptions (i) to (iv) following
cout<<”,”; it. Also, write the maximum values that canbe
cout<- - x; assigned to each of the variables N and M.
cout<<”,”; Note:● Assume all the required header files are
cout<<y- -<<”,”<<- -y; already being included inthe code. (2017)2
} ● The function random(n) generates an integer
Ans: 5,3,4,4 between 0 and n-1
void main()
MODEL 5):Possible Output (Random)– 2M { randomize();
1.Observe the following program and find out, int N=random(3),M=random(4);
which output(s) out of (i) to (iv) willbe expected int DOCK[3][3] = {{1,2,3},{2,3,4},{3,4,5}};
from the program? What will be the minimum and for(int R=0; R<N; R++)
the maximum value assigned to the variable Alter? { for(int C=0; C<M; C++)
Note: Assume all required header files are already cout<<DOCK[R][C]<<" ";
being included in the program. 2019SP(2) cout<<endl;
void main( ) }
{ randomize(); } Ans:
int Ar[]={10,7}, N;
int Alter=random(2) + 10 ;
for (int C=0;C<2;C++)
{ N=random(2) ;
cout<<Ar[N] +Alter<<”#”;
}
}
(i) 21#20# (ii) 20#18# Correct Options : (ii) and (iii)
(iii) 20#17# (iv) 21#17# Maximum value of N = 2
Ans: The output expected from the program is Maximum value M = 3
(iii) 20#17#
4)Observe the following program carefully and
Minimum Value of Alter = 10
attempt the givenquestions: 2
Maximum Value of Alter = 11
#include<iostream.h> (2017 MP)
(Note: The above answer is given in the marking Scheme.
But I feel personally that the answer is incorrect. #include<conio.h>
Minimum value and maximum value of Alter is correct) #include<stdlib.h>
void main()
2) Look at the following C++ code and find the {
possible output(s) from the options (i) to (iv) clrscr();
following it. Also, write the highest and lowest randomize();
values that can be assigned in the array A. char courses[][10]={"M.Tech","MCA","MBA","B.Tech"};
Note: 2018 int ch;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 13 PRAISE THE LORD
for(int i=1;i<=3;i++) Note:‐Assume all required header files are already
{ ch=random(i)+1; being included inthe program. (2015)
cout<<courses[ch]<<"\t"; ‐random(n) function generates an integer between 0
} and n‐1.
getch(); void main()
} { randomize();
I. Out of all the four courses stored in the variable int VAL;
courses, which course will never be displayed in the VAL=random(3)+2;
output and which course will always be displayed char GUESS[]=”ABCDEFGHIJK”;
at first in the output? for (int I=l;I<=VAL;I++)
Ans: M.Tech will never be displayed in the output. { for(int J=VAL;J<=7;J++)
MCA will always be displayed at first in the output. cout«GUESS[J];
II. Mention the minimum and the maximum value cout«endl;
assigned to thevariable ch? }
Ans: Minimum value of ch=1 }
Maximum value of ch=3 (i) (ii) (iii) (iv)
BCDEFGH CDEFGH EFGH FGHI
5)Look at the following C++ code and find the BCDEFGH CDEFGH EFGH FGHI
possible output(s) from the options (i)to (iv) EFGH FGHI
following it. Also, write the maximum and the EFGH FGHI
minimum values that can be assigned to the A)(ii) and (iii)
variable PICKER. 2 Min Value of VAL = 2
Note:‐ Assume all the required header files are Max Value of VAL = 4
already being included in the code. 7)Read the following C++ code carefully and find out,
‐ The function random(n) generates an integer which out of the given option (i) to (iv) are expected
between 0 and n‐1 (2016) correct output(s) of it. Also, write the maximum and
void main() minimum value that can be assigned to the variable
{ Taker used in the code: (2014)
randomize(); void main( )
int PICKER; { int GuessMe[4]={100,50,200,20};
PICKER=1+random(3); Int Taker=random(2)+2;
char For(int Change=0;Change<Taker;Change++)
COLOR[][5]={”BLUE”,”PINK”,”GREEN”,”RED”}; Cout<<GuessMe[Change]<<”#”;
for(int I=0;I<=PICKER; I++) }
{ for(int J=0; J<=I;J++) (i) 100# (ii) 50#200#
cout<<COLOR[J]; (iii)100#50#200# (iv)100#50#
cout<<endl; Answer:(iii) and (iv)
} Maximum Value = 3
} Minimum Value = 2
8)Based on the following C++ code, find out the
expected correct output(s) from the options (i) to (iv).
Also, find out the minimum and the maximum value
that can be assigned to the variable Trick used in the
code at the time when value of Count is 3: 2
A) void main( ) (2013)
{ char Status[ ][10]={“EXCEL”,”GOOD”,”OK”};
int Turn=10, Trick;
for(int Count=1;Count<4;Count++)
{ Trick=random(Count);
cout<<Turn-Trick<<Status[Trick]<<”#”;
}
Minimum Value of PICKER = 1 }
Maximum Value of PICKER = 3 (i) 10EXCEL#10EXCEL#80K#
(ii) 10EXCEL#80K#9GOOD#
6) Study the following program and select the (iii) 10EXCEL#9GOOD#10EXCEL#
possible output(s)from the option (i) to (iv) (iv) 10EXCEL#10GOOD#80K#
following it. Also, write the maximumand the A) Minimum Value for Trick: 0
minimum values that can be assigned to the Maximum Value for Trick: 2
variableVAL. 2 (i) & (iii)

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 14 PRAISE THE LORD


9) Observe the following program and find out, which (iii) 29:26:24:28: (iv) 29:26:25:26:
output(s) out of (i) to (iv) will not be expected from Ans. (iv) 29:26:25:26:
the program? What will be the minimum and the Justification is as follows:
maximum value assigned to the variable Chance? I POINT Number
#include<iostream.h> (2012 D) Minimum Maximum
#include<stdlib.h> 1 5 25 29
void main( ) 2 4 25 28
{ randomize( ); 3 3 25 27
int Arr[ ] ={9,6},N; 4 2 25 26
int Chance=random(2)+10; The only option that satisfies these values is option (iv).
for(int C=0;C<2;C++) 12) Study the following program and select the
{ N=random(2); possible output from it :2
cout<<Arr[N]+Chance<<”#”; #include<iostream.h> (2009 OD)
} #include <stdlib.h>
} const int MAX=3 ;
(i) 9#6# (ii)19#17# void main ( )
(iii)19#16# (iv) 20#16# { randomize( ) ;
Ans: (i) 9#6# int Number ;
Minimum Value: 10 Maximum Value: 11 Number = 50 + random{MAX) ;
10) Go through the C++ code shown below, and find for (int P=Number; P>=50; P– –)
out the possible output or outputs from the suggested cout<<p<< “ # ” ;
Output Options (i) to (iv). Also, write the minimum cout<<endl;
and maximum values, which can be assigned to the }
variable MyNum. 2 (i)53#52#51#50#(ii) 50#51#52#
#include<iostream.h> (2011 OD) (iii) 50#51#(iv)51#50#
#include <stdlib.h> Ans(iv) 51#50#
void main ( ) (Solution: MAX value is 3. That‟s why
{randomize ( ) ; random(MAX)can produce 0 or 1 or 2.
int MyNum, Max=5; (random(N)will produce no.between 1 to n-1). The
MyNum = 20 + random (Max) ; Number value may be 50 or 51 or 52. The P value
for (int N=MyNum; N<=25;N++) starts from Number, upto50,each time decreases by 1.
cout<N<”*”; So Possible outputs are as follows:
} 52#51#50#
(i)20*21*22*23*24*25 51#50#
(ii) 22*23*24*25* 50#.
(iii) 23*24* As the output 51#50# is available in given answers, so
(iv)21*22*23*24*25 51#50# is the answer.)
Ans (ii) 22*23*24*25* 13) In the following program, find the correct possible
Minimum value 20 output(s) from the options: 2
Maximum value 24 #include<stdlib.h> (2008 OD)
11) The following code is from a game, which #include<iostream.h>
generates a set of 4 random numbers. Praful is playing void main( )
this game, help him to identify the correct option(s) { randomize( );
out of the four choices given below as the possible set char Area[
of such numbers generated from the program code so ][10]={“NORTH”,”SOUTH”,”EAST”,”WEST”};
that he wins the game. Justify your answer. 2 int ToGo;
#include<iostream.h> (2010 OD) for(int I=0; I<3;I++)
#include <stdlib.h> { ToGo=random(2) + 1;
const int LOW=25; cout<<Area[ToGo]<<”:”;
void main () }
{ randomize() ; }
int P01NT=5,Number; Ans: Outputs:
for (int I=1;I<=4;I++) (i) SOUTH : EAST : SOUTH :
{ Number=LOW+random(POINT); (ii) NORTH : SOUTH : EAST :
cout<<Number<<“:”; (iii) SOUTH : EAST : WEST :
P0INT--; (iv) SOUTH : EAST : EAST :
} Ans)Since random(2) gives either 0 or 1, ToGo value
} will be either 1 or 2. (random(n) gives you any
(i)29:26:25:28: (ii) 24:28:25:26: number between 0 to n-1)Area[1] is
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 15 PRAISE THE LORD
“SOUTH”.Area[2] is “EAST”. Since I value from 0 to void main()
2 (ie<3), 3 iterations will takes place. So the possible { int N,Guessme;
output consists 3 strings separated by :, each of them randomize();
may be either “SOUTH” or “EAST”. cin>>N;
So the possible output will be Guessme=random(N)+10;
(i) SOUTH : EAST : SOUTH : cout<<Guessme<<endl;
(iv) SOUTH : EAST : EAST : }Ans: Maximum Value:24 Minimum Value:10
14) In the following C++ program what is the 18)In the following program, if the value of N given
expected value of MyMarks from options (i) to by the user is 20, what maximum and minimum values
(iv)given below. Justify answer. 2 the program could possibly display? 2
#include<stdlib.h> (2007 D) #include<iostream.h> (2008-09 MP2) (2009-10 MP2)
#include<iostream.h> #include <stdlib.h>
void main( ) void main()
{ randomize( ); { int N,Guessnum;
int Marks[]={99,92,94,96,93,95},MyMarks; randomize();
MyMarks = Marks [1+random(2)]; cin>>N;
cout<<MyMarks<<endl; Guessnum=random(N-10)+10;
} cout<<Guessnum<<endl;
(i)99 (ii)94 (iii)96 (iv) None of the above. }Ans: Maximum Value:19 Minimum Value:10
Ans: (ii) 94 19) In the following program, if the value of Guess
15) In the following C++ program what is the entered by the user is 65, what will be the expected
expected value of Mysore from options (i) to (iv) output(s) from the following options (i), (ii), (iii) and
given below.Justify your answer. 2 (iv)? 2
#include<stdlib.h> (2007 OD) #include <iostream.h>
#include<iostream.h> #include<stdlib.h> (2009-10 MP1)
void main( ) void main()
{ randomize( ); { int Guess;
int Score[ ] = {25,20,34,56,72,63},Myscore; randomize();
cout<<Myscore<<endl; cin>>Guess;
} for (int I=1;I<=4;I++)
(i) 25 (ii) 34 (iii) 20 (iv) None of the above. { New=Guess+random(I);
Ans: Expected Output: cout<<(char)New;
}
(i) None of the above.
}
16) Observe the following program GAME.CPP (i)ABBC (ii) ACBA (iii)BCDA (iv) CABD
carefully, if the value of Num entered by the user is A)(i) ABBC
14, choose the correct possible output(s) from the
options from (i) to (iv),and justify your option.2 MODEL 6): Theory Question – 2M
//Program:GAME.CPP
1)Explain conditional operator with suitable
#include<stdlib.h> (2005 OD)
example? 2
#include<iostream.h> A) Conditional operator is also known as ternary
void main( ) operator because itrequires three operands and can be
{ randomize( );
used to replace simple if-elsecode. It is used to check
int Num,Rndnum; the condition and execute first expression ifcondition
cin>>Num; is true else execute other. (2017 MP)
Rndnum=random(Num)+7;
Syntax:
for(int N=1;N<=Rndnum;N++) Conditional expression? Expression 1 : Expression 2;
cout<<N<<” “; Explanation:
} If the conditional expression is true then expression 1
Output Options: executesotherwise expression 2 executes.
(i) 1 2 3 (ii) 1 2 3 4 5 6 7 8 9 10 11 Example:
(iii) 1 2 3 4 5 (iv) 1 2 3 4 int y=10,x;
Ans: Expected Output x=y>10?1:0;
(ii) 1 2 3 4 5 6 7 8 9 10 11 cout<<x;
17)In the following program, if the value of N given Output: 0
by the user is 15, what maximum and minimum values 2) What is the difference between call by reference
the program could possibly display? 2 and call by value with respect to memory allocation?
#include <iostream.h> Give a suitableexample to illustrate using aC++ code.
#include<stdlib.h> (2008-09 MP1) (2014 OD) (2010 OD)(2009) (2005D) 2
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 16 PRAISE THE LORD
}
Call by value Call by reference
The actual arguments will The formal perameters 4) Give the difference between the type casting and
be copied into formal are the reference to the automatic type conversion. Also, give a suitable C++
perameters. actual arguments code toillustrate both (2012D) (2011 OD) (2010 D)2
If we done any If we done any Ans.Automatic Type Conversion: It is an implicit
process of conversion of a data from one data type to
modifications to the modifications to the
another. It is performed by the compiler.Compiler
formal perameters, formal perameters,
converts entire expression to biggest datatype so it is
actual arguments will not actual arguments will be also called as type promotion.
be modified. modified. Example:
We should use call by We should use call by int N = 65;
value when we do not reference when we want char C = N; // Automatic type conversion
want to change the to change the original cout<<C;
original values. values. Output:A
Type Casting: It is an explicit process of conversion
Formal perameters Formal perameters of a data from one type to another.
declaration will not be declaration will be (It is performed by the programmer.)
preceded by & in the preceded by & in the Example:
function definition. function definition. int A=1, B=2;
Ex: float C = (float)A/B; //Type Casting
Void Compute(int A, int &B) cout<<C;
{A++; Output: 0.5
B++; 5) What is the difference between Local Variable and
cout<<”In the function”<<endl; Global Variable?Also, give a suitable C++ code to
cout<<”A=”<<A<<“&”<<“B=”<<B<<endl; illustrate both. (2011D)(2003) 2
} Ans:Local Variables: Local variables are those
void main () variables which are declared within a function or a
{int I=50,J=25; compound statement(block) and these variables can
cout<<”Before function call “<<endl; only be used within that function/scope.
cout<<”I=”<<I<<”&”<<”J=”<<J <<endl; Global Variables: In contrast to local variables,
Compute (I,J) ; variables declared outside of all the functions in a
cout<<”After function call “<<endl; program are called global variables. These variables
cout<<I=”<<I<<”&”<<”J=”<<J <<endl; are defined outside of any function, so they are
} accessible to all functions. They are also known as
Here in the above example, A is called by value and External Variables.
B is called byreference. Example Code:
OUTPUT int a,b;
Before function call void main()
I=50&J=25 { float f;
In the function ---;
A=51&B=26 ---;
After function call }
I=50&J=26 In the above program segment, a and b are global
3) What is the benefit of using function prototype for a variables, we can access a and b from any function. F
function? Give a suitable example to illustrate it using is local variable to function main( ), we can access f
a C++ code. (2013D)2 from main( ) only.
A) The benefit of using function prototype for a
function is that, it tells the compilr that there is a some 5) What is the difference between Global Variable
function defined somewhere in the program and we and Local Variable?
can access it. (2008-09 MP1) (2009-10 MP1) 2
Example: Answer:
void Add(int,int) //function prototype Global Variable Local Variable
void main( )  It is a variable,  It is a variable,
{ Add(4,6); which is declared which is declared
} outside all the with in a function
void Add(int a, int b) functions or with in a
{ compound
cout<<a+b; statement
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 17 PRAISE THE LORD
 It is accessible  It is accessible only compiler, before the code is turned into binary. This
throughout the within a means that the compiler makes the substitution when
program function/compound you compile the application.
statement in which Eg: #define number 100
it is declared In this case every instance of “number” will be
#include <iostream.h> replaced by the actual number 100 in your code, and
float NUM=900; //NUM is a global variable this means the final compiled program will have the
void LOCAL(int T) number 100 (in binary).
{ int Total=0; //Total is a local variable #define with different types of data:
for (int I=0;I<T;I++) *The #define preprocessor allows u s to define
Total+=I; symbolic names and constants.
cout<<NUM+Total; Eg: #define PI 3.14159
} *The #define allows you to make text
void main() substitutions before compiling the program.
{ LOCAL(45); Eg: #define MAX 70
} * Before compilation, if the C++ preprocessor
finds MAX as one word, in the source code, it
6) What is the difference between Actual Parameter replaces it with the number 70.
and Formal Parameter?Give an example in C++ to * The #define preprocessor can be used in the
illustrate both types of parameters. creation of macros (code substitution).
(2009 OD) (2009-10 MP2) 2 Eg: #define SQUARE(x) x*x
Ans A parameter used in the function call is known as Before compilation, if the C++ preprocessor
Actual Parameter. It is used to send the data to finds SQUARE(x), where x is any value in the source
function. code, it replaces it with its square (ie x*x). Here a
A parameter used in the function definition is macro substitutes text only; It does not check for data
known as Formal Parameter, Itis used to accept the types.
data from actual parameter. On the other hand, when we use const and the
void Seventimes(int A) //A is formal parameter application runs, memory is allocated for the constant
{ cout<<7*A; and the value gets replaced when the application is
} run.
void main () Syntax: const type variable_name=value;
{ int P=6; Eg: const int a=10;
Seventimes(P); //p is actual parameter The value of a constant is fixed and in
} the above example, the value for a in entire program is
/* Other answer for the same question: 10 only. You cannot change the value of a, since it is
The parameters in the function call statement (or declared as constant.
calling function) are called as Actual Parameters. Difference between #define and const in
The parameters in the function definition (or declaration:.
called function) are called as Formal Parameters. 1.#define: #define symbolic_constant value.
Eg: Eg: #define number 100 //No semicolon ,no equal to
void manip(int x, int y) symbol.
{ --- 2.const: const type variable_name=value;
--- Eg: const number=100; //Semicolon, equal to
} symbol.
void main( ) 8) Illustrate the use of #define in C++ to define a
{ macro. 2
int a,b; Ans: The #define preprocessor can be used in the
---- creation of macros (code substitution).(2006 D)
manip(a,b); Eg: #define SQUARE(x) x*x
} Before compilation, if the C++ preprocessor finds
Here a,b are Actual Parameters and SQUARE(x), where x is any value in the source
x,y are Formal Parameters. code, it replaces it with its square (ie x*x). Here a
*/ macro substitutes text only; It does not check for data
types.
7) What is the difference between #define and const?
Explain with suitable example.(2008 D)2 9) What is the purpose of using a typedef command
Ans: While they both serve a similar purpose, #define in C++?Explain with suitable example (2008 OD) 2
and const act differently. When using #define the Ans: C++ allows you to define explicitly new data
identifier gets replaced by the specified value by the type names by using the keyword typedef. Using
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 18 PRAISE THE LORD
typedef does not actually create a new data class, (ii)cin<<a;In this statement, since stream insertion
rather it defines a new name for an existing type. This operator (<<) has given instead of stream extraction
can increase the portability of a program as only the operation(>>), there will occurs a syntax error.
typedef statements would have to be changed.
11) Differentiate between a Logical Error and Syntax
Typedef makes your code easier to read and
Error. Also give suitable examples of each in C++.2
understand. Using typedef can also aid in self
Ans:Logical Error: A logical error is that error which
documenting your code by allowing descriptive names
causes a program to produce incorrect or undesired
for the standard data types.
output.
The syntax of the typedef statement is
An incorrectly implemented algorithm or use
typedef type name;
of a variable before its initialization, or unmarked end
Where type is any C++ data type and name is the new
for a loop, or wrong parameters passed are causes
name for this type. This defines another name for the
logical errors. These must be handled carefully.
standard type of C++. For example, you could create
For instance, if we are trying to print the table
a new name for float values by using the following
of a number 5 and if we say (2007 OD)
statement:
counter=1;
typedef float amount;
while(counter>8)
This statement tells the compiler to recognize amount
{ cout<<n*counter;
as an alternative name for float. Now you could
counter=counter+1;
create float variables using amount.
}
Amount loan, saving, installment;
Here the loop would not be executed even once as the
Using typedef does not replace the standard C++ data
condition (counter>8) is not fulfilled at all. Therefore,
type name with the new name, rather the new name is
no output will be produced. Such an error is logical
in addition to the existing name. You still can create
error.
float variables using float. Once a new name has been
Syntax Error: Syntax errors occur when rules of a
defined by typedef, it can be used as a type for another
programming languages (syntax) is misused. Ie when
typedef also.
a grammatical rule of C++ is violated.
Eg: typedef amount money;
Eg (i) c=a+b
Now, this statement tells the compiler to
In this statement, since there is no semicolon at the
recognize money as another name for amount, which
end of the statement, there will occurs a syntax error.
itself is another name for float. Typedef does not
(ii)cin<<a; In this statement, since stream
create any new data types rather provides an
insertion operator (<<) has given instead of stream
alternative name for standard types. Reference
extraction operation(>>), there will occurs a syntax
provides an alias name for a variable and typedef
error.
provides an alias name for a data type.
12) What are Nested Structures? Give an example.
Ans: Nested structures are structures as member of
10) Differenctiate between a Run Time Error and
another structure. For example, the date of birth is
Syntax Error. Also give suitable examples of each in
astructure within the structure of a student as shown
c++. (2007 D)2
below. These types of structures are known as nested
Ans:Run Time Errors: Errors that occur during the
structures. (2006D)
execution of a program are called as run time errors. It
is caused of some illegal operation taking place or
inavailability of desired or required conditions for the
Eg1:
execution of the program. For instance, if a program
struct date
is trying to open a file which does not exist or it could
{ int dd;
not be opened, it results into an execution error.
int mm;
Similarly, if enough memory is not available or an
int yy;
expression is trying to divide a number by zero are
};
run-time errors.
struct student
Eg: Division by zero. C=a/b ;
{ char name[20];
User will give the values of a and b at the time of
int roll;
program execution.If he give the value of b as „0‟ ,
date dob;
then division by zero, ie a run time error occurs.
int marks;
Syntax Errors:Syntax errors occur when rules of a
};
programming languages (syntax) is misused. Ie when
The member of a nested structure is referenced from
a grammatical rule of C++ is violated.
the outermost to innermost with the help of dot
Eg (i) c=a+bIn this statement, since there is no
operators.
semicolon at the end of the statement, there will
Student stud;
occurs a syntax error.
Then the members of the nested structure can be
accessed as stud.dob.mm=10;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 19 PRAISE THE LORD
Eg2: cout<<”\nThe sum of the series =
struct addr “<<SumSequence(x,n);
{ int houseno; getch();
char area[26]; }
char city[26]; double SumSequence(int x1,int n1)
char state[26]; {double sum=0;
}; int c=0;
struct emp for(int i=1;i<=(2*n1);i=i+2)
{ int empno; { int f=1;
char name[26]; for(int j=1;j<=I;j++)
char design[16]; { f=f*j;
addr address; }
float basic; c=c+1;
}worker; if(c%2==1)
13) Why main( )function is so special. Give two { sum=sum+f/(pow(x1,c));
reasons? (1999) 1 }
Ans: Execution of the program starts and ends at else
main( ). The main( ) is the driver function of the { sum=sum-f/(pow(x1,c));
program. If it is not present in a program,no }
execution can take place. }
return sum;
14)Differentiate between the post increment and pre
}
increment operators. Also, give a suitable C++ code
2) Write a C++ function SUMFUN( ) having two
to illustrate both. (2011-12 MP1)2
parameters Y(of type double) and m(of type integer)
Post Increment: ++ is an increment operator to
with a result type as double to find the sum of the
increment the value of a variable by one. When used
series given below: (2003)
after the operand it is known as post increment
operator. Y + Y3 / 2! + Y5 /3! + ------ + Y 2m-1 / m!
#include<iostream.h>
Pre Increment: When ++ is used before an operand #include<math.h>
to increment its value by one, it is called a pre- #include<conio.h>
increment operator. double SUMFUN(int y1,int m1);
Example: void main()
#include<iostream.h> { int y;
void main( ) int m;
{ int NUM=9; clrscr();
cout<<++NUM; //10 will be displayed cout<<”Enter the vaue of Y and M”;
cout<<NUM++;//10 will be displayed cin>>y>>m;
cout<<NUM;//11 will be displayed cout<<”\nThe sum of the series = “<<SUMFUN(y,m);
} getch();
}
MODEL 7): Write a function definition for the double SUMFUN(int y1,int m1)
following sequence { double sum=0;
1)Write definition for a function SumSequence( ) in double upper;
C++ with two arguments/ parameters – double X and for(int i=1;i<=m1;i++)
int n. The function should return a value of type { int f=1;
double and it should perform sum of the following for(int j=1;j<=I;j++)
series. (2004) { f=f*j;
1/x- 3!/x2 + 5!/x3 – 7!/x4 + 9!/x5 - ------upto n terms. }
Note: The symbol ! represents Factorial of a number upper=pow(y1,(i*2-1));
ie 5!= 1 X 2 X 3 X 4 X 5. sum=sum+upper/f;
#include<iostream.h> }
#include<math.h> return sum;
#include<conio.h> }
double SumSequence(int x1,int n1);
void main() 3) Write a function named SUMFIN( ), with
{ int x; arguments x, N, which returns the sum of N terms of
int n; the following series.: (2001)4
clrscr(); x – x^3/3 + x^5/5 – x^7/7 + x^9/9
cout<<”Enter the vaue of X and N”; #include<iostream.h>
cin>>x>>n; #include<math.h>
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 20 PRAISE THE LORD
#include<conio.h> #include<conio.h>
double SUMFIN(int x1,int n1); #include<math.h>
void main() float sum_series(float X,int N) //function being
{ int x; declared
int n; { float sum=0,term;
clrscr(); int fact,f;
cout<<”Enter the vaue of X and N”; sum+=1;
cin>>x>>n; for(int i=1;i<=N;i++)
cout<<”\nThe sum of Series = “<<SUMFIN(x,n); { fact=1;
getch(); for(f=1;f<=(i+1);f++)
} fact*=f;
double SUMFIN(int x1,int n1) term=pow(X,i)/fact;
{ double sum=0; sum+=term;
int c=0; }
for(int i=1;i<=(2*n1);i=i+2) return(sum);
{ c=c+1; }
if(c%2==1) void main( )
{ sum=sum+(pow(x1,i))/I; { float x1;
} int n1;
else cout<<”\nEnter the value of X and N”;
{ sum=sum-(pow(x1,i))/I; cin>>x1>>n1;
} cout<<”\nThe Sum of the Series sum_series(x1,n1);
} }
return sum;
MODEL 8): Mislleneous
}
4) Write a function seqsum( ) in C++ with two 1)Write a function called zero_Small() that has two
arguments, double x and int n. The function should integer arguments being passed by reference and sets
return a value of type double and it should find the the smaller of the two numbers to 0. Write the main
sum of the following series. (2000) program to access this function. (2002)
1+ x/2! + x2/4! + x3/6! + x4/8! + x5/10! + ----+ xn/(2n)! #include<iostream.h>
#include<iostream.h> #include<conio.h>
#include<math.h> void zero_Small(int &A,int &B)
#include<conio.h> { if(A<B)
double seqsum(int x1,int m1); A=0;
void main() else
{ int x; B=0;
int m; }
clrscr(); void main( )
cout<<”Enter the vaue of X and M”; { clrscr();
cin>>x>>m; int a,b;
cout<<”\nThe sum of the series = “<<seqsum(x,m); cout<<”Enter any two values…”;
getch(); cin>>a>>b;
} cout<<”Initial values of a and b are “;
double seqsum(int x1,int m1) cout<<a<<”“<<b<<endl;
{ double sum=1; zero_Small(a,b);
for(int i=1;i<=m1;i++) cout<<endl<<”The final values of a and b are “;
{ int f=1; cout<<a<<”,”<<b;
for(int j=1;j<=2*I;j++) cout<<endl;
{ f=f*j; cout<<”\nPress any key to continue...”;
} getch();
sum=sum+pow(x1,i)/f; }
} 2) Write a C++ function that converts a 2-digit octal
return sum; number into binary number and prints the binary
} equivalent.
5) Write a C++ function having two value parameters #include<iostream.h> (1999)
X and N with result type float to find the sum of series #include<conio.h>
given below: (1998) void binary(int a)
1 + x /2! + x /3! + x /4! + x /5! + - - - - - - xn/(n+1)!
1 2 3 4
//member function for conversion
#include<iostream.h> { int I,b[5]; //integer array 6
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 21 PRAISE THE LORD
for(i=3;i>=1;i--) 2.OBJECT ORIENTED PROGRAMMING
{ b[i]=a%2; &
a=a/2; 3. FUNCTION OVERLOADING
}
for(i=1;i<=3;i++) 1. Write the output of the following C++ code.
cout<<b[i]; Also, write the name of feature of Object Oriented
} Programming used in the following program
void main() jointly illustrated by the Function 1 to Function 4.
{ int n,x,y; (2019SP)(2011)2
cout<<”Enter a two digit octal number: “; void My_fun ( ) // Function 1
cin>>n; { for (int I=1 ; I<=50 ; I++)
x=n/10; cout<< "-" ;
y=n%10; cout<<end1 ;
binary(x); }
binary(y); void My_fun (int N) // Function 2
} { for (int I=1 ; I<=N ; I++)
cout<<"*" ;
cout<<end1 ;
}
void My_fun (int A, int B) // Function 3
{ for (int I=1. ;I<=B ;I++)
cout <<A*I ;
cout<<end1 ;
}
void My_fun (char T, int N) // Function 4
{ for (int I=1 ; I<=N ; I++)
cout<<T ;
cout<<end1;
}
void main ( )
{ int X=7, Y=4, Z=3;
char C='#' ;
My_fun (C,Y) ;
My_fun (X,Z) ;
}
Ans: ####
71421
Polymorphism OR Function Overloading
2.Which function(s) out of the following can be
considered as overloaded function(s) in the same
program? Also, write the reason for not
considering the other(s) as overloaded function(s).
void Execute(char A,int B); //Function 1 2018
void Execute(int A,char B); //Function 2
void Execute(int P=10); //Function 3
void Execute(); //Function 4
int Execute(int A); //Function 5
void Execute(int &K); //Function 6
Ans:
Option [i]: Functions 1,2,3 are overloaded
Reason:Function 4,5,6 would give ambiguity for Function 3
OR
Option [ii]:Functions 1,2,4,5 are overloaded
Reason: Function 3 and 6 not considered in this case
because it would give redeclaration error for Function 5
OR
Option [iii]: Functions 1,2,4,6 are overloaded
Reason: Function 3 and 5 not considered in this case
because it would give redeclaration error for Function 6

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 22 PRAISE THE LORD


3) Define the term Data Encapsulation in the context Ans: A class groups its members into three sections:
of Object Oriented Programming. Give a suitable private, protected and public. The private and
example using a C++ code to illustrate the same. protected members remain hidden from outside world.
(2005 OD) (2009-10MP1)(2008-09MP1)(1998) 2 Thus through private and protected members, a class
Ans: Data Encapsulation: Wrapping up of enforces data – hiding. (The outside world is given
characteristics and behavior into one unit is called as only the essential and necessary information through
Data Encapsulation. While implementing public members, rest of the things remain hidden,
encapsulation, following things are taken care: which is nothing but abstraction. The act of
a)Encapsulation is used to hide unimportant representing only essential features without including
implementation details from other objects. background details is known as abstraction.)
b)Packaging an object‟s variables within the Eg: class ABC
protective custody of its methods is called { private: int a,b;
encapsulation and this task is accomplished through protected: int c,d;
classes. Ie the data and associated functions are public: int e,f;
wrapped up in one unit called class. void disp( )
A class binds together data and its { ----
associated functions under one unit thereby ----
enforcing encapsulation. }
Eg: -----
class Computer }
{ char CPU[10];int RAM; //Data Hiding In the above class public members
public: //Data Encapsulation (ie e,f and disp( )) only will be available to outside
void STOCK(); the class.. The other private members (a,b), protected
void SHOW(); members (c,d) will not be available to outside the
}; class. This concept is called data hiding.
Eg: Here in the above class the data members ie CPU,
RAM, STOCK( ) and SHOW( ) are bind together in a 6) What do you understand by Data Encapsulation and
class named as Computer. Ie The member functions Data Hiding? Also, give a suitable C++ code to
can access any data member in the class. illustrate both. 2
Benefits with encapsulation: (2010 OD) (2009-10 MP1) (2008-09 MP1)
(i) Modularity (ii) Information hiding A)Data Encapsulation: Wrapping up of data and
functions together in a single unit is known as Data
4) Define the following terms: (1998) Encapsulation. In a class, we wrap up the data and
(i) Inheritance (ii)Encapsulation.
functions togetherin a single unit.
Ans:a) Inheritance: The capability of one class to
Data Hiding: Keeping the data in private visibility
inherit properties from another class is called as
mode of the class to prevent it fromaccidental change
inheritance.The class inheritance, lets you generate a
is known as Data Hiding.
model that is closer to the real world. The class
class Computer
inheritance lets you derive new classes (derived class)
{ char CPU[10];int RAM; //Data Hiding
from old ones (base class), with the derived class
public: //Data Encapsulation
inheriting the properties, including the methods of the
void STOCK();
old class.
void SHOW();
Uses of Inheritance: };
i)Capability to express the inheritance relationship
which ensures the closeness with the real world 7) What is function overloading? Give an example in
models. C++ to illustrate functionoverloading.
ii) Reusability. (2014 OD)(2009OD) (2003)(2000)
iii)Transitive nature of inheritance. What do you understand by Function overloading or
Types of Inheritance: Functionalpolymorphism? Explain with suitable
(i) Single Inheritance example. (2017MP)
(ii) Multiple Inheritance Ans: A function name having several definitions that
(iii) Hierarchical Inheritance are differentiable by the number or types of their
(iv) Multi Level Inheritance arguments, is known as an overloaded function and
(v) Hybrid Inheritance this process is known as function overloading.
Function overloading is an example of
5) Define the term Data Hiding in the context of
polymorphism, where the functions having same name
Object Oriented Programming. Give a suitable with different set of parameters perform different
example using a C++code to illustrate the same.
operations.
(2015 D)2 Function overloading not only implements
polymorphism but also reduces number of
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 23 PRAISE THE LORD
comparisons in a program and thereby makes the Disp(x);//call for Function 2 - Prints numbers from 1 to 5
program run faster. Disp(); //call for Function 1 - Prints Hello
Example: }
void Disp() //Function 1
{ cout<<”Hello”<<endl; 9) Write any four important characteristics of
} Object Oriented Programming? Give example of
void Disp(int N) // Function 2 any one of the characteristics using C++. (2016) 2
A) Encapsulation,Data Hiding, Polymorphism,
{ for (int I=1;I<=N;I++)
Inheritance, Modularity.
cout<<I<<end1;
} Example of Encapsulation:
class student
void main () { int rno;
{ int x=5; char name[20];
Object Oriented Procedural Programming public:
Programming void input()
 Emphasis on Data  Emphasis on doing { cin>>rno;
things (functions) gets(name);
 Follows Bottom-Up  Follows Top-down
approach in program approach in program }
design design void output()
 Data hiding feature  Presence of Global { cout<<rno<<” “<<name<<endl;
prevents accidental variables increase }
change in data chances of accidental };
change in data The data members and member functions are wrapped
 Features like data  Such features are not up together(encapsulated ) into a single unit called
encapsulation, available class.
polymorphism,
inheritance are 10) What is the difference between Object Oriented
present Programming and Procedural Programming?2
Disp(x);//call for Function 2 - Prints numbers from 1 to 5
Disp(); //call for Function 1 - Prints Hello
}

8) What do you understand by Polymorphism? Also,


give an example in C++to illustrate the same.
(2009-10 MP1)( 2008-09 MP2) (2010 D)2
Ans. The process of using an - operator or a function
in different ways for different set of inputs given is
known- as polymorphism.
C++ implements polymorphism through
virtual functions, through overloaded functions and
overloaded operators.

Function overloading is- an example of


polymorphism, where the functions having same name
with different set of parameters perform different
operations.
( A virtual function is used to specify the interface in
abstract class, but its implementation details are made
available by the concrete class(es). when two or more
distinct meanings are defined for an operator, it is said to be
an „overloaded operator‟. It is the compiler‟s job to select
the specific action as it applies to each situation.)
Example:
void Disp() //Function 1
{ cout<<”Hello”<<endl;
}
void Disp(int N) // Function 2
{ for (int I=1;I<=N;I++)
cout<<I<<end1;
}
void main ()
{ int x=5;

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 24 PRAISE THE LORD


4. CLASSES, 5.CONSTRUCTORS & void Ele_Bill :: Display( )
MODEL WISE QUESTION & ANSWERS {cout<<Cname<<Pnumber<<No_of_units<<Amount;
MODEL 1A: Define a class (without strings) ( 4 M) }
1. Define a class Ele_Bill in C++ with the 2. Write the definition of a class CONTAINER in C++
with the following description: (2018)
following descriptions: 2019SP4 Private Members:
Private members: -Radius, Height //float
Cname of type character array - Type // int (1 for cone, 2 for cylinder)
Pnumber of type long - Volume // float
No_of_units of type integer - CalVolume ( ) //Member function to calculate volume as
per the type
Amount of type float.
Type Formula to calculate volume
Calc_Amount( ) This member function should 1 3.14 * Radius * Height
calculate the amount asNo_of_units*Cost . 2 3.14 * Radius * Height/3
Amount can be calculated accordingto the following Public Members:
conditions: -GetValues( ) /*A function to allow user to enter value of
No_of_units Cost Radius, Height and Type. Also, call function CalVolume( )
First 50 units Free from it */
Next 100 units 0.80 @ unit -ShowAll( ) /*A function to display Radius, Height, Type
Next 200 units 1.00 @ unit and volume of Container */
Ans)
Remaining units 1.20 @ unit class CONTAINER
Public members: { float Radius, Height, Volume;
* A function Accept( ) which allows user to enter int Type;
Cname, Pnumber, No_of_units and invoke function void CalVolume( );
Calc_Amount(). public:
* A function Display( ) to display the values of all void GetValues();
the data members on the screen. void ShowAll( );
};
Answer: void CONTAINER ::CalVolume( )
class Ele_Bill { if (type= =1)
{ Volume=3.14*Radius*Height;
char Cname[20]; else if (type= =2)
long Pnumber; Volume=3.14*Radius*Height/3;
int No_of_units; }
/* OR
float Amount;
void CONTAINER::CalVolume()
void Calc_Amount( ); { switch (Type)
public: { case 1: Volume =3.14*Radius*Height;
void Accept(); break;
void Display(); case 2: Volume=3.14*Radius*Height/3;
}; }
void Ele_Bill : : Calc_Amount( ) */
void CONTAINER ::GetValues( )
{ if(No_of_units<=50) { cout<<”Enter value of Radius, Height and Type”;
{ Amount=0; cin>>Radius>>Height>>Type;
} CalVolume( );
else if(No_of_units<=150) }
{ Amount=(No_of_units-50)*0.80; void CONTAINER ::ShowAll( )
} { cout<<”\nRadius = “<<Radius;
else if(No_of_units<=350) cout<<”\nHeight =”<<Height;
cout<<”\nType = “<<Type;
{Amount=80+(No_of_units-150)*1.00; cout<<”\nVolume = “<<Volume;
} }
else 3.Write the definition of a class BOX in C++ with
{Amount=80+200+(No_of_units-350)*1.20; following description: (2017)
} Private Members
} - BoxNumber // data member of integer type
void Ele_Bill :: Accept( ) - Side // data member of float type
{ gets(Cname); - Area // data member of float type
cin>Pnumber>>No_of_units; - ExecArea() // Member function to calculate and assign
// Area as Side * Side
Calc_Amount( );
Public Members
}
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 25 PRAISE THE LORD
- GetBox() // A function to allow user to enter values of }
// BoxNumber and Side. Also, this void CITY::DenCal()
// function should call ExecArea() to calculate {
// Area Density= Pop/KM;
}
- ShowBox()// A function to display BoxNumber,
//Side and Area 5) Define a class Applicant in C++ with following
Ans) description: (2011)
Private Members
class BOX
_ A data member ANo (Admission Number) of type long
{ int BoxNumber ; _ A data member Name of type string
float Side ; _ A data member Agg (Aggregate Marks) of type float
float Area ; _ A data member Grade of type char
void ExecArea(){ Area=Side*Side;} _ A member function GradeMe() to find the Grade as per
public: the AggregateMarks obtained by a student. Equivalent
void GetBox(); Aggregate Marks range andthe respective Grades are shown
void ShowBox(); as follows:
}; Aggregate Marks Grade
void BOX::GetBox() >=80 A
less than 80 and >=65 B
{
less than 65 and >=50 C
cin>>BoxNumber>>Side; less than 50 D
ExecArea(); Public Members
} _ A function ENTER() to allow user to enter values for
void BOX::ShowBox() ANo, Name, Agg& call function GradeMe() to find the
{ Grade._ A function_RESULT( ) to allow user to view the
cout<<BoxNumber<<” ”<<Side<<” ”<<Area<<endl; content of all the dataMembers
} A)
class Applicant
4) Write the definition of a class CITY in C++ with { long ANo;
following description: (2016) char Name [20] ;
Private Members float Agg;
Ccode //Data member for City Code (an integer) char Grade;
CName //Data member for City Name (a string) void Grademe ( ) ;
Pop //Data member for Population (a long int) public:
KM //Data member for Area Coverage (a float) void Enter ( ) ;
Density //Data member for Population Density (a float) void Result ( ) ;
DenCal() //A member function to calculate Density as PopKM };
Public Members void Applicant: :GradeMe( )
Record() /*A function to allow user to enter values of {if (Agg>=80)
Acode,Name,Pop,KM and call DenCal() function */
Grade=' A' ;
View() /*A function to display all the data members also display a
message ”Highly Populated City” if the Density is more than 10000*/
else if(Agg>=65)
Ans) Grade=' B' ;
class CITY else if(Agg>=50)
{ int Ccode; Grade=' C' ;
char CName[20]; else
long int Pop; Grade=' D' ;
float KM; }
float Density; void Applicant: :Enter ( )
void DenCal(); {cin>>ANo;
public: gets (Name) ;
void Record(); cin>>Agg;
void View(); GradeMe() ;
}; }
void CITY::Record() void Applicant: :Result ( )
{cin>>Ccode; {
gets(CName); // OR cin>>CName; cout<<ANo<<Name<<Agg<<Grade<<end1;
cin>>Pop; }
cin>>KM; 6) Define a class STOCK in C++ with following
DenCal(); description: (2010 OD)
} Private Members
void CITY::View() _ ICode of type integer (Item Code)
{cout<<Ccode<<CName<<Pop<<KM<<Density; _ Item of type string (Item Name)
//Ignore endl _ Price of type float (Price of each item)
if(Density>10000) _ Qty of type integer (Quantity in stock)
cout<<”Highly Populated City”; //Ignore endl _ Discount of type float (Discount percentage on the item)
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 26 PRAISE THE LORD
_ A member function FindDisc() to calculate discount as public:
per the following rule: void Checkin() ;
If Qty<=50 Discount is 0 void Checkout() ;
If 50<Qty<=100 Discount is 5 };
If Qty>100 Discount is 10 float HOTEL::CALC()
Public Members { float Amount = Tariff*NOD;
_ A function Buy() to allow user to enter values for ICode, if (Amount>10000)
Item, Price, Qty and call function FindDisc() to calculate Amount = 1.05*NOD*Tariff;
the Discount. return Amount;
_ A function ShowAll() to allow user to view the content of }
all the data members. void HOTEL::Checkin()
Ans. {cin>>Rno;
class STOCK gets (Name);
{ int ICode,Qty; cin>>Tariff;
char Item[20]; cin>>NOD;
float Price,Discount; }
void FindDisc();
public: void HOTEL::Checkout()
void Buy(); { cout<<Rno<<” “<<Name<<“ “<<Tariff<<”
void ShowAll(); “<<NOD<<CALC ( )<<endl;
}; }
void STOCK::Buy() 8) Define a class named HOUSING in C++ with the
{ cin>>ICode; following descriptions: (2006 OD)
gets(Item); Private Members:
cin>>Price; REG_NO integer(Ranges 10-1000)
cin»Qty; NAME Array of characters(String)
FindDisc(); TYPE Character
} COST Float
void STOCK::FindDisc() Public Members:
{ if (Qty<=50) Function Read_Data( ) to rread an object of HOUSING type.
Discount=0; Function Display( ) to display the details of an object.
else if (Qty<=100) Function Draw_Nos( ) to choose and display the details of 2
Discount=5; // =0.05; houses selected randomly from an array of 10 objects of
else type HOUSING. Use random function to generate the
Discount=10; // =0.1; registration nos. to match with REG_NO from the array.
} Ans:
void STOCK::ShowAll() class HOUSING
{ { int REG_NO;
cout<<ICode<<‟\t‟<<Item<<‟\t‟<<Price<<‟\t‟ char NAME[31];
<< Qty<<‟\t‟<<Discount<<endl; char TYPE;
} float COST;
7) Define a class HOTEL in C++ with the following public:
description: (2009 OD) void Read_Data( )
Private Members: { cout<<"\nEnter the House Registration Number: ";
_ Rno //Data member to store Room No cin>>REG_NO;
_ Name //Data member to store customer name cout<<"\nEnter the House Name: ";
_ Tariff //Data member to store per day charges gets(NAME);
_ NOD //Data member to store number of days of stay cout<<"\nEnter the House Type: ";
_ CALC( ) /*A function to calculate and return Amount as cin>>TYPE;
NOD*Tariff and if the value of NOD*Tariff is more than cout<<"\nEnter the House Cost: ";
10000 then as cin>>COST;
1.05*NOD*Tariff */ }
Public Members void Display()
_ Checkin ( ) / / A function to enter the content { cout<<"\nThe Registration Number of the
Rno, Name, Tariff and NOD House: "<<REG_NO;
_ Checkout( ) / / A function to display Rno, cout<<"\nThe name of the House: “<<NAME;
Name, Tariff,NOD and Amount (Amount to cout<<"\nThe Type of the House: "<<TYPE;
be displayed by calling function CALC( )) cout<<"\nThe Cost of the House: "<<COST;
Ans }
class HOTEL void Draw_Nos();
{ int Rno; };
char Name[20]; void HOUSING::Draw_Nos( )
float Tariff; { //Dear Students, a test for you. Complete this member
int NOD; function.
float CALC() ; }

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 27 PRAISE THE LORD


9) Declare a class myfolder with the following char name[20];
specifications: (2004) char class_st[8];
Private members of the class: int marks[5];
Filenames an array of strig of size[10][25] float percentage;
(to represent all the names of files inside myfolder) float calculate( )
Availspace long { percentage=(marks[0]+marks[1]+marks[2]+
(to represent total number of bytes available in myfolder) marks[3]+marks[4])/5;
Usedspace long return percentage;
(to represent total number of bytes used in myfolder) }
Public members of the class: public:
Newfileentry() : A function to accept values of Filenames, void Readmarks( )
Availspace and Usedspace from user. { cout<<”\nEnter any 5 subject marks;
Retavailspace(): A function that returns the value of total cin>>marks[0]>>marks[1]>>marks[2]>>
kilobytes available marks[3]>>marks[4];
(1 kilobyte=1024 bytes) calculate( );
Showfiles( ): A function that displays the names of all the }
files in myfolder void Displaymarks( )
Ans: { cout<<”\nThe Roll Number of the Student: “<<roll_no;
class myfolder cout<<”\nThe Name of the Student:” <<name;
{ char Filenames[10][25]; cout<<”\nThe class of the Student: “ <<class_st;
long Availspace; cout<<”\n5 subject marks of the student…\n”;
long Usedspace; cout<<marks[0]<<”\t”<<marks[1]<<”\t”<<arks[2]<<”\t”;
public: cout<<marks[3]<<”\t”<<marks[4]<<”\n”;
void Newfileentry( ) cout<<”Percentage =”<<percentage;
{ cout<<"\nEnter any 10 file names: "; }
for(int i=0;i<=9;i++) };
{cout<<"\nEnter the "<<i+1<<" file name: "; 11) Declare a class to represent bank account of 10
gets(Filenames[i]); customers with the following data members. Name of
} the depositor, account number, type of account (S for
cout<<"\nEnter the Available Space (In Savings and C for Current), Balance amount. The class
Kilobytes): "; also contains member functions to do the following:
cin>>Availspace; (i)To initialize data members. (2001)
cout<<"\nEnter the Used Space (In (ii) To deposit money
Kilobytes): "; (iii)To withdraw money after checking the balance
cin>>Usedspace; (minimum balance is Rs.1000)
} (iv) To display the data members.
[Note:You are also required to give detailed function
long RetavailSpace( ) definitions.]
{ ret Availspace; class Bank
} { char name[15];
void Showfiles( ) int acc_no;
{ cout<<"\nThe names of the files in char acc_type;
myfolder object...."; float bal_amount;
for(i=0;i<=9;i++) public:
{ puts(Filenames[i]); void readData( )
cout<<endl; { cout<<”\nEnter the name: “;
} gets(name);
} cout<<”\nEnter the account number: “;
10) Define a class Student for the following cin>>acc_no;
specifications. (2002) cout<<”\nEnter the account type: “;
Private members of the Student are: cin>>acc_type;
roll_no integer cout<<”\nEnter the amount to deposit: “;
name array of characters of size 20 cin>>bal_amount;
class_st array of characters of size 8 }
marks array of integers of size 5 void deposit( )
Percentage float { float deposit;
Calculate( ) that calculates overall percentage marks and cout<<”\nEnter your account number: “;
returns the percentage cin>>acc_no;
Public Members of the Student are: cout<<”\nEnter the amount to deposit: “;
Readmarks reads mark and invoke the cin>>deposit;
calculate function bal_amount=bal_amount + deposit;
Displaymarks prints the data. }
Ans: void withdraw( )
class Student { float w_amount;
{ int roll_no; cout<<”\nEnter your account number: “;

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 28 PRAISE THE LORD


cin>>acc_no; Public members:
cout<<”\nEnter amount to withdraw”; ReadData( ): Function accepts the data values and invoke
cin>>w_amount; the calculate function.
if((bal_amount-w_amount)<1000) DisplayData( ):Function prints the data on the screen.
cout<<”\nWithdraw is not possible”; class Teacher
else { char Name[20];
{ bal_amount=bal_amount-w_amount; char subject[10];
cout<<”\nThe balance is float Basic,DA,HRA,Salary;
“<<bal_amount-w_amount; float Calculate( )
} { Salary=Basic+DA+HRA;
} return Salary;
void display( ) }
{ cout<<”\nName of the depositor:“<<name; public:
cout<<”\nAccount Number: “<<acc_no; void ReadData( )
cout<<”\nAccount Type: “<<acc_type; { cout<<"\nEnter Basic, Dearness Allowance and “
cout<<”\nThe balance amount is “<<bal_amount; cout<<” House Rent Allowance: ";
} cin>>Basic>>DA>>HRA;
}; Calculate();
12) Define a class worker with the following }
specification. (2000) void DisplayData( )
Private member of class worker: { cout<<"\nThe Basic : "<<Basic;
wname 25characters cout<<"\nThe Dearness Allowance: "<<DA;
hrwrk,wgrate float (hours worked and cout<<"\nThe House Rent Allowance: "<<HRA;
wagerate per hour) cout<<"\nThe Salary: "<<Salary;
totwage float(hrwrk*wgrate) }
cakcwg() A function to find hrwrk*wgrate };
with float return type 14) Define a class student with the following
Public members of class worker: specifications: (1998)
In_data( ): A function to accept values for wno, wname, Private members of class student:
hrrwrk, wgrate and invoke calcwg( ) to calculate totpay. Admno integer
Out_data( ): A function to display all the data members on Sname 20 character
the screen you should give definitions of functions. English float
class worker Math float
{ char wname[25]; Science float
float hrwrk,wgrate; Total float
float totwage; Ctotal( ) A function to calculate
float cakcwg( ) English + math + science with float return type
{ return hrwrk*wgrate; Public member functions of class student:
} Takedata( ):Function to accept values for admno,sname,
public: English, math, science and invoke ctotal to calculate total.
void In_data( ) Showdata( ):Function to display all the data members on the
{ cout<<”\nEnter Worker number,name, screen.
hours worked and wage rate”; class student
cin>>wno; { int Admno;
gets(wname); char Sname[20];
cin>>hrwrk>>wgrate; float English,Math,Science,Total;
calcwg( ); float Ctotal()
} { Total=English+math+science;
void Out_data( ) return Total;
{ cout<<”\nThe Worker Number: “<<wno; }
cout<<”\nThe Name of the worker “<<wname; public:
cout<<”\nNumber of hours worked by the worker: void Takedata()
“<<hrwrk; { cout<<”\nEnter the admission
cout<<”\nThe Wage Rate of the Worker:“<<wgrate; number,name of the student: “;
cout<<”\nThe total wages of the worker:“<<totwage; cin>>Admno;
} gets(sname);
13) Define a class Teacher with the following class cout<<”\nEnter English, Maths,
specification: (1999) Science Marks: “;
Private members: cin>>English>>Math>>Science;
Name 20 characters Ctotal( );
Subject 10 characters }
Basic, DA, HRA float void Showdata( )
Salary float cout<<”\nThe admission number of
Calculate( ) function computes the salary and returns the student: “<<Admno;
it. Salary is sum of Basic, DA and HRA cout<<”\nThe name of the student: “<<Sname;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 29 PRAISE THE LORD
cout<<”\nEnglish , Maths and Science Marks are…”; (NoCandidates/100+1)
cout<<english<<”\t”<<math<<”\t”<<science<<”\n”; Public Members
cout<<”\nTotal marks of the student: “<<Total; • A function SCHEDULE() to allow user to enter values for
}; TestCode,
Description, NoCandidate & call function CALCNTR() to
15)Define a class in C++ with following description: calculate the number of
(2009-10 MP2) (2008-09MP2) Centres
Private Members • A function DISPTEST() to allow user to view the content
*A data member Flight number of type integer of all the data members
*A data member Destination of type string A)
*A data member Distance of type float class TEST
*A data member Fuel of type float { int TestCode;
*A member function CALFUEL() to calculate the value of char Description[20];
Fuel as per the following criteria int NoCandidate,CenterReqd;
Distance Fuel void CALCNTR();
<=1000 500 public:
more than 1000 and <=2000 1100 void SCHEDULE();
more than 2000 2200 void DISPTEST();
Public Members };
*A function FEEDINFO() to allow user to enter values for void TEST::CALCNTR()
Flight Number, Destination, Distance & call function {
CALFUEL() to calculate the quantity of Fuel CenterReqd=NoCandidate/100 + 1;
*A function SHOWINFO() to allow user to view the }
content of all the data members void TEST::SCHEDULE()
Answer: {
class FLIGHT cout<<"Test Code :";cin>>TestCode;
{ int Fno; cout<<"Description :";gets(Description);
char Destination[20]; cout<<"Number :";cin>>NoCandidate;
float Distance, Fuel; CALCNTR();
void CALFUEL(); }
public: { cout<<"Test Code :"<<TestCode<<endl;
void FEEDINFO(); cout<<"Description :"<<Description<<endl;
void SHOWINFO(); cout<<"Number :"<<NoCandidate<<endl;;
}; cout<<"Centres :"<<CenterReqd<<endl;;
void FLIGHT::CALFUEL() }
{ if (Distance<1000)
Fuel=500; MODEL 1B: Define a class (with strings) 4 Marks
else 1.Define a class DanceAcademy in C++ with following
if (Distance<2000) description: (2017 MP)
Fuel=1100; Private Members
else ● Enrollno of type in ● Name of type string
Fuel=2200; ● Style of type string ● Fee of type float
} ● A member function chkfee( ) to assign the value of fee
void FLIGHT::FEEDINFO() variable according to the style entered by the user
{cout<<”Flight No :”;cin>>Fno; according to the criteria as given below:
cout<<”Destination :”;gets(Destination); Style Fee
cout<<”Distance :”;cin>>Distance; Classical 10000
CALFUEL();
Western 8000
}
void FLIGHT::SHOWINFO() Freestyle 11000
{ Public Members:
cout<<”Flight No :”<<Fno<<endl; *A function enrollment() to allow users to enter values
cout<<”Destination :”<<Destination<<endl; for Enrollno,Name, Style and call function chkfee()to
cout<<”Distance :”<<Distance<<endl;; assign value of fee variable according to the Style
cout<<”Fuel :”<<Fuel<<endl;; entered by the user.
} *A function display() to allow users to view the details
of all the data members.
16) Define a class TEST in C++ with following Ans)
description: (2008-09MP1) (2009-10 MP1) class DanceAcademy
Private Members { int Enrollno;
• TestCode of type integer char Name[20];
• Description of type string char Style[20];
• NoCandidate of type integer float Fee;
• CenterReqd (number of centers required) of type integer void chkfee()
• A member function CALCNTR() to calculate and return { if(strcmpi(Style, "Classical")= =0)
the number of centers as Fee=10000;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 30 PRAISE THE LORD
else if(strcmpi(Style, "Western")= =0) 3) Define a class RESTRA in C++ with following
Fee=8000; description : 2012
else if(strcmpi(Style, "Freestyle")= =0) Private Members
Fee=11000; �FoodCode of type int
} �Food of type string
public: �FType of type string
void enrollment() �Sticker of type string
{ A member function GetSticker () to assign the following
cout<<"Please enter Enrollno,Name,Style"; value for Stickeras per the given FType:
cin>>Enrollno;
gets(Name);
gets(Style);
chkfee();
}
void display()
{cout<<"\n Entered Enrollno, Name, Style and Fee is:" Public Members
<<Enrollno<<"\t"<<Name<<"\t"<<Style<<"\t"<<Fee; �A function GetFood () to allow user to enter values for
} FoodCode.
}; Food, FType and call function GetSticker() to assign
2)Write the definition of a class Photo in C++ with Sticker.
followingdescription: (2015) �A function ShowFood() to allow user to view the content
Private Members of all the datamembers.
Pno //Data member for Photo Number(an integer) Ans
Category //Data member for Photo Category(a string) class RESTRA
Exhibit //Data member for Exhibition Gallery(a string) {int FoodCode;
FixExhibit //A member function to assign Exhibition char Food[20], FType [20],Sticker[20];
//Gallery as per Categoryas shown in the following table void GetSticker () ;
Category Exhibit public:
Antique Zaveri void GetFood () ;
Modern Johnsen void ShowFood () ;
Classic Terenida };
void RESTRA::GetSticker() {
Public Members
if (strcmp (FType, "Vegetarian") = =0)
Register()//A function to allow user to entervalues
strcpy (Sticker,"GREEN") ;
//Pno,Category and call FixExhibit()function
ViewAll()//A function to display all the datamembers else if (strcmp (FType,"Contains Egg")= =O)
strcpy (Sticker, "YELLOW") ;
Ans)
else if (strcmp (FType,'Non-Vegetarian")= =O)
class Photo
strcpy(Sticker,"RED");
{
}
int Pno;
void RESTRA::GetFood()
char Category[20];
char Exhibit[20]; {
void FixExhibit(); cin>>FoodCode;
gets (Food);
public:
void Register(); gets (FType) ;
void ViewAll(); GetSticker () ;
}; }
void RESTRA::ShowFood ()
void Photo::FixExhibit()
{ {
if(strcmpi(Category,”Antique”)= =0) cout<<FoodCode<<":"<<Food<<FType<<":"<<Sticker<<e
ndl;
strcpy(Exhibit,”Zaveri”);
else if(strcmpi(Category,”Modern”)= =0) }
strcpy(Exhibit,”Johnsen”); MODEL 1C: Define a class
else if strcmpi(Category,”Classic”)= =0) (Using Constructors) 4 Marks
strcpy(Exhibit,”Terenida”);
} 1) Define a class Tourist in C++ with the following
void Photo::Register() specification: (2014)
{ cin>>Pno; Data members:
gets(Category);  CNO – to store Cab no
FixExhibit();  CType – to store a character „A‟,‟B‟ or „C‟ as City
} type
void Photo:: ViewAll()  PerKM – to store per kilometer charges
{ cout<<Pno<<Category<<Exhibit<<endl;  Distance – to store distance travelled (in km)
} Member functions:

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 31 PRAISE THE LORD


 A constructor function to initialize CType as „A‟ and  A function CalcFare( ) to calculate Fare as per the
CNo as „0000‟ following criteria:
 A function CityCharges( ) to assign PerKM as per the TYPE FARE
following table. „O‟ 15*Distance
Type PKM „E‟ 20*Distance
A 20 „L‟ 24*Distance
B 18  A function Allocate( ) to allow user to enter values for
C 15 Busno, From, To, Type and Distance. Also, this
 A function RegisterCab( ) to allow administration to function should call CalcFare( ) to calculate Fare.
enter the values for CNo and CType. Also, this  A function Show( ) to display the content of all the
function should call CityCharges( ) to assign PerKM data members on screen.
Charges. Answer:
 A function Display( ) to allow user to enter the value #include<iostream.h>
of Distance and display CNo, CType, PerKM, #include<conio.h>
PerKM*Distance(as Amount) on screen. class Bus
{
Answer: private:
class Tourist char From[20],To[20];
{ int CNo; int fare,busno,distance;
char CType; char Type;
int PerKM; public:
int Distance; Bus( );//Constructor
public: ~Bus( );//Destructor
Tourist( ) int CalcFare( );
{ CType=‟A‟; void Allocate( );
CNo=0; } void Show( );
void CityCharges( ) };
{ if(CType==‟A‟) Bus::Bus( )
PerKM=20; { Fare=500;
else if(CType==‟B‟) Type=‟O‟;
PerKM=18; }
else if(CType==‟C‟) void Bus::Allocate( )
PerKM=15; {cout<<”Enter the Bus no: “;
} cin>>busno;
void RegisterCab( ) cout<<”From: “;
{ cout<<”Enter the CabNo”; cin>>From;
cin>>CNo; cout<<”To: “;
cout<<”Enter Cab Type”; cin>>To;
cin>>CType; cout<<”Enter the Type: “;
cityCharges( ); cin>>Type;
} cout<<”Enter the distance: “;
void Display( ) cin>>distance;
{ CalcFare( );
cout<<”Enter the distance”; }
cin>>Distance; int Bus::CalcFare( )
cout<<”Cab No is: “<<CNo<<endl; { if(Type= =‟O‟)
cout<<”Cab Type is : “<<CType<<endl; fare=15*distance;
cout<<”Per Kilometer charges is :“<<PerKM<<endl; else if(Type= =‟E‟)
cout<<”Amount is: “<<PerKM*Distance; fare=20*distance;
} else if(Type= =‟L‟)
}; fare=24*distance;
2) Define a class Bus in C++ with the following else
specifications: (2013) cout<<Wrong Type”;
Date Members: return fare;
 Busno – to store Bus No }
 From – to store Place name of origin void Bus::Show( )
{
 To – to store place name of destination
cout<<”Bus no: “<<busno<<endl;
 Type – to store Bus Type such as „O‟ for ordinary
cout<<”From: “<<From<<endl;
 Distance – to store the Distance in Kilometers cout<<”To: “<<To<<endl;
 Fare – to store the Bus Fare cout<<”Type: “<<Type<<endl;
Member Functions: cout<<”Distance: “<<distance<<endl;
 A constructor function to initialize Type as „O‟ and cout<<”Total Fare: “<<fare<<endl;
Fare as 500 }
Bus::~Bus( )
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 32 PRAISE THE LORD
{ cout<<”Bus Object is Deleted”; cout<<"\nEnter the cloth material: ";
} gets(material);
3 ) Define a class clothing in c++ with the following calc_price( );
descriptions : (2008OD) }
private members : void show( )
code of type string { cout<<"\nThe Cloth Code: "<<Code;
type of type string cout<<"\nThe Cloth Type: "<<Type;
size of type intiger cout<<"\nThe Cloth Size: "<<size;
material of type string cout<<"\nThe Cloth Material: “<<material;
price of type float cout<<"\nThe Cloth Price: "<<price;
A function calc_price( )which calculates and assigns the }
value of GPrice as follows ; };
For the value of material as “COTTON” : void main( )
Type price (Rs) { clothing C;
TROUSER 1500. C.enter( );
SHIRT 1200. C.show( );
}
for material other than “COTTON”, the above mentioned
4) Define a class Travel in C++ with the description
GPprice price gets reduced by 25%
given below : (2007 OD)
public members :
Private Members:
* A constructor to assign initial values of code ,type and
T_Code of type string
material with the word “NOT ASSIGNED “and size and
No_ of_ Adults of type integer
price with 0.
No _of _Children of type integer
* A function enter() to input the values of the data
Distance of type integer
members code, type, size and material and invoke the
TotalFare of type float
caclPrice () function.
Public Members:
* A function show which displays the content of all the
 A constructor to assign initial values as follows:
data members for a clothing.
TCode with the word “NULL”
#include<iostream.h>
No _of_ Adults as 0
#include<string.h>
No_ of_Children as 0
#include<conio.h>
Distance as 0
#include<stdio.h>
class clothing TotalFare as 0
{ char Code[21],Type[21];  A function AssignFare() which calculates and
int size; assigns the value of the data member Totalfare as
char material[21]; follows
float price; For each Adult
void calc_price( ) Fare (Rs) For Kilometers
{ if(strcmp(strupr(material),"COTTON")= =0) 500 >=1000
{ if(strcmp(strupr(Type),"TROUSER")= =0) 300 <1000 &>=500
price=1500; 200 <500
if(strcmp(strupr(Type),"SHIRT")= =0)
price=1200; For each Child the above Fare will be 50% of the Fare
} mentioned in the above table
else For Example:
{if(strcmp(strupr(Type),"TROUSER")= =0) If Distance is 750, No_of_adults =3 and No_of_Children =2
price=1500*0.75; Then TotalFare should be calculated as
if(strcmp(strupr(Type),"SHIRT")= =0) Num_of _Adults *300+ No_of_Children *150
price=1200*0.75; i.e., 3*300+ 2 *150 =1200
}  A function EnterTour() to input the values of the
} data members T_Code, No_of_Adults,
public: No_of_Children and Distance ; and invoke the
clothing( ) AssignFare() function.
{ strcpy(Code,"NOT ALLOTED");  A function ShowTravel() which displays the
strcpy(Type,"NOT ALLOTED"); content of all the data members for a Travel.
size=0; #include<conio.h>
strcpy(material,"NOT ALLOTED"); #include<stdio.h>
price=0; #include<string.h>
} #include<iostream.h>
void enter( ) class Travel
{ cout<<"\nEnter the Cloth Code: "; { char T_Code[21];
gets(Code); int No_of_Adults,No_of_Children,Distance;
cout<<"\nEnter the Cloth Type: "; float TotalFare;
gets(Type); public:
cout<<"\nEnter the Cloth Size: "; Travel( )
cin>>size; { strcpy(T_Code,"NULL");

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 33 PRAISE THE LORD


No_of_Adults=No_of_Children=Distance=TotalFare=0; public:
} Travel( )
void AssignFare( ) { TravelCode=201;
{ strcpy(Place,"Nainital");
if(Distance>=1000) No_of_travellers=5;
TotalFare=No_of_Adults*500+No_of_Children*250; No_of_buses=1;
else if(Distance>=500) }
TotalFare=No_of_Adults*300+No_of_Children*150; void NewTravel( )
else { cout<<"\nEnter the Travel Code: ";
TotalFare=No_of_Adults*200+No_of_Children*100; cin>>TravelCode;
} cout<<"\nEnter the Place to Travel: ";
void EnterTravel( ) gets(Place);
{ cout<<"\nEnter the Travel Code: "; cout<<"\nEnter the Number of Travellers: ";
gets(T_Code); cin>>No_of_travellers;
cout<<"\nEnter the Number of Adults: "; if(No_of_travellers>=40)
cin>>No_of_Adults; No_of_buses=3;
cout<<"\nEnter the Number of Children: "; else if(No_of_travellers>=20)
cin>>No_of_Children; No_of_buses=2;
cout<<"\nEnter the Distance in Kilometres: "; else
cin>>Distance; No_of_buses=1;
AssignFare( ); }
} void ShowTravel( )
void ShowTravel( ) { cout<<"\nThe Plan Code: "<<TravelCode;
{ cout<<"\nThe Travel Code: “ <<T_Code; cout<<"\nThe Place of Travel: "<<Place;
cout<<"\nThe Number of Adults: “ <<No_of_Adults; cout<<"\nNumber of Travellers: “ <<No_of_travellers;
cout<<"\nThe Number of Children: “<<No_of_Children; cout<<"\nNumber of Buses: “<<No_of_buses;
cout<<"\nThe Distance in Kilometres: "<<Distance; }
cout<<"\n\nThe Total Fare: "<<TotalFare; };
} void main( )
}; { clrscr( );
void main( ) Travel T;
{ Travel T; T.NewTravel( );
T.EnterTravel( ); T.ShowTravel( );
T.ShowTravel( ); getch();
} }
5) Define a class Travel in C++ with the following 6) Define a class Play in C++ with the following
descriptions: (2005 OD) specifications: (2003 D)
Private Members: Private members of class Play
Travelcode of type long *Play code integer
Place of type character array(string) *Playtime 25 character
Number_of_travellers of type integer *Duration float
Number_of_buses of type integer *Noofscenes integer
Public Members: Public member function of class Play
* A constructer to assign initial values of TravelCode as *A constructer function to initialize Duration as 45 and
201, Place as “Nainital”, Number_of_travellers as 10, Noofscenes as
Number_of_buses as 1 *Newplay() function to values for Playcode and Playtitle.
* A function NewTravel() which allows user to enter *Moreinfor() to assign the values of assign the values of
TravelCode, Place and Number_of travelers. Also, assign Duration and Noofscenes with the of corresponding values
the value of Number_of_buses as per the following passed as parameters to this function.
conditions: *Shoplay() function to display all the dataq members on the
Number_of_travellers Number_of_buses screen.1
less than 20 1 Ans: #include<iostream.h>
Equal to or more than 20 and less than 40 2 #include<conio.h>
Equal to 40 or more than 40 3 #include<string.h>
* A function ShowTravel() to display the content of all the #include<stdio.h>
data members on the screen. class Play
Ans: { int Playcode;
#include<iostream.h> char Playtitle[25];
#include<conio.h> float Duration;
#include<stdio.h> int Noofscenes;
#include<string.h> public:
class Travel Play( )
{ long TravelCode; { Duration=45;
char Place[21]; Noofscenes=5;
int No_of_travellers,No_of_buses; }

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 34 PRAISE THE LORD


void Newplay( ) ii) Write Statement 1 and Statement 2 to execute
{ cout<<"\nEnter the Play Code: "; Member Function 1 and Member Function 2
cin>>Playcode; respectively.
cout<<"\nEnter the Play Title: "; A) TEST T1;
gets(Playtitle);
TEST T2(T1); //Statement 2
}
void Moreinfor(float D,int N) OR
{ Duration = D; TEST T2=T1; //Statement 2
Noofscenes = N; 2.Answer the questions(i) and (ii) after going through
} the following class: (2017 MP)
void Showplay( ) class planet
{ cout<<"\nThe Play Code : “ <<Playcode; {char name[20];char distance[20];
cout<<"\nThe Play Title :“<<Playtitle; public:
cout<<"\nThe Duration :”<<Duration; planet() //Function 1
cout<<"\nThe No of Scenes:"<<Noofscenes; {strcpy(name, "Venus");
} strcpy(distance,"38 million km");
}; }
void main( ) void display(char na[],char d[]) //Function 2
{ clrscr( ); {cout<<na<<"has"<<d<<"distancefromEarth"<<endl;
Play P; }
P.Newplay( ); planet(char na[], char d[]) //Function 3
float Dur; { strcpy(name,na);
int NS; strcpy(distance,d);
cout<<"\nEnter the Duration and }
Number of Scenes: "; ~planet() //Function 4
cin>>Dur>>NS; { cout<<"Planetarium time over!!!"<<endl;
P.Moreinfor(Dur,NS); }
P.Showplay( ); };
getch( ); I. What is Function 1 referred as? When will it be executed?
} II. Write suitable C++ statement to invoke Function 2.
AnsI. Constructor. It will be executed at the time of object
MODEL 2: Answer the questions (i) and (ii) after going creation.
through the following class 2Marks II. planet p;
1. Observe the following C++ code and answer the p.display(“Pluto”,”7.5 Billion Km”);
questions (i) and (ii). (2017) 3)Observe the following C++ code and answer the
Note: Assume all necessary files are included. questions (i) and (ii). Assume allnecessary files are
class TEST included: (2016)
class BOOK
{long TCode; { long Code ;
char TTitle[20]; char Title[20];
float Score; float Price;
public: public:
TEST() //Member Function 1 BOOK() //Member Function 1
{ TCode=100; {cout<<”Bought”<<endl;
strcpy(TTitle,”FIRST Test”); Code=10;strcpy(Title,”NoTitle”);Price=100;
Score=0; }
} BOOK(int C,char T[],float P) //Member Function 2
{ Code=C;
TEST(TEST &T) //Member Function 2
strcpy(Title,T);
{ TCode=E.TCode+1; Price=P;
strcpy(TTitle,T.TTitle); }
Score=T.Score; void Update(float P) //Member Function 3
} { Price+=P;
}; }
void main() void Display() //Member Function 4
{___________________ //Statement 1 {cout<<Code<<”:”<<Title<<”:”<<Price<<endl;
___________________ //Statement 2 }
} ~BOOK() //Member Function 5
{cout<<”Book Discarded!”<<end1;
i) Which Object Oriented Programming feature is
}
illustrated by the Member Function 1 and Member };
Function 2 together in the class TEST? void main() //Line 1
A) Polymorphism OR Constructor overloading OR { //Line 2
Function Overloading BOOK B,C(101,”Truth”,350}; //Line 3
for (int I=0;I<4;I++) //Line 4
{ //Line 5
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 35 PRAISE THE LORD
B.Update(50);C.Update(20); //Line 6 A) Function 1 will be executed when the statement 1 is
B.Display();C.Display(); //Line 7 executed.
} //Line 8 (ii) Write a statement to declare a new object G with
} //Line 9 reference to already existing object H using Function 3.
(i) Which specific concept of object oriented programming A) Hospital G(H);
out of the following isillustrated by Member Function 1 and 6) Answer the questions (i) and (ii) after going through
Member Function 2 combined together? the following class: (2013)
● Data Encapsulation ● Polymorphism class Race
● Inheritance ● Data Hiding {int CarNo,Track;
Ans Polymorphism public:
(ii) How many times the message ”Book Discarded!” will Race( );//Function 1
be displayed afterexecuting the above C++ code? Out of Race(int CN);//Function 2
Line 1 to Line 9, which line isresponsible to display the Race(Race &R);//Function 3
message ”Book Discarded!” void Register( );//Function 4
Ans 2 times void Drive( );//Function 5
Line 9 };
4)Observe the following C++ code and answer the void main( )
questions (i) and (ii) : (2015) {
class Passenger Race R;
{long PNR; ----
char Name [20] ; ----
public: }
Passenger() //Function 1 (i) Out of the following, which of the option is correct for
{ cout<<"Ready"<<endl; } calling Function 2?
void Book(long P,char N[]) //Function 2 (a) Option 1 – Race T(30);
{ PNR = P; strcpy(Name, N); (b) Option 2 – Race U(R);
} Ans) (a) Option 1 – Race T(30);
void Print() //Function 3 (ii) Name the feature of Object Oriented Programming
{ cout«PNR << Name <<endl; which is illustrated by Function 1, Function 2 and Function
} 3 combined together.
~Passenger() //Function 4 Anser) Constructor Overloading.
{ cout<<"Booking cancelled!"<<endl; 7) Answer the questions (i) and (ii) after going through
} the following class (2012)
}; class Travel
(i) Fill in the blank statements in Line 1 and Line 2 to {int PlaceCode; char Place[20] ; float Charges;
executeFunction 2 and Function 3 respectively in the public:
following code: Travel () //Function 1
v oid main() {PlaceCode=l;strcpy (Place, "DELHJ:") ; Charges = 1000;
{Passenger P; }
___________ //Line 1 void TravelPlan (float C) //Function 2
___________ //Line 2 {cout<<PlaceCode<<":"<<Place«":"<<Charges<<endl;
}//Ends here }
Ans P.Book(1234567,”Ravi”); //Line 1 ~Travel ( ) //Function 3
P.Print(); //Line 2 {Cout<<"Travel Plan Cancelled"<<endl;
(ii) Which function will be executed at }//Ends here? What }
is thisfunction referred as ? Travel (int PC, char P[], float C) //Function 4
AnsFunction 4OR~Passenger(). It is a Destructor function. {PlaceCode=PC;strcpy(Place,P); Charges=C;
5)Answer the questions (i) and (ii) ater going through }
the following class: (2014) };
class Hospital (i) In Object Oriented Programming, what are Function 1
{ int Pno,Dno; and Function 4combined together referred as?
public: Ans (i) Polymorphism OR Constructor Overloading
Hospital(int PN); //Function 1 OROverloaded ConstructorORFunction Overloading
Hospital( ); //Function 2 OROverloaded FunctionsOR
Hospital (Hospital &H); //Function 3 Default Constructor and Parameterized Constructor
void In( ); //Function 4 (ii) In Object Oriented Programming, which concept is
void Disp ( ); //Function 5 illustrated byFunction 3? When is this function
}; calledlinvoked?
void main( ) Ans. (ii) Destructor. It is called / Invoked when an object of
{ Hospital H(20); //Statement 1 the class goes outof scope.
}
(i) Which of the function out of function 1,2,3,4 or 5 will 8) Answer the questions (i) and (ii) after going through
get executed when the statement 1 is executed in the above the following class: (2010OD)
code? class Exam
{ int Rno,MaxMarks,MinMarks,Marks;
public:
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 36 PRAISE THE LORD
Exam ( ) //Module 1 10) Answer the questions (i) and (ii) after going through
{ Rno=101; the following program: (2008OD)
MaxMarks=l00; #include<iostream.h>
MinMarks=40; #include<string.h>
Marks=75; class Retail
} { char category[20];
Exam (int Prno, int Pmarks) //Module 2 char item[20];
{ Rno=Prno; int qty;
MaxMarks=l00; float price;
MinMarks=40; retail () //function 1
Marks=Pmarks; { strcpy (category, “cerial”);
} strcpy (Item, “Rice”);
~Exam () //Module 3 qty =100 ;
{ cout<<“Exam Over”<<endl; price =25 ;
} }
void Show () //Module 4 public;
{ void show() //function 2
cout<<Rno<<“:”<<MaxMarks<<“:”<<MinMarks<<endl; { cout << category <<”-“<< Item << “
cout<<“[Marks Got]”<<Marks<<endl; :”<<Qty<<“@”<< price<<endl;
} }
}; };
(i) As per Object Oriented Programming, which concept is void main()
illustrated byModule 1 and Module 2 together? { Retail R; //statement 1
Ans. Polymorphism (OR) Constructor Overloading R. show (); //statement 2
(OR) Function Overloading }
(ii) What is Module 3 referred as ? When do you think, (i) will statement 1 initialize all the data members for
Module 3 will be invoked/called? objects R with the given in the function 1 ? (YES OR
Ans. Destructor. It is invoked as soon as the scope of the NO). Justify your Answer suggesting the corrections(s) to
object gets over. be made in the above code.
Ans:No. The reason is the constructor should be defined
9) Answer the questions (i) and (ii) after going through
under the public visibility label.
the following class: (2009 OD)
(ii) What shall be the possible out put when the program
class Job
gets executed ? (Assuming, if required the suggested
{ int JobId;
correction(s) are made in the program)
char JobType;
Ans: Possible Output:
public:
cerial–Rice:100@25
~Job ( ) //Function 1
{ cout<< “Resigned” <<end1; 11) Answer the questions (i) and (ii) after going through
} the following class : (2007OD)
Job ( ) //Function 2 class Science
{ JobId=10 ; { char Topic[20] ;
JobType =„T” ; int Weightage ;
} public :
void TellMe( ) //Function 3 Science () //Function 1
{ cout<<JobId<< “: ” <<JobType<<end1; { strcpy (Topic, “Optics”) ;
} Weightage =30
Job (Job &J) //Function 4 cout<<”Topic Activated”;
{ JobId=J.JobId+10; }
JobType=J.JobType+l; ~Science() //Function 2
} { cout<<”Topic Deactivated”; }
}; };
(i) Which member function out of Function 1, Function 2, (i)Name the specific features of class shown by Function 1
Function 3 and Function 4 shown in the above definition of and Function 2 in the above example.
class Job is called automatically, when the scope of an Ans: Member function 1 is a (non-parameterized or default)
object gets over? Is it known as Constructor OR Destructor constructor
OR Overloaded Function OR Copy Constructor? (, which will be executed automatically at the time of
Ans Function 1. creation of an object of class Science).
Destructor. Member function 2 is a destructor (,which will be
(ii) Job P ; //Line 1 executed automatically at the time of destruction of an
Job Q(P) ; //Line 2 object of class Science).
Which member function out of Function 1, Function 2, (ii)How would Function 1 and Function 2 get executed ?
Function 3 and Function 4 shown in the above definition of Ans: They will be executed automatically.
class Job will be called on execution of statement written as Member function 1 will be executed at the time of creation of an
object of class Science. Member function 2 will be executed at the
Line 2 ? What is this function specifically known as out of
time of destruction of an object of class Science.
Destructor or Copy Constructor or Default Constructor?
Ans Function 4. Copy Constructor.
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 37 PRAISE THE LORD
12) Answer the following questions (i) and (ii) after void MyWork( )
going through the following class. (2006 OD) { cout<<”Attempting Questions”<<endl;
class Exam }
{ int Year; };
public: (i) In Object Oriented programming, what is
Exam(int y) //Constructor 1 Function 1 referred as and when does it get
{ Year=y; invoked/called?
} Ans: Function 1 is called as Destructor, It will
Exam(Exam &t); //Constructor 2 automatically executed at the time ofdestruction of the
}; object of class TestMeOut.
(i) Create an object, such that it invokes Constructor 1 (ii) In Object Oriented Programming, what is
Ans: Exam E((2008); Function 2 referred as and when does it get
(ii)Write complete definition for constructor 2. invoked/called?
Ans: Exam(Exam &t) Ans: Function 2 is called as constructor (Non-
//Copy Constructor. parameterized or default constructor) , it will
{ Year=t.Year; automatically executed at the time of creation of the
} object of class TestMeOut.
13) Answer the following questions (i)and (ii) after going
15)Answer the questions (i) and (ii) after going through
through the following class. (2005 OD)
the following class: (2009-10 MP1) (2008-09MP1)
class Exam
class Seminar
{ int Marks;
{ int Time;
char Subject[20];
public:
public:
Seminar() //Function 1
Exam() //Function 1
{ Time=30;cout<<”Seminar starts now”<<end1;
{ strcpy(Subject,”Computer”);
}
Marks=0;
void Lecture() //Function 2
}
{ cout<<”Lectures in the seminar on”<<end1;
Exam(char S[]) //Function 2
}
{ strcpy(Subject,S);
Seminar(int Duration) //Function 3
Marks=0;
} {Time=Duration;cout<<”Seminar starts now”<<end1;
Exam(int M) //Function 3 }
{ strcpy(Subject,”Computer”); ~Seminar() //Function 4
Marks=M; { cout<<”Vote of thanks”<<end1;
} }
Exam(char S[],int M) //Function4 };
{ Strcpy(Subject,P); i)In Object Oriented Programming, what is Function 4
Marks=M; referred as and when does it get invoked/called?
} Answer:
}; Destructor, it is invoked as soon as the scope of the object
(i)Write statements in C++ that would execute Function 3 gets over.
and Function 4 of class Exam. ii)In Object Oriented Programming, which concept is
(let char name[20]; illustrated by Function 1 and Function 3 together? Write an
int X=60; example illustrating the calls for these functions.
strcpy(name,”COMPUTERSCIENCE”); Answer:
are declared in the program) Constructor Overloading (Polymorphism)
(i) Exam A(X); Seminar S1,S2(90);
//Will execute Funciton 3 16) Answer the questions (i) and (ii) after going through
(ii) Exam B(name,X); the following program: (2008-09 MP2) (2009-10 MP2)
//Will execute Function 4 class Match
(ii)Which feature Object Oriented Programming is { int Time;
demonstrated using Function 1, Function 2, Function 3 and public:
Function 4 in the above class text? Match() //Function 1
Ans: Function overloading (here it is constructor {
overloading). Time=0;
14) Given the following C++ code, answer the questions cout<<"Match commences"<<end1;
(i)and(ii) (2004 D) }
class TestMeOut void Details() //Function 2
{ public: {
~TestMeOut( ) //Function 1 cout<<"Inter Section Basketball Match"<<end1;
{ cout<<”Leaving the examination hall”<<endl; }
} Match(int Duration) //Function 3
TestMeOut( ) //Function 2 {Time=Duration;
{cout<<”Appearing for examination”<<endl; cout<<"Another Match begins now"<<end1;
} }

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 38 PRAISE THE LORD


Match(Match &M) //Function 4 s4=s2;
{Time=M.Duration; s4.show();
cout<<"Like Previous Match "<<end1; getch();
} }
};
A)
i) Which category of constructor - Function 4 belongs to
and what is the purpose of using it? Registration@5000
A) Copy constructor, It will help to copy the data from one Registration with Discount@4000
object to another ICT@7000
ii) Write statements that would call the member Functions 1 Cyber Crime@6500
and 3 Genetic Mutation@7000
A) Match M; //Function 1 Cyber Crime@6500
Match N(10); //Function 3
2)Find and write the output of the following C++
MODEL 3): Output(Using Class Concept)–3M program code: (2016)
Note: Assume all required header files are already
1.Write the output of the following C++ program being included in the program. 3
code:Note: Assume all required header files are class Share
already being included inthe program.3 { long int Code;
class seminar (2017 MP) float Rate;
{char topic[30]; int DD;
int charges; public:
public: Share()
seminar() { Code=1000;Rate=100;DD=1;
{strcpy(topic,"Registration"); }
charges=5000; void GetCode(long int C,float R)
} { Code=C;
seminar(char t[]) Rate=R;
{ strcpy(topic,t); }
charges=5000; void Update(int Change,int D)
} { Rate+=Change;
seminar(int c) DD=D;
{strcpy(topic,"Registration with Discount"); }
charges=5000-c; void Status()
} { cout<<”Date:”<<DD<<endl;
void regis(char t[],int c) cout<<Code<<”#”<<Rate<<endl;
{ strcpy(topic,t); }
charges=charges+c; };
} void main()
void regis(int c=2000) { Share S,T,U;
{ charges=charges+c; S.GetCode(1324,350);
} T.GetCode(1435,250);
void subject(char t[],int c) S.Update(50,28);
{ strcpy(topic,t); U.Update(25,26);
charges=charges+c; S.Status();
} T.Status();
void show() U.Status();
{ cout<<topic<<"@"<<charges<<endl; }
} A)
}; Date:28
void main() 1324#400
{ Date:1
seminar s1,s2(1000),s3("Genetic Mutation"),s4; 1435#250
s1.show(); Date:26
s2.show(); 1000#125
s1.subject("ICT",2000);
s1.show(); 3)Write the output of the following C++ program
s2.regis("Cyber Crime",2500); code: Note: Assume all required header files are
s2.show(); already being includedin the program. (2015) 3
s3.regis(); class Eval
s3.show(); { char Level;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 39 PRAISE THE LORD
int Point; }
public: void Game::Play(int GS)
Eval() { Score+=GS;
{Level=‟E‟;Point=0; if(Score>=30)
} Level=3;
void Sink(int L) else if(Score>=20)
{ Level= L; Level=2;
} else
void Float(int L) Level=1;
{ Level += L; }
Point++; A) P@1
} 0
void Show() P@1
{cout<<Level<<”#”<<Point<<endl; 11
} P@2
}; 25
void main()
5) Obser the following C++ code carefully and obtain
{ Eval E;
the output,which will appear on the screen after
E.Sink(3);
execution of it3
E.Show();
#include<iostream.h> (2013)
E.Float(7);
class Aroundus
E.Show();
{ int Place, Humidity, Temp;
E.Sink(2);
public:
E.Show();
Aroundus(int P=2)
}
{ Place=P; Humidity=60; Temp=20;
A B#0
}
I#1
void Hot(int T)
G#1
{ Temp+=T;
4) Obtain the output of the following C++ Program, }
which wll appear on the screen after its execution 3 void Humid(int H)
Important Note: (2014) { Humidity+=H;
-All the desired header files are already included in }
the code, which are required to run the code.
class Game void JustSee( )
{ int Level, Score; {cout<<Place<<”:”<<Temp<<”&”<<Humidity<<”%”
char Type; <<endl;
public: }
Game(char GType=‟P‟) };
{ Level=1;Score=01;Type=GType; } void main( )
void play(int GS); { Aroundus A,B(5);
void Change( ); A.Hot(10);
void Show( ); A.JustSee( );
{ B.Humid(15);
cout<<Type<<”@”<<Level<<endl; B.Hot(2);
B.JustSee( );
cout<<Score<<endl;
A.Humid(5);
} A.JustSee( );
}; }
void main( ) A) 2:30&60%
{ 5:22&75%
Game A(„G‟),B; 2.30&65%
B.Show( );
6.Find the output of the following program: 3
A.Play(11);
#include <iostream.h> (2012)
A.Change( );
class METRO
B.Play(25);
{ int Mno,TripNo,PassengerCount;
A.Show( );
B.Show( ); public:
METRO(int Tmno=l)
}
{Mno=Tmno;TripNo=0;PassengerCount=0;
void Player:: Change( )
}
{ Type=(Type==‟P‟)?‟G‟:‟P‟;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 40 PRAISE THE LORD
void Trip(int PC=20) public:
{TripNo++;PassengerCount+=PC; product()
} { product_code=0;qty=0;price=0;
void status Show () name=NULL;
{cout<<Mno<<":"<<TripNO<<":" }
<<PassengerCount<<endl: void entry()
} {cout<<"\n Enter code,qty,price";
}; cin>>product_code>>qty>>price;
void main () gets(name);
{ METRO M(5), T; }
M. Trip () ; void tot_price()
M. StatusShow() ; { return qty*price;
T. StatusShow() ; }
M. Status Show () ; };
} void main()
Ans: 5:1:20 {p product;
1:1:50 p.entry();
5:2:50 cout<<tot_price();
7)Write the output of the following program. }
Ans: #include<iostream.h> A)#include<conio.h>
class Counter #include<iostream.h>
{ private: #include<string.h>
unsigned int count; #include<stdio.h>
public: class product
Counter() {
{ count=0; int product_code,qty,price;
} char name[20];
void inc_Count() public:
{ count++; product(){
} product_code=0;qty=0;price=0;
int get_Count() strcpy(name,NULL);
{ return count; }
} void entry()
}; {cout<<"\n Enter code,qty,price";
void main()(2002) cin>>product_code>>qty>>price;
{ Counter C1,C2; gets(name);
cout<<"\nC1="<<C1.get_Count(); }
cout<<"\nC2="<<C2.get_Count(); int tot_price() {return qty*price;}
C1.inc_Count(); };
C2.inc_Count(); void main()
C2.inc_Count(); {
cout<<"\nC1="<<C1.get_Count(); product p;
cout<<"\nC2="<<C2.get_Count(); p.entry();
} cout<<p.tot_price();
}
MODEL 4): Rewrite the following 2) Rewrite the following program after removing the
program after removing the syntactical syntactical errors (if any). (2012 OD)
Underline each correction. 2
errors (if any). Underline each correction #include <iostream.h>
(Using Class) -2 Marks Class 1tem
1)Rewrite the following program after removing the {
syntactical errors(if any). Underline each correction.2 long IId, Qty;
#include<conio.h> (2017 MP) public :
#include<iostream.h> void Purchase{cin>>IId>>Qty;}
#include<string.h> void Sale ( )
#include<stdio.h> {
class product cout«setw(5)<<IId<<"Old:"<<Qty<<endl;
{ int product_code,qty,price; cout<<''New: "<<Qty«end1;
char name[20]; }

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 41 PRAISE THE LORD


}; void AddInfo ( )
void main ( ) { cin>>FlightCode; gets (Description) ;
{ }
Item I ; void ShowInfo ( )
Purchase ( ) ; { cout<<FlightCode<<”:”<<Description<<endl;
I.Sale ( ) ; }
I.Sale ( ) };
} void main ( )
Ans { FLIGHT F;
#include<iosteam.h> F.AddInfo( ) ;
class Item // C Capital F. ShowInfo ( ) ; / / Error 4
{ }
long IId,Qty;
4)Rewrite the following program after removing the
public:
syntactical errors (if any). (2009 OD)2
void Purchase ( ){cin>>IId>>Qty;}
Underline each correction.
void Sale ( )
include <iostream.h>
{ cout<<setw(5)<<IId<<" Old: "<<Qty<<endl;
include <stdio.h>
//Either the statement setw(5) is removed
class MyStudent
//or header file included as#include<iomanip.h>
{ int StudentId = 1001;
cout<<"New:"<<--Qty<<endl;
char Name [20] ;
}
public
};
MyStudent( ){ }
void main ( )
void Register ( ) {cin>>StudentId; gets (Name) ;}
{
void Display ( ) {cout<<StudentId<< “:”
Item I;
<<Name<<end1;}
I.Purchase( ); // Object missing
};
I. Sale ( ) ;
void main ( )
I. Sale ( ) ; // ; is missing
{MyStudent MS ;
}
Register.MS( ) ;
3) Rewrite the following C++ program code after
MS.Display( ) ;
removing the syntax error(s) (if any). Underline each
}
correction.2
Ans
include<iostream.h> (2010 OD)
# include <iostream.h>
class FLIGHT
# include <stdio.h>
{
long FlightCode;
class MyStudent
char Description[25];
{ int StudentId;
public
char Name[20];
void AddInfo ( )
public :
{ cin>>FlightCode; gets (Description) ;
MyStudent( )
{
{ StudentId = 1001;
void ShowInfo ()
}
(cout<<FlightCode<<“:”<<Description<<endl;
void Register( )
}
{ cin>>StudentId;
};
gets (Name);
void main()
}
{FLIGHT F;
void Display ()
AddInfo.F();
{ cout«StudentId<<”:“<<Name<<endl;
ShowInfo.F();
}
}
};
Ans.
void main ()
#include <iostream.h> / / Error 1
{ MyStudent MS;
#include <stdio.h> / / Error 2
MS. Register ();
class FLIGHT
MS. Display () ;
{ long FlightCode;
}
//not required if gets( ) is re-placed with
5) Rewrite the following program after removing the
//cin.getline( ) or cin
syntactical errors (if any). (2009 D)
char Description[25];
Underline each correction.2
public : / / Error 3
#include [iostream.h]
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 42 PRAISE THE LORD
#include [stdio.h] void Show(){cout<<Charge;}
class Employee };
{ void main()
int EmpId=901; { PAYITNOW P;
char EName [20] ; P.Raise();
public P.Show();
Employee(){} }
void Joining() {cin>>EmpId; gets (EName);} 7 )Rewrite the following program after removing the
void List () {cout<<EmpId<<” : “<<EName<<endl;} syntactical errors (if any).(2009-10 MP1)
}; Underline each correction. 2
void main () #include [iostream.h]
{Employee E; class MEMBER
Joining.E(); {int Mno;float Fees;
E.List() PUBLIC:
} void Register(){cin>>Mno>>Fees;}
Ans void Display{cout<<Mno<<" : "<<Fees<<endl;
#include <iostream.h> }
#include <stdio.h> };
class Employee void main()
{ int EmpId; { MEMBER M;
char EName[20]; Register();
public : M.Display();
Employee() }
{ EmpId=901; A)
} #include <iostream.h>
void Joining( ) class MEMBER
{ cin>>EmpId; { int Mno;float Fees;
gets (EName); public:
} void Register()
void List ( ) { cin>>Mno>>Fees;
{ cout<<EmpId<<”: “<<EName<<endl; }
} void Display()
}; { cout<<Mno<<":"<<Fees<<endl;
void main () }
{ Employee E; };
E.Joining (); void main()
E.List (); { MEMBER M;
} M.Register();
6)Rewrite the following program after removing the M.Display();
syntactical errors (if any). Underline each correction.2 }
#include [iostream.h](2008-09 MP1)
class PAYITNOW MODEL 5: Theory Questions (Classes)
{ int Charge;
1.
PUBLIC:
void Raise(){cin>>Charge;} Difference between Year
void Show{cout<<Charge;} protected and private 2017, 2008 OD
}; Public and Private 2012D, 2008D
void main()
{ What is the difference between the members in private
PAYITNOW P; visibility mode and the members in public visibility
mode inside a class? Also, give a suitable C++ code to
P.Raise(); illustrate both.
Show(); DIFFERENCE BETWEEN PUBLIC & PRIVATE
}
Answer: (Access Specifiers: It is used to define the behaviour of the
#include <iostream.h> variable and function in a class. It tells which object can
class PAYITNOW access the variable and function. It is public, private and
protected. It is therefore used in class.
{ int Charge; Visibility Mode: It is used in C++ to show the relationship
public: between the base and the derived class. It specifies what the
void Raise(){cin>>Charge;}
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 43 PRAISE THE LORD
derived class can derive from the base class. It is therefore same class as well as that of They cannot access from
used in inheritance.) its derived class only (They objects of the class.
(Important Note: For Visibility modes differences, in the
cannot access from outside They cannot accessible from
marking schemes answers were given for access specifier
differences. So Student is adviced to differentiate in of the class ie from objects.) derived classess.
context of access specifiers as well as visibility modes) Must keep keyword It is default visibility mode.
Public Visibility Private visibility “protected” to make a (implicit visibility mode)
Members in public visibility Members in private visibility member as public.
mode of the class are mode of the class are (explicit visibility mode)
accessible from within the accessible from within the The concept of data hiding is implemented through the
private access specifier only.
class as well as outside of class only (member
functions of the class only). Eg:
the class ie (member
They cannot access from class student
functions of the class & objects of the class. { private:
objects of the class.) int rno;
Must keep keyword It is default visibility mode. char name[21];
“public” to make a member (implicit visibility mode) protected:
as public. int age;
(explicit visibility mode)
public:
The concept of data hiding is implemented through the void input( );
private access specifier only. void display( );
Eg: }
class student Here, since rno and name are declared in private, they can
{ private: be accessed only inside the class.(They are not accessible
int rno; from derived class)
char name[21]; Where as age is derived privately, it can be accessed only
public: inside the class .(They can also accessible from derived
int age; class)
void input( );
void display( ); Protected and private visibility modes in context of
} INHERITANCE:
Here, since rno and name are declared in private, they can Protected visibility mode: With protectedly derived class,
be accessed only inside the class. Since age,input( ) and the public and protected members of the base calss become
display() are declared in public, they can be accessed from protected members of the derived class. That means the
outside class also. inherited members are now not available to the outside
world and can be accessed only through the member
Public and private visibility modes in context of functions of the derived class and the classes based upon
INHERITANCE: the derived classes.
Public visibility mode: With publicly derived class, the Private visibility mode: With privately derived class, the
public members of the base class become the public public and protected members of the base class become
members of the derived class, the protected members of the private members of the derived class and the private
base class become the protected members of the derived members of the base class are not accessible in the derived
class and the private members of the base class are not class.
accessible in the derived class.
Visibility Inheritable Inheritable
Private visibility mode: With privately derived class, the
Mode public protected Private
public and protected members of the base class become
member member member of
private members of the derived class and the private
becomes ( in becomes (in base class
members of the base class are not accessible in the derived
derived derived are not
class.
class) class) directly
Visibility Inheritable Inheritable Private accessible to
Mode public protected member of derived
member member base class class.
becomes ( in becomes (in are not protected Protected protected
derived class) derived directly private Private private
class) accessible to
derived 2) What do you understand about a member function?
class. How does a member function differ from an ordinary
public Public protected function? (2002)
privatee Private private Ans: A member function is a function declared within a
DIFFERENCE BETWEEN PROTECTED & PRIVATE class. It is said to be defined in two ways. Ie Outside the
class and inside the class. When a member function is
Protected Visibility Private visibility defined outside the class, the name of the function must be
Members in protected Members in private visibility the full name including the class name as well. When a
visibility mode of the class mode of the class are member function is defined inside the class, the name of the
are accessible to the accessible from within the function is similar to an ordinary function but it will
member functions of the class only (member become an inline function.
functions of the class only).
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 44 PRAISE THE LORD
3) Illustrate the use of Inline function in C++ with the With a default constructor, objects are created just the same
help of an example. (2006 OD) way as variables of other data types are created.
Ans: INLINE FUNCTIONS: The inline functions are a class X
C++ enhancement designed to speed up programs. The { int i ;
coding of normal functions and inline functions is similar public:
except that inline functions definitions start with the int j, k ;
keyword inline. ------ //Members Functions
The working of inline functions: ------
After writing any program, it is first compiled to };
get an executable code. After loading the executable Eg: X ob1;
program in the computer memory, these instructions are Student s1;
executed step by step. If a class has no explicit constructor defined, the compiler
When a function call instruction is encountered, will supply a default constructor. This implicitly declared
the program stores the memory address of the instruction default constructor is an inline public members of its class.
immediately following the function call statement, loads the Declaring a constructor with arguments hides the default
function being called into the memory, copies argument constructor.
values, jumps to the memory location of the called function, There can be a default constructor as well as
executes the function code, stores the return value of the another constructor with arguments for a class, having
function, and then jumps back to the address of the multiple constructors is called as constructor overloading.
instruction that was saved just before executing the called
function. 2.What is a copy constructor? Illustrate with a
With inline code, the compiler replaces the suitable C++ example. (2019SP)(2015)(2009D) (2)
function call statement with the function code itself (this Ans: A copy constructor is an overloaded
process is called expansion) and then compiles the entire constructor in which an object of the same class is
code. Thus, with inline functions, the compiler does not passed as reference parameter.
have to jump to another location to execute the function,
(It is used when an object‟s data value is related to or is
and then jump back as the code of the called function is
initialised using another object‟s data value of the same
already available to the calling program.
class. In the example below the values of data members of
Inline functions run a little faster than the object P2 are dependent on the values of data members of
normal functions as function calling overheads are object P1)
saved, however there is a memory penalty. If 10 times
an inline function is called, there will be 10 copies of the Ex:
class X
function inserted into the code.
{ int a;
A function can be declared inline by placing the public:
keyword inline before it. An inline function definition X()
should be placed above all the functions that call it. The { a=0;
functions should be inlined only when they are small. Since }
for large functions, they will become memory penalty. X(X &ob) //copy constructor
The inlining does not work for following situations: { a=ob.a;
a. For functions that return values and are having a loop or a }
switch or a goto. };
void main()
b. For functions not returning values, if a return statement {
exists. Point P1;
c. If functions contain static variables. Point P2(P1); //Copy constructor is called here
d. If the function is recursive(a function that calls itself). //OR Point p3=p1;
Inlining and the member functions: }
The member function of a class, if defined within 3) Differentiate between a default constructer and copy
the class definition, are inlined by default. Therefore, only constructer, giving suitable examples of each. (2005 OD)
very small member functions should be defined within the Ans: A default constructor also called as non-parameterized
class definition. constructor will take no argument and initialize the object
The member functions defined outside the class with the predefined values in that constructor,
definition can be made explicitly inline by placing the Where as a copy constructor will take an already
keyword inline before their definition. created object of that class and stores that object values into
Inline functions are best for small functions that are called the newly created object of that class. A copy constructor
often.The compiler may even ignore your attempt to linline takes a reference to an object of the same class as an
a function if it consists more than 50 lines of code. argument.

4. Write any four differences between


MODEL 6: Theory Questions (Constructors)
Constructor and Destructor function with
respect to object oriented programming(2019SP)2
1) What is a default constructor? How does it differ
from destructor? (2006 OD)
a) Default constructor: A constructor that accepts no
parameter is called the default constructor.

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 45 PRAISE THE LORD


Constructor can be Destructors cannot
overloaded be overloaded
-------------------------- -------------------------
It is defined in public It is defined in public
visibility mode visibility mode
Pointers and references Pointers and references
cannot be used on cannot be used on
constrctors and constrctors and
destructors because their destructors because their
addresses cannot be taken. addresses cannot be taken.
Example: Example:
class Area class Area
{ {
float l,b,a; float l,b,a;
5) Write any two similarities between constructor and public: public:
destructor. Write the function headers for constructor Area( ) -------------
and destructor of a class Flight. (2013) { l=b=a=0.0; } -------------
Answer: Similarities: ~Area( )
(i) Constructors and destructors have the name of the class ------------ { cout<<”One Object
(destructor name will be prexixed by ~), do not have any ------------ destroyed”;
return type not even void, they will be called automatically. }; }
(ii) Pointers and references cannot be used on constrctors ------------
and destructors because their addresses cannot be taken. ------------
Example: };
class Student
{ char name[30]; 7) Why is destructor function required in classes?
float m1,m2,m3; Illustrate with the function with an example. (2000 D)
public: Ans: A destructor is a function which de-allocates/frees the
Student( ); //Constructor for class Student memory which was reserved by the constructor.
~Student( ); //Destructor for class Student Eg:
}; class Sample
{
6) Differentiate between Constructor and Destructor Int i,j;
function in context of Classes and Objects Using C++? Public:
Sample(int a, int b) //Constructor
(2011) (2007 D) { i=a; j=b; }
Ans: Constructor: A constructor is used to intitialize the ~Sample()
objects of that class type with a legal initial value.If a class { cout<<”Destructor at work\n”; }
has a constructor, each object of that class will be initialized ------
};
before any use is made of the object. void main( )
(A member function with the same name as its {
class is called Constructor and it is used to initialize the Sample s1(3,4); //Local object s1 constructed with values 3
objects of that class type with a legal initial value. ) // and 4 using Sample ( )
------
Destructor: A destructor is used to destroy the objects that ----//Automatically s1 is destructed at the end of the block
have been created by a constructor. A destructor destroys //using destructor ~Sample( )
the values of the object being destroyed. }
Constructor Destructor Here in the above example the destructor ~Sample( ) will be
Purpose: Is used to Purpose: Is used to automatically executed at the time of destruction of an
intitialize the objects destroy the objects object, and which is used to de-allocate the memory, before
of that class type that have been doing it whatever written in the destructor will be executed.
with a legal initial created by a Ie in the above example whenever an object of the class is
value constructor being destroyed, “Destructor at work” will be displayed.
Name: The name of Name:The name of 8) What is a copy constructor? What do you understand
the class the class preceded by by constructer overloading? (1998D)
a ~. Ans: copy constructor is a constructor of the form
classname(classname &). The compiler will use the copy
Calling: It will be Calling: It is
constructor whenever you initialize an instance using values
called automatically automatically called
of another instance of same type.
at the time of and executed when
Eg: Sample S1; //Default constructor used
creation or scope of an object
Sample S2 = S1;//Copy constructor used. Also
declaration of the gets over. //Sample S2(S1);
object. In the above code, for the second statement, the compiler
Ie Implicite calling Ie Implicite calling will copy the instance S1 to S2 member by member. If you
Return Type: No Return Type: No have not defined a copy constructor, the compiler
return type not even return type not even automatically, creates it and it is public.
void void A copy constructor takes a reference to an object of the
-------------------------- -------------------------- same class an argument.
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 46 PRAISE THE LORD
Constructor Overloading: X ( ); //Only constructor declaration.
With same constructor name, having several ------ //Other members
definitions that are differentiable by the number or types of ------
their arguments(ie Parameterized, non-parameterized and };
copy constructors) is known as an overloaded constructor X :: X ( ) //Constructor defined outside
and this process is known as constructor overloading. {
Constructor overloading implements i = j = k = 0;
polymorphism. }
Generally constructor will be defined under public
An Example using Constructor Overloading:
section, which can be available to non members also. But
(It is given in Constructors – Material)
it can also be defined under private or protected. A private
MATERIAL or protected constructor is not available to the non-member
CHAPTER 5 - CONSTRUCTORS& DESTRUCTORS functions. Ie With a private or protected constructor, you
Constructor: A member function with the same name as cannot create an object of the same class in a non-member
its class is called Constructor and it is used to initialize the function.
objects of that class type with a legal initial value. There are three types of constructors
If a class has a constructor, each object of that A) Non-parameterized or Default Constructor
class will be initialized before any use is made of the object. B) Parameterized Constructor
Need for Constructors: A variable, an array or a structure C) Copy Constructors Default constructor:
in C++ can be initialized at the time of their declaration. A constructor that accepts no parameter is called
Eg: int a=10; the default constructor.
int a[3]= {5,10,15}; With a default constructor, objects are created just the same
struct student way as variables of other data types are created.
{ int rno; class X
float m1,m2,m3; { int i ;
}; public:
student s1={1,55.0,90.5,80.0}; int j, k ;
But this type of initialization does not work for a ------
class because the class members have their associated //Members Functions
access specifiers. They might not be available to the ------
outside world (outside their class). A Constructor is used to };
initialize the objects of the class being created Eg: X ob1;
(automatically called by the compiler). Student s1;
Difference between a constructor and an ordinary If a class has no explicit constructor defined, the
member function: compiler will supply a default constructor. This implicitly
CONSTRUCTOR MEMBER FUNCTION declared default constructor is an inline public members of
Name Name of the class Any valid identifier its class. Declaring a constructor with arguments hides the
Purpose
default constructor.
Initialize the object For any general
There can be a default constructor as well as
when it is being purpose another constructor with arguments for a class, having
created multiple constructors is called as constructor overloading.
Call Implicit Explicit A constructor can also have default arguments. A
Return Type Should not keep Must be there at least constructor with default arguments is equivalent to a default
void constructor.
Declaration and Definition: Eg: class Rectangle
A constructor is a member function of a class with { float l,b,a;
the same name as that of its class name. A constructor is public:
defined like other member functions of a class. It can be Rectangle ( float len = 5.0, float bre = 5.0)
defined either inside the class definition or outside the class //Constructor with Default arguments
definition. { l = len;
Eg: class X b = bre;
{ int i; }
public: -----
int j,k; -----
X( ) //Constructor };
{ i = j = k = 0; void main( )
} { Rectangle first(7.0,9.5);
------ Rectangle second;
//Other members //Takes default argument values. Equivalent to second(5.0,5.0)
------ ----
}; ----
This simple constructor (X::X ( ) ) is as an inline }
member function. Constructors can be written as outline The default constructors are very useful when you
functions also as it is shown below: want to create objects without having to type the initial
class X objects every time with pre specified initial values or if you
{ int i ; want to create array of objects of your class type. You can‟t
public: create an array of objects unless your class has a default
int j, k ; constructor (implicitly or explicitly defined).

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 47 PRAISE THE LORD


b) Parameterized Constructor: int i(3), j(4), k(5); //i,j,k initialized
A constructor that take arguments, is called as c) Copy Constructor:
parameterized constructor. A copy constructor is a constructor of the form
The parameterized constructor allow us to initialize the classname(classname &). The compiler will use the copy
various data elements of different objects with different constructor whenever you initialize an instance using values
values when they are created. This is achieved by passing of another instance of same type.
different values as arguments to the constructor function Eg: Sample S1; //Default constructor used
when the objects are created. Sample S2=S1; //Copy constructor used.Also Sample
Eg: class Rectangle S2(S1);
{ float l,b,a; In the above code, for the second statement, the
public: compiler will copy the instance S1 to S2 member by
Rectangle ( float len , float bre ) member. If you have not defined a copy constructor, the
//Parameterized Constructor. compiler automatically, creates it and it is public.
{ l = len; A copy constructor takes a reference to an object
b = bre; of the same class an argument.
} Eg:
----- class Sample
}; { int i,j;
void main( ) public:
{ Sample (int a, int b) //Constructor
Rectangle first(7.0,9.5); { i = a;
---- j = b;
---- }
} Sample (Sample &s) //Copy Constructor
With a parameterized constructor, the initial values { i=s.i;
must be passed at the time of object created. This can be j=s.j;
done in two manners: cout<<”Copy constructor
(i)By calling the constructor implicitly Working\n”;
(implicit call) }
Eg: Rectangle first(8.5,3.9); void print( )
(ii)By calling the construct or explicitly {
(Explicit call) cout<<i<<”\t”<<j<<”\n”;
Eg: Rectangle first = Rectangle (8.5,3.9); }
Temporary Instances: -----
A temporary instance lives in the memory as long -----
it is being used or referenced in an expression and after this };
it dies. A temporary instance will not have any name. The void main( )
explicit call to a constructor also allows you to create a {
temporary instance or temporary object. The temporary Sample S1(4,9); //S1 initialized first constructor used
instances are deleted when they are no longer referenced. Sample S2(S1); //S1 copied to S2. Copy constructor called.
Eg: class Sample Sample S3=S1;//S1 coped to S3. Copy constructor called
{ int i,j; again.
public: -----
sample (int a, int b) -----
{ i=a; }
j=b; Why the argument to a copy constructor is passed by
} reference:
void print ( ) If we try to pass the argument by value to a copy
{ cout<<i<<j<<”\n”; constructor (ie, for a class X, if we use an X(X) constructor
} in place of X(X&), the compiler complaints out of memory.
---- The reason is, when an argument is passed by value, a copy
---- of it is constructed. To create a copy of the object, the copy
}; constructor works. But the copy constructor is creating a
void test ( ) copy of the object for itself, thus it calls itself. Again the
{ Sample S1(2,5); called copy constructor requires another copy so again it is
//An object S1 created called. In fact it calls itself again until the compiler runs out
S1.print ( ); of memory. So, in the copy constructor, the argument must
//Data values of S1 printed be passed by reference, so that to make a copy of the passed
Sample (4,9).print ( ); object, original object is directly available.
//Data values of a temporary Dynamic initialization of objects: The dynamic
//sample instance printed initialization means that the initial values may be provided
} during runtime. The benefit of dynamic initialization is that
The primitive (fundamental) types also have their it provides the flexibility of assigning initial values at run
own constructors. When no values are provided, they use time.
their default constructors but when you provide initial Initialization of Const & Reference Members:
values, the newly created instance is initialized with the If your class contains a constant and a reference as member
provided value. field, then you need to specify that through Member-
Eg: int a,b,c; Initialization List.
//Default constructor used
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 48 PRAISE THE LORD
A constructor can initialize the constituent data 1. Constructor functions are invoked automatically
members of its class through a mem-initialization list that when the objects are created.
appears in the function header of the constructor. 2. If a class has a constructor, each object of that
Eg: class will be initialized before any use is made of
class Test the object.
{ int a ; 3. Constructor functions obey the usual access rules.
char b; Ie private and protected constructors are available
public: only for member and friend functions, however,
Test(int i,char j):a(i), b(j); public constructors are available for all the
//a(i) initializes member a with value i, b(j)….b functions. Only the functions that have access to
with j. the constructor of a class, can create an object of
{ the class.
…. 4. No return type (not even void) can be specified for
} a constructor.
} 5. They cannot be inherited, though a derived class
You can even have a combination of mem-initialization list can call the base class constructor.
and initialization within constructor body. 6. A constructor may not be static.
Eg: 7. Default constructors and copy constructors are
class Test generated(by the compiler) where needed.
{ …… Generated constructors are public.
public: 8. Like other c++ functions, constructors can also
Test(int i, char j):a(i) have default arguments.
{ 9. It is not possible to take the address of a
b=j; constructor.
} 10. An object of a class with a constructor cannot be a
….. member of a union.
}; 11. Member functions may be called from within a
And if your class contains a const and /or a constructor.
reference member, then these members must be initialized 12. A constructor can be used explicitly to create new
through mem-initialization list as these cannot be initialized objects of its class type, using the syntax class-
within constructor body. name (expression-list)
Eg: Eg: Sample obj1=Sample(13,22.42);
struct Sname DESTRUCTORS
{ char fname[25]; Destructor:
char lname[25]; A destructor is used to destroy the objects that
} S1; have been created by a constructor. A destructor destroys
class Test the values of the object being destroyed.
{ int a,b; A destructor is also a member function whose name
const int max; //const member is the same as the class name but is preceded by tilde(~). A
Sname &name; //reference member destructor takes no arguments, and no return types can be
public: specified for it (not even void). It is automatically called by
Test ( ):max(300),name(S1) the compiler when an object is destroyed. A local object,
{ a=0; local to a block, is destroyed when the block gets over; a
b=10; global or static object is destroyed when the program
} terminates. A destructor cleans up the storage (memory
------ area of the object) that is no longer accessible.
}; Eg:
Mem-initialization lists are especially used in the class Sample
following four cases: { int i,j;
(i)initialization of const members. Public:
(ii)initialization of reference members. Sample(int a, int b) //Constructor
(iii)Invoking base class constructor. { i=a; j=b;
(iv)Initialization of member objects. }
Constructor Overloading: ~Sample()
The constructor of a class may also be overloaded { cout<<”Destructor at work\n”;
so that even with different number and types of initial }
values, an object may still be initialized. ------
Default Arguments Versus Overloading: ------
Using default arguments gives the appearance of };
overloading, because the function may be called with an void main( )
optional number of arguments. {
Eg: Sample s1(3,4);
Prototype : //Local object s1 constructed with values 3 & 4 using
float amount (float principal, int time=2, float rate=0.08); Sample ( )
Can be called as -----
Amount(2000.0,4,0.10); ---- /*Automatically s1 is destructed at the end of the
Amount(3520.5,3); block using destructor ~Sample( )*/
Amount(5500.0); }
Special Chracteristics of Constructors: Need for Destructors:
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 49 PRAISE THE LORD
During construction of any object by the Circle c3(c2); //Copy Constructor will be called implicitly
constructor, resources may be allocated for use. (for c1.take( );
example, a constructor may7 have opened a file and a c1.calculate( );
memory area may be allotted to it). These allocated c1.display( );
resources must be de allocated before the object is c2.display( );
destroyed.A destructor performs these types of tasks. c3.display( );
Some Characteristics of Destructors: getch();
1. Destructor functions are invoked automatically when the }
objects are destroyed.
2. If a class has a destructor, each object of that class will be 2. Program to process student data using class concept,
deinitialized before the object goes out of scope.(Local constructors and destructor.
objects at the end of the block defining them and global and
static objects at the end of the program). #include<iostream.h>
3. Destructor functions also, obey the usual access rules as #include<conio.h>
other member functions do. class Student
4.No argument can be provided to a destructor, neither does { float m1,m2,m3,total,avg;
it return any value. public:
5. They cannot be inherited. Student()
6. A destructor may not be static. { m1=0.0;
7. It is not possible to take the address of a destructor. m2=0.0;
8. Member functions may be called from within a m2=0.0;
destructor. total=0.0;
9. An object of a class with a destructor cannot be a avg=0.0;
member of a union. }
Student(float x,float y,float z)
CONSTRUCTORS AND DESTRUCTORS (PROGRAMS) { m1=x;
m2=y;
1.Program to find area of a circle using class, m3=z;
constructor functions and destructor. total=m1+m2+m3;
#include<iostream.h> avg=total/3;
#include<conio.h> }
class Circle Student(Student &Test)
{ float r,a; //r and a are private { m1=Test.m1;
public: m2=Test.m2;
Circle( ) //Non parameterized or Default Constructor m3=Test.m3;
{ r=0.0; total=Test.total;
a=0.0; avg=Test.avg;
} }
Circle(float rad) //Parameterized Constructor ~Student()
{ r = rad; { cout<<"The Object is being Destroyed....";
a = 3.1415*r*r; }
} void readProcess()
Circle(Circle &obj) //Copy Constructor { cout<<"\nEnter the 3 Subject marks of a
{ r = obj.r; student: ";
a = obj.a; cin>>m1>>m2>>m3;
} total=m1+m2+m3;
~Circle( ) avg=total/3;
{cout<<"\nThe object is being destroyed...."; }
} void display()
void take( ) { cout<<"\nTotal Marks = "<<total;
{ cout<<"\nAverage Marks = "<<avg;
cout<<"Enter the value of Radius: "; }
cin>>r; };
} void main()
void calculate( ) { clrscr();
{ Student S1;
a = 3.1415*r*r; Student S2(50.5,90.0,75.5);
} Student S3=S2;
void display( ) S1.readProcess();
{ cout<<"\nThe Radius of the Circle = "<<r; S1.display();
cout<<"\nThe Area of the Circle = "<<a; S2.readProcess();
} S2.display();
}; S3.display();
void main() getch();
{ clrscr( ); }
Circle c1; /*Default Constructor will be called implicitly.
ie c1.r = 0.0 and c1.a = 0.0 */
Circle c2(10.3); //Parameterized Constructor will be called
implicitly

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 50 PRAISE THE LORD


6.INHERITANCE (4 Marks) sdisplay( ),sprocess( )
f) Write the names of all members which are accessible
IMPORTANT QUESTION WHICH COVERS MORE MODELS from objects of class Teacher.
Answer the questions based on the following code: A) Data Members: NIL
class Student Member functions : Ttake( ), Tdisplay( ), stake( ),
{ char fname[20]; sdisplay ()
float marks; g) Write the names of members which are accessible from
int rno; member functions of class Teacher.
int getrno(); A) Data Members: Tqua, tname, salary, tid, admno;
protected: Member functions: Ttake( ), Tdisplay( ), TProcess(),
long admno; TTest( ), stake( ),sdisplay( ),sprocess( );
void sprocess(); h) What is the base class and derived class of „Teacher‟?
public: A)base class of Teacher – Student
Student(); Derived class of Teacher - HM
void stake(); i) If HM class derived privately from class Teacher, Write
void sdisplay(); the names of all members which are accessible from objects
}; of class HM.
class Teacher:public Student A) Data Members: NIL
{ char tname[30]; Member Functions: hmtake( ), hmdisplay( );
float salary;
int tid; Model 1
void TTest();
protected: 1.Answer the questions (i) to (iv) based on the
char Tqua[10]; following: (2019SP)4
void Tprocess(); class Faculty
public: {
Teacher( ); int FCode;
void Ttake( );
void Tdisplay();
protected:
~Teacher( ); char FName[20];
}; public:
class HM:public Teacher Faculty();
{ char hmname[25]; void Enter();
float hmsalary; void Show();
int hmrno(); };
protected: class Programme
char hmplace[35]; {
int noofsubjects; int PID;
void hmprocess( );
public:
protected:
HM( ); char Title[30];
void hmtake( ); public:
void hmdisplay()( ); Programme();
~HM(); void Commence();
}; void View();
a) Which type of inheritance is depicted by above example? };
A)Multi level inheritance class Schedule: public Programme, Faculty
b) How many bytes will be required by an object of class {
Student, Teacher, HM? int DD,MM,YYYY;
A) Student Object – 30,
Teacher Object –30 + 46 = 76,
public:
HM object - 30 + 46 + 66 = 142 Schedule();
c) Write the names of all members accessible from objects void Start();
of class HM. void View();
A) Data Members: NIL };
Member Functions: hmtake( ),hmdisplay( ), void main()
Ttake(),Tdisplay( ),sTake( ),sdisplay( ) {
d) Write the names of data members accessible from Schedule S; //Statement 1
member functions of class HM.
A) Data Members: hmname, hmsalary, hmplace,
___________ //Statement 2
noofsubjects, Tqua, admno; }
e) Write the names of member functions accessible from (i)Write the names of all the member functions, which
member functions of class HM. are directly accessible by the object S of class
Member Functions: hmtake( ),hmdisplay( ),hmprocess(), Schedule as declared in main() function.
hmrno( ), Ttake( ),Tdisplay( ),Tprocess( ),Stake( ),

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 51 PRAISE THE LORD


Ans: Start(), Schedule::View(), Commence(), iii) Write the names of all the members, which are
Programme::View() directly accessible by the object S of class Schedule
(ii) Write the names of all the members, which are declared in the main( )function.
directly accessible by the memberfunction Start( ) of A) Data Members: Nil
class Schedule. Member Functions: Start( ), View( ), Initiate( ),
Ans:DD,MM,YYYY, Schedule::View() Display( );
Title, Commence( ), Programme::View() iv) What will be the order of execution of the
Fname, Enter(), Show() constructors, when the object S of class Schedule is
(iii) Write Statement 2 to call function View( ) of class declared inside the main( ) function ?
Programme from the object S of class Schedule. A) Course( ), Teacher( ), Schedule( )
Ans: S.Programme::View( );
3)Answer the questions (i) to (iv) based on the
(iv) What will be the order of execution of the
following: (2017)
constructors, when the object S of class Schedule is
class First
declared inside main()?
{
Ans: Programme( ), Faculty( ), Schedule( )
int X1;
2) Answer the questions (i) to (iv) based on the protected:
following: (2018) float X2;
class Teacher public:
{ int TCode; First();
protected: void Enter1(); void Display1();
char Name[20]; };
public: class Second : private First
Teacher( ); {
void Enter( ); int Y1;
void show( ); protected:
}; float Y2;
class Course public:
{ Second();
int ID; void Enter2();
protected: void Display();
char Title[30]; };
public: class Third : public Second
Course( ); {
void Initiate( ); int Z1;
void Display( ); public:
}; Third();
class Schedule: public Course, private Teacher void Enter3();
{ int DD,MM,YYYY; void Display();
public: };
Schedule( ); void main()
void Start( ); {
void View( ); Third T; //Statement 1
}; __________________;//Statement 2
void main( ) }
{ Schedule S; i) Which type of Inheritance out of the following is
} illustrated in the above example?
(i) Which type of Inheritance out of the following is Single Level Inheritance, Multilevel Inheritance,
illustrated in the above Example? Multiple Inheritance
Single Level Inheritance, Multilevel Inheritance, A) Multilevel Inheritance
Multiple Inheritance. ii) Write the names of all the member functions, which
A) Multiple Inheritance are directly accessible by theobject T of class Third as
ii) Write the names of all the members, which are declared in main() function.
directly accessible by the member function View( ) of A) Enter2( ), Display( ) of class Second
class Schedule. Enter3(), Display() of class Third
A) Data members: DD,MM,YYYY,Title,Name OR
Member functions: Start( ), Initiate( ), Display( ), Enter2( )
Enter( ), Show( ); Second::Display()
Enter3()
Display() OR Third::Display()
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 52 PRAISE THE LORD
iii) Write Statement 2 to call function Display() of 5) Answer the questions (i) to (iv) based on the
class Second from the object T of following:
class Third. class ITEM (2016)
A) T.Second::Display(); {
int Id;
iv) What will be the order of execution of the
char IName[20];
constructors, when the object T of class protected:
Third is declared inside main()? float Qty;
A) First, Second, Third public:
4) Answer the questions (i) to (iv) based on the ITEM();
following: void Enter(); void View();
class indoor_sports (2017 MP) };
{ class TRADER
int i_id; {
char i_name[20]; int DCode;
char i_coach[20]; protected:
protected: char Manager[20];
int i_rank,i_fee; public:
void get_ifee(); TRADER();
public: void Enter();
indoor_sports(); void View();
void iEntry(); };
void ishow(); class SALEPOINT : public ITEM,private TRADER
}; {
class outdoor_sports char Name[20],Location[20];
{ public :
int o_id; SALEPOINT();
char o_name[20]; void EnterAll();
char o_coach[20]; void ViewAll();
protected: };
int orank,ofee; (i) Which type of Inheritance out of the following is
void get_ofee(); illustrated in the above example?
public: ‐ Single Level Inheritance
outdoor_sports(); ‐ Multi Level Inheritance
void oEntry(); ‐ Multiple Inheritance
void oshow(); Ans Multiple Inheritance
}; (ii) Write the names of all the data members, which are
class sports:public indoor_sports,protected outdoor_sports directly accessible from the
{ member functions of class SALEPOINT.
char rules[20]; Ans Name, Location, Manager, Qty
public: (iii) Write the names of all the member functions, which are
sports(); directly accessible by an
void registration(); object of class SALEPOINT.
void showdata(); Ans EnterAll(), ViewAll(), Enter(), View()
}; (iv) What will be the order of execution of the constructors,
(i) Name the type of inheritance illustrated in the above when an object of class
C++ code. SALEPOINT is declared?
Ans. Multiple Inheritance Ans (i) ITEM()(ii) TRADER()(iii) SALEPOINT()
(ii) Write the names of all the members, which are 6)Answer the questions (i) to (iv) based on the following:
accessible from the objects belonging to class class Interior 2015
outdoor_sports. {
Ans Data Members: None int OrderId;
Member Functions: oEntry(), oShow() char Address[20];
(Note:No marks to be awarded for any partial or additional protected:
answer(s) ) float Advance;
(iii) Write the names of all the member functions, which are public:
accessible from the member function of class sports. Interior();
Ans registration(), showdata(), oEntry(), oShow(), void Book(); void View();
get_ofee(), iEntry(), };
iShow(), get_ifee() class Painting:public Interior
(iv) What will be the size of the object belonging to class {
indoor_sports? int WallArea,ColorCode;
Ans 46 Bytes protected:
char Type;
public:
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 53 PRAISE THE LORD
Painting(); A)Member functions: void Enroll( ); void View( ); void
void PBook(); Enter( );void Show( );
void PView(); (iii) Write the anem of those data members , which can be
}; directly accessible from the member functions of class
class Billing:public Painting student.
{ A)Data Members: long Rollno;char Name[20];double
float Charges; Budget;
void Calculate(); (iv) Is it possible to directly call function Display ( ) of
public: class university from an object of class Department?
Billing(); (Answer as YES or NO).
void Bill(); A) No, it is not possible because Display( ) function of
void BillPrint(); Campus becomes private for the object of Department class.
};
(i) Which type of Inheritance out of the following is 8) Consider the following C++ code and answer the
illustrated in the above example? questions from (i) to (iv). (2013)
‐Single Level Inheritance class Personal
‐Multi Level Inheritance {
‐Multiple Inheritance int Class, Rno;
Ans Multi Level Inheritance char Section;
(ii) Write the names of all the data members, which are protected:
directly accessible from the member functions of class char Name[20];
public:
Painting.
Ans WallArea, ColorCode,Type, Advance Personal( );
(iii) Write the names of all the member functions, which void pentry( );
void Pdisplay( );
are directly accessible from an object of class Billing.
Ans Bill(), BillPrint(), PBook(), PView(), Book(), View() };
class Marks: private Personal
● Constructors can be ignored
(iv) What will be the order of execution of the constructors, {
when an object of class Billing is declared? float M[5];
Ans Interior, Painting, Billing protected:
char Grade[5];
7) Consider the following C++ code and answer the public:
question from (i) to (iv). (2014) Marks( );
class University void Mentery( );
{ long Id; void Mdisplay( );
char City[20]; };
protected: class Result:public Marks
char Country[20]; {
public: float Total,Avg;
Universitye( ); public:
void Register( ); char FinalGrade,comments[20];
void Display( ); Result( );
}; void Rcalculate( );
class Department: private University void Rdisplay( );
{ };
long DCode[10]; (i) Which type of inheritance is shown in the above
char HOD[20]; example.
double Budget; A) Multilevel Inheritance
public: (ii) Write the names of those data members, which can be
Department( ); directly accessed from the objects of class Result.
void Enter( ); A)FinalGrame, comments
void Show( ); (iii)Write the names of those member functions which can
}; be directly accessed from the objects of class Result.
class Student:public Department A)Rcalculate( );Rdisplay( ),Mentry( ),Mdisplay( );
{ long RollNo; (iv) Write names of those data members, which can be
char Name[20]; directly accessed from the Mentry( ) function of class
public: Marks.
Student( ); A) Name[20], M[5], Grade[5];
void Enroll( );
9) Answer the questions (i) to (iv) based on the
void View( );
following:
};
class COMPANY (2012)
(i) Which type of inheritance is shown in the above
{
example?
char Location[20] ;
A) Multi-level inheritance is shown in the above example.
double Budget, Income ;
(ii) Write the names of those member functions, which are
protected:
directly accessed from the objects of class Student;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 54 PRAISE THE LORD
void Accounts () ; };
public: class Course: public Student, private Teacher
COMPANY () ; }
void Register(); long CCode [10]; char CourseName [50];
void Show() ; char StartDate [8] , EndDate [8];
}; public:
class FACTORY:public COMPANY Course ( ) ;
{ void Commence ( );
char Location[20] ; void CDetail ( ) ;
int Workers; };
protected: (i) Write the names of member functions, which are
double Salary ; accessible from objects ofclass Course
void Computer() ; Ans Commence( ), CDetail( ), Enroll( ),Display( )
public: Note: No marks to be awarded for a partially correct
FACTORY () ; answer Constructor functions to be ignored
void Enter () ; ii) Write the names of all the data members, which is/are
void Show() ; accessible from memberfunction Commence of class
}; Course
class SHOP:private COMPANY Ans CCode, CourseName, StartDate, EndDate, Salary
{ iii) Write the names of all the-members, which are
char Location[20] ; accessible from objects ofclass Teacher.
float Area; Ans Enter( ), Show( )
double Sale; iv) Which type of Inheritance is illustrated in the above
public: C++ code?
SHOP () ;void Input( ) ;void Output ( ) ; Ans Multiple Inheritance
}; 11) Answer the questions (i) to (iv) based on the
(i) Name the type of inheritance illustrated in the above following: (2010 D)
C++ code. class Chairperson
Ans Hierarchical Inheritance { long CID; //Chairperson Identification Number
(ii) Write the name of data members, which are accessible char CName[20];
from memberfunctions of class SHOP. protected:
Ans Location, Area, Sale char Description [40];
(iii) Write the names of all the member functions, which are void Allocate();
accessible fromobjects belonging to class FACTORY. public:
Ans Enter ( ), FACTORY::Show ( ), Register ( ), Chairperson();
COMPANY::Show ( ) void Assign();
OR void Show();
Enter ( ), Show ( ), Register ( ) // Show function may be };
present twice class Director
(iv) Write the names of all the members, which are { int DID; //Director ID
accessible from objects of class SHOP char Dname[20];
Ans Input ( ), Output ( ) protected:
10)Answer the questions (i) to (iv) based on the char Profile[30];
following: public:
class Student ( 2011) Director();
{ void Input();
int Rollno: void output();
char SName[20]; };
float Marksl; class Company:private Chairperson, publicDirector
protected: { int CID; //Company ID
void Result ( ) ; char City[20], Country[20];
public: public:
Student ( ) ; Company();
void Enroll ( ) ;void Display ( ) ; void Enter();
}; void Display();
class Teacher };
{ (i) Which type of inheritance out of the following is
long TCode; specifically is illustrated in
char TName [20]; the above C++ code?
protected: (a) Single Level Inheritance
float Salary; (b) Multi Level Inheritance
public: (c) Multiple Inheritance
Teacher ( ); Ans. (c) Multiple Inheritance
void Enter ( ) ; (ii) Write the names of data members, which are accessible
void Show ( ) ; by objects of class type Company.
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 55 PRAISE THE LORD
Ans None class Distance
(iii) Write the names of all member functions, which are { char StudyCentreCode [5] ;
accessible by objects of class type Company. public:
Ans. Enter(), Display(), Input(), output() void InDistance( );
(iv) Write the names of all members, which are accessible void OutDistance( );
from member functions of class Director. };
Ans. Input(), output(), Profile, Dname, DID class Course: public Regular, private Distance
12) Answer the questions (i) to (iv) based on the { char Code [ 5] ;
following: (2010 OD) float Fees;
class Director int Duration;
{ long DID; //Director Identification Number public:
char Name[20]; void InCourse( );
protected: void OutCourse( );
char Description[40]; };
void Allocate () ; (i) Which type of Inheritance is shown in the above
public: example?
Director() ; Ans Multiple Inheritance
void Assign () ; (ii) Write names of all the member functions accessible
void Show () ; from OutCourse function of class Course.
}; Ans InCourse( ), InDistance( ), OutDistance( ),
class Factory:public Director InRegular( ), OutRegular( )
{ int FID; //Factory ID (iii) Write name of all the .:members accessible througb an
char Address[20]; object of class Course.
protected: Ans InCourse( ), OutCourse( ), InRegular( ),
int NOE; //No. of Employees OutRegular( )
public: (iv) Is the function InRegular( ) accessible inside the
Factory(); function InDistance( )? Justify your answer.
void Input (); Ans. No, function InRegular( ) is not accessible inside the
void Output (); function InDistance( ), because InRegular( ) is a member of
}; class Regular and InDistance( ) is a member of class
class ShowRoom:private Factory Distance, and the classes Regular and Distance are two
{ int SID; //Showroom ID independent classes.
char City[20]; 14) Answer the questions (i) to(iv) based on the
public: following code : (2008 OD)
ShowRoom(); class Toys
void Enter (); { char Tcode[5];
void Display (); protected:
}; float Price;
(i) Which type of inheritance out of the following is void Assign(float);
illustrated in the above C++ public:
code? Toys();
(a) Single Level Inheritance void Tentry();
(b) Multi Level Inheritance void Tdisplay();
(c) Multiple Inheritance };
Ans. (b) Multilevel Inheritance class SoftToys:public Toys
(ii) Write the names of data members, which are accessible { char STName[20];
by objects of class float Weight;
type ShowRoom. public:
Ans. None SoftToys();
(iii) Write the names of all member functions which are void STentry();
accessible by objects of class type ShowRoom. void STDisplay();
Ans. Enter(), Display() };
(iv) Write the names of all members, which are accessible class ElectronicToys:public Toys
from member functions of class Factory. { char ETName[20];
Ans. FID, Address, NOE, Description, int No_of_Batteries;
Input(), Output(), Assign(), Show(), Allocate() public:
ElecronicToys();
13) Answer the questions (i) to (iv)based on the void ETEntry();
following: (2009 OD) void ETDisplay();
class Regular };
{ char SchoolCode[10]; (i)Which type of Inheritance is shown in the above
public: example?
void InRegular( ); Ans: Hierarchical Inheritance.
void OutRegular( ); Since the sub classes are derived from a single base class(Dolls).
};

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 56 PRAISE THE LORD


(ii)How many bytes will be required by an object of the Member Funcions:Teacher::AssignSal( )
class SoftToys ? Teacher::TEntry( )
Ans: 33 Bytes Teacher::TDisplay( )
(Explonation: The memory will be reserved as follows: Student::Sentry( )
char Tcode[5]; //5 Bytes Student::SDisplay( )
float Price; //4 Bytes School::SChEntry( )
char STName[20]; //20 Bytes School::SChDisplay( )
float Weight; // 4 Bytes Total = 33 (iv) If class School was derived privately from class
Bytes) Learner and privately from class Trainer, then name the
(iii)Write name of all data members accessible from member function(s)that could be accessed through Objects
member function of the class SoftToys. of class School.
Ans: Toys::Price, Ans: School::SChEntry( )
SoftToys::STName, School::SChDisplay( )
SoftToys::Weight 16)Answer the questions (i) to(iv) based on the following
(iv)Write name of member functions accessible an object of code: (2006 OD)
the class ElectronicToys ? class furniture
Ans: ElectronicToys::ETEntry( ), { char Type;
Electronic Toys::ETDisplay( ), char Mode[10];
Toys::TEntry( ), public:
Toys::TDisplay( ) furniture( );
15) Answer the questions (i) to(iv) based on the void Read_fur_details();
following code: (2007 OD) void Disp_fur_details();
class Teacher };
{ char TNo[5],Tname[20],Dept[10]; class sofa:public furniture
int Workload; { int no_of_seats;
protected : float cost_sofa;
float Salary; public:
void AssignSal(float); void Read_sofa_details();
public: void Disp_sofa_details();
Teacher(); };
void TEntry(); class office:public sofa
void TDisplay(); { int no_of_pieces;
}; char delivery_date[10];
class Student public:
{ char Admno[10],SName[20],Stream[10]; void Read_office_details();
protected: void Didp_office_details();
int Attendance,Totmarks; };
public: void main()
Student(); {
void SEntry(); office MyFurniture;
void SDisplay(); }
}; (i)Mention the member names which accessible by
class School:public Student,public Teacher Myfurniture declared in main() function.
{ char SCode[10],SName[20]; Ans:
public: Data Members: No data member can be called from
School( ); Myfurniture object.
void SchEntry(); Member Functions:
void SchDisplay(); Furniture::Read_fur_details()
}; Furniture::Disp_fur_details()
(i)Which type of inheritance is depicted by above example? Sofa::Read_sofa_details()
Ans: Multiplel Inheritance. Sofa::Disp_sofa_details()
(ii)Identify the member function(s) that cannot be called Office::Read_office_details()
directly from the objects of class School from the following Office::Didp_office_details()
TEntry() (ii)what is the size of Myfurniture in bytes?
SDisplay() Ans: 29 Bytes
SchEntry() (iii)Mention the names of functions accessible from the
Ans: All the above three member function(s) can be called member function Read_office_details() of class office.
from the objects of class School. Ans:
(iii)Write name of all member(s) accessible from member Furniture::Read_fur_details( )
functions of class School. Furniture::Disp_fur_details( )
Ans: Data Members : Teacher::Salary Sofa::Read_sofa_details( )
Student::Attendance Sofa::Disp_sofa_details( )
Student::Totmarks Office::Disp_office_details( )
School::SCode
School::SName

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 57 PRAISE THE LORD


17) Answer the questions (i) to(iv) based on the class ape: private livingbeing
following code: (2005 OD) { int no_of_organs,no_of_bones;
class Drug protected:
{ char Category[10]; int iq_level;
char Date_of_manufacture[10]; public:
char Company[20]; void readape();
public: void showape();
Medicines(); };
void enterdrugdetails(); class human:public ape
void showdrugdetails(); { char race[20];
}; char habitation[30];
class tablet:public Drug public:
{ protected: void readhuman();
char tablet_name[30]; };
char volume_lable[20]; (i)Name the members, which can be accessed from the
public: member functions of class human.
float Price; Ans: Data Members - ape::iq_level
Tablet(); human::race
void entertabletdetails(); human::habitation
void showtabletdetails(); Member Function – ape::readape( )
}; ape::showape( )
class PainReliever:public Tablet (ii)Name the members, which can be accessed by an object
{ int Dosage_units; of class human.
char side_effects[20]; Ans: Data Members - No data members can be accessed.
int Use_within_days; Member Functions: ape::readape();
public: ape::showape();
PainReliever(); human::readhuman();
void enterdetails(); (iii)What will be the size of an object of the (in bytes) of
void showdetails(); class human?
}; Ans: 78 Bytes.
(i)How many bytes will be required by an object of class 19)Consider the following and answer the questions
Drug and an object of class PainReliever respectively? given below. (2003 D)
Ans: Drug Object - 40 Bytes class MNC
Pain Reliever – 118 Bytes { char Cname[25]; //Company name
(ii)Write the names of all the member functions accessible protected:
from the object of class PainReliever. char Hoffice[25]; //Head office
Ans: Drug::enterdrugdetails() public:
Drug::void showdrugdetails() MNC( );
Tablet::entertabletdetails() char Country[25];
Tablet::showtabletdetails() void EnterData( );
PainReliever::enterdetails() void DisplayData( );
PainReliever::showdetails() };
(iii)Write the names of all the members accessible from class Branch:public MNC
member functions of class Tablet. { long NOE; //Number of Employees
Ans:Data Members: char Ctry[25]; //Country
Tablet::tablet_name[30]; protected:
Tablet::volume_lable[20]; void Association( );
Tablet::Price; public:
Member Functions: Branch( );
Drug::enterdrugdetails() void Add( );
Drug::showdrugdetails() void Show( );
Tablet::entertabletdetails() };
Tablet::showtabletdetails() class Outlet:public Branch
(iv)Write names of all the data members which are { char State[25];
accessible from objects of class PainReliever. public:
Ans:Data Members: Tablet::Price Outlet( );
18) Given the following definitions answer the following: void Enter( );
(2004 D) void Output( );
class livingbeing };
{ char specification[20]; Ans: i) Which class constructor can be called first at the
int average; time of declaration of an object of class Outlet?
public: Ans: MNCclass constructor can be called first at the time of
void read(); declaration of an object of class Outlet.
void show(); (When an object of the derived class is declared, in order to
}; create it, firstly the constructor of the base class is invoked
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 58 PRAISE THE LORD
an then, the constructor of the derived class is invoked. On { int diesel_petrol;
the other hand, when an object of the derived class is protected:
destroyed, first the destructor of the derived class is invoked int load:
followed by the destructor of the base class). public:
ii) How many bytes does an object belonging to class Outlet void readdata(int,int);
require? void writedata();
Ans: 133 Bytes };
iii) Name the member function(s) which are accessed from class bus:private heavy_vehicle
the object(s) of class Outlet. {
Ans: Outlet::Enter( ) char make[20];
Outlet::Output( ) public:
MNC::EnterData( ) void fetchdata(char);
MNC::DisplayData( ) void displaydata();
Branch::Add( ) };
Branch::Show( ) (i)Name the base class and derived class of the class
iv)Name the data member(s), which are accessible from the heavy_vehicle.
object(s) of class Branch. Ans: Base class of heavy_vehicle – vehicle
Ans: MNC::Country Derived class of heavy_vehincle – bus
(ii)Name the data member(s) that can be accessed from
20)Consider the following and answer the questions
function displaydata.
given below: (2000 D)
Ans: bus::make
class School
heavy_vehicle::load
{ int A;
vehicle::passenger
protected:
(iii)Name the data member(s) that can be accessed by an
int B,C;
object of bus class.
public:
Ans: No data member can be accessed by an object of bus
void INPUT(int);
class.
void OUTPUT();
(iv)Is the member function outputdata accessible to the
};
objects of heavy_vehicle class?
class Dept:protected School
Ans: No.
{ int X,Y;
protected: 22) Consider the following declarations and answer the
void IN(int,int) questions below: (1998 D)
public: class PPP
void OUT(); { int H;
}; protected:
class Teacher:public Dept int S;
{ int P; public:
void DISPLAY(void); void INPUT(int);
public: void OUT();
void ENTER(); };
}; class QQQ:private PPP
(i)Name the base class and derived class of the class Dept. { int T;
Ans: Base class of Dept - School protected:
Derived class of Dept - Teacher int U;
(ii)Name the data member(s) that can be accessed from public:
function OUT(). void INDATA(int,int);
Ans: Dept::X Dept::Y void OUTPUT();
School::B };
School::C class RRR:public QQQ
(iii)Name the private member function(s) of class Teacher. { int M;
Ans: Teacher::Display( ) public:
(iv)Is the member function OUT() accessible the objects of void DISP(void);
Dept? };
Ans: Yes. Since it is public member function. (i)Name the base class and derived class of the class QQQ.
Ans:Base class of QQQ – PPP
21)Consider the following declarations and answer the Derived class of QQQ – RRR
questions below: (1999 D) (ii)Name the data member(s) that can be accessed from
class vehicle function DISP().
{ int wheels; Ans: QQQ::U , RRR::M
protected: (iii)Name the member function(s) , which can be accessed
int passenger; from the object of class RRR.
void inputdata(int,int); Ans: QQQ::INDATA( ) QQQ::OUTPUT( )
void outputdata(); RRR::DISP( )
}; (iv) Is the member function OUT() accessible by the objects
class heavy_vehicle:protected vehicle of the class QQQ? Ans: No.
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 59 PRAISE THE LORD
29) Answer the questions (i) to (iv) based on the (i) Write the names of data members, which are accessible
following: (2008-09 MP2) from objects belong-ing
class CUSTOMER to class AUTHOR.
{ int Cust_no; Ans)None of data members are accessible from objects
char Cust_Name[20]; belonging to class AUTHOR.
protected: (ii) Write the names of all the member functions which are
void Register(); accessible from ob-jects
public: belonging to class BRANCH.
CUSTOMER(); Ans) Haveit( ), Giveit( )
void Status(); (iii) Write the names of all the members which are
}; accessible from member func-tionsof class AUTHOR.
class SALESMAN Ans) Data members: Employees, Acode, Aname,
{ int Salesman_no; Amount
char Salesman_Name[20]; Member function: Register(), Enter(), Display(), Haveit(),
protected: Giveit(), Start(), Show(),
float Salary; (iv) How many bytes will be required by an object
public: belonging to class AUTHOR?
SALESMAN(); Ans) 70
void Enter();
void Show(); MODEL 1B)
};
class SHOP : private CUSTOMER , public SALESMAN Consider the following class State : 2019SP4
{ char Voucher_No[10]; class State
char Sales_Date[8]; { protected :
public:
SHOP(); int tp;
void Sales_Entry(); public :
void Sales_Detail(); State( )
}; { tp=0;
i)Write the names of data members which are accessible
from objects belonging to class CUSTOMER. }
Ans: None of data members are accessible from objects void inctp( )
belonging to class CUSTOMER. { tp++;
ii)Write the names of all the member functions which are
accessible from objects belonging to class SALESMAN. }
Ans: Enter(), Show() int gettp( )
iii)Write the names of all the members which are accessible { return tp;
from member functions of class SHOP. }
Ans: Data members: Voucher_No, Sales_Date,
Salary };
Member functions:Sales_Entry( ), Sales_Details( ), Write a code in C++ to publically derive another
Enter (), Show( ),Register( ), Status( ). class ‗District‘ with the following additional
iv)How many bytes will be required by an object belonging
to class SHOP? members derived in the public visibility mode.
Answer: 66 Data Members :
23) Answer the questions (i) to (iv) based on the Dname string
following: (2008-09 MP1) (2009-10 MP1) Distance float
class PUBLISHER Population long int
{ char Pub[12]; Member functions :
double Turnover;
protected: DINPUT( ):To enter Dname, Distance and population
void Register(); DOUTPUT( ):To display the data members on the screen.
public: Answer:
PUBLISHER();
void Enter(); class District : public State
void Display(); { public :
}; char Dname[20];
class BRANCH float Distance;
{ char CITY[20];
protected: long int Population;
float Employees; void DINPUT( )
public: { gets(Dname);
BRANCH();
void Haveit(); cin>>distance;
void Giveit(); cin>>Population;
}; }
class AUTHOR : private BRANCH , public void DOUTPUT( )
PUBLISHER
{ int Acode; { cout<<Dname<<endl;
char Aname[20]; cout<<Distance<<endl;
float Amount; cout<<population<<endl;
public:
AUTHOR(); }
void Start(); };
void Show();
};
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 60 PRAISE THE LORD
MODEL 2 ------
}
1. Observe the following C++ code and answer the class B:public class A
questions (i) and (ii). Note: Assume all necessary { -----
files are included. (2018) -----
class FIRST }
{ int Num1; class C:protected B
public: { ----
-----
void Display( ) //Member Function 1
}
{ cout<<Num1<<endl; Multiple Inheritance: When a sub class inherits from
} multiple base classes, it is known as multiple inheritance.
}; Eg: (for Multiple
class SECOND:public FIRST Inheritance)
{ int Num2; class A
{ -----
public: ------
void Display( ) //Member Function 2 }
{ cout<<Num2<<endl; class B
{ -----
} -----
}; }
void main( ) class C:public A,protected B
{ ----
{ SECOND S; -----
_________________ //Statement 1 }
_________________ //Statement 2 3) Illustrate the concept of Inheritance with the help of
} an example. (2002 D)
(i) Which Object Oriented Programming feature is Ans: The capability of one class to inherit propertied from
illustrated by the definitions of classes FIRST and another class, is called as inheritance.
SECOND? The most important advantage of inheritance is code
A) Inheritance (OR Encapsulation OR Data reusability.
Abstraction OR Data Hiding) There are 5 types of inheritance:
(ii) Write Statement 1 and Statement 2 to execute (i) Single Inheritance): When a sub class inherits
only from one base class, it is known as single
Member Function 1 and Member Function 2
inheritance.
respectively using the object S. (ii) Multiple Inheritance: When a sub class
A) S.FIRST::Display( ); // Statement 1 inherits from multiple base classes, it is
S.SECOND::Display( ); Statement 2 known as multiple inheritance.
// or S.Display( ); (iii) Hierarchical Inheritance: When many sub
classes inherit from a single base class, it is
MODEL 3 – THEORY QUESTION known as hierarchical inheritance.
(iv) Multilevel Inheritance: When a subclass
inherits from a class that itself inherits from
1) Differentiate between Protected and Private another class, it is known as multilevel
members of a class in context of inheritance using C++. inheritance.
(2007 OD) (v) Hybrid Inheritance: Hybrid inheritance
Ans: Protected members will be inherited into the derived combines two or more forms of inheritance.
class (they are accessible from the derived class). But
Private members cannot be accessed from the derived class. 4) Reusability of classes is one of the major properties
(Remember that the memory will be reserved for private as of OOP. How is it implemented in C++. (2001)
well as protected members for the derived class object) Ans: Resuability of classes can be implemented through
Inheritance. Ie After developing a class, if you want a class
2) Define Multilevel and Multiple inheritance in context which consists the features of this class( ie members ) and
of Object Oriented Programming. Give suitable the other features also, then instead of developing a class
example to illustrate the same (2006 D) which consists all these features, you can inherited the
Ans: Multilevel Inheritance: When a subclass inherits existing features (members) and you can develop new class
from a class that itself inherits from another class, it is consists the remaining features using inheritance (in
known as multilevel inheritance. Object Oriented Programming ie in C++.)
5)What do you understand by visibility modes in class
derivations? What are these modes? (1999)

Eg: (for Multi Level Inheritance)


class A
{ -----
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 61 PRAISE THE LORD
7.DATA FILE HANDLING (6Marks) void main( )
{ fstream SFIN;
MODEL 1a: Output 1 Mark SFIN.open(“SCHOOLS.DAT”,ios::binary|ios::in);
1. Find the output of the following C++ code SCHOOLS S;
considering that the binary file PRODUCT.DAT SFIN.seekg(5*sizeof(S));
exists on the hard disk with a list of data of 500 SFIN.read((char*)&S, sizeof(S));
S.Display();
products. 2019SP1
cout<<”Record :”<<SFIN.tellg( )/sizeof(S)+1<<endl;
class PRODUCT SFIN.close();
{ }
int PCode;char PName[20]; Ans) 1004#Holy Education School#140
public:
Record :7
void Entry();void Disp();
}; 4. Find the output of the following C++ code
void main() considering that the binary fileCLIENTS.DAT
{ exists on the hard disk with a data of 200
fstream In; clients. (2017)
In.open("PRODUCT.DAT",ios::binary|ios::in); class CLIENTS
PRODUCT P; {
In.seekg(0,ios::end); int CCode;char CName[20];
cout<<"Total Count: "<<In.tellg()/sizeof(P)<<endl;
public:
In.seekg(70*sizeof(P));
In.read((char*)&P, sizeof(P)); void REGISTER();void DISPLAY();
In.read((char*)&P, sizeof(P)); };
cout<<"At Product:"<<In.tellg()/sizeof(P) + 1; void main()
In.close(); {
} fstream File;
Answer: Total Count:500 File.open("CLIENTS.DAT",ios::binary|ios::in);
At Product: 73 CLIENTS C;
2. Which file stream is required for seekg()? File.seekg(6*sizeof(C));
Answer: fstream/ ifstream 2019SP1 File.read((char*)&C, sizeof(C));
3. Find the output of the following C++ code: cout<<"Client Number:"<<File.tellg()/sizeof(C) +
Considering that the binary file SCHOOLS.DAT exists 1;
on the hard disk with the following records of 10 schools File.seekg(0,ios::end);
of the class SCHOOLS as declared in the following
class.
cout<<" of "<<File.tellg()/sizeof(C)<<endl;
class SCHOOLS 2018 (1) File.close();
{ int SCode; //School Code }
char SName[20]; //School Name Ans)Client Number 8 of 200
int NOT; //Number of Teachers in the school
5. Find the output of the following C++ code considering
public:
that the binary file sp.dat already exists on the hard disk
void Display( )
with 2 records in it. (2017MP)1
{ cout<<SCode<<”#”<<SName<<”#”<<NOT<<endl;
class sports
}
{
int RNOT( )
int id;
{ return NOT; }
char sname[20];
};
char coach[20];
public:
SCode SName NOT void entry();
1001 Brains School 100 void show();
1003 Child Life School 115 void writing();
1002 Care Share School 300 void reading();
}s;
1006 Educate for Life School 50 void sports::reading()
1005 Guru Shishya Sadan 195 {
1004 Holy Education School 140 ifstream i;
1010 Play School 95 i.open("sp.dat");
while(1)
1008 Innovate Excel School 300
{
1011 Premier Education School 200 i.read((char*)&s,sizeof(s));
1012 Uplifted Minds School 100 if(i.eof())
break;

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 62 PRAISE THE LORD


else Ans)1 (Since, the file is opened in out mode, it looses all the
cout<<"\n"<<i.tellg(); previous content, if the file mode is app, then result will be 4)
} 9) (2006 OD)
i.close(); void main( )
} { char ch = „A‟ ;
void main() fstream fileout(“data.dat”, ios :: app);
{ s.reading(); fileout<<ch ;
} int p = fileout.tellg( ) ;
Ans) 42 cout << p ;
84 }
6. Find the output of the following C++ code considering What is the output if the file content before the execution of
that the binary file CLIENT.DAT exists on the hard the program is the string “ABC” ?
disk with a data of 1000 clients. (2016)1 (Note that “ “ are not part of the file)
class CLIENT Ans) 4
{ int Ccode;char CName[20]; (Since, the file is opened in app mode, it retains the
public: previous content also, if the file mode is out, then result will
void Register();void Display(); be 0 since it will loose all the old content of the file.)
};
void main() MODEL 1b):FILL IN THE BLANKS (1 Mark)
{ fstream CFile; 1.Fill in the blanks marked as the Statement 1 and the
CFile.open(“CLIENT.DAT”,ios::binary|ios::in); Statement 2, in the program segment given below the
CLIENT C; appropriate functions for the required task. (2014) 1
CFile.read((char*)&C, sizeof(C)); class Agency
cout<<”Rec:”<<CFile.tellg()/sizeof(C)<<endl; { int ANo;
CFile.read((char*)&C, sizeof(C)); char Name[20]; //Agent Code
CFile.read((char*)&C, sizeof(C)); chart Mobile[12]; //Agent Mobile
cout<<”Rec:”<<CFile.tellg()/sizeof(C)<<endl; public:
CFile.close(); void Enter( ) //Function to enter details of agent
} void Disp( ); //Function to display details of agent
Ans) Rec:1 int RANo( )
Rec:3 {return ANo;
7. Find the output of the following C++ code considering }
that thebinary file MEMBER.DAT exists on the hard void UpdateMobile( )//Function to change Mobile
disk with records of 100 members: (2015) 1 { cout<<”Update Mobile: “;
class MEMBER gets(Mobile);
{int Mno; char Name[20]; }
public: };
void In();void Out(); void AgentUpdate( )
}; { fstream F;
void main() F.open(“AGENT.DAT”,ios::binary|ios::in|ios::out);
{ int Updt=0;
fstream MF; int UAno;
MF.open("MEMBER.DAT”,ios::binary|ios::in); cout<<”Ano (Agent No – To update Mobile): “;
MEMBER M; cin>>UAno;
MF.read((char*)&M,sizeof(M)); Agency A;
MF.read((char*)&M,sizeof(M)); while(!Updt && F.read((char *)&A,sizeof(A)))
MF.read((char*)&M,sizeof(M)); {if(A.RAon( )= =UAno)
int POSITION=MF.tellg()/sizeof(M); {
cout<<"PRESENT RECORD:"<<POSITION<<endl; //Statement 1: To call the function to update Mobile No.
MF.close(); _______________________________
} //Statement 2: To reposition file pointer to re-write the
Ans) PRESENT RECORD: 3 //updated object back in the file
________________________________________
8) (2006 D) F.write((char *)&A,sizeof(A));
void main( ) Updt++;
{ char ch = „A‟ ; }
fstream fileout(“data.dat”, ios::out) ; }
fileout<<ch ; if(Updt)
int p = fileout.tellg( ) cout<<”Mobile Update for Agent”<<UAno<<endl;
cout<<p ; else
} cout<<”Agent not in the Agency”<<endl;
What is the output if the file content before the execution of F.close( );
the program isthe string “ABC”(Note that ― ― are not }
part of the file).
Answer)
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 63 PRAISE THE LORD
Statement 1:A.UpdateMobile( ); }
Statement 2: F.seekg(-1*sizeof(A),ios::cur); };
void PurchaseItem(int Pino,int PQty)
2.Fill in the blanks marked as Statement 1 and
{ fstream File;
Statement 2, in the program segment given below with
File.open("STOCK.DAT", ios::binary|ios: :in|ios: :out);
appropriate functions for the required task. (2013)1
Stock S;
class Club
int Success=O;
{long int MNo;//Member Number
while (Success==O && File.read((char*)&S,sizeof(S)))
char MName[20];//Member Name
{
char Email[30];//Email of Member
if (Pino==S. GetIno())
public:
{ S.PurchaSe(PQ) ;
void Register( );//Function to register member
_________________ // Statement 1
void Disp( );//Function to display details
_________________ // Statement 2
void ChangeEmail( ) //Function to change Email
Success++;
{ cout<<”Enter Changed Email: “;
}
cin>>Email;
}
}
}
long int GetMno( )
if (Success=l)
{ return MNo;
cout<<"Purchase Updated"<<endl;
}
else
};
cout<<''Wronq Item No"<<endl;
void ModifyData( )
File.close() ;
{ fstream File;
}
File.open(“CLUB.DAT”, ios::binary | ios::in|ios::out);
(i) Write statement 1 to position the file pointer to the
int Modify=0, Position;
appropriate place so that the data ucdation is done for the
long int ModiMno;
reauired item.
cout<<”Mno – Whose email required to be modified: “;
Ans File.seekp(File.tellg() - sizeof(Stock));
cin>>ModiMno;
OR File. seekp (-sizeof (Stock) ,ios::cur));
Club CL;
(ii) Write statement 2 to perform the write operation so that
while(!Modify && File.read((char *)&CL.sizeof(CL)))
the updation is done in the binary file.
{ if(CL.GetMno( )==ModiMno)
Ans File.write((char*)&S,sizeof(S));
{ CL.ChangeEmail( );
OR File.write((char*)&S,sizeof(Stock));
Position=File.tellg( )-sizeof(CL);
//Statement 1: To place file pointer to the required position 4.Observe the program segment given below carefully
______________________________ and fill the blanks marked as Statement 1 and
//Statement:To write the object CL on to the binary file Statement 2 using seekg( ), seekp( ) tellp( ) and tellg( )
______________________________ functions for performing the required task.
Modify++; (2011 OD)1
} #include <fstream.h>
} class ITEM
if(Modify) {int Ino;char Iname[20]; float Price;
cout<<”Email changed…..”<<endl; public:
else void ModifyPrice() ;//The function is to modify
cout<<”Member not found….”<<endl; price of a particular ITEM
File.close( ); };
} void item: :ModiyPrice()
Ans) {fstream File;
Statement 1: File.seekp(Position); File.open ("ITEM.DAT", ios::binary | ios::in | ios: :out) || ;
Statement 2: File.write((char *)&CL,sizeof(CL)); int CIno;
cout<<"Item No to modify price:";cin>>CIno;
3) Observe the program segment given below carefully while (file.read ((char*) this, sizeof (ITEM)))
and the questions that follow:(2012) 1 { if (CIno==Ino)
class Stock { cout<<"Present Price:"<<Price<<end1;
{ int Ino, Qty ; char Item [20]; cout<<"Changed price:"; cin>>Price;
public: int FilePos = __________ ; //Statement 1,
void Enter() ___________________; //Statement 2
{cin>>Ino;qets(Item) ; cin>>Qty; File.write((char*)this,sizeof(ITEM)) ;// Re-writing
} the record
void issue(int Q) }
{Qty+=O; }
} File.close( ) ;
void Purchase(int Q) }
{Q-=Q; Ans Option 1
} Statement 1: File.tellp ( ) ; OR File. tellg ( ) ;
int GetIno () Statement 2: File.seekp (FilePos - sizeof (ITEM) ) ;
{return Ino; OR File.seekp (-sizeof (ITEM), ios: :cur));
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 64 PRAISE THE LORD
OR File.seekg(FilePos - sizeof (ITEM)); }
OR. File.seekg(-sizeof (ITEM), ios: :cur)); };
Option 2 void BuyBook(long BANo,int BQty)
Statement 1: File. tellp ( ) – sizeof (ITEM) ; //BANo ->Ano of the book purchased
OR File.tellg()- sizeof (ITEM) ; //BQty ->Number of books purchased
Statement 2: File.seekp (FilePos) ; { fstream File;
OR File.seekg (FilePos) ; File.open(“STOCK.DAT” , ios::binary|ios::in|ios::out);
5) Observe the program segment given below carefully int position=-l;
and fill the blanks marked as Statement 1 and Library L;
Statement 2 using tellg() and seekp() functions for while(Position==-l &&
performing the required task. (2010 OD)1 File.read((char*)&L,sizeof(L)))
#include <fstream.h> if (L.GetAno()==BANo)
class Customer {L.Buy(BQty); //To update the number of Books
{ long Cno; Position = File.tellg()-sizeof(L) ;
char Name[20],Mobile[12]; ____________________;
public: //Line 1: To place the file pointer to the required position
void Enter( );//Function to allow user to enter the Cno, ____________________;
Name,Mobile //Line 2:To write the object L on to the binary file
void Modify( ); //Function to allow user to enter modify mobile }
number if (Position==-l)
long GetCno( ) //Function to return value of Cno cout<< “No updation do:r{e as
{ return Cno; required Ano not found..”;
} File.close( );
}; }
void ChangeMobile( ) Ans)Statement 1:File.seekp(Position);
{Customer C; OR File. seekp (-sizeof (L), ios::cur);
fstream F; Statement 2: File.write((char*)&L, sizeof(L));
F.open(“CONTACT.DAT”,ios::binary| OR File.write((char*)&L,sizeof(Library));
ios::in|ios::out);
7)Observe the program segment given below carefully,
long Cnoc; //Customer no. whose mobile numberneeds to be
changed
and answer the question that follows (2008 OD)
cin>>Cnoc; class candidate
while (F.read((char*)&C,sizeof(C))) { long Cid ; // Candidate‟s Id
{ if (Choc==C.GetCno( )) char CName[20]; // Candidate‟s Name
{ C.Modify( ); float Marks ; // Candidate‟s Marks
int Pos=_____________ //Statement 1 public ;
//To find the current position of file pointer void Enter( ) ;
______________ //Statement 2 void Display( ) ;
//To move the file pointer to write the modified record back void MarksChange( ) ;
onto //the file for the desired Cnoc //Function to change marks
F.write((char*)&C, sizeof(C)); long R_Cid( )
} { return Cid;
} }
F. close ( ); };
} void MarksUpdate (long Id)
Ans) { fstream File ;
Statement 1: F.tellg( ) ; File.open (“CANDIDATE.DAT”, ios ::
Statement 2 : F.seekp(Pos-sizeof(C)); binary|ios::in|ios :: out) ;
OR File.seekp(-l*sizeof(C),ios::cur); Candidate C ;
int Record = 0, Found = 0 ;
6) Observe the program segment given below carefully while (!Found&&File.read((char*)&C, sizeof(C)))
and fill the blanks marked as Line 1 and Line 2 using {
fstream functions for performing the required task. if (Id = =C.R_Cid( ))
(2009 OD) { cout << “Enter new Marks” ;
#include <fstream.h> C.MarksChange( ) ;
class Library ____________ //Statement1
{ long Ano; //Ano - Accession Number of the Book ___________ //Statement 2
char Title[20]; //Title - Title of the Book Found = 1 ;
int Qty; //Qty - Number of Books in Library }
public: Record++ ;
void Enter (int); //Function to enter the content }
void Display(); //Function to display the content if (Found = = 1)
void Buy(int Tqty) //Function to increment in Qty cout << “ Record Updated” ;
{ Qty+=Tqty; File.close( ) ;
long GetAno( ) }
{ return Ano;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 65 PRAISE THE LORD
Write the Statement to position the File Pointer at the { int Member_no ;
beginning of the Record for which the Candidate‟s Id char Member_name[20] ;
matches with the argument passed, and Statement 2 to write public :
the updated Record at that position. void enterdetails ( );//function to enter Member details
Ans) void showdetails ( );/ /function to display Member details
Statement 1:File.seekp(File.tellp( )-sizeof(C)); int RMember_no( )
OR File.seekp(Record*sizeof(C)); { return Member_no;
Statement 2: File.write((char*)&C,sizeof(C)); } //function to return Member_no
OR File.write((char*)&C,sizeof(Candidate)); };
void Update (Member NEW)
8) Observe the program segment given below
{ fstream File ;
carefully,and answer the question that follows:(2007OD) File.open(“MEMBER.DAT” , ios ::binary |ios :: in | ios :: out) ;
class Labrecord Member OM ;
{ int Expno; int Recordsread = 0, Found = 0 ;
char Experiment[20] ; while (!Found && File.read((char*) &OM, sizeof(OM)))
char Checked ; { Recordsread++ ;
int Marks ; if (NEW.RMember_no( ) == OM.RMember_no( ))
public : { ___________ //Missing Statement
void EnterExp( ) ; File.write((char*) & NEW ,
//function to enter Experiment details sizeof(NEW) ;
viod ShowExp( ) ; Found = 1 ;
//function to display Experiment details }
char RChecked( ) else
//function to return Expno File.write((char*) & OM,
{ return Checked; sizeof(OM)) ;
} }
void Assignmarks (int M) if (!Found)
//function to assign Marks cout<<”Record for modification does not exist” ;
{ Marks = M; File.close( ) ;
} }
}; If the function Update( ) is supposed to modify a record in
void ModifyMarks( ) file MEMBER.DAT with the values of Member NEW
{ fstream File ; passed to its argument, write the appropriate statement for
File.open (“Marks.Dat”, ios :: binary l Missing statement using seekp( ) or seekg( ), whichever
ios :: in l ios :: out) ; needed, in the above code that would write the modified
Labrecord L ; record at its proper place.
int Rec=0 ; Ans)File.seekp((Recordsread-1)*sizeof(OM));
while (File.read ( (char*) &L,sizeof (L))) OR File.seekp(Recordsread*sizeof(OM));
{ if (L.RChecked( )= =‟N‟) OR File.seekp(-l*sizeof(OM),ios::curr);
L.Assignmarks(0) OR File.seekp(file.tellg()-sizeof(OM));
else
L.Assignmarks (10) 10) Observe the program segment given below carefully
_______________; //Statement 1 and fill the blanks marked as Statement 1 and
________________;//Statement 2 Statement2 using seekp( ) and seekg( ) functions for
performing the required task. (MP109-10)
Rec++ ; #include <fstream.h>
} class Item
File.close( ) ; { int Ino;
} char Item[20];
If the function ModifyMarks ( ) is supposed to modify public:
marks for the records in the file MARKS.DAT based on void Search(int );//Function to search and display the
their status of the member Checked (containg value either //content from a particular record number
„Y‟ or „N‟).Write C++ statements for the statement 1 and void Modify(int); //Function to modify the content of a
statement 2,where, statement 1 is required to position the //particular record number
file write pointer to an appropriate place in the file and };
statement 2 is to perform the write operation with the void Item::Search(int RecNo)
modified record. {fstream File;
Ans) File.open("STOCK.DAT",ios::binary|ios::in);
Statement 1: File.seekp(File.tellp( )-sizeof(L)); ________________ //Statement 1
OR File.seekp(Rec*sizeof(L)); File.read((char*)this,sizeof(Item));
Statement 2: File.write((char*)&L,sizeof(L)); cout<<Ino<<"==>"<<Item<<endl;
OR File.write((char*)&L,sizeof(Labrecord)); File.close( );
}
9) Observe the program segment given below carefully void Item::Modify(int RecNo)
and answer the question that follows : (2005 OD) {fstream File;
class Member File.open("STOCK.DAT",ios::binary|ios
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 66 PRAISE THE LORD
::in|ios::out); MODEL 2: Function using files (without objects) (2M)
cout>>Ino;cin.getline(Item,20);
________________ //Statement 2 CHARACTERWISE OPERATIONS
File.write((char*)this,sizeof(Item)); 1) Write a function in C++ to count the number of
File.close( ); alphabets present in a text file "NOTES.TXT".
} Ans) (MP209-10) (MP208-09)
Ans) void CountAlphabet()
Statement 1: File.seekg(RecNo*sizeof(Item)); {
Statement 2 :File.seekp(RecNo*sizeof(Item)); ifstream FIL("NOTES.TXT");
11) Observe the program segment given below carefully int CALPHA=0;
and fill the blanks marked as Statement 1 and char CH=FIL.get();
Statement 2 using seekg() and tellg() functions for while (!FIL.eof())
performing the required task. (MP209-10) { if (isalpha(CH))
#include <fstream.h> CALPHA++;
class Employee CH=FIL.get( );
{ int Eno;char Ename[20]; }
public: cout<<"No. of Alphabets:"<< CALPHA<<endl;
int Countrec( ); //Function to count the total number of records }
}; 2.Write a function in C++ to count the number
int Item::Countrec( ) of lowercase alphabets present in a text file
{fstream File; ―BOOK.txt". 2019SP2
File.open("EMP.DAT",ios::binary|ios::in);
__________________ //Statement 1 int Countalpha()
int Bytes =_______ //Statement 2 { ifstream fin ("BOOK.txt");
int Count = Bytes/sizeof(Item); char ch;
File.close( ); int count =0;
return Count;
while (!fin.eof())
} Ans) Statement 1:File.seekg(0,ios::end);
Statement 2: File.tellg( ); { fin.get(ch);
12) Observe the program segment given below if(islower(ch))
carefully and fill the blanks marked as Statement 1 and count ++;
Statement 2 using seekp() and seekg() functions for }
performing the required task. (MP108-09) fin.close();
#include <fstream.h> return (count)
class Item
{ int Ino;char Item[20];
}
public: 3)Write a function in C++ to count the number of
void Search(int ); uppercase alphabets present in a text file
//Function to search and display the content ―ARTICLE.TXT‖. (2008 OD)
//from a particular record number Solution:
void Modify(int);//Function to modify the content of a void UpperLetters( )
//particular record number { clrscr( );
ifstream fin("ARTICLE.TXT",ios::in);
};
char ch;
void Item::Search(int RecNo)
{ int uppercount=0;
fstream File; while(fin)
File.open(“STOCK.DAT”,ios::binary|ios::in); { fin.get(ch);
_______________ //Statement 1 if(isupper(ch))
File.read((char*)this,sizeof(Item)); uppercount++;
cout<<Ino<<”==>”<<Item<<endl; }
cout<<"\nTotal number of Uppercase
File.close( );
} alphabets in the file = "<<uppercount;
void Item::Modify(int RecNo) getch( );
{fstream File; }
File.open(“STOCK.DAT”,ios::binary|ios 4)Write a function to count the number of words
present in a text file named ―PARA.TXT‖. Assume that
::in|ios::out);
cout>>Ino; each word is separated by a single blank/space
cin.getline(Item,20); character and no blanks/spaces in the beginning and
_________________ //Statement 2 end of the file. (2006 D)
File.write((char*)this,sizeof(Item)); Solution:
File.close( ); void WordsCount( )
} { clrscr( );
ifstream fin("PARA.TXT",ios::in);
Answer:
Statement 1 :File.seekg(RecNo*sizeof(Item)); char ch;
int Words=1;
Statement 2 :File.seekp(RecNo*sizeof(Item));
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 67 PRAISE THE LORD
if(!fin) CCE guidelines further.
{ cout<<”No words at all in the file”; The AECount( ) function should display the output as
exit(0); A:1
} E:7
while(fin) Answer)
{ fin.get(ch); void AECount( )
if(ch= =‟ „) { char Ch;
Words++; ifstream fcin(“NOTES.txt”);
} int count1=0,count2=0;
cout<<"\nTotal number of Words in the file = "<<Words; while(!fcin.eof( ))
getch( ); { fcin.get(CH);
} if(Ch= =‟A‟||Ch==‟a‟)
5) Write a function in C++ to count the words ―to‖ and count1++;
―the‖ present in a text file ―POEM.TXT‖.(2010) (2009) else if (Ch= =‟E‟||Ch==‟e‟)
[Note that the words “to” and “the” are complete words] count2++;
Ans) }
void COUNT( ) fcin.close( );
{ ifstream Fil; cout<<”A: “<<count1<<endl;
Fil. open (“POEM.TXT”);//OR ifstream Fill(“POEM.TXT”); cout<<”E:”<<count2<<endl;
char Word[8O], Ch; }
int Cl =0, C2=0, i=0; 8) A text file named MATTER.TXT contains
while(Fil.get(Ch)) some text, which needs to be displayed such
{ if (Ch! = „ „)
Word[i++] = Ch; that every next character is separated by a
else symbol ‗#‘.
{ Word[i] = „\0‟; Write a function definition for HashDisplay( ) in C++
if (strcmp (Word, “to”) ==0) that would display the entire content of the file
Cl++; MATTER.TXT in the desired format. (2018)(3)
else if (strcmp (Word, “the”) ==0) Example:
C2++;
If the file MATTER.TXT has the following
i=0;
} content stored in it:
} The WORLD IS ROUND
cout<<”Count of -to- in file:”<<Cl; The function HashDisplay( ) should display the
cout<<”Count of -the- in file:”<<C2; following content:
Fil.close( ); T#H#E# #W#O#R#L#D# #I#S# #R#O#U#N#D#
}
Answer:
6)Write a function to count the number of blanks
present in a text file named ―PARA.TXT‖. (2006)(2003) void HashDisplay( )
Solution: { char ch;
void BlanksCount( ) ifstream F("MATTER.TXT" );
{ clrscr( ); /* ifstream F;
ifstream fin("PARA.TXT",ios::in); F.open(“MATTER.TXT”);
char ch; OR
int Blanks=0; fstream F;
if(!fin) F.open(“MATTER.TXT”,ios::in);
*/
{cout<<”No words at all in the file.So no blank spaces”;
exit(0); while(F.get(ch))
} cout<<ch<<”#”;
while(fin) }
{fin.get(ch); F.close();
if(ch= =‟ „)
}
Blanks++;
} 9. Polina Raj has used a text editing software to type
cout<<"\nTotal number of Blank some text in an article. Aftersaving the article as
Spaces in the file = "<<Blanks; MYNOTES.TXT , she realised that she has wrongly
getch( ); typed alphabetK in place of alphabet C everywhere in
} the article.Write a function definition for
7)Write the function AECount( ) in C++, which should PURETEXT() in C++ that would display the
read character of a text file NOTES.txt, should count correctedversion of the entire article of the file
and display the occurrence of alphabets A and E MYNOTES.TXT with all the alphabets “K” tobe
(including small case a and e too) (2014) 2
displayed as an alphabet “C” on screen. (2017)
Example:
If the file content is as follows: Note: Assuming that MYNOTES.TXT does not
CBSE enhanced its contain any C alphabet otherwise.
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 68 PRAISE THE LORD
Example: char STR [10];
If Polina has stored the following content in the file int count = 0;
MYNOTES.TXT : while (!Fil.eof ( ))
I OWN A KUTE LITTLE KAR. {Fil>>STR ;
I KARE FOR IT AS MY KHILD. if (strcmp (STR, "He") ==0 | | strcmp (STR, "She")= =0)
The function PURETEXT() should display the following count++;
content: }
I OWN A CUTE LITTLE CAR. cout<<"Count of He/She in file : "<<count<<end1;
I CARE FOR IT AS MY CHILD. Fil.close( );
Ans) }
3)Write a function CountYouMe( ) in C++ which reads
void PURETEXT( ) the contents of a text file story.txt and counts the words
{ char ch; You and Me (not case sensitive) (2013) (2010D )[2
ifstream F("MYNOTES.TXT" ); For example, if the file contains:
while(F.get(ch)) You are my best friend.
{if(ch= =‟K‟) You and me make a good team.
The function should display the output as
ch=‟C‟; Count for You: 2
cout<<ch; Count for Me: 1
} Answer)
F.close(); #include<conio.h>
} #include<iostream.h>
#include<fstream.h>
10) Write a C++ program, which initializes a string
variable to the content ―Time is a great teacher but #include<string.h>
unfortunately it kills all its pupils. Berlioz‖ and outputs void COUNT( )
the string one character at a time to the disk file { ifstream File;
OUT.TXT. You have to include all the header files if File.open(“STORY.TXT”);
required. (2002) char Word[80];
int C1=0,C2=0;
while(!File.eof( ))
WORDWISE OPERATIONS
{ File>>Word;
1)Write function definition for TOWER( ) in C++ to if(strcmpi(Word,”You”)= =0)
read the content of a text file WRITEUP.TXT, count the C1++;
presence of word TOWER and display the number of else if(strcmpi(Word,”me”)= =0)
occurrences of this word. (2015)2 C2++;
Note : The word TOWER should be an independent word }
‐ Ignore type cases (i.e. lower/upper case) cout<<”Count for you: “<<C1<<endl;
Example: cout<<”Count for me: “<<C2;
If the content of the file WRITEUP.TXT is as follows: File.close( );
Tower of hanoi is an interesting problem. }
Mobile phone tower is away from here. Views 4)Write a function in C++ to print the count of the word
from EIFFEL TOWER are amazing. the as an independent word in a text file STORY.TXT.
The function TOWER () should display the following:3 For example,if the content of the file STORY.TXT is
Ans) There was a monkey in the zoo.The monkey was very
void TOWER() naughty. (2007 OD)
{ int count=0; Then the output of the program should be 2
ifstream f("WRITEUP.TXT"); Solution:
char s[20]; void COUNT_THE ( )
while (!f.eof()) { ifstream Fil; //OR ifstream Fi1(“NOTES.TXT”);
{ f>>s; Fil.open(“STORY.TXT”)
if (strcmpi(s,”TOWER”)= =0) char Word[80],Ch;
count++; int Count =0, I=0;
} while(Fil.get(Ch))
cout<<count; { if (Ch!= „ „)
f.close(); Word [I++] = Ch;
} else
2) Write a function in C++ to count the no. of "He" or { Word[I] = „\0‟;
"She" words present in a text file "STORY. TXT". if (strcmp (strupr(Word), “THE”) = =0)
If the file "STORY. TXT" content is as follows: Count++;
He is playing in the ground. She is Playing with her dolls. I=O;
The output of the function should be }
Count of He/She in file: 2 }
Ans (2011 OD)2 Fil.close( );
void COUNT ( ) cout<<”Count of-the- in file: “<<Count;
{ ifstream Fil ("STORY.TXT"); }
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 69 PRAISE THE LORD
5)Write a user defined function word_count() in C++ to }
count how many words are present in a text file named File.close();
―opinion.txt‖.For example, if the file opinion.txt contains }
following text:Co-education system is necessary for a 9)Write a function in C++ to count and display the
balanced society. Withco-education system, Girls and Boys number of lines starting with alphabet ‗A‘ present in a
may develop a feeling of text file ―LINES.TXT‖. (2005 D)
mutual respect towards each other. (2017MP)2 Example :
The function should display the following: If the file “LINES.TXT” contains the following lines,
Total number of words present in the text file are: 24 A boy is playing there.
Ans) There is a playground.
void word_count() An aeroplane is in the sky.
{ifstream i;char ch[20];int c=0; Alphabets and numbers are allowed in the password.
i.open("opinion.txt "); The function should display the output as 3
while(!i.eof()) Ans)
void counter( )
{ i>>ch;
{ char Aline[80];
c=c+1; int Count=0;
} ifstream Fin (“LINES.TXT”);
cout<<" Total number of words present in the text file are: “<<c; while(Fin.getline(Aline,80, „\n‟))
} if (Aline[0]== „A‟)
6)Write function definition for DISP3CHAR( ) in C++ Count++;
to read the content of a text file KIDINME.TXT, and Fin.close( );
display all those words, which have three characters in cout<<Count<<endl;
it. (2016)2 }
Example: 10) Write a function in C++ to count and display the
If the content of the file KIDINME.TXT is as follows: number of lines not starting with alphabet ‗A‘ present in
When I was a small child, I used to play in the garden a text file ―STORY.TXT‖. (2005 OD)
with my grand mom. Those days were amazingly funful Example :
and I remember all the moments of that time If the file “STORY.TXT” contains the following lines,
The function DISP3CHAR() should display the following: The rose is red.
was the mom and all the A girl is playing there.
Ans) There is a playground.
{ ifstream Fil; An aeroplane is in the sky.
Fil.open(“KIDINME.TXT”); Numbers are not allowed in the password.
char W[20]; The function should display the output as 3
Fil>>W; Ans)
while(!Fil.eof()) // OR while(Fil) void COUNTALINES()
{ if (strlen(W)) = = 3) { ifstream FILE(“STORY.TXT”);
cout<<W<< “ “; int CA=0;
Fil>>W; char LINE[80];
} while (FILE.getline (LINE,80))
Fil.close(); //Ignore if (LINE[0]!=‟A‟)
} CA++;
7) Write a function in C++ to count the number of lines cout<<”Not Starting with A counts to “<<CA<<endl;
present in a text file "STORY.TXT". (MP109-10) (MP108-09) FILE.close( );
Ans) }
void CountLine() 11)Write a function RevText( ) to read a text file
{ ―Input.txt ― and Print only word starting with ‗I‘ in
ifstream FIL("STORY.TXT"); reverse order . 2019SP2
int LINES=0; Example: If value in text file is: INDIA IS MY
char STR[80]; COUNTRY
while (FIL.getline(STR,80)) Output will be: AIDNI SI MY COUNTRY
LINES++; Answer:
cout<<"No. of Lines:"<<LINES<<endl; void RevText( )
f.close( ); { ifstream Fin(“Input.txt”);
} char Word[20];
8) Write a function in C++ to read the content of a text while(!Fin.eof())
file "DELHI.TXT' and display all those lines on screen, { Fin>>Word;
which are either starting with 'D' or starting with 'M' if(Word[0]==‟I‟)
Ans (2012) 2 strrev(Word);
void DispDorM() cout<<Word<< “ ”;
{ if stream File("DELHI.TXT"); }
char Str[80]; Fin.close( );
while(File.getline(Str,80)) }
{ if(Str[0]='D' || Str[0]='M')
cout«Str«endl;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 70 PRAISE THE LORD
12) Assuming that a text file named FIRST.TXT STU S;
contains some text written into it, write a function char ch='Y';
named vowelwords( ), that reads the file FIRST.TXT while (Ch=='Y' || Ch = = 'y')
and creates a new file named SECOND.TXT, to contain { S.Enter();
only those words from the file FIRST.TXT which start ofile.write (Char*) & S, sizeof(s));
with start with a lowercase vowel (i.e. with ‗a‘, ‘e‘, ‘I‘, cout << "more (Y/N)";
‗o‘, ‗u‘). For example if the file FIRST.TXTcontains cin>>ch;
Carry umbrella and overcoat when it rains (2004) }
Then the file SECOND.TXT shall contain: ofile.close();
umbrella and overcoat it }
MODEL 3: USING CLASS CONCEPT. 3 Mark 3) Write a definition for a function TotalTeachers( ) in
C++ to read each object of a binary file
1.Write a function in C++ to search and display details, SCHOOLS.DAT, find the total number of teachers,
whose destination is ―Cochin‖ from binary file whose data is stored in the file and display the same.
―Bus.Dat‖. Assuming the binary file is containing the Assume that the file SCHOOLS.DAT is created with the
objects of the following class: 2019SP3 help of objects of class SCHOOLS, which is defined
class BUS below: 2018(2)
{ int Bno; // Bus Number class SCHOOLS
char From[20]; // Bus Starting Point { int SCode; //School Code
char To[20]; // Bus Destination char SName[20]; //School Name
public: int NOT; //Number of Teachers in the school
char * StartFrom ( ) public:
{ return From; void Display( )
} {cout<<SCode<<”#”<<SName<<”#”<<NOT<<endl;
char * EndTo( ) }
{ return To; int RNOT( )
} { return NOT;
void input() }
{ cin>>Bno>>; gets(From); get(To); };
} Ans)
void show( ) void TotalTeachers()
{ cout<<Bno<< “:”<<From << “:” <<To<<endl; {
} ifstream F;
}; F.open("SCHOOLS.DAT",ios::binary);
Answer: int Count=0;
void Read_File( ) SCHOOLS S;
{ while(F.read((char*)&S,sizeof(S)))
BUS B; Count += S.RNOT();
ifstream Fin; cout<<"Total number of teachers"<<Count<<endl;
Fin.open(“Bus.Dat”, ios::binary); F.close();
while(Fin.read((char *) &B, sizeof(B))) }
{ if(strcmp(B.EndTo(), “Cochin”)= =0) OR
{ B.show( ) ; void TotalTeachers()
} {
} ifstream F;
Fin.close( ); F.open("SCHOOLS.DAT",ios::binary);
} SCHOOLS S;
2. Write a function in C++ to add more new objects at while(F.read((char*)&S,sizeof(S)))
the bottom of a binary file "STUDENT.dat", assuming cout<<S.RNOT()<<endl;//OR S.Display();
the binary file is containing the objects of the following F.close();
class : 2019SP3 }
class STU 4. Write a definition for function COUNTPICS() in C++
{ int Rno; to read each object of abinary file PHOTOS.DAT, find
char Sname[20]; and display the total number of PHOTOS of
public: typePORTRAIT. Assume that the file PHOTOS.DAT is
void Enter() created with the help of objects of class PHOTOS, which
{ cin>>Rno;gets(Sname); is defined below: (2017)
} class PHOTOS
void show() {
{ count << Rno<<sname<<endl; int PCODE;
} char PTYPE[20];//Photo Type as
}; “PORTRAIT”,”NATURE”
Answer: public:
void Addrecord() void ENTER()
{ ofstream ofile; { cin>>PCODE;gets(PTYPE);
ofile.open("STUDENT.dat", ios ::out);
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 71 PRAISE THE LORD
} { cin>>TID;gets(Toy);gets(Status);cin>>MRP;
void SHOWCASE() }
{ cout<<PCODE<<":"<<PTYPE<<endl; void View()
}
char *GETPTYPE(){return PTYPE;} {cout<<TID<<”:”<<Toy<<”:”<<MRP<<””:”<<Status<<en
}; dl;
Ans) }
void COUNTPICS() char *SeeOffer()
{ {return Status;
ifstream F; }
F.open("PHOTOS.DAT",ios::binary); };
int count=0; Ans)
PHOTOS obj; void ONOFFER()
while(F.read((char*)&obj, {
sizeof(obj))) TOYS T;
{if(strcmp(obj.GETPTYPE(),“PORTRAIT”)==0) ifstream fin;
count++; fin.open(“TOYS.DAT”, ios::binary);
} while(fin.read((char*)&T, sizeof(T)))
cout<<”Number of PORTRAIT photos :”<<count; {
F.close(); if(strcmp(T.SeeOffer(),”ON OFFER”)==0)
} T.View();
5.Write a function display () in C++ to display all the }
students who have got a distinction(scored percentage fin.close();
more than or equal to 75) from a binary file ―stud.dat‖, }
assuming the binary file is containing the objects of the 7.Write a definition for function COSTLY() in C++ to
following class: (2017MP)3 read each record of a binary file GIFTS.DAT, find and
class student display those items,which are priced more that 2000.
{ int rno; Assume that the file GIFTS.DAT is created with the
char sname [20]; help of objects of class GIFTS, which is defined below:
int percent; class GIFTS (2015)3
public: {
int retpercent() int CODE;char ITEM[20]; float PRICE;
{ return percent; public:
} void Procure()
void getdetails() {cin>>CODE; gets(ITEM);cin>>PRICE;
{ cin>>rno; }
gets(sname); void View()
cin>>percent; {cout<<CODE<<":"<<ITEM<<":"<<PRICE<<endl;
} }
void showdetails() float GetPrice() {return PRICE;}
{ cout<<rno; };
puts(sname); Ans)
cout<<percent; void COSTLY()
} { GIFTS G;
}; ifstream fin(“GIFTS.DAT”,ios::binary);
Ans) while (fin.read((char *)&G,sizeof(G)))
void display() { if(G.GetPrice()>2000)
{ student s; G.View();
ifstream i(“stud.dat”); }
while(i.read((char*)&s,sizeof(s))) fin.close();
{ if(s.retpercent()>=75) }
s.showdetails(); 8.Assume the class TOYS as declared below, write a
} function in C++ to read the objects TOYS from binary
i.close(); file TOYS.DAT and display those details of those TOYS,
} which are meant for children of AgeRange ―5 to 8‖.
6.Write a definition for function ONOFFER( ) in C++ to class TOYS (2014) 3
read each object of a binary file TOYS.DAT, find and { int ToyCode;
display details of those toys, which has status as char ToyName[10];
―ÖNOFFER‖. Assume that the file TOYS.DAT is char AgeRange;
created with the help of objects of classTOYS, which is public:
defined below: (2016) 3 void Enter( )
class TOYS {cin>>ToyCode;
{ int TID;char Toy[20],Status[20]; float MRP; gets(ToyName);
public: gets(AgeRange);
void Getinstock() }

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 72 PRAISE THE LORD


void Display( ) 10) Write a function in C++ to search for the details
{cout<<ToyCode<<”:”<<ToyName<<endl; (Phone no and Calls) of those Phones, which have more
cout<<AgeRange<<endl; than 800 calls from a binary file "phones.dat" Assuming
} that this binary file contains records/objects of class
char *WhatAge( ) Phone, which is defined below. (2012)3
{return AgeRange; class Phone
} { char Phoneno [10] ; int Calls ;
}; public:
Answer) void Get 0
void Show( ) {gets (Phoneno) ; cin>>ea11s;
{TOY T; }
ifstream fcin(“TOY.DAT”,ios::in|ios::binary); void Bi11ing( )
while(fcin) {cout<<Phoneno<<"#"<<Ca11s«end1:
{ fcin.read((char *)&T,sizeof(T)); }
if(strcmp((T,WhatAgeR( ),”5 to 8”)= =0) int GetCa11s ()
T.Display( ); {return Ca11s;
} }
fcin.close( ); };
} Ans
9.Assuming the class ANTIQUE as declared below, void Search ( )
write a function in C++ to read the objects of ANTIQUE {Phone P;
from binary file ANTIQUE.DAT and display those fstream fin;
antique items, which are priced between 10000 and fin. open ("phones. dat", ios: :binary| ios: :in);
15000. (2013) 3 whi1e (fin.read((char*) &P, sizeof (P)))
class ANTIQUE { if(P.GetCa11s ( ) > 800)
{ int ANO; P.Billing ( ) ;
char Aname[10]; }
float Price; fin.c1ose () ;
public: }
void BUY( ) 11) Write a function in C++ to search for a camera from
{ cin>>ANO; a binary file "CAMERA.DAT" containing the objects of
gets(Aname); class" CAMERA (as defined below). The user should
cin>>price; enter the Model No and the function should search
} display the details of the camera. (2011 OD)3
void SHOW( ) class CAMERA
{ cout<<ANO<<endl; { long ModelNo;
cout<<Aname<<endl; float MegaPixel;
cout<<Price<<endl; int Zoom;
} char Details[120];
float GetPrice( ) public:
{ return Price; void Enter ( )
} {cin>>ModelNo>>MegaPixel>>Zoom;gets(Details);
}; }
Answer) void Display ( )
void Search(float pr) {cout<<ModelNo<<MegaPixel<<Zoom<<Details<<endl;
{ ifstream ifile(“ANTIQUE.DAT”,ios::in|ios::binary); }
if(!file) long GetModelNo ( )
{ cout<<”Could not open ANTIQUE.DAT file”; {return ModelNo;
exit(0); }
} };
else Ans
{ ANTIQUE A; void Search ( )
int found=0; { CAMERA C;
while(!file.read((char *)&A,sizeof(A))) long modelnum;
{ pr=A.GetPrice( ); cin>>modelnum;
if(pr>=10000 && pr<=15000) ifstream fin;
{ A.SHOW( ); fin.open ("CAMERA.DAT", ios: :binary | ios: :in) ;
found=1; while (fin.read((char*) &C,sizeof (C)))
break; { if (C. GetModelNo ( ) modelnum)
} C.Display() ;
} }
} Fin.close( ) ;
if(found= =0) }
cout<<”Given Price not Match”; OR
} void Search (long modelnum)

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 73 PRAISE THE LORD


{ CAMERA C; void DisplayL_M( )
ifstream fin; { CLUB C;
fin.open ("CAMERA.DAT", ios: :binary | ios: :in); fstream fin;
while(fin.read((char*)&C,sizeof(C))) fin. open (“CLUB.DAT”,ios::binary|ios::in);
{ if (C.GetModelNo() = = modelnum) //OR ifstream fin (“CLUB.DAT”, ios::binary);
C. Display (); while(fin.read((char*)&C, sizeof(C))
} { if(C.WhatType()==‟L‟||C.WhatType()==‟M‟)
Fin.close( ); C .Display ( );
} }
12) Write a function in C++ to search and display fin.close( );
details. of all trains, whose destination is ―Delhi‖ . from }
a binary file ―TRAIN.DAT‖. Assuming the binary file is OR
containing the objects of the following class. (2010 OD) void Disp1ayL_M ( )
class TRAIN { CLUB C;
{ int Tno; // Train Number fstream fin;
charFrom[20]; // Train Starting Point fin.open (“CLUB.DAT”, ios::binary | ios::in);
charTo [20]; // Train Destination //ifstream fin (“CLUB.DAT”,ios::binary);
public: if(fin)
char* GetFrom( ) {fin.read((char*)&C, sizeof(C));
{ return From; while(!fin.eof())
} { if(C.WhatType()==‟L‟||C.WhatType()==‟M‟)
char* GetTo( ) C. Display( );
{ return To; fin.read((char*)&C, sizeof(C));
} }
void Input( ) }
{ cin>>Tno; fin.close( );
gets(From); }
gets(To); 14) Given a binary file TELEPHON.DAT, containing
} records of the following class Directory : (2008 OD)
void Show( ) class Directory
{ { char Name[20] ;
cout<<Tno<<“:”<<From<<“:”<<To<<endl; char Address[30] ;
} char AreaCode[5] ;
}; char phone_No[15] ;
Ans) public ;
void Read ( ) void Register( ) ;
{ void Show( ) ;
TRAIN T; int CheckCode(char AC[ ])
ifstream fin; { return strcmp(AreaCode, AC) ;
fin. open (“TRAIN.DAT”,ios::binary); }
//OR ifstream fin (“TRAIN.DAT”, ios::binary); };
while(fin.read((char*)&T, sizeof(T))) Write a function COPYABC( ) in C++, that would copy
{ if(strcmp(T.GetTo(),”Delhi”)==O) all those records having AreaCode as ―123‖ from
T.Show( ) ; TELEPHON.DAT to TELEBACK.DAT.
} Solution:
fin.close( ); void COPYABC( )
} { ifstream fin(“TELEPHON.DAT‟,ios::in|ios::binary);
13) Write a function in C++ to read and display the ofstream fout(“TELEBACK.DAT”,ios::out,ios|binary);
detail of all the members whose membership type is ‗L‘ Directory D;
or ‗M‘ from a binary file ―CLUB.DAT‖. Assume the while(fin) // or while(!fin.eof( ))
binary file ―CLUB.DAT‖ contains objects of class { fin.read((char*)&D,sizeof(D));
CLUB,which is defined as follows: (2009 OD) if(D.CheckCode(“123”)= = 0)
class CLUB fout.write((char*)&D,sizeof(D));
{ int Mno; //Member Number }
char Mname [20]; //Member Name fin.close( );
char Type; //Member Type: L Life Member M fout.close( );
//Monthly Member G Guest }
public: 15)Given a binary file SPORTS.DAT,containg records
void Register( ); //Function to enter the content of the following structure type: (2007 OD)
void Display( ); //Function to display all data members struct Sports
char WhatType( ) { char Event[20] ;
{ return Type; char Participant[10][30] ;
} };
}; Write a function in C++ that would read contents from the
Ans) file SPORTS.DAT and creates a file named

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 74 PRAISE THE LORD


ATHLETIC.DAT copying only those records from Ans)
SPORTS.DAT where the event name is “Athletics”. void Distinction()
Solution: { Student S;
void AthletsList( ) fstream Fin;
{ Fin.open(“STUDENT.DAT”,
ifstream fin(“SPORTS.DAT‟,ios::in, ios::binary);); ios::binary|ios::in);
ofstream fout(“ATHLETIC.DAT”, ios::out|ios::binary); while(Fin.read((char*)&S, sizeof(Student))
Sports S; if (S.ReturnPercentage()>75)
while(fin) // or while(!fin.eof( )) S.DisplayData();
{ fin.read((char*)&S,sizeof(Sports)); Fin.close();
if(strcmp(S.Event,”Athletics”)= = 0) }
fout.write((char*)&S,sizeof(S)); 18)Assuming a binary file FUN.DAT is containing
} objects belonging to a class LAUGHTER (as defined
fin.close( ); below).
fout.close( ); class LAUGHTER
} { int Idno; // Identification number
16) Following is the structure of each record in a data char Type[5]; //LAUGHTER Type
file named ―PRODUCT.DAT‖ . (2006 OD) char Desc[255];//Description
struct PRODUCT public :
{ char Product_Code[10] ; void Newentry( )
char Product_Description[10] ; { cin>>Idno;gets(Type);gets(Desc);
int Stock ; }
}; void Showonscreen( )
Write a function in C++ to update the file with a new value of {
Stock. The Stock and the Product_Code, whose Stock to be cout<<Idno<<”:”<<Type<<endl<<Desc<<endl;
updated, are read during the execution of the program. }
Solution: };
void Update( ) Write a user defined function in C++ to add more
{ fstream finout(“PRODUCT.DAT”, ios::in|ios::out); objects belonging to class LAUGHTER at the bottom of
PRODUCT P; it. (2003)
finout.seekg(0); 19) Assuming the class FLOPPYBOX, write a function
while(finout) in C++ to perform following:
{finout.read((char *)&P, sizeof(P)); class FLOPPYBOX
cout<<”\nThe Product Code is “<P.Product_Code; { int size;
cout<<”\nThe Product Description is” char name[10];
<<P.Product_Description; public:
cout<<”\nEnter the Stock: “; void getdata()
cin>>P.Stock; { cin>>size;gets(name);
finout.seekp(finout.seekp( )-sizeof(P)); }
finout.write((char *)&P,sizeof(P)); void showdata(){cout<<size<<" <<name<<endl;}
} };
} (i) Write the objects of FLOPPYBOX to a binary file.
17)Given a binary file STUDENT.DAT, containing (ii) Reads the objects of FLOPPYBOX from binary file
records of the following class Student type (2005D) and display them on screen. (1999)
class Student
20) Assuming the class EMPLOYEE given below, write
{ char S_Admno[10] ; //Admission number of student functions in C++ to perform the following:
char S_Name[30] ; //Name of student class EMPLOYEE
int Percentage ; //Marks Percentage of student { int ENO;
public : char ENAME[10];
void EnterData( ) public:
{ gets(S_Admno); void GETIT( )
gets(S_Name); { cin>>ENO;
cin >> Percentage ; gets(ENAME);
} }
void DisplayData( ) void SHOWIT( )
{ cout << setw(12) << S_Admno ; { cout<< ENO<<ENAME<<endl;
cout << setw(32) << S_Name ; }
cout << setw(3) << Percentage << endl ; };
} (i) Write the objects of EMPLOYEE to a binary file.
int ReturnPercentage( ) (ii) Read the objects of EMPLOYEE from binary file
{ return Percentage; and display them on the screen. (1998)
}
}; 21) Assuming the class DRINKS defined below, write
Write a function in C++, that would read contents of file functions in C++ to perform the following:
STUDENT.DAT and display the details of those class DRINKS
Students whose Percentage is above 75. { int DCODE;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 75 PRAISE THE LORD
char DNAME[13]; //Name of the drink FIL.open("STUDENT.DAT",ios::binary|ios::app);
int DSIZE,; //Size in liters STUD S;
float DPRICE; char CH;
public: do
void getdrinks( ) { S.Enter();
{ cin>>DCODE>>DNAME>>DSIZE>>DPRICE; FIL.write((char*)&S,sizeof(S));
} cout<<"More(Y/N)?";cin>>CH;
void showdrinks( ) }
{ cout<<DCODE<<DNAME<<DSIZE<<DPRICE<<endl; while(CH!='Y');
} FIL.close( );
char *getname( ) }
{return DNAME;} Model 4 : Complete the function definitions of class
};
4.b) Consider the class declaration
(i)Write the objects of DRINKS to a binary file. class FLIGHT
(ii) Read the objects of DRINKS from binary file and
{ protected:
display them on screen when DNAME has value "INDY
int flight_no;
COLA". (2000) char destination[20];
22) Write a function in C++ to search for a BookNo float distance;
from a binary file "BOOK.DAT", assuming the binary public:
file is containing the objects of the following class.
void INPUT( ); //To read an object from the keyboard
class BOOK (MP109-10)
void write_file(int); //To write N objects into the file,
{int Bno; //Where N is passed as argument.
char Title[20]; void OUTPUT( ); //To display the file contents on the monitor.
public: }; (2001)
int RBno( ) Complete the member functions definitions.
{return Bno;}
Model 5 : Theory Questions
void Enter( )
1)What is the difference between pub( ) and write( ) ? (2002)
{cin>>Bno;gets(Title);}
2) Distinguish between ios::out and ios::app. (2001)
void Display( )
Ans) The ios::out mode opens the file in output mode only.
{cout<<Bno<<Title<<endl;}
The ios::app mode opens the file in append mode, where the
};
file can be appended.
Ans)
3) Name two member functions of ofstream class. (2000)
void BookSearch()
4) Differentiate between functions read( ) and write( ). (1999)
{fstream FIL;
5) Write name of two member functions belonging to
FIL.open("BOOK.DAT",ios::binary|ios::in);
fstream class. (1998)
BOOK B;
int bn,Found=0; 8.POINTERS
cout<<"Enter Book No. to search…"; cin>>bn;
while (FIL.read((char*)&S,sizeof(S))) Model 1 : Output (Without Class) - 2 Marks
if (FIL.RBno()==bn) 1. Find and write the output of the following C++
{ S.Display(); program code: Note: Assume all required header
Found++;
}
files are already being included in the program.
if (Found==0) void main( ) 2019SP(3)
cout<<"Sorry! Book not found!!!"<<endl; { int Ar[ ] = { 6 , 3 , 8 , 10 , 4 , 6 , 7} ;
FIL.close( ); int *Ptr = Ar , I ;
} cout<<++*Ptr++ << '@' ;
23) Write a function in C++ to add new objects at the I = Ar[3] - Ar[2] ;
bottom of a binary file "STUDENT.DAT", assuming the cout<<++*(Ptr+I)<<'@'<<"\n" ;
binary file is containing the objects of the following
class. (MP209-10)
cout<<++I + *Ptr++ << '@' ;
class STUD cout<<*Ptr++ <<'@'<< '\n' ;
{ int Rno; for( ; I >=0 ; I -=2)
char Name[20]; cout<<Ar[I] << '@' ;
public: }
void Enter( ) Ans: 7@11@
{ cin>>Rno;gets(Name);
}
6@8@
void Display( ) 11@3@
{ cout<<Rno<<Name<<endl;
} 2) Find and write the output of the following
}; C++ program code: (2018)
Ans) Note: Assume all required header files are
void Addnew( ) already included in the program (2)
{fstream FIL; #define Modify(N) N*3+10
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 76 PRAISE THE LORD
void main( ) Important Note: (2014 OD)
{ int LIST[ ]={10,15,12,17}; - All the desired header files are already included in the
int *P=LIST,C; code, which are required to run the code.
for(C=3;C>=0;C- -) void main( )
LIST[C]=Modify(LIST[C]); { char *Text=”AJANTA”;
for(C=0;C<=3;C++) int *P,Num[ ]={1,5,7,9};
{ cout<<*P<<”:”; P=Num;
P++; cout<<*P<<Text<<endl;
} Text++;
} P++;
Ans) 40:55:46:61: cout<<*P<<Text<<endl;
}
(Note: Actually LIST[I] ]=Modify(LIST[I]);Was printed on A) 1AJANTA
paper, Considered LIST[I] replaced with LIST[C] ) 5JANTA
3. Find and write the output of the following C++ 6) Observe the following C++ code carefully and obtain
program code: (2017)3 the output, which will appear on the screen after
Note: Assume all required header files are already execution of it.
being included in the program. Important Note: (2013 D)2
void main( ) -All the desired header files are already included in the
code, which are required to run the code.
{ int *Point, Score[]={100,95,150,75,65,120};
void main( )
Point = Score; { char *String=”SHAKTI”;
for(int L = 0; L<6; L++) int *Point,Value[ ]={10,15,70,19};
{ if((*Point)%10==0) Point=Value;
*Point /= 2; cout<<*Point<<String<<endl;
else String++;
*Point -= 2; Point++;
if((*Point)%5==0) cout<<*Point<<String<<endl;
*Point /= 5; }
Point++; A) 10SHAKTI
15HAKTI
}
7) Find the output of the following program: 2
for(int L = 5; L>=0; L--) #include <iostream.h> (2012 OD)
cout<<Score[L]<<"*"; #include <ctype.h>
} typedef char str80 [80] ;
Ans) 12*63*73*15*93*10* void main ( )
4) Write the output of the following C++ program code: { char *Notes ;
Note: Assume all required header files are already being str80 str="vR2GooD";
included in the program. int L=6;
void change(int *s) (2017 MP) Notes=Str;
{ for(int i=0;i<4;i++) while (L>=3)
{ if(*s<40) { Str[L]=(isupper(Str[L])?tolower(Str[L]):
{ if(*s%2==0) toupper(Str[L]));
*s=*s+10; cout<<Notes<<endl;
else L--;
*s=*s+11; Notes++;
} }
else }
{ if(*s%2==0) Ans: vR2Good
*s=*s-10; R2GoOd
else 2GOOd
*s=*s-11;
gOOd
}
cout<<*s<<" "; 8.Find the output of the following program: 2
s++; #include<iostream.h> (2011OD)
} void main ( )
} {int *Queen, Moves [ ] = {11, 22, 33, 44};
void main() Queen = Moves;
{ int score[]={25,60,35,53}; Moves [2] + = 22;
change(score); Cout<< "Queen @"<<*Queen<<end1;
} *Queen - = 11;
A) 36 50 46 42 Queen + = 2;
cout<< "Now @"<<*Queen<<end1;
5) Obtain the output of the following C++ program as Queen++;
expected to appear on the screen after its execution.2 cout<< "Finally@"<<*Queen«end1;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 77 PRAISE THE LORD
cout<< "New Origin @"<<Moves[0]<<end1; 12) Give the output of the following program segment.
} (Assuming all required header files are included in the
Ans Queen @11 program) (2001)
Now @55 void main( )
Finally @44 { int a=32,*x=&a;
New origin @0 char ch=65,&cho=ch;
9) Find the output of the following program(2009 OD) cho+=a;
#include<iostream.h> *x+=ch;
void main( ) cout<<a<<‟,‟<<ch<<endl;
{int A[ ] = {10, 15, 20, 25, 30} }
int *p = A; 13) Give the output of the following program. (1999)
while (*p < 30) #include<stdio.h>
{ if (*p%3 ! = 0) void main( )
*p = *p + 2 ; { char *p=”Difficult”;
else char c;
*p = *p + 1; c=*p++;
p++; printf(“%c”,c);
} }
for (int J = 0; J<=4; J++) 14)Find the output of the following program:2
{ cout << A[J] << “*” ; #include <iostream.h> (MP2 2008-09)
if ( J%3 = = 0) struct Game
cout<<end1; { char Magic[20];int Score;
} };
cout<<A[4] * 3<<end1; void main()
} { Game M={“Tiger”,500};
Ans) 12* char *Choice;
16*22*27* Choice=M.Magic;
30*90 Choice[4]=‟P‟;
Choice[2]=‟L‟;
10)Find the output of the following program: (2007 OD) M.Score+=50;
#include<iostream.h> cout<<M.Magic<<M.Score<<endl;
void main( ) Game N=M;
{ int Numbers[]={2,4,8,10}; N.Magic[0]=‟A‟;N.Magic[3]=‟J‟;
int *ptr=Numbers; N.Score-=120;
for(int C=1;C<3;C++) cout<<N.Magic<<N.Score<<endl;
{ cout<<*ptr<<”@”; }
ptr++; Answer: TiLeP550
} AiLJP430
cout<<endl;
for(C=0;C<4;C++) Model 2 : Output (Within Class) - 2 Marks
{ (*ptr)*=2; 1) Find the output of the following program. (2006 OD)
--ptr; #include<iostream.h>
} #include<string.h>
for(C=0;C<4;C++) class student
cout<<Numbers[C]<<”#”; { char *name;
cout<<endl; int I;
} public:
11) What will be the output of the following program: student( )
#include<iostream.h> (2004) { I=0;
#include<conio.h> name=new char[I+1];
#include<ctype.h> }
#include<string.h> student(char *s)
void ChangeString(char Text[],int &Counter) { I=strlen(s);
{ char *Ptr=Text; name=new char[I+1];
int Length=strlen(Text); strcpy(name,s);
for(;Counter<Length- 2; Counter+=2,Ptr++) }
{ *(Ptr+Counter)=toupper(*(Ptr+Counter)); void display( )
} { cout<<name<<endl;
} }
void main( ) void manipulate(student &a, student &b)
{ clrscr( ); { I=a.I+b.I;
int Position=0; delete name;
char Message[]=”Pointers Fun”; name=new char[I+1];
ChangeString(Message,Position); strcpy(name,a.name);
cout<<Message<<”@”<<Position; strcat(name,b.name);
}
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 78 PRAISE THE LORD
} class Rectangle
}; { float area,len,bre;
void main( ) public:
{ char *temp=”Jack”; void input( )
Student name1(temp),name2(“Jill”), { cout<<"\nEnter the length and breadth: ";
name3 (“John”),S1,S2; cin>>this->len>>this->bre;
S1.manipulate(name1,name2); }
S2.manipulate(S1,name3); void calculate( )
S1.display( ); { area=len*bre; //Here Implicit 'this' pointer will be
S2.display( ); worked.
} }
2) Give the output of the following program (2001) void output( )
#include<iostream.h> {
#include<string.h> cout<<"\nThe Area of the
class per Rectangle:"<<this->area;
{ char name[20]; }
float salary; };
public: void main( )
per(char *s, float a) { Rectangle R;
{ strcpy(name,s); clrscr( );
salary=a; R.input( );
} R.calculate( );
per *GR(per &x) R.output( );
{ if(x.salary>=salary) getch();
return &x; }
else 2) Distinguish between
return this; int *ptr=new int(5);
} int *ptr=new int[5]; (2001)
void display( ) Ans: The int *ptr=new int(5); declares and creates the
{ cout<<”Name:“<<name<<”\n”; space for the new data directly.
cout<<”Salary:“<<salary<<”\n”; Ie The new operator reserves 2 bytes of memory
} from heap memory (free pool) and returns the address of
}; that memory location to a pointer variable called ptr, 5 is
void main( ) the initial value to be stored in the newly allocated memory.
{ Per P1(“REEMA”,10000), The int *ptr = new int[5]; initializes an array
P2(“KRISHNAN”,20000), element. A memory space for an integer type of array
P3(“GEORGE”,5000); having 5 elements will be created from the heap memory
per *P; (free pool).
P=P1.GR(P3);P->display( );
P=P2.GR(P3);P->display( ); } Model 4 : Errors/Rewrite - 2 Marks
1) Identify the syntax error(s), if any, in the following
Model 3 : Theory Question - 2 Marks program.Also give reason for errors. (2001)
void main( )
1) What is “this” pointer? Give an example to illustrate the { const int i=20;
use of it in C++. (2006 OD) const int* const ptr=&i;
Ans: A special pointer known as this pointer stores the (*ptr)++;
address of the object that is currently invoking a member int j=15;
function. The this pointer is implicitly passed to the ptr=&j;
member functions of a class whenever they are invoked. }
(As soon as you define a class, the member Ans:
functions are created and placed in the memory space only Error Line 5 : Cannot modify a const object.
once. That is, only one copy of member functions is Error Line 7 : Cannot modify a const object.
maintained that is shared by all the objects of the class. Warning Line 8 : „j‟ is assigned a value that is never used.
Only space for data members is allocated separately for Warning Line 8 : „ptr‟ is assigned a value that is never
each object. used.
When a member function is called, it is automatically Explanation:
passed an implicit(in built) argument that is a pointer to the (1)Error 1 is in Line no.5 ie (*ptr)++
object that invoked the function. This pointer is called this. Here ptr is a constant pointer ie the contents cann‟t be
If an object is invoking a member function, then an implicit modified.
argument is passed to that member function that points to (2)Error 2 is in Line no.7 ie ptr=&j;
(that) object. The programmer also can explicitly specify Here ptr is a constant pointer the
„this‟ in the program if he desires.) address in this pointer can‟t be modified.
Eg: Example program to demonstrate the usage of this (It is already pointing the address of i.)
pointer.
#include<iostream.h>
#include<conio.h>
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 79 PRAISE THE LORD
9.ARRAYS(8 Marks) void swap_row(int ARR[3][3])
{ int Temp, j;
MODEL 1: Function to Receive an array and for (j=0; j<3; J++)
ChangeElements. (2 or 3 Marks) { Temp = A[0][j];
A[0][j] = A[2][j];
1. Write a user defined function Reverse(int A[ ],int n) A[2][j] = Temp;
which accepts an integer array and its size as }
arguments(parameters) and reverse the array. }
Example : if the array is 10,20,30,40,50 then reversed array 4) Define a function SWAPCOL ( ) in C++ to swap
is 50,40,30,20,10 2019SP3 (interchange) the first column elements with the last
Answer: column elements, for a two dimensional integer array
void Reverse( int A[ ] , int n) passed as the argument of the function. (2009 D)
{ int temp; Example: If the two dimensional array contains
for(int i=0;i<n/2;i++)
{ temp=A[i];
A[i]=A[n-1-i];
A[n-1-i]=temp;
}
}
2. Write the definition of a function AddUp(intArr[ ], int
N) in C++, in which all even positions (i.e. 0,2,4,...) of the
array should be added with the content of the element in After swapping of the content of 1st column and last
the next position and odd positions (i.e. 1,3,5,...) column, it shoud be
elements should be incremented by 10. (2017)3
Example: if the array Arr contains
23 30 45 10 15 25
Then the array should become
53 40 55 20 40 35
NOTE: ● The function should only alter the content in the
same array.
● The function should not copy the altered content in
another array. Ans) void SWAPCOL(int A[][100], int M, int N)
● The function should not display the altered content of the { int Temp, I;
array. for(I=O; I<M; I++)
● Assuming, the Number of elements in the array are Even. { Temp = A [I][0] ;
Ans) A[I][0] = A[I][N-l];
void AddUp(intArr[], int N) A[I][N-l] = Temp;
{ for(int i=0; i<N; i++) }
{ if(i%2= =0) } OR
Arr[i]=Arr[i]+Arr[i+1]; void SWAPCOL(int A[4][4])
else { int Temp, I;
Arr[i]=Arr[i]+10; for(I=O; I<4; I++)
} {
} Temp = A[I][0];
3. Write a user-defined function swap_row (int A[I][0] = A[I][3];
ARR[][3],intR,int C) in C++ to swap the first row values A[I][3] = Temp;
with the last row values: (2017MP) (2009 OD)2 }
For example if the content of the array is: }
10 20 30 4.Write the definition of a function grace_score (int
40 50 60 score [], int size) in C++, which should check all the
70 80 90 elements of the array and give an increase of 5 to those
Then after function call, the content of the array should scores which are less than 40. (2016)3
be: Example: if an array of seven integers is as follows:
70 80 90 45, 35, 85, 80, 33, 27, 90
40 50 60 After executing the function, the array content should
10 20 30 be changed as follows:
Ans) 45, 40, 85, 80, 38, 32, 90
void swap_row(int ARR[][3],intR,int C) Ans)
{ int i,j,temp; void grace_score(int score[],int size)
for( i=0,j=0;j<C;j++) { for(int i=0;i<size;i++)
{ temp=ARR[i][j]; { if(score[i]<40)
ARR[i][j]=ARR[R-1][j]; score[i]=score[i]+5;
ARR[R-1][j]=temp; cout<<score[i]<<" ";
} }
} }
OR
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 80 PRAISE THE LORD
5.Write the definition of a function FixSalary(float array by shifting each of them to the next position and
Salary[], int N) in C++, which should modify each by shifting the last element to the first position.
element of the array Salary having N elements, as per For example: if the content of array is (2013) 3
the following rules: (2016) 2 0 1 2 3 4
12 15 17 13 21
The changed content will be
0 1 2 3 4
21 12 15 17 13
Ans)
A) void FixSalary(float Salary[ ], int N) void Change(int P[ ], int N)
{ for (int i=0;i<N;i++) { int temp;
if(Salary[i]<100000) int temp1;
Salary[i]+= 0.35 *Salary[i]; for(int i=0;i<(N-1);i++)
else if (Salary[i]>=100000 && Salary[i]<20000) { temp=P[size-1];
Salary[i]+= 0.3 * Salary[i]; P[N-1]=P[i];
else if(Salary[i]>=200000) P[i]=temp;
Salary[i]+= 0.20 * Salary[i]; }
} }
6.Write the definition of a function Change(int P[], int 9) Write a function SWAP2BEST (int ARR[], int Size) in C++
to modify the content of the array in such a way that the
N) in C++,which should change all the multiples of 10 in
elements, which are multiples of 10 swap with the value
the array to 10and rest of the elements as 1. For present in the very next position in the array. (2012) 3
example, if an array of 10integers is as follows:(2015)2 For example:
If the content of array ARR is
90, 56, 45, 20, 34, 54
The content of array ARR should become
56, 90, 45, 34, 20, 54
Ans
void SWAP2BEST(int ARR[], int Size)
{ int t;
for(int i=0;i<Size-1;i++)
{ if (ARR[i] %10=0)
A)void Change(int P[ ],int N) { t=ARR[i];
{ for (int i=0;i<N;i++) ARR[i]=ARR[i+1];
if(P[i]%10==0) ARR[i+1]=t;
P[i]=10; }
else }
P[i]=1; }
} 10.Write a Get2From1() function in C++ to transfer the
7.Write a code for function EvenOdd(int T[ ], int C) in content from one array ALL[] to two different arrays
C++, to add 1 in all the odd values and 2 in all the even Odd[] and Even[]. The Odd[] array should contain the
values of the array T.(2014) 3 values from odd positions (1,3,5,...) of ALL[] and Even []
Example: If the original content of an array S is array should contain the values from even positions (0,
T[0] T[1] T[2] T[3] T[4] 2, 4,…..) of ALL [ ]. (2011 OD) 3
35 12 16 69 26 Example
The modified content will be: If the ALL[ ] array contains
12, 34, 56, 67, 89, 90
T[0] T[1] T[2] T[3] T[4] The Odd[ ] array should contain
36 14 18 70 28 34, 67, 90
Answer) And the Even [ ] array should contain
void EvenOdd(int T[ ],int C) 12,56,89
{ int I; Ans
for(i=0;i<C;i++) void Get2From1 (int All [],int Even [], int Odd [], int Size)
{ if(T[i]%2==0) { int J=0,K=0;
T[i]=T[i]+2; for (int I=0 ;I<Size; 1++)
else { if (I%2==0)
T[i]=t[i]+1; { Even [J]=All[I] ;
} J++;
cout<<”Modified content will be: “; }
for(i=0;i<C;i++) else
cout<<T[i]; { Odd[K]=All[I);
} K++;
8.Write code for a function void ChangOver(int P[],int }
N) in C++, which repositions all the elements of the }
}
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 81 PRAISE THE LORD
11) Write a function REASSIGNO in C++, which cout<<A[i]<<‟\t‟; */
accepts an array of integers and its size as parameters }
and divide all those array elements by 5 which are 14)Write a function in C++ which accepts an integer
divisible by 5 and multiply other array elements by 2. array and its size as arguments and replaces elements
Sample Input Data of the array having even values with its half and elements having odd
values with twice its value . (2007OD)
Example : If an array of five elements initially contains the
elements as 3, 4, 5, 16, 9
then the function should rearrange content of the array as
6, 2, 10, 8, 18
Content of the array after calling REASSIGNO function Solution:
void accept(int a[ ],int size)
{
for (int i=0;i<size;i++)
{ if (a[i]%2= =0)
Ans) (2010OD) a[i]=a[i]/2;
void REASSIGN (intArr[ ], int Size) else
{ for (int i=0;i<Size;i++) a[i]=a[i]*2;
if (Arr[i]%5==0) cout<<a[i]<<‟,‟;
Arr[i]/=5; }
else }
Arr[i]*=2; 15)Write function in C++ which accepts an integer
} OR array and size as arguments and assign values into a 2D
void REASSIGN(intArr[ ],int Size) array of integers in the following format : (2006D)
{ for (int i=0;i<Size;i++) If the array is 1, 2, 3, 4, 5, 6
Arr[i]%5 ? Arr[i]/=5 : Arr[i] *= 2; The resultant 2D array is given below
} 1 2 3 4 5 6
12) Write a function in C++, which accepts an integer 1 2 3 4 5 0
array and its size as parameters and rearranges the 1 2 3 4 0 0
array in reverse. (2008D) 1 2 3 0 0 0
Example: 1 2 0 0 0 0
If an array of nine elements initially contains the elements 1 0 0 0 0 0
as 4, 2, 5, 1, 6, 7, 8, 12, 10 If the array is 1, 2, 3
Then the function should rearrange the array as The resultant 2D array is given :
10,12, 8, 7, 6, 1, 5, 2, 4 1 2 3
Solution: 1 2 0
void receive(int A[ ], int size) 1 0 0
{ int temp; Solution:
for(i=0,j=size-1;i<size/2;i++,j--) void input (int a[ ],int size)
{ temp=A[i]; { int b[size] [size];
A[i]=A[j]; for (int i=0;i.<size;i++)
A[j]=temp; {
} for (int j=0;j<size;j++)
} //end of receive function. {
13)Write a function in C++, which accepts an integer if(( i+j)>=size)
array and its size as arguments and swap the elements b[i][j]=0;
of every even location with its following odd location. else
Example : (2008OD) b[i][j]=a[j];
If an array of nine elements initially contains the elements cout<<b[i][j]<<‟\t‟;
as 2,4,1,6,5,7,9,23,10 }
then the function should rearrange the array as cout<<endl;
4,2,6,1,7,5,23,9,10 }
void SwapArray(int A[ ], int N) }
{ inti,j,temp; 16)Write function in C++ which accepts an integer
/* cout<<”\nThe elements before doing the desired array and size as arguments and assign values into a 2D
alterations…”; array of integers in the following format : (2006OD)
for(i=0;i<N;i++) If the array is 1, 2, 3, 4, 5, 6
cout<<A[i]<<‟\t‟; */ The resultant 2D array is given below :
for(i=0;i<N-1;i+=2) 1 0 0 0 0 0
{ temp=A[i]; 1 2 0 0 0 0
A[i]=A[i+1]; 1 2 3 0 0 0
A[i+1]=temp; 1 2 3 4 0 0
} 1 2 3 4 5 0
/* cout<<”\nThe elements after completed the desired 1 2 3 4 5 6
alterations…”; If the array is 1, 2, 3
for(i=0;i<N;i++)
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 82 PRAISE THE LORD
The resultant 2D array is given: Example :
1 0 0 If the array initially contains
1 2 0 {2, 5, 9, 14, 17, 8, 19, 16}
1 2 3 Then after rearrangement the array should contain
Solution: {5, 2, 14, 9, 8, 17, 16, 19}
void input (int a[ ],int size) Solution:
{ int b[size] [size]; void SwapArray(int NUMBERS[ ], int N)
for (int i=0;i.<size;i++) {
{ inti,j,temp;
for (int j=0;j<size;j++) /* cout<<”\nThe elements before doing the desired
{ alterations…”;
if(( i<j) for(i=0;i<N;i++)
b[i][j]=0; cout<<NUMBERS[i]<<‟\t‟; */
else for(i=0;i<N-1;i+=2)
b[i][j]=a[j]; {
cout<<b[i][j]<<‟\t‟; temp=NUMBERS[i];
} NUMBERS[i]=NUMBERS[i+1];
cout<<endl; NUMBERS[i+1]=temp;
} }
} OR /* cout<<”\nThe elements after completed the desired
constint R = 100, C = 100; alterations…”;
void Arrayconvert(int A1D[ ], int N) for(i=0;i<N;i++)
{ int A2D[R][C]={0}; cout<<NUMBERS[i]<<‟\t‟; */
for(int I = 0; I<N; I++) }
for (int J = 0; J <=I; J++) 19) Write a user-defined function in C++ to find and
A2D[I][J] = A1D[J]; display the sum of diagonal elements from a 2D array
} MATRIX[6][6] containing integers.
17)Write a function in C++ which accepts an integer void displaysum( )
array and its size as arguments and exchanges the {int i,j,D1=0,D2=0,MATRIX[6][6];
values of first half side elements with the second half cout<<”\nEnter any 36 values….”;
side elements of the array. (2005OD) for(i=0;i<6;i++)
Example : for(j=0;j<6;j++)
If an array of 8 elements initial content as { cin>>MATRIX[i][j];
8, 10, 1, 3, 17, 90, 13, 60 if(i= = j)
The function should rearrange array as D1=D1+MATRIX[i][j];
17, 90, 13, 60, 8, 10, 1, 3 else if ((i+j)= =(size-1))
Ans) D2=D2+MATRIX[i][j];
void Exchange(int A[],int N) }
{ for (int I=0;I<N/2;I++) cout<<”\nThe sum of the elements of the Main Diagonal = “
{ int Temp=A[I]; <<D1;
A[I]=A[N/2+I]; cout<<”\nThe sum of the elements of
A[N/2+I]=Temp; the Other Diagonal = “<<D2;
} }
} OR 20) Write a function in C++ to combine the contents of
void Exchange(int A[],int N) two equi-sized arrays A and B by adding their
{ for (int I=0,J=N/2;I<N/2;I++,J++) corresponding elements as the formula A[i]+B[i]; where
{ int Temp=A[J]; value i varies from 0 to N-1 and transfer the resultant
for (int K=J;K>I;K--) content in the third same sized array C. (MP209-10) 3
A[K]=A[K-1]; Ans)
A[I]=Temp; void AddNSave(int A[ ],int B[ ],int C[ ],int N)
} { for (int i=0;i<N;i++)
} OR C[i]=A[i]+B[i];
void Exchange(int A[],int N) }
{ int M=(N%2=0)?N:N+l; 21)Write a function in C++ to combine the contents of
for (int I=0;I<M/2;I++) two equi-sized arrays A and B by computing their
{ int Temp=A[I]; corresponding elements with the formula 2*A[i]+3*B[i];
A[I]=A[M/2+I]; where value i varies from 0 to N-1 and transfer the
A[M/2+I]=Temp; resultant content in the third same sized array.
} Ans) (MP208-09)4
} void AddNSave(int A[ ],int B[ ],int C[ ],int N)
18) Define the function SwapArray(int[ ], int),that { for (int i=0;i<N;i++)
would expect a 1D integer array NUMBERS and its size C[i]=2*A[i]+3*B[i];
N. the function should rearrange the array in such a }
way that the values of that locations of the array are
exchanged. (Assume the size of the array to be even). (2004)

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 83 PRAISE THE LORD


MODEL 2: Function to Display the array elements in a Sum of odd values = 99 ( ie 25+21+53)
particular order.(2 or 3 Marks) Answer:
1.Write a user-defined function AddEnd4 (int A[][4],int void SumEO(int VALUES[ ], int N)
R,int C) in C++ to find and display the sum of all the { int odd=0, even=0;
values, which are ending with 4 (i.e., unit place is 4). for(int i=0;i<N;i++)
2019SP2 { if (VALUES[i] %2= = 0)
For example if the content of array is: even=even +VALUES[i];
24 16 14 else
odd=odd+VALUES[i];
19 5 4
}
The output should be 42 cout<<”\nSum of even values = “<<even;
Answer: cout<<”\nSum of Odd values = “<<odd;
void AddEnd4(int A[ ][4], int R, int C) }
{ int I,J,sum=0; 5) Write a definition for a function UpperHalf(int
for(I=0;I<R;I++) Mat[4][4]) in C++, which displays the elements in the
{ for(J=0;J<C;J++) same way as per the example shown below:
if(A[I][J]%10 = =4) For example, if the content of the array Mat is as follow:
sum=sum+A[I][J];
25 24 23 22
}
cout<<sum; 20 19 18 17
} 15 14 13 12
2.Write a user defined function in C++ to find the sum 10 9 8 7
of both left and right diagonal elements from a two The function should display the content in the following
dimensional array. 2019SP2 format:
void Diagsumboth(int A[][4], int n) 25 24 23 22
{ int sumLt=0,sumRt=0; 20 19 18
for(int i=0;i<n;i++) 15 14
{ sumLt+=A[i][i]; 10
sumRt+=A[n-1-i][i]; Answer:
} void UpperHalf(int Mat[4][4])
cout<<”sum of left diagonal”<<sumlt<<endl; { for (int I=0;I<4;I++)
cout<<”sum of right diagonal”<<sumRt<<endl; { for (int J=0;J<4-I;J++)
} cout<<MAT[I][J]<< " " ;
3.Write a user-defined function EXTRA_ELE (int A[ ], cout<<endl;
int B[ ], int N) in C++ to find and display the extra }
element in Array A. Array A contains all the elements of } OR
array B but one more element extra. (Restriction: array void UpperHalf(int Mat[4][4])
elements are not in order) 2019SP3 { for(int i=0;i<4;i++)
Example If the elements of Array A is { for (int j=0;j<4;j++)
14, 21, 5, 19, 8, 4, 23, 11 if ((i+j)<=3)
and the elements of Array B is cout<<MAT[i][j]<< " " ;
23, 8, 19, 4, 14, 11, 5 cout<<endl;
Then output will be 21 /* for(int j=0;j<4;j++)
Answer: if ( (i+j) > 3 )
void EXTRA_ELE(int A[], int B[],int N) cout<<‟ „;
{ int i,j,flag=0; else
cout<<Mat[i][j];
for(i=0;i<N;i++)
cout<<endl;
{ for(j=0;j<N;j++) */
{ if(A[i]==B[j])
{ flag=1;
}
break; }
} 6. Write a definition for a function SUMMIDCOL(int
} MATRIX[][10],intN,int M) in C++,which finds the sum
if(flag= =0) of the middle column‘s elements of the MATRIX
cout<<"Extra element"<<A[i]; (Assuming N represents number of rows and M
flag=0; represents number of columns, which is an odd integer).
} Example: if the content of array MATRIX
} having N as 5 and M as 3 is as follows: (2017)2
4) Write the definition of a function SumEO (int 1 2 1
VALUES[ ], int N) in C++, which should display the
sum of even values and sum of odd values of the array
2 1 4
separately. (2) 3 4 5
Example: If the array VALUES contains 4 5 3
25 20 22 21 53 5 3 2
Then the functions should display the output as
Sum of even values = 42 (ie 20 + 22)
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 84 PRAISE THE LORD
The function should calculate the sum and display }
the following:Sum of Middle Column: 15 } OR
void REVROW(int P[ ][5],intN,int M)
Ans) { for(int I=0; I<N; I++)
{int mid=M/2; { for(int J=0; J<M/2; J++)
int sum=0; { int T = P[I][J];
for(int i=0; i<N; i++) P[I][J] = P[I][MJ1];
{ sum=sum+MATRIX[i][mid]; P[I][MJ1] = T;
}
} }
cout<<” Sum of Middle Column”<<sum; for(I=0; I<N; I++)
} { for(int J=0; J<M; J++)
7.Write definition for a function DISPMID(int cout<<P[I][J];
A[][5],intR,int C) in C++ to display the elements of cout<<endl;
middle row and middle column from a two dimensional }
array A having R number of rows and C number of }
columns. (2016)3 9.Write user-defined function AddEnd2(int A[ ][4], int
For example, if the content of array is as follows: N, int M) in C++ to find and display the sum of all the
values which are ending with 2(ie units place is 2). For
example if the content of array is (2014)
22 16 12
19 5 2
The function should display the following as output The output should be
103 901 921 802 601 36
516 921 609
Answer)
Ans) void AddEnd(int A[ ][4], int N, int M)
void DISPMID(int A[][5],intR,int C)
{ intI,j,Sum=0;
{for (int J=0;J<C;J++) for(i=0;i<N;i++)
cout<<A[R/2][J]<< “ “; { for(j=0;j<M;j++)
cout<<endl; { if(A[i][j]%10==2)
for (int I=0;I<R;I++) Sum=Sum+A[i][j];
cout<<A[I][C/2]<< “ “; }
} OR }
void DISPMID(int A[][5],intR,int C) cout<<Sum;
{ if(R%2!=0) }
{ for (int J=0;J<C;J++)
10.Write a user defined function DispTen(int A[ ][4],
cout<<A[R/2][J]<< “ “;
intN,int M) in C++ to find and display all the numbers
}
which are divisible by 10. For example, if the content of
else
array is (2013) 2
cout<<”No Middle Row”;
cout<<endl; 12 20 13
if(C%2!=0) 2 10 30
{ for (int I=0;I<R;I++) The output should be
cout<<A[I][C/2]<< “ “; 20 10 30
} Answer)
else void DispTen(int A[ ][3], intN,int M)
cout<<”No Middle Column”; { intI,j,S=0;
} for(i=0;i<N;i++)
8.Write a function REVROW(int P[][5],int N, int M) in for(j=0;j<M;j++)
C++ todisplay the content of a two dimensional array, if(A[i][j]%10= =0)
with each rowcontent in reverse order. (2015) 3 cout<<A[i][j]<<” “;
}
11.Write a function ALTERNATE (int A[ ] [3], int N, int
M) in C++ to display all alternate elements from two-
dimensional array A (staring from A [0] [0]). (2012)1
The function should display output as: For example:
51 45 56 12 15 If the array is containing:
63 87 92 91 13 23 54 76
81 46 61 23 81 37 19 28
A) 62 13 19
void REVROW(int P[][5],intN,int M) The output will be
{for(int I=0; I<N; I++) 23 76 19 62 19
{ for(int J=M1;J>=0; J) Ans.
cout<<P[I][J]; void ALTERNATE (int A [] [3], int N, int M)
cout<<endl; {int T=0;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 85 PRAISE THE LORD
for (int I=0 ; I<N; I++) The function should add elements B[0][0], B[0][2], B[l][l],
for (int J=0 ; J<M ; J++) B[2][0] and B[2][2].
{ if (T%2= =0) Ans.
cout<<A[I] [J]<<" "; int ALTERSUM(int B[ ][5] ,intN,int M)
T++ ; {int Sum=0;
} for (int I=0;I<N;I++)
} OR for (int J=(I%2==0)?0:1;J<M;J+=2)
void ALTERNATE (int A[] [3], int N, int M) Sum+=B[I][J] ;
{ int *P=&A[O] [0] ; return Sum;
for (int I=0; I<N*M ; I+=2) } OR
{ cout<<*p<<" "; int ALTERSUM(int B[ ][5],intN,int M)
P+=2 ; { int Sum=0,J=0;
} for (int I=0;I<N;I++)
} {for (;J<M;J+=2)
11) Write a DSUMO function in C++ to find sum of Sum+=B[I][J] ;
Diagonal Elements from a NxN Matrix. (2011 OD) 2 J-=M;
(Assuming that the N is a odd number) }
Ans return Sum;
void DSUM (int A [ ] [100] ,int N) } OR
{int SUMR =0, SUML=0; int ALTERSUM(int B[ ][5],intN,int M)
for (int i=0; i<N;i++} { int *P=&B[0][0],Sum=0;
{ SUMR=SUMR + A[i] [i] ; for (int I=0;I<M*N;I+=2)
SUML = SUML + A[i] [N-1-i] ; { Sum+=(*P);
} P+=2;
cout<< " Sum of Diagonal Elements = " }
<<SUMR + SUML –A[N/2] [N/2] ; return Sum;
} OR } OR
void DSUM (int A[] [100], int N) int ALTERSUM (int B[ ][5], int N, int M)
{int SUMR =0, SUML=0; { int S=0, C=0;
for (int i=0; i<N; i++) for(int I = 0; 1< N; 1++)
{ SUMR = SUMR + A[i] [i] ; for (int J = 0; J<M; J++ )
SUML = SUML + A[i] [N-1-i] ; {
} if (C%2 == 0)
cout<< "Sum of Right Diagonal Elements = " S = S + B[I][J];
<<SUMR<<end1; C++;
cout<< "Sum of Left Diagonal Elements = " }
<<SUML<<end1; return S;
} OR } OR
void DSUM (int A[] [100] , int N) int ALTERSUM(int B[ ][5],intN,int M)
{ int SUMR =0, SUML=0; { int Sum=0;
for (int i = 0; i<N; i++) for (int I=0;1<N;1++)
{ for (int j = 0; j<N; j++) for (int J=0;J<M;J++)
{ if (i==j) if ((I+J)%2==0)
SUMR=SUMR + A[i] [j] ; Sum+=B [I][J] ;
else if (i+j == N-1) return Sum;
SUML = SUML + A[i] [j]; } OR
} int ALTERSUM(int B[ ][5],intN,int M)
} { int Sum=0;
cout<< "Sum of Diagonal Elements =" for (int I=0;1<N;1++)
<< SUMR + SUML - A[N/2] [N/2]; for (int J=0;J<M;J++)
} { if ((I%2==0 && J%2=0)||(1%2!=0
12) Write a function int ALTERSUM (int B[ ] [5], int N, int && J%2!=0))
M in C++ to find and return the sum of elements from all Sum+=B [I][J] ;
alternate elements of a two-dimensional array starting from }
B[0][0]. (2010 OD) return Sum;
Hint: If the following is the content of the array: }
13)Write a function in C++ to print the product of each
column of a two dimensional array passed as the
arguments of the function. (2008D)

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 86 PRAISE THE LORD


Example : If the two dimensional array contains void accept(int a[ ][ ],int size)
Then the output should appear as: { inti,j;
Product of Column 1 = 24 cout<<"Diagonal One:";
Product of Column 2 = 30 for (int i=0;i<size;i++)
Product of Column 3 =240 for(int j=0;j<size;j++)
void receive(int A[ ][ ],intr,int c) if (i= = j)
{ inti,j,B[c]; cout<<a[i][j]<<‟\t‟;
for(i=0;i<c;i++) cout<<"\n Diagonal Two:";
B[i]=1; for (i=0;i<size;i++)
for(i=0;i<r;i++) for(j=0;j<size;j++)
for(j=0;j<c;j++) if((i+j)= =(size-1))
B[j]=B[j]*A[i][j]; cout<<a[i][j]<<‟\t‟;
for(i=0;i<c;i++) }
cout<<”\nProduct of Column “<<i+1<<” = “<<B[i]; 16)Write a function in C++ which accepts a 2D array of
} OR integers and its size as arguments and displays the
void ProdCol(intArr[][100], int Row, int Col) elements of middle row and the elements of middle
{ int i, j, Prod; column. [Assuming the 2D Array to be a square matrix
for (j = 0; j < Col; j++) with odd dimensioni.e., 3x3, 5x5, 7x7 etc…](2007OD)
{ Prod=1; Example : If the array content is
for (i = 0; i < Row; i++) 3 5 4
Prod * = Arr[i][j]; 7 6 9
cout<<“Product of Column”<<j<< “=” <<Prod<<endl; 2 1 8
} Output through the function should be :
} Middle Row :7 6 9
14)Write a function in C++ to print the product of each Middle Column : 5 6 1
row of a two dimensional array passed as the arguments Solution:
of the function (2008OD) void accept(int a[ ][ ],int size)
Example: if the two dimensional array contains {inti,j;
cout<<"Middle Row:";
for (int i=0;i<size;i++)
for(int j=0;j<size;j++)
if (i= = size/2)
cout<<a[i][j]<<‟\t‟;
cout<<"\n Middle Column:";
for (i=0;i<size;i++)
for(j=0;j<size;j++)
Then the output should appear as: if(j= =size/2)
Product of Row 1 = 8000 cout<<a[i][j]<<‟\t‟;
Product of Row 2 = 6000 }
Product of Row 3 =3600 17) Write a function in C++ to print sum of all values
Product of Row 4 = 2400 which either are divisible by 3 or divisible by 5 present
void receive(int A[ ][ ],intr,int c) in a 2D array passed as the argument of the function.
{ inti,j,B[r]; Ans) (2005OD)
for(i=0;i<r;i++) void Sum(int A[ ][ ],intR,int C)
B[i]=1; { int S=0,i,j;
for(i=0;i<r;i++) for(i=0;i<R;i++)
for(j=0;j<c;j++) for(j=0;j<C;j++)
B[i]=B[i]*A[i][j]; if((a[i][j]%3= =0)||(a[i][j]%5= =0))
for(i=0;i<r;i++) S=S+A[i][j];
cout<<”\nProduct of Row “<<i+1<< cout<<" nThe Sum of all the values
” = “<<B[i]; which are divisible by 3 or 5 in the array = “<<S;
} }
15)Write a function in C++ which accepts a 2D array of 18) Write a function in C++ to find the sum of diagonal
integers and its size as arguments and displays the elements from a 2D array of type float. Use the array
elements which lie on diagonals. [Assuming the 2D and its size as parameters with float as its return type.
Array to be a square matrix with odd dimension i.e., Solution: (2004)
3x3, 5x5 ,7x7 etc…] (2007D) float diasum(float A[ ][ ],intR,int C)
Example : if the array content is { inti,j;
5 4 3 float Dsum=0.0;
6 7 8 for(i=0;i<R;i++)
1 2 9 for(j=0;j<C;j++)
Out put through the function should be : if((i= = j)| | (i+j)= =(size-1))
Diagonal One : 5 7 9 Dsum=Dsum+A[i][j];
Diagonal Two : 3 7 1 return Dsum;
Solution: }
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 87 PRAISE THE LORD
19)Write a user-defined function in C++ to display those 23) Write a user-defined function in C++ to find and
elements of 2D array T[4][4] which are divisible by 100. display the sum of diagonal elements from a 2D array
Assume the content of the array is already present and R[7][7] containing integers. (1998)
the function prototype is as follows: (2003) void displaysum( )
void showhundred( int T[4][4]); { int i,j,D1=0,D2=0,R[7][7];
void showhundred(int T[4][4]) cout<<”\nEnter any 49 values….”;
{ int i,j; for(i=0;i<7;i++)
cout<<”\nThe elements in the array for(j=0;j<7;j++)
which are divisible by 100 …..”; { cin>>R[i][j];
for(i=0;i<4;i++) if(i= = j)
for(j=0;j<4;j++) D1=D1+R[i][j];
if(T[i][j]%100= =0) else if ((i+j)= =(size-1))
cout<<T[i][j]<<‟\t‟; D2=D2+R[i][j];
} }
20)Write a user-defined function named Lower_half() cout<<”\nThe sum of the elements of
which takes 2D array A, with size N rows and N the Main Diagonal = “<<D1;
columns as argument and prints the lower half of the cout<<”\nThe sum of the elements of
array. (2001) the Other Diagonal = “<<D2;
Eg: Input: }
2 3 1 5 0 24) Write a function in C++ to find the sum of both left
7 1 5 3 1 and right diagonal elements from a two dimensional
2 5 7 8 1 array (matrix). (MP108-09) (MP109-10) 2
0 1 5 0 1 Ans)
3 4 9 1 5 void DiagSum(int M[][4],intN,int M)
Output: { int SumD1=0,SumD2=0;
2 for (int I=0;I<N;I++)
7 1 { SumD1+=M[I][I];SumD2+=M[N-I-1][I];
2 5 7 }
0 1 5 0 cout<<"Sum of Diagonal 1:" <<SumD1<<endl;
3 4 9 1 5 cout<<"Sum of Diagonal 2:" <<SumD2<<endl;
Solution: }
void Lower_half( int A[ ][ ],int N) 25) Write a function in C++ to find sum of rows from a
{ inti,j; two dimensional array. (MP209-10) (MP208-09)2
for(i=0;i<N;i++) Ans)
for(j=0;j<N;j++) void MatAdd(int M[][4],intN,int M)
{ if(i<j) { for (int R=0;R<N;R++)
cout<<A[i][j]<<‟\t‟; {
cout<<endl; intSumR=0;
} for (int C=0;C<M;C++)
} SumR+=M[C][R];
21) Write a user-defined function in C++ to find and cout<<SumR<<endl;
display the multiplication of row elements of two }
dimensional array A[4][6] containing integers. (1999) }
void rowmul( )
{ int A[4][6],i,j,rowmul; MODEL 3A: Address Calculation of 2-D array.
cout<<”\nEnter any 24 values…”; (Row-Major) (3 Marks)
for(i=0;i<4;i++) 1. An array A[30][10] is stored in the memory with each
for(j=0;j<6;j++) element requiring 4 bytes of storage ,if the base address
cin>>A[i][j]; of A is 4500 ,Find out memory locations of A[12][8], if
for(i=0;i<4;i++) the content is stored along the row. 2019SP3
{ rowmul=1; Loc of A[12][8]= B+W*(N*(I-LBR)+(J-LBC))
for(j=0;j<6;j++) =4500+4*(10*12+8)
rowmul=rowmul*A[i][j]; = 4500 4*(128)
cout<<”\nThe multiplication of “<<i+1 =4500 + 512
<<” row = “<<rowmul; = 5012
} 2) Let us assume Data[20][15] is a two-dimensional
} array, which is stored in the memory along the row with
22) An array T[15][10] is stored in the memory with each of its elements occupying 2 bytes. Find the address
each element requiring 2 bytes of storage. If the base of the element Data[10][5] , if the element Data[15][10]
address of T is 2000, determine the location of T[7][8] is stored at the memory location 15000.
when the array VAL is stored 2018 (3)
(i) Row major (ii) Column major. (1998) Answer:
Solution: Children, Try this as an assignment. Address of A[I][J] = B + W[(I-Lr)*C + (J-Lc)]
Lr = 0 Lc = 0 R = 20 C=15 W=2
Data[15][10]= 15000

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 88 PRAISE THE LORD


Here I=15 J=10 A)
Data[15][10] = B + 2(15*15 + 10) Loc(R[I][J])
15000 = B + 2 * 235 =BaseAddress + W [( I – LBR)*C + (J – LBC)]
B= 15000 – 470 = 14530 (where
Data[10][5] = 14530 + 2 [10 * 15 + 5] W=size of each element = 8 bytes,
= 14530 + 310 = 14840 R=Number of Rows=10, C=Number of Columns=50)
OR Assuming LBR = LBC = 0
LOC(Data[10][5]) = LOC(Data[15][10])+2(15*(10-15)+(5-10)) LOC(R[8][10])
= 15000 + 2((-75) + (-5)) 45000 = BaseAddress + W[ I*C + J]
= 15000 + 2(-80) 45000 = BaseAddress + 8[8*50 + 10]
= 15000 - 160 45000 = BaseAddress + 8[400 + 10]
= 14840 45000 = BaseAddress + 8 x 410
OR BaseAddress = 45000 3280
LOC(Data[I][J]) = Base(Data)+W*(NC*(I-LBR)+(J-LBC)) = 41720
Taking LBR=1, LBC=1 LOC(R[5][15])= BaseAddress + W[ I*C + J]
LOC(Data[15][10]) = Base(Data)+2*(15*14+9) = 41720 + 8[5*50 + 15]
15000 = Base(Data)+2*(15*14+9) = 41720 + 8[250 + 15]
Base(Data) = 15000 - 2*(219) = 41720 + 8 x 265
Base(Data) = 15000 - 438 = 41720 + 2120
Base(Data) = 14562 = 43840
LOC(Data[10][5])= 14562 + 2*(15*9+4) OR
= 14562 + 2*(139) Loc(R[I][J])
= 14562 + 278 =Reference Address + W [( I – LR)*C + (J – LC)]
= 14840 (where
W=size of each element = 8 bytes,
3.ARR[15][20] is a two-dimensional array, which is R=Number of Rows=10, C=Number of Columns=50)
stored in the memory along therow with each of its Reference Address= Address of given cell R[8][10]=45000
elements occupying 4 bytes. Find the address of the LR = Row value of given cell = 8
elementARR[5][15], if the element ARR[10][5] is stored LC = Column value of given cell = 10
at the memory location 35000. (2017)3 LOC(R[5][15])= LOC(T[8][10]) + 8[(5 8)*50 + (15 10)]
Ans) LOC(R[15][5]) = 45000 + 8[3*50 + 5]
Loc(ARR[I][J]) =BaseAddress + W [( I – LBR)*C + (J – LBC)]
= 45000 + 8[150+ 5]
(where W=size of each element = 4 bytes, R=Number of
= 45000 + 8 x (145)
Rows=15, C=Number of Columns=20 )
= 45000 1160
Assuming LBR = LBC = 0
= 43840
35000 = BaseAddress + W(I*C + J)
35000 = BaseAddress + 4(10*20 + 5) 5.A two dimensional array ARR[50][20] is stored in
35000 = BaseAddress + 4(205) the memory along the row with each of its elements
35000 = BaseAddress + 820 occupying 4 bytes. Find the address of the element
BaseAddress = 35000 – 820 = 34180 ARR[30][10], if the elementARR[10] [5] is stored at
LOC(ARR[5][15])= BaseAddress + W(I*C + J) the memory location 15000. (2015) 3
= 34180 + 4(5*20 + 15) Loc(ARR[I][J]) along the row
= 34180 + 4(100 + 15) =BaseAddress + W [( I – LBR)*C + (J – LBC)]
= 34180 + 4 x 115 (where C is the number of columns, LBR = LBC = 0
= 34180 + 460 LOC(ARR[10][5])
= 34640 = BaseAddress + W [ I*C + J]
OR 15000 = BaseAddress + 4[10*20 + 5]
Loc(ARR[I][J]) = Ref. Address + W (( I – LR)*C + (J – = BaseAddress + 4[200 + 5]
LC)) = BaseAddress + 4 x 205
(where W=size of each element = 4 bytes, = BaseAddress + 820
R=Number of Rows =15, C=Number of Columns=20 BaseAddress = 15000- 820 = 14180
Reference Address= Address of given cell LOC(ARR[30][10])= 14180 + 4[30 * 20 + 10]
ARR[10][5]=35000 = 14180 + 4 * 610
LR = Row value of given cell = 10 = 14180 + 2440
LC = Column value of given cell = 5 = 16620
LOC(ARR[5][15]) = LOC(ARR[10][5]) + 4((5-10)*20 + OR
(15-5)) LOC(ARR[30][10])
LOC(ARR[5][15]) = 35000 + 4(-100 + 10) = LOC(ARR[10][5])+ W[( ILBR)*
= 35000 + 4[-90] C + (JLBC)]
= 35000 -360 = 15000 + 4[(3010)*
= 34640 20 + (105)]
4. R[10][50] is a two dimensional array, which is stored = 15000 + 4[ 20*20 + 5]
in the memory along the row with each of its element = 15000 + 4 *405
occupying 8 bytes, find the address of the element = 15000 + 1620
R[5][15], if the element R[8][10] is stored at the memory = 16620
location 45000. (2016) 3 OR
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 89 PRAISE THE LORD
Where C is the number of columns and LBR=LBC=1 B = 7950
LOC(ARR[10][5]) LOC (Arr [20] [50]) = 7950+(20*100+50)*2
15000 = BaseAddress + W [( I1)*C + (J1)] = 7950 + (2050*2)
= BaseAddress + 4[9*20 + 4] = 7950+4100
= BaseAddress + 4[180 + 4] = 12050
= BaseAddress + 4 * 184 OR
= BaseAddress + 736 Assuming LBR=LBC=1
BaseAddress = 15000- 736 = 14264 S=2 bytes
LOC(ARR[30][10]) Number of Rows (N) = 50
= 14264 + 4[(301)*20 + (101)] Number of Columns (M) =100
= 14264 + 4[29*20 + 9] LOC (Arr [I] [J])
= 14264 + 4[580 + 9] =B +((I-LBR)*M+(J-LBC))*S
= 14264 + 4*589 LOC (Arr [10] [25])
= 14264 + 2356 =B +((10–1)*100+(25–1))*2
= 16620 10000 = B +(900+24)*2
6.An array A[20][30] is stored along the row in the B = 10000-1848
memory with each element requiring 4 bytes of storage. B = 8152
If the base address of array A is 32000, find out the LOC (Arr [20] [50])
location of A[15][10]. Also find the total number of = 8152+ ((20-1)*100+ (50-1))*2
elements present in this array. (2014) = 8152 + (1949*2)
Answer) = 8152+3898
B=32000 W=4 =12050
A[15][10]=32000+4[30(15-0)+(10-0)] 10)An array Arr[15][20] is stored in the memory along
=32000 +4[450+10] the row with each element occupying 4 bytes. Find out
=32000+4[460] the Base address of the location Arr[3][2], if the location
=32000+1840 Arr[5][2] is stored at the address 1500. (2007OD)
=33840 Solution:
Location of a[10][15]=33840 Given Data: Arr[15][20] W=4 B=? R=15 C=20
Total number of elements present in this array = 20*30 = 600 Lr = 0 Lc = 0
7.An array T[15][10] is stored along the row in the Address of Arr[3][2] = ?
memory with each element requiring 8 bytes of storage. Address of Arr[5][2] = 1500.
If the base address of array T is 14000, find out the Address of an element (I,J) in row major
location of T[10][7]; (2013)3 = B+W(C(I-Lr)+(J-Lc))
Answer) Therefore,
Address of T[10][7]=14000+(10*7+10)*8 1500 = B+4(20(5-0)+(2-0))
=14000+(80)*8 1500 = B+4(20*5+2)
=14000+640 1500 = B+4*102
=14640 1500 = B+408
B =1500-408
8.An array G[50][20] is stored in the memory along B=1092
the row with each of its elements occupying 8 bytes. Address of Arr[3][2]
Find out the location of G[10][15], if G[0][0] is stored =1092+4(20*3+2)
at 4200. (2011 OD) 3 =1092+4(62)
Ans Assuming LBR=LBC=0 =1092+248
B=4200 =1340.
W=8 bytes 11)An array MAT[20][10] is stored in the memory along
Number of Rows(N)=50 the row with each element occupying 4 bytes of the
Number of Columns (M)=20 memory. Find out the Base address and the address of
LOC(Arr[I] [J]) = B +(I*M + J) *W element MAT[10][5] , if the location MAT[3][7] is stored
LOC (Arr [10] [15]) = 4200+ (10*20+15)*8 at the address 1000. (2006OD)
= 4200 + (215*8) Ans) For Row wise allocation
= 4200+1720 Address of A[I][J]
= 5920 = BA + W( (I-LBR) x N + (J-LBC))
9) An array Arr[50][10] is store in the memory along the Where
row with each element occupying 2 bytes. Find out the BA = Base Address
Base address of the location Arr[20][50], if the location W = Size of each element in bytes
Arr[10][25] is stored at the address 10000. (2008OD) = 4 bytes (given)
Ans) Assuming LBR=LBC=0 N = No. of columns in the 2D Array
S=2 bytes = 10 (given)
Number of Rows (N)=50 Address of MAT[3][7] given is 1000.
Number of Columns (M)=100 Therefore
LOC (Arr [I] [J]) = B + (I*M+J)*S (Assumption 1: LBR = LBC = 0)
LOC (Arr [10] [25]) = B +(10*100+25)*2 MAT[3][7]=100 = BA + 4 (10 (3-0) + (7-0))
10000 = B +(1000+25)*2 = BA + 148
B = 10000-2050 BA = 1000 – 148 = 852
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 90 PRAISE THE LORD
Therefore,Base Address = 852 OR
Thus, Address of MAT[10][5] = 852 + 4 ( 10 (10-0) + (5-0)) LOC(Arr[I][J])
= 852+420 =Base(Arr)+W*(No. of Cols*(I-1)+(J-1)
= 1272 LOC(Arr[2][2])
OR =Base(Arr)+4*(15*(2-1)+(2-1))
(Assumption 2: LBR = LBC = 1) 3000 =Base(Arr)+4*(16)
MAT[3][7]=1000 = BA + 4 (10 (3-1) + (7-1)) 3000 =Base(Arr)+64
= BA + 104 Base(Arr) =3000-64
BA = 1000 – 104 Base(Arr) =2936
= 896 LOC(Arr[20][5])
Therefore,Base Address = 896 =Base(Arr)+4*(15*(20-1)+(5-1))
Thus, Address of MAT[10][5] =2936+4*(289)
= 896 + 4 ( 10 (10-1) + (5-1)) =2936+1156
= 896+376 =4092
= 1272
12)An array Arr[15][35] is stored in the memory along 14)An array S[40][30] is stored in the memory along the
the row with each of its element occupying 4 bytes . Find row with each of the element occupying 2 bytes, find out
out the Base address and the address of element the memory location for the element S[20][10], if the
Arr[2][5] , if the location Arr[5][10] is stored at the Base Address of the array is 5000. 3 (MP109-10)
address 4000. (2005D) Ans)
Given,W=2
Ans) LOC(Arr[I][J] )
N=40
=Base(Arr)+W*(I + No.of Rows * J )
M=30
LOC(Arr[5][10])
Base(S)=5000
=Base(Arr)+8*(5+15*10)
4000 =Base(Arr)+8*(155)
Row Major Formula:
4000 =Base(Arr)+1240
Loc(S[I][J])
Base(Arr) =4000-1240
=Base(S)+W*(M*I+J)
Base(Arr) =2760
Loc(S[20][10])
LOC(Arr[2][5]) =Base(Arr)+8* (2 + 15*5)
=5000+2*(30*20+10)
=2760+8*(77)
=5000+2*(600+10)
=2760+616
=5000+1220
=3376
=6220
OR
LOC(Arr[I][J]) 15) An array S[40][30] is stored in the memory along the
=Base(Arr)+W*( (I-1) + No. of Rows * (J-l) ) row with each of the element occupying 2 bytes, find out
the memory location for the element S[20][10], if an
LOC(Arr[5][10])
element S[15][5] is stored at the memory location 5500.
=Base(Arr)+8*[(5-1)+15* (10-1)]
(MP108-09)4
4000 =Base(Arr)+8*(139)
4000 =Base(Arr)+1112 Ans)
Base(Arr) =4000-1112 Given,
Base(Arr) =2888 W=2 N=40 M=30
LOC(Arr[2][5]) Loc(S[15][5])=5500
=Base(Arr)+ 8*[(2-1)+15*(5-1)] Row Major Formula:
=2888+8*(61) Loc(S[I][J]) =Base(S)+W*(M*I+J)
=2888+488 Loc(S[15][5] =Base(S)+2*(30*15+5)
=3376 5500 =Base(S)+2*(450+5)
13)An array Arr[35][15] is stored in the memory along Base(S) =5500- 910
the row with each of its element occupying 4 bytes . Find Base(S) =4590
out the Base address and the address of element Loc(S[20][10]) =4590+2*(30*20+10)
Arr[20][5] , if the location Arr[2][2] is stored at the =4590+2*(600+10)
address 3000. (2005OD) =4590+1220
Ans) = 5810
LOC(Arr[I][J]) MODEL 3B: Address Calculation of 2-D array.
Base(Arr)+W*(No. of Cols*I+J) (Column-Major) (3
LOC(Arr[2][2]) =Base(Arr)+4*(15*2+2) Marks)
3000 =Base(Arr)+4*(32) 1. An array S[10] [30] is stored in the memory
3000 =Base(Arr)+128 along the column with each of its element
Base(Arr) =3000-128
Base(Arr) =2872
occupying 2 bytes. Find out the memory location
of S[5][10], if element S[2][15] is stored at the
LOC(Arr[20][5])
=Base(Arr)+4*(15*20+5)
location 8200. 2019SP3
=2872+4*(300+5) OPTION 1:
=2872+4*305 ASSUMING LBR=LBC=0
=2872+1220 W=2 BYTES, NUMBER OF ROWS(M)=10,
=4092 NUMBER OF COLUMNS(N)=30
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 91 PRAISE THE LORD
LOC(S[I][J]) = B +(I + J*M)*W = 7600 - 144
LOC(S[2][15]) = B +(2+15*10)* 2 = 7456
8200 = B + (152*2) OR
Assuming LBR=LBC=l
B = 8200 - 304 W=2 bytes
B = 7896 Number of Rows (M) = 20
LOC(S[5][10]) = 7896 +(5+10*10)* 2 Number of Co1umns (N) = 10
= 7896 + (105*2) LOC (T[I] [J]) = B +((I-LBR) + (J-LBC)*M)*W
= 7896 + 210 LOC (T[2] [9]) = B +((2-1) + (9-1)*20)* 2
= 8106 7600 = B + (161*2)
B = 7600 - 322
OPTION 2: B = 7278
ASSUMING LBR=2,LBC=15 AND B = 8200 LOC (T[10] [5]) = 7278 +((10-1)+(5-1)*20)* 2
W=2 BYTES, NUMBER OF ROWS(M)=10, = 7278 + (9+80) *2)
NUMBER OF COLUMNS(N)=30 = 7278 + 178
LOC(S[I][J]) = B +((I-LBR) + (J-LBC)*M)*W = 7456
LOC(S[5][10])= 8200 + ((5-2) + (10-15)*10)*2 4) An array P[50] [60] is stored in the memory along the
= 8200 + (3 + (-5)*10) * 2 column with each of the element occupying 2 bytes, find
out the memory location for the element P[10][20], if the
= 8200 + (3 + (-50)) * 2 Base Address of the array is 6800. (2010D)
= 8200 + (3 – 50) * 2 Ans)
= 8200 + (-47) * 2 Loc(P[I] [J]) = Base(P)+W(I+J*M)i Loc(P[10][20]) =
= 8200 – 94 Base(P)+2(10+20*50)
= 8106 Loc(P[10] [20]) = 68OO + 2(10+20*50)
2.An array P[30][20] is stored along the column in the = 6800 + 2 (10+1000)
memory witheach element requiring 2 bytes of storage. = 6800 + 2*1010
If the base address of the array P is 26500, find out the = 6800 + 2020
location of P[20][10]. (2016)3 = 8820
Total number of rows= 30 OR
Total size= 2 bytes Address of P[i] [j] = BaseAddress
Base Address= 26500 + W((i–L1)+(j–L2)*M)
LOC (P[I][J]) = BaseAddress+((I-LBR) + (J-LBC) * R)*W Address of P[10] [20]= 6800 +
Assuming Lower Bound of Row(LBR)=0 2((10-0)+(20-0)x50)
Lower Bound of Column(LBC)=0 = 6800 + 2 x 1010
Total number of Rows(R)=30 = 6800 + 2020
Size of each element(W)=2 = 8820
LOC(P[20][10])= 26500 +((20-0)+(10-0)*30)*2 OR
LOC(P[20][10])= 26500 +640 Address of P[I] [J] along the column
LOC(P[20][10])= 27140 = BaseAddress + W((I–LBR)+(J–
3) An array T[20][10] is stored in the memory along the LBC)*M)
column with each of the elements occupying 2 bytes. (where N is the number of rows, LBR = LBC = 1)
Find out the memory location of T[10][5], if the element Address of P[10][20]
T[2][9] is stored at the location 7600.(2012)3Ans =6800+2((10-1)+(20-l)x50)
Assuming LBR=LBC=0 = 6800 + 2 ( 9 + 19 x 50 )
W=2 bytes = 6800 + 2 x 959 = 6800 + 1918 = 8718
Number of Rows (M) =20 5) An array T[90][100] is stored in the memory along the
Number of Co1umns(N)=10 column with each of the elements occupying 4 bytes. Find
LOC(T[I] [J]) = B +(I + J*M)*W out the memory location for the element T[10][40], if the
LOC(T[2] [9]) = B +(2+9*20)* 2 Base Address of the array is 7200. (2010D)
7600 = B + (182*2) Ans.
B = 7600 - 364 Loc(T[I][J)) = Base(T)+W(I+J*N)
B = 7236 (where N is the number of rows, LBR = LBC = 0)
LOC (T[10] [5]) = 7236 +(10+5*20)* 2 = 7200 + 4[10 + 40 x 90]
= 7236 + (110*2) = 7200 + 4[10+3600]
= 7236 + 220 = 7200 + 4 x 3610
= 7456 = 7200 + 14440
OR = 21640
Assuming LBR=2, LBC=9 and B = 7600 OR
W=2 bytes Address of T[I][J] along the column
Number of Rows (M) = 20 = BaseAddress + W [(I-LBR)+(J-LBC)* N]
Number of Co1umns (N) = 10 (where N is the number of rows, LBR=LBC = 1)
LOC (T[I] [J]) = B + ((I-LBR) + (J-LBC)*M)*W
LOC (S[10] [5]) = 7600 + ((10-2) + (5-9)*20)*2 Address of T[10][40] = BaseAddress +
= 7600 + (8-80) * 2 4[ (10 - 1) +(40 - l)x 90]
= 7600 + (-72)) * 2 = 7200+4[9 + 39 x 90]

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 92 PRAISE THE LORD


= 7200+4[9 + 3510] Loc(T[30][15])
= 7200+4 x 3519 = 7700 + 4(30+15*50)
= 7200+14076 = 7700 + 4(30+750)
= 21276 = 7700 + 4*780
6) An array S[40][30] is stored in the memory along the = 7700 + 3120
column with each of the element occupying 4 bytes, find = 10820
out the base address and address of element S[20][15], if OR
an element S[15][10] is stored at the memory location Address of T[i][j]
7200. (2009 D) =BaseAddress + W [(i - L1) + (j - L2) * M]
Ans) Address of T[25] [10] =
Loc(S[I][J]) = Base(S)+W(I+J*N) BaseAddress + 4[(25 - 0)+(10 - 0)*50]
Loc(S[15][10]) = 9800 = Base Address + 4 [525]
Base(S)+4(15+10*40) Base Address = 9800 - 4 * 525
Base(S) = 7200-4*415 = 9800 - 21.00
Base(S) = 7200-1660 = 7700
Base(S) = 5540 Address of T[30][15]
Loc(S[20][15]) = =7700 + 4 [(30 - 0) + (15 - 0) x 50]
Base(S)+4(20+15*40) = 7700 + 4 x 780
Loc(S[20][15]) = 7700 + 3120
= 5540 + 4(20+15*40) = 10820
= 5540 + 4(20+600) OR
= 5540 + 4*620 Address of T[i][j] along the column
= 5540 + 2480 =Base Address+ W[( i - L1)+(j - L2)* M]
= 8020 Address of T[25][10]
OR =BaseAddress + 4[(25 - 1) +(10 -1)x50]
Address of S[i][j]=BaseAddress + 9800= Base Address + 4 [474]
W[(i-L1) + ( j - L2) *M] Base Address
Address of S[15] [10] = = 9800 - 4 x 474
BaseAddress+ 4[(15–0)+(10 - 0)*40] = 9800 - 1896
7200= Base Address + 4 [415] = 7904
Base Address = 7200 - 4 * 415 Address of T[30][15]
= 7200 - 1660 = 7904 + 4 [(30 - 1) + (15 - 1) x 50]
= 5540 = 7904 + 4 x 729
Address of S[20][15] = 7904 + 2916
= 5540 + 4 [(20 - 0) + (15 - 0) x 40] = 10820
= 5540 + 4 x 620 8) An array Arr[40][10] is store in the memory along the
= 5540 + 2480 column with each element occupying 4 bytes. Find out
= 8020 the base address of the location Arr[3][6] if the location
OR Arr[30][10] is stored at the address 9000. (2008D)
Address of Sri] [j] along the column = Solution:
Base Address + W [( i - L1) + (j - L2) * M] Address of Array[i][j] along the column =Base Address +
Address of S[15)[10] = W [( i - L1) + (j - L2) * M]
BaseAddress + 4[(15 - 1)+(10-1) x 40] where,
7200= Base Address + 4 [374] W = size of each location in bytes = 4
Base Address = 7200 - 4 x 374 L1 = Lower Bound of rows = 0
= 7200 - 1496 L2 = Lower Bound of columns = 0
= 5704 M = Number of rows per column = 40
Address of 5[20)[15]
= 5704 + 4 [(20 - 1) + (15 - 1) x 40] Address of Array[30][10]
= 5704 + 4 x 579 = Base Address + 4 * (30 + 10 * 40)
= 5704 + 2316 9000 = Base Address + 4 * 430
= 8020
7) An array T[50][20] is stored in the memory along the Base Address = 9000 - 4 x 430
column with each of the elements occupying 4 bytes. = 9000 -1720
Find out the base address and address of element = 7280
T[30][15], if an element T[25][10] is stored at the Address of Array[3][6]
memory location 9800. (2009 OD) = 7280 + 4 * (3 + 6 * 40)
Ans) = 7280 + 4 * 243
Loc(T[I][J]) = Base(T)+W(I+J*N) = 7280 + 972
Loc(T[25][10]) = Base(T)+4(25+10*50) = 8252
Base(T) = 9800-4*525 OR
Base(T) = 9800-2100 Address of Array[i][j] along the column = Base Address +
Base(T) = 7700 W (( i - L1) + (j - L2) * M)
Loc(T[30][15]) = where,W = size of each location in bytes = 4
Base(T)+4(30+15*50) L1 = Lower Bound of rows = 1

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 93 PRAISE THE LORD


L2 = Lower Bound of columns = 1 W = Size of each element in bytes
M = Number of rows per column = 40 = 8 bytes (given)
Address of Array[30][10] M = No. of rows in the 2D Array = 30
= Base Address + 4 * ((30 -1) +(10 -1) * 40) (given)
9000 = Base Address + 4 * (29+9*40) Address of MAT[5][7] given is 1000.
9000 = Base Address + 4 * (29+360) Assumption 1 : LBR=LBC=0
9000 = Base Address + 4 * (389) Therefore
Base Address 1000 = BA + 8 (7 × 30 + 5)
= 9000 - 4 * 389 = BA + 8 × 215 = BA + 1720
= 9000 -1556 BA = 1000 – 1720 = -720
= 7444 Therefore,Base Address = - 720
Address of Array[3][6] Thus, Address of MAT[20][5] = -720 + 8 ( 5 × 30 + 20)
= 7444 + 4 * ((3 -1) + (6 -1) * 40) = -720 + 8 × 170
= 7444 + 4 * (2+5 * 40) = -720 + 1360
= 7444 + 4 * (2+200), = 640
= 7444 + 4 * 202 Assumption 2 : LBR=LBC=1
= 7444 + 808 Therefore
= 8252 1000 = BA + 8 [(7-1) × 30 +(5-1)]
OR = BA + 8[6 × 30 + 4]
Address of Array[i][j] along the column =Address of = BA + 8 ×184
Array[x][y] + W [( i-x) + (j - y) * M] = BA + 1472
where, BA = 1000 – 1472 = -472
W = size of each location in bytes = 4 Therefore,Base Address = - 472
M = Number of rows per column = 40 Thus, Address of MAT[20][5]
i , j = Index value of the unknown element = -472 + 8 ( 4 × 30 + 19)
x , y = Index value of the known element = -472 + 8 × 139
Address of Array[3][6] = -472 + 1112
= Address of Array[30][10]+ 4 [(3 - 30) +(6 -10) * 40] = 640
= 9000 + 4 [-27 -160] 11) An array P[20][30] is stored in the memory along
= 9000 - 4 x 187= 9000 -748= 8252 the column with each of the element occupying 4 bytes,
9)An array Array[20][15] is stored in the memory along find out the Base Address of the array, if an element
the column with each element occupying 8 bytes. Find P[2][20] is stored at the memory location 5000.
out the base address of the element Array[2][3] if the Ans)Given, (MP209-10)3
element Array[4][5] is stored at the address 1000. W=4 N=20 M=30
(2007D) Loc(P[2][20]) =5000
Solution: Column Major Formula:
Given Data: Aray [20][15] W=8 B=? Loc(P[I][J]) = Base(P)+W*(N*J+I)
R=20 C=15 Lr = 0 Lc = 0 Loc(P[2][20]) = Base(P)+4*(20*20+2)
Address of Array [2][3] =? Base(P) = 5000 -4*(400+2)
Address of Array[4][5] =1000. =5000-1608
Address of an element (I,J) in column major =3392
=B + W ( (I-Lr) + R(J-Lc) ) 12) An array P[20][30] is stored in the memory along
Therefore the column with each of the element occupying 4 bytes,
1000=B+8*((4-0)+20(5-0)) find out the memory location for the element P[5][15], if
1000=B+8*(4+20*5) an element P[2][20] is stored at the memory location
1000 =B+8*104 5000. (MP208-09)4
1000=B+832 Ans) Given,
B =1000-832 W=4 N=20 M=30
B =168 Loc(P[2][20])=5000
Therefore Address of Column Major Formula:
Array[2][3]=168+8*((2-0)+20(3-0)) Loc(P[I][J])=Base(P)+W*(N*J+I)
=168+8*(2+20*3) Loc(P[2][20])=Base(P)+4*(20*20+2)5000
=168+8*62 =Base(P)+4*(400+2)
=168+496 Base(P) = 5000- 1608
=664 Base(P) = 3392
10) An array MAT[30][10] is stored in the memory Loc(P[5][15]) =3392+4*(20*15+5)
along column wise with each element occupying 8 bytes =3392+4*(300+5)
of the memory. Find out the Base address and the =3392+1220
address of element MAT[20][5] , if the location =4612
MAT[3][7] is stored at the address 1000. (2006D) 13) An array ARR[5][5] is stored in the memory with
Ans) For Column wise allocation each element occupying 3 bytes of space. Assuming the
Address of A[I][J] base address of ARR to be 1500, compute the address of
= BA + W[ (J –LBC) x M + (I - LBR)] ARR[2][4], when the array is stored: (2004)
Where Solution: Children, Try this answer as an assignment.
BA = Base Address
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 94 PRAISE THE LORD
14)An array X[30][10] is stored in the memory with
each element requiring 4 bytes storage. Find out the
Base address of X is 4500, find out memory locations of
X[12][8] and X[2][14], if the content is stored along the
row. (2003)
Solution: Children, Try this answer as an assignment.
15) The array A[20][10] is stored in the memory with
each element requiring one byte of storage if the base
address of a is 0, determine the location of A[10][5]
when the array A is stored by column major. (2002)
Solution: Children, Try this answer as an assignment.
16) An array X[10][20] is stored in the memory with
each element requiring 4 bytes of storage. If the Base
address of the array is 1000, calculate location of
X[5][15] when the array X is stored using column major
Ans)
order. (2001) void SORTPOINTS(Game G[], int N)
NOTE: X[10][20] means valid row indices are 0 and 9 and
{ Game Temp;
valid column indices are 0 and 19
for (int I = 0; I<N-l; I++)
Solution: Children, Try this answer as an assignment.
for (int J = 0; J<N-I-l; J++)
17) An array VAL[1…15][1…10] is stored in the if(G[J].Points < G[J+l].Points)
memory with each element requiring 4 bytes of storage. {
If the base address of the array VAL is 1500, determine Temp = G[J];
the location of VAL[12][9] when the array VAL is G[J] = G[J+l];
stored (i) Row wise (ii) Column wise. (2000) G[J+l] = Temp;
Solution: Given Data:
}
VAL[1…15][1…10]
}
Word Length (W) = 4 Bytes
2) Write a function SORTSCORE( ) in C++ to sort an
Base Address of VAL(B) = 1500
array of structure Examinee in descending order of
VAL[12][9] = ?
Score using Bubble Sort. (2009 OD)
C = Total No of Columns
Note: Assume the following definition of structure
R = Total No of Rows
Examinee
Lr = Least Row=1
struct Examinee
Lc = Least Column=1
{ long RollNo;
( i ) Row Major:
char Name[20] ;
Address of an element (I,J) in row major float Score;
= B + W ( C (I-Lr) + (J – Lc))
};
VAL [12][9] = 1500 + 4 (10 * (12-1) + (9-1))
= 1500 + 4 (10 * 11+8)
= 1500 + 4 (118)
= 1500 + 472
( i ) Column Major:
Address of an element (I,J) in column major
= B + W ( (I-Lr) + R(J – Lc))
VAL [12][9] = 1500 + 4 ((12-1) +15 * (9-1))
= 1500 + 4 (11 + 15 * 8)
= 1500 + 4 ( 11+ 120)
= 1500 + 4 * 131
= 1500 + 524
= 2024.
18) An array A[10][20] is stored in the memory with each
element requiring 4 bytes of storage. If the base address of the
array in the memory is 400, determine the location of A[8][13]
when the array VAL is stored (i) Row major (ii) Column
major. Ans)
Solution: Children, Try this answer. void SORTSOORE (Examinee E[ ], int N)
{ Examinee Temp;
MODEL 4: Sorts & Search for (int I = 0; I<N-l; I++)
1) Write a function SORTPOINTS( ) in C++ to sort an for (int J = 0; J<N-I-l; J++)
array of structure Game in descending order of Points if(E[J].Score < E[J+l].Score)
using Bubble Sort. (2009 D) { Temp = E[J];
Note: Assume the following definition of structure Game E[J] = E[J+l];
struct Game E[J+l] = Temp;
{ long PNo; //Player Number }
char PName [20] ; }
long Points;
};
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 95 PRAISE THE LORD
3)Assume a array E containing elements of structure void MERGE(int X[ ], intm,int Y[ ], intn,int Z[ ])
Employee is required to be arranged in descending { intmn,i,,left=0,right=mn-1;
order of Salary. Write a C++ function to arrange same mn=m+n;
with the help of bubble sort, the array and its size is for(i=0;i<m;i++)
required to be passed as parameters to the function. if (X[i]%2= = 1)
Definition of structrure Employee is as follows: (2003) Z[left++]=X[i];
Struct Employee //For copying odd numbers of
{ intEno; //X into Z from left to right else
char name[25]; Z[right- -]=X[i];
float Salary; //For copying even number of
}; //X into Z from right to left
Solution: for(i=0;i<n;i++)
void bubble(Employee E[ ],int n) if (X[i]%2= = 1)
{ inti,j; Z[left++]=Y[i];
Employee Etemp; //For copying odd numbers of
for(i=0;i<n;++i) //Y into Z from left to right
for(j=0;j<(n-1)-i ;j++) else
if(E[j].salary<E[j+1].salary) Z[right- -]=Y[i];
{ Etemp=E[j]; //For copying even number of
E[j]=E[j+1]; // X into Z from right to left
E[j+1]=temp; }
} 6) Suppose A, B, C are arrays of integers of size M, N and
cout<<"The details of the employee in ascending order of salary "; M+N respectively. The numbers in array A appear in
for(i=0;i<n;i++) ascending order while numbers in array in descending
cout<<E[i].Eno<<'\t'<<E[i].name<<‟\t<<E[i].Salary<<endl; order. Write user defined function in C++ to produce third
} array C by merging array A by B in ascending order. Use
4) Considering the following key set: 42,29,74,11,65,58, A, B and C as arguments in the function. (2000)
use insertion sort to sort the data in ascending order and void Merge(int A[ ],intM,int B[ ], intN,int C[ ])
indicate the sequences of steps required. (2002) { inta,b,c;
Solution: for(a=0,b=N-1,c=0;a<M&&b>=0;)
In this, Suppose an array A with n elements { if(A[a]<=B[b])
A[1],A[2],…A[N] is in memory. The insertion sort C[c++]=A[a++];
algorithm scans A from A[1] to A[N], insertion each else
element A[K] into its proper position in the previously C[c++]=B[b--];
sorted subarray A[1],A[2],…,A[K-1]. }
This sorting algorithm is frequently used when n is small. if(a<M)
The array contains 6 elements as follows: { while(a<M)
42,29,74,11,65,58 C[c++]=A[a++];
}
Pass A[0] A[1] A[2] A[3] A[4] A[5] A[6] else
K=1 -32768 42 29 74 11 65 58 { while(b>=0)
K=2 -32768 42 29 74 11 65 58 C[c++]=B[b--];
K=3 -32768 29 42 74 11 65 58 }
K=4 -32768 29 42 74 11 65 58 }
K=5 -32768 11 29 42 74 65 58 7) Suppose a 1D array AR containing integers is
K=6 -32768 11 29 42 65 74 58 arranged in ascending order. Write a user defined
Sort -32768 11 29 42 58 65 74 function in C++ to search for one integer from AR with
ed the help of binary search method, to show presence of
5) Given two arrays of integers X and Y of sizes m and n the number in the array. The function should have three
respectively. Write a function named MERGE() which parameters: (1) an array AR (2) the number to be
will third array named Z, such that the following searched and (3) the number of elements N in the array.
sequence is followed.(2001) void BinSearch(int AR[ ], intSno, int N)
(i) All odd numbers of X from left to right are copied { int l=0,u=N-1,m,flag=0;
into Z from left to right. while(l<=u)
(ii) All even numbers of X from left to right are copied { m=(l+u)/2;
into Z from right to left. if (Sno= = AR[m])
(iii) All odd numbers of Y from left to right are copied { flag=1;
into Z from left to right. break;
(iv) All even numbers of Y from left to right are copied }
into Z from right to left. else if(Sno<AR[m])
X, Y and Z are passed as arguments to MERGE( ). u=m-1;
Eg. X is {3, 2, 1, 7, 6, 3} and {9, 3, 5, 6, 2, 8, 10} else
The resultant array Z is l=m+1;
{3, 1, 7, 3, 9, 3, 5, 10, 8, 2, 6, 6, 2} }
Ans) if( flag = = 0)

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 96 PRAISE THE LORD


cout<<”\nThe Search Element “ else
<<Sno<<” is not available”; { C[K++]=A[I++];
else J--;
cout<<”\nThe Search Element “ }
<<Sno<<” is available”; }
} for (int T=I;T<N;T++)
8) Suppose an array P containing float is arranged in C[K++]=A[T];
ascending order. Write a user defined function in C++ for (T=J;T>=0;T--)
to search for one float from p with the help of binary C[K++]=B[T];
search method. The function should return an integer 0 }
to show absence of the number in the array. The
function should have the parameters as (1) an array P MODEL 5:Theory / Mislleneous
(2) the number DATA to be searched (3) number of 1) Define array and pointer. (2002)
elements N. (1998) Solution: An array refer to a named list of a finite number
intBinSearch(float P[ ], float DATA, int N) n of similar data elements. Each of the data elements can
{ int l=0,u=N-1,m; be referenced respectively by a set of consecutive numbers.
while(l<=u) Arrays can be one dimensional, two dimensional or multi
{ m=(l+u)/2; dimensional.
if (DATA= = P[m]) An array can be declared as :
return 1; Syntax:data_typeArray_name[size];
else if(DATA<P[m])
u=m-1; Eg:int A[10]; //Then location of
else //the array are A[0], A[1],…….A[9].
l=m+1; int B[5][4]; //This array can holds 5 X 4 = 20 elements.
}
return 0;
}
9) Write a function in C++ to merge the contents of two
sorted arrays A & B into third array C. Assuming array
A and B are sorted in ascending order and the resultant
array C is also required to be in ascending order.
Ans) (MP109-10)3
void AddNSave(int A[ ],int B[ ],int C[ ],
intN,int M, int&K)
{ int I=0,J=0;
K=0;
while (I<N && J<M)
if (A[I]<B[J])
C[K++]=A[I++];
else if (A[I]>B[J])
C[K++]=B[J++];
else
{
C[K++]=A[I++];
J++;
}
for (;I<N;I++)
C[K++]=A[I];
for (;J<M;J++)
C[K++]=B[J];
}
10. Write a function in C++ to merge the contents
of two sorted arrays A & B into third array C.
Assuming array A is sorted in ascending order, B is
sorted in descending order, the resultant array is
required to be in ascending order. (MP108-09) 4
Answer:
void AddNSave(int A[],int B[],int C[],intN,int M, int&K)
{ int I=0,J=M-1;
K=0;
while (I<N && J>=0)
{ if (A[I]<B[J])
C[K++]=A[I++];
else if (A[I]>B[J])
C[K++]=B[J--];
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 97 PRAISE THE LORD
10. LINKED LISTS , STACKS AND QUEUES case „P‟ : ST.Push( ); break;
case „O‟ :ST.Pop(); break;
MODEL 1: Program on Stack case „D‟ :ST.Disp();
}
1) Write a complete program in c++ to implement a } while (Ch!=‟Q‟);
dynamically allocated Stack containing names of }
Countries. (D 2010)
Ans) 2)Each node of a STACK contains the following
#include<iostream.h> information, in addition to pointer field: (2001)
#include<stdio.h> (i).Pin code of city
struct Node (ii).Name of city
{ char Country [20] ; Give the structure of node for the linked STACK in
Node *Link; question. TOP is a pointer that points to the topmost node
}; of the STACK. Write the following functions:4
class Stack a)PUSH( ) – To push a node into the STACK, which is
{ allocated dynamically.
Node *Top; b)POP( ) – To remove a node from the STACK, and
public: release the memory.
Stack( ) Solution:
{ Top = NULL; struct City
} { longCpin ;
void Push() ; charCName[20] ;
void Pop() ; City *Next ;
void Display() ; };
~Stack () ; class Stack
}; { City *Top;
void Stack::Push( ) public:
{ Node *Temp = new Node; Stack( ) { Top = NULL; }
gets(Temp -> Country); void Push( );
Temp -> Link = Top; void Pop( );
Top = Temp; void Display( );
} };
void Stack::Pop( ) void Stack::PUSH( )
{ if (Top !=NULL) { City *Temp;
{ Node *Temp = Top; Temp=new City;
Top = Top -> Link; if(Temp= =NULL)
delete Temp; { cout<<”\nNo memory to create the node…”;
} exit(1);
else }
cout<<“stack Empty”; cout<<”\nEnter the City Pin Code to be inserted: “;
} cin>>TempCpin;
void Stack::Display( ) cout<<”\nEnter the City Name to be inserted: “;
{ gets(TempCName);
Node *Temp = Top; TempNext=Top;
while (Temp! = NULL) Top=Temp;
{ }
cout<<Temp -> Country <<endl; void Stack::POP( )
Temp = Temp -> Link; { City *Temp;
} if( Top= = NULL)
} cout<<”Stack Underflow…”;
Stack::~Stack ( ) else
{ while (Top!=NULL) { cout<<”\nThe City Pin Code for the element to delete:
{ NODE *Temp=Top; “<<TopCpin;
Top=Top->Link; cout<<”\nThe City name of the element
delete Temp; to delete: “<<TopCName;
} Temp=Top;
} Top=TopNext;
void main ( ) delete Temp;
{ Stack ST; }
char Ch; }
do
{ cout<<“p/O/D/Q” ;
cin>>Ch;
switch (Ch)
{
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 98 PRAISE THE LORD
3. Write the definition of a member function PUSH() in
MODEL 1A: Stack (Insert – Push) C++, to add a new book in a dynamic stack of BOOKS
considering the following code is already included in the
1.Write the definition of a member function program: (2015) 4
PUSHGIFT() for a class STACK in C++, to add a GIFT struct BOOKS
in a dynamically allocated stack of GIFTs considering { char ISBN[20], TITLE[80];
the following code is already written as a part of the BOOKS *Link;
program: (2017) 4 };
struct GIFT class STACK
{ int GCODE; //Gift Code { BOOKS *Top;
char GDESC[20]; //Gift Description public:
GIFT *Link; STACK()
}; { Top=NULL;
class STACK }
{ Gift *TOP; void PUSH();
public: void POP();
STACK(){TOP=NULL;} ~STACK();
void PUSHGIFT(); };
void POPGIFT(); A)
~STACK(); void STACK::PUSH()
}; {BOOKS *Temp;
Ans) Temp=new BOOKS;
void STACK::PUSHGIFT() gets(Temp>ISBN);
{ GIFT *T = new GIFT; gets(Temp>TITLE);
cin>>T->GCODE; Temp>Link=Top;
gets(T->GDESC); Top=Temp;
T->Link = TOP; }
TOP = T; 4.Write a function PUSHBOOK( ) in C++ to perform
} insert operation on a Dynamic Stack, which contains
2.Write the definition of a member function push() for a Book_No and Book_Title. Consider the following
class Library in C++ to insert a book information in a definition of NODE, while writing your C++ code.(2014)
dynamically allocated stack of books considering the Struct NODE
following code is already written as a partof the {intBook_No;
program: (2017MP)4 charBook_Title[20];
struct book NODE *Next;
{ int bookid; };
char bookname[20]; Answer)
book *next; voidPOPBook( )
}; { NODE *P=new NODE;
class Library cout<<”Enter Book No, and Book Title”;
{ book *top; cin>>p->Book_No;
public: gets(PBook_Title);
Library() if(top= = NULL)
{ top=NULL; pNext=NULL;
} top=p;
void push(); else
void pop(); { pNext=top;
voiddisp(); top=p;
~Library(); }
}; }
Ans) 5) Write a function in C++ to perform PUSH operation on a
void Library::push() dynamically allocated stack containing real numbers.
{ book *nptr; struct Node (D 2006)
nptr=new book; { float Number ;
cout<<"Enter values for bookid and bookname"; Node *Link ;
cin>>nptr->bookid; };
gets(nptr->bookname); class STACK
nptr->next=NULL; { Node *Top ;
if(top= =NULL) public :
top=nptr; STACK( )
else { Top = NULL;
{ nptr->next=top; }
top=nptr; void PUSH( ) ;
} void POP( ) ;
} ~STACK( ) ;

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 99 PRAISE THE LORD


}; cout<<”\nNo memory to create the node…”;
Solution: exit(1);
struct Node }
{ cout<<”Enter the value of X and Y”;
float Number ; cin>>TempX>>TempY;
Node *Link ; TempLink=Top;
}; Top=Temp;
class STACK }
{ 7) Write a function in C++ to perform Push operation on a
Node *Top ; dynamically allocated Stack containing real numbers.
public : Ans) (MP208-09) (MP209-10)4
STACK( ) struct NODE
{ Top = NULL; { float Data;
} NODE *Link;
void PUSH( ) ; };
void POP( ) ; class STACK
~STACK( ) ; { NODE *Top;
}; public:
void STACK::PUSH( ) STACK( );
{ Node *Temp; void Push();
Temp=new Node; void Pop();
if(Temp= =NULL) void Display();
{ cout<<”\nNo memory to create the node…”; ~STACK();
exit(1); };
} void STACK::Push()
cout<<”\nEnter the Number to be inserted: “; {NODE *Temp;
cin>>TempNumber; Temp=new NODE;
TempLink=Top; cin>>Temp->Data;
Top=Temp; Temp->Link=Top;
} Top=Temp;
6) Write a function in C++ to perform a PUSH operation in }
a dynamically allocated stack considering the following : MODEL 1B: Stack (Delete – Pop)
struct Node (O2005) 1. Write a function in C++ to delete a node
{int X,Y ;
Node *Link ;
containing Books information ,from a
}; dynamically allocated stack of Books
class STACK implemented with the help of the following
{Node *Top ; structure: 2019MP4
public : struct Book
STACK( ) { int BNo;
{Top = Null ;} char BName[20];
void PUSH( ) ;
void POP( ) ; Book *Next;
~STACK( ) ; };
}; Answer:
Solution: struct Book
struct Node { int BNo;
{int X,Y ; char BName[20];
Node *Link ; Book *Next;
};
}*temp,*top;
class STACK
{ Node *Top ; void pop()
public : { temp=new Book ;
STACK( ) temp=top;
{ Top = NULL; top=top->next;
} delete temp;
void PUSH( ) ; }
void POP( ) ;
2)Write a function in C++ to delete a node containing
~STACK( ) ;
Book‘s information, from a dynamically allocated Stack
};
of Books implemented with the help of the following
void STACK::PUSH( ) structure. (D 2007)
{Node *Temp; struct Book
Temp=new Node; { int BNo ;
if(Temp= =NULL) char BName[20] ;
{ Book *Next ;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 100 PRAISE THE LORD
}; MODEL 1D: Stack (Using Arrays)
Solution: 1) Introduction (OD2006)
struct Book class stack
{ int BNo ; { int data[10] :
char BName[20] ; int top ;
Book *Next ; public :
}; stack( )
class Stack { top = - 1;
{ Book *Top; }
public: void push( ) ; //to push an element into the stack
Stack( ) void pop( ) ; //to pop an element from the stack
{ Top = NULL; void Delete(int ITEM) ;
} //To delete all elements which are equal to ITEM.
void Push( ); };
void Pop( ); Complete the class with all function definitions. Use
void Display( ); another stack to transfer data temporarily.
};
void Stack::Pop( ) Solution:
{ Book *Temp; void stack::push( )
if( Top= = NULL) { if(top>=9)
cout<<”Stack Underflow…”; cout<<”Stack Overflow…”;
else else
{cout<<”\nThe Book number of the { top++;
element to delete: “<<TopBNo; cout<<”\nEnter the element to be inserted…”;
cout<<”\nThe Book name of the cin>>data[top];
element to delete: “<<TopBName; }
Temp=Top; }
Top=TopNext; void stack::pop( )
delete Temp; { if(top= =-1)
} cout<<”\nStack Underflow”;
} else
3) Give the necessary declaration of a linked {cout<<”\nThe element to be deleted = “<<data[top];
implemented stack containing integer type numbers; top--;
also write a user defined function in C++ to pop a }
number from this stack. (1998) }
Solution: void stack::Delete(int ITEM)
struct Node { //Dear children, try to complete this function.
{ float Number; }
Node *Next ; OR
}; void stack::push( )
class Stack { int n;
{ Node *Top; cout<<”Enter a value”;cin>>n;
public: if (top==10)
Stack( ) cout<<”Stack Overflow”;
{ Top = NULL; else
} data[++top]=n;
void Push( ); }
void Pop( ); void stack::pop( )
void Display( ); { if (top==-1)
}; cout<<”Stack Underflow”;
void Stack::Pop( ) else
{ Node *Temp; cout<<data[top--];
if( Top= = NULL) }
cout<<”Stack Underflow…”; void stack::Delete(int ITEM);//Ignore this part
else 2) Given the following class, (2002)4
{cout<<”\nThe Number of the element to delete: “ char *msg[ ]={“over flow”,”under flow”};
<<TopNumber; class Stack
Temp=Top; { int top; //the stack pointer
Top=TopNext; int stk[5]; //the elements
delete Temp; voiderr_rep(inte_num)
} { cout<<msg[e_enum]; //report error message
} }
public:
voidinit( )
{ top=0;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 101 PRAISE THE LORD
} //initialize the stack pointer Temp=Temp->Next;
void push(int); //put new value in stk }
void pop( ); //get the top value. }
}; Queue:: ~Queue( )//Destructor Function
Define pop outside the Stack. In your definition take care { while (Front!=NULL)
of under flow condition. Function pop should invoke { NODE *Temp=Front;
err_rep to report under flow. Front=Front->Next; delete Temp;
Solution: }
void Stack::pop( ) }
{ //Dear children, try to complete this function. void main( )
{ Queue QU;
} char Ch;
do
MODEL 2: Program on Queue {
:
1) Write a complete program in C++ to implement a
:
dynamically allocated Queue containing names of Cities.
} while (Ch!=‟Q‟);
Ans) (OD2010)4
}
#include <iostream.h>
2)Define member functions queins( ) to insert nodes and
#include <conio.h>
quedel ( ) to delete nodes of the linked list implemented
struct NODE
class queue, where each node has the following structure:
{ char City[20];
struct node (2004)
NODE *Next;
{ char name[20] ;
};
int age ;
class Queue
node *Link ;
{ NODE *Rear,*Front;
};
puplic:
class queue
Queue( )
{
{ Rear=NULL;Front=NULL;
node *rear, *front ;
}
public :
voidQinsert( );
queue( )
voidQdelete( );
{ rear = NULL; front = NULL} ;
voidQdisplay( );
voidqueins( ) ;
~Queue( );
voidquedel( ) ;
};
};
void Queue::Qinsert( )
Solution:
{ NODE *Temp;
void queue::queins( )
Temp=new NODE;
{
cout<<”Data:”;
node *ptr;
gets (Temp->City);
ptr=new node;
Temp->Next=NULL;
if(ptr= = NULL)
if (Rear==NULL)
{cout<<”\nNo memory to create a new node….”;
{ Rear=Temp;
exit(1);
Front=Temp;
}
}
cout<<”\nEnter the name….”;
else
gets(ptrname);
{ Rear–>Next=Temp;
cout<<”\nEnter the age…”;
Rear=Temp;
cin>>ptrage;
}
ptrLink=NULL;
}
if(rear= = NULL)
void Queue::Qdelete( )
front=rear=ptr;
{ if (Front!=NULL)
else
{ NODE *Temp=Front;
{rearLink=ptr;
cout<<Front->City<<”Deleted \n”;
rear=ptr;
Front=Front->Next;
}
delete Temp;
}
if (Front==NULL)
void queue::quedel( )
Rear=NULL;
{node *temp;
}
if(front= = NULL)
else
cout<<”Queue Underflow”;
cout<<”Queue Empty..”;
else
}
{cout<<”\nThe name of the element to delete: “
Queue::Qdisplay( )
<<frontname;
{ NODE *Temp=Front;
cout<<”\nThe age of the element to
while (Temp!=NULL)
delete: “<<frontage;
{ cout<<Temp->City<<endl;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 102 PRAISE THE LORD
temp=front; void Queue::QUEINS( )
front=frontLink; { Node *Temp;
delete temp; Temp = new Node;
} cin>>Temp->PId;
} gets(Temp->Pname);
//Or cin>>Temp->Pname;
MODEL 2A: Queue (Insert) //cin.get1ine(Temp->Pname);
Temp->Next = NULL;
1) Write a function in C++ to perform Insert operation in a if (Rear = = NULL)
static circular Queue containing Book's information { Front = Temp;
(represented with the help of any array ofstructure BOOK) Rear = Temp;
struct BOOK (2012) 4 }
{longAccno; //Book Accession Number e1se
char Title [20] //Book Title { Rear->Next = Temp;
}; Rear = Temp;
Ansconstint Max = 10; }
void insert(Book B[], int&a, int F) } OR
{if ( (R+l) %Max! =F) void QUEINS (Node *&Front, Node *&Rear)
{ R= (R+l) %Max; { Node *Temp = new Node;
cin>>B [R] . Accno; cin>>Temp->PId;
//cin>>B[R].Title OR cin.getline(B[R] .Title,20); OR gets (Temp->Pname);
gets(B[R].Title) ; //or cin>>Temp->Pname;
} //cin.get1ine(Temp->Pname);
else Temp->Next = NULL;
cout<<"Queue Full"; if(Rear == NULL)
} OR Front = Temp;
constintmax =10; e1se
void insert( long newAC, char newTitle[], Book B [], Rear -> Next = Temp;
int&F,int&R) Rear = Temp;
{if ( (F = 0 && R=max-l) II (F=R+l)) }
cout<<"Queue Overflow"; 3) Write a function in C++ to insert an element into a
else dynamically allocated Queue where each node contains a
{ if (R -1) name (of type string) as data. (D 2008) (OD2006) (2000)
F=0; R=0; Assume the following definition of THENODE for the
else if (R = max-i) same.
R = 0; struct THENODE
else { char Name[20];
R = R + 1; THENODE *Link;
B[R].Accno = newAC;//oRcin>>B[R].Accno; };
strcpy(B[R].Title, newTitle); Solution:
// OR gets(B[R].Title); OR cin>>B[R].Title OR struct THENODE
//cin.getline(B[R].Title,20) ; { char Name[20];
} THENODE *Link;
} };
2) Write a function QUEINS( ) in C++ to insert an element class Queue
in a dynamicallyallocated Queue containing nodes of the { THENODE *front,*rear;
following given structure: (D 2009) 4 public:
struct Node Queue( )
{ {front = rear = NULL;
intPId ; //Product Id }
charPname [20] ; void Insert( );
NODE *Next ; void Delete( );
}; void Display( );
Ans) };
class Queue void Queue::Insert( )
{ Node *Front, *Rear; { THENODE *ptr;
public: ptr=new THENODE;
QUEUE( )//Constructor to initia1ize Front and Rear if(ptr= = NULL)
{ Front = NULL; { cout<<”\nNo memory to create a new node….”;
Rear = NULL; exit(1);
} }
void QUEINS( ); //Function to insert a node cout<<”\nEnter the name….”;
void QUEDEL( ); //Function to de1ete a node gets(ptrName);
void QUEDISP( );//Function to disp1ay nodes ptrLink=NULL;
~Queue( ); //Destructor to de1ete a11 nodes if(rear= = NULL)
};
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 103 PRAISE THE LORD
front=rear=ptr; if (Rear==NULL)
else { Rear=Temp;
{ rearLink=ptr; Front=Temp;
rear=ptr; }
} else
} { Rear->Link=Temp;
4)Consider the following portion of a program, which Rear=Temp;
implements passengers Queue for a train. Write the }
definition of function. Insert (whose prototype is shown }
below); to insert a new node in the queue with required MODEL 2B: Queue (Delete)
information. (2003)
struct NODE 1) Write the definition of a member function
{ long Ticketno; AddPacket( ) for a class QUEUE in C++, to
char PName[20];//Passengers Name remove/delete a Packet from a dynamically allocated
NODE * Next; QUEUE of Packets considering the following code is
}; already written as a part of the program. 2018 (4)
classQueueoftrain (Note: In the given problem, we should write a function
{ NODE * Rear, * Front; to remove/delete a packet with function name
public : AddPacket() )
Queueoftrain( ) struct Packet
{ Rear = NULL; Front = NULL: { int PID;
} char Address[20];
void Insert( ); Packet *LINK;
void Delete( ); };
~Queueoftrain( ); class QUEUE
}; { Packet *Front, *Rear;
Solution: public:
voidQueueoftrain::Insert( ) QUEUE( )
{ NODE *ptr; { Front = NULL; Rear = NULL;
ptr=new NODE; }
if(ptr= = NULL) void AddPacket( );
{ cout<<”\nNo memory to create a new node….”; void DeletePacket( );
exit(1); ~QUEUE( );
} };
cout<<”\nEnter the Ticket Number….”; Answer:
cin>>ptrTicketno; void QUEUE::AddPacket()
cout<<”\nEnter the Passenger Name..”; {if( Front !=NULL)
gets(ptrPName); { Packet *T = Front;
ptrNext=NULL; cout<<Front  PID<<Front Address<<” is
if(rear= = NULL) removed”<<endl;
front=rear=ptr; //OR cout<<T->PID<<T->Address<<" removed"<<endl;
else Front= FrontLINK;
{ rearNext=ptr; delete T;
rear=ptr; if(Front = = NULL)
} { Rear=NULL;
} }
5) Write a function in C++ to perform Insert operation in a }
dynamically allocated Queue containing names of students. else
Ans) (MP108-09)(MP109-10)4 cout<<”Queue Empty”<<endl;
struct NODE }
{ char Name[20]; 2. Write the definition of a member function DELETE()
NODE *Link; for a class QUEUE in C++, to remove a product from a
}; dynamically allocated Queue of products considering
class QUEUE the following structure. (2016) (2013) (2011 OD) (OD
{ NODE *R,*F; 2009) (OD 2007) 4
public: struct PRODUCT
QUEUE(); {int PID;
void Insert(); char PNAME[20];
void Delete(); PRODUCT *Next;
}; };
void QUEUE::Insert() A)
{ NODE *Temp; class QUEUE
Temp=new NODE; { PRODUCT *R,*F;
gets(Temp->Name); public:
Temp->Link=NULL; QUEUE()

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 104 PRAISE THE LORD


{R=NULL;F=NULL;} public:
void INSERT(); CQUEUE( )
void DELETE(); { Front = -1;
~QUEUE(); Rear=-1;
}; }
void QUEUE::DELETE() void Ins_Player(); // To add player in a static circular queue
{if( F!=NULL) void Del_Player(); // To remove player from a static
{ PRODUCT *T = F; circular queue
cout<<T  PID<<T PNAME; void Show_Player(); // To display static circular queue
F= F Next; };
delete T; Answer:
if(F==NULL) void CQUEUE : : Ins_Player( )
{ R=NULL; { if((Front==0 && Rear==size-1) || (Front==Rear+1)
} { cout<< “Overflow”;
} return;
else }
cout<<”Queue Empty”; else if(Rear = = -1)
} { Front=0;
3) Write a function in C++ to perform a DELETE Rear=0;
operation in a dynamically allocated queue considering }
the following description : (OD 2008) (1999) (OD2005)4 else if(Rear= =size-1)
struct Node { Rear=0;
{ float U, V ; }
Node *Link ; else
}; { Rear++;
class QUEUE }
{ Node *Rear, *Front ; cout<< “Enter Player Id=”;
public : cin>>Ar[Rear].Pid;
QUEUE( ) cout<< “Enter Player Name=”;
{ Rear = NULL; gets(Ar[Rear].Pname);
Front = NULL; }
}
void INSERT( ) ; 2) (D 2006)
void DELETE( ) ; class queue
~ QUEUE( ) ; {
}; int data[10] ;
Solution: int front, rear;
void Queue::DELETE( ) public :
{ NODE *temp; queue( )
if(front= = NULL) {
cout<<”\nQueue Underflow”; front = - 1;
else rear = - 1 ;
{cout<<”\nThe value of U of the element to delete: “ }
<<FrontU; void add( ); //to add an element into the queue
cout<<”\nThe value of V of the element to delete: “ void remove( ); //to remove an element from the queue
<<FrontV; void Delete(int ITEM( );
temp=Front; //to delete all elements which are equal to ITEM
Front=FrontLink; };
delete temp; Complete the class with all function definitions for a
} circular array Queue. Use another queue to transfer data
} temporarily.
MODEL 2D: Queue (Using Arrays) Solution:
void queue::add( )
1. Write the definition of a member function
{if((front= = 0 && rear = = 9) | | (front= =rear+1)
Ins_Player() for a class CQUEUE in C++, to add a
cout<<”\nQueue Overflow”;
Player in a statically allocated circular queue of
else if (rear= = -1)
PLAYERs considering the following code is already
{front=rear=0;
written as a part of the program: 2019MP4
cout<<”\nEnter the element to be inserted”;
struct Player
cin>>data[rear];
{ long Pid;
}
char Pname[20];
else if(rear= =9)
};
{rear=0;
const int size=10;
cout<<”\nEnter the element to be inserted”;
class CQUEUE
cin>>data[rear];
{ Player Ar[size];
}
int Front, Rear;
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 105 PRAISE THE LORD
else else
{ rear++; {cout<<”\nEnter an item to add : “;
cout<<”\nEnter the element to be inserted”; cin>>item;
cin>>data[rear]; if(front==-1)
} { front=0;rear=0;
} }
void queue::remove( ) else
{ if(front= = -1) rear=rear+1;
cout<<”\nQueue Underflow…”; if(rear==10)
else rear=0;
{cout<<”\nThe element to be deleted” <<data[front]; data[rear]=item;
if(front= =rear) }
front=rear=-1; } OR
else if (front= =9) void queue::remove( )
front=0; { if((front==-1 )
else cout<<”\nQueue Underflow Error”;
front++; else
} { int item=data[front];
} if(front==rear)
void queue::Delete(int ITEM ) front=rear=-1;
{//Children, try to complete this function. else if(front==9)
} OR front=0;
void queue::add( ) else
{if ( (rear + 1) % 10 != front ) front=front+1;
{ if (rear == -1 ) cout<<”\nDeleted item is : “<<item;
front = rear = 0 ; }
else }
rear = (rear + 1) %10;
cin>>data[rear]; MODEL 3: Evaluate the Postfix Notation using Stack
}
else 1.Evaluate the following Postfix expression :
cout<<”Queue full !! Overflow Error !!\n”; 4,10,5,+,*,15,3,/,- (2)
} Answer: 55 2019SP2
void queue::remove( ) 2. Evaluate the following POSTFIX expression. Show the
{if (front != -1) status of Stack after execution of each operation separately:
{ cout<<data[front]<<” deleted ”; 45, 45, +, 32, 20, 10, /, -,* (2017MP) 2
if(front==rear) Ans) 2700
front=rear=-1;
else
front = (front+1)%10;
}
else
cout<<”Queue empty ! Underflow Error!!\n”; }
OR
void queue::add( )
{if ( (rear + 1) % 10 != front )
//Ignoring –1 initial values
{rear = (rear + 1) %10; 3. Evaluate the following postfix expression. Show the
cin>>data[rear]; status of stack after execution of each operation
} separately. (2014) 2
else T,F,NOT,AND,T,OR,F,AND
cout<<”Queue full !! Overflow Error !!\n”; Symbol Operation Stack
} T PUSH T
void queue::remove() F PUSH T,F
{if (front != rear) //Ignoring –1 initial values NOT Pop One Element T,T
{front = (front+1)%10; Apply NOT
cout<<data[front]<<” deleted…”; AND Pop Two Elements. T
} Apply AND
else T PUSH T,T
cout<<”Queue empty ! Underflow Error!!\n”;
OR Pop Two elements. T
} OR Apply OR
void queue::add( )
F PUSH T,F
{int item;
AND Pop two elements. F
if((front==0 && rear==9) || front==rear+1)
Apply AND
cout<<”\nQueue overflow error”;

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 106 PRAISE THE LORD


4. Evaluate the following postfix expression. Show the
status of stack after execution of each operations:
5,2,*,50,5,/,5,-,+ (2013)
Element Scanned STACK
5 5
2 5,2
* 10
50 10,50
5 10,50,5
- 10,45
+ 55
5) Evaluate the following POSTFIX notation. Show
status of Stack after every step of evaluation (i.e. after
each operator): (2012) 2 OR
True, False, NOT, AND, False, True, OR, AND

6.Evaluate the following postfix notation of expression:


(2011 OD) 2
True, False, NOT, AND, True, True, AND,OR

7. Evaluate the following postfix notation of expression:


(Show status of Stack after each operation) (D 2010)2
False, True, NOT, OR, True, False, AND, OR
Ans.
8) Evaluate the following postfix notation of expression:
(Show status of Stack after each operation) (OD 2010)2
True, False, NOT, OR, False, True, OR, AND

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 107 PRAISE THE LORD


13) Evaluate the following postfix notation of expression :
10 20 + 25 15 - * 30 / (O2005)

9) Evaluate the following postfix notation of expression


(Show status of stack after execution of each operation ):
4, 10, 5, +, *, 15, 3, /, - (D2008)2 Ans)
Result : 55 14)Evaluate the following postfix notation of expression :
10)Evaluate the following postfix notation of expression 20 10 + 5 2 * - 10 / (OD2005)
(Show status of stack after execution of each operations): Ans)
5, 20, 15, -, *,25, 2, *, + (OD 2008)2
Ans)

15)Evaluate the following postfix expression using a stack


and show the contents of stack after execution of each
operation: 20, 45, +, 20, 10, -, 15, +, * (2003)
Ans) Children, Try this answer as an assignment.
16)Evaluate the following postfix expression using a stack.
11)Evaluate the following postfix notation of expression:2
Show the contents of stack after execution of each
25 8 3 - / 6 * 10 + (D 2007)
operation: 20, 8, 4, /, 2, 3, +, *, - (2000)
Ans) Children, Try this answer as an assignment.
17)Evaluate the following postfix expression using a stack
and show the contents of the stack after execution of each
operation. 5,11,-,6,8,+,12,*,/ (1999)
Ans) Children, Try this answer as an assignment.
18)Evaluate the following postfix expression using a stack
and show the contents of stack after execution of each
operation: 50, 40, +, 18, 14, -, 4, *, + (1998)
Ans) Children, Try this answer as an assignment.
19) Evaluate the following postfix notation of expression:2
20, 30, +, 50, 40, - ,* (MP109-10)

12)Evaluate the following postfix notation of expression :


15 3 2 + / 7 + 2 *
Ans) (OD2007)2

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 108 PRAISE THE LORD


20) Evaluate the following postfix notation of expression:
True, False, AND, True, True, NOT, OR, AND 3. Convert the following Infix expression to its
Ans) False (MP208-09) (MP209-10)2 equivalent Postfix expression, showing the stack
21) Evaluate the following postfix notation of expression: contents for each step of conversion: (2017)2
20,30,+,50,40,-,* (MP108-09) 2 X-(Y+Z)/U*V
Ans) 500
MODEL 4: Convert infix expression to postfix
expression
1. Convert the following Infix expression to its
equivalent Postfix expression, showing the stack
contents for each step of conversion. 2019MP2
A/B+C*(D-E)

OR

2. Convert the following infix expression to the


equivalent Postfix expression, showing the stack
contents for each step of conversion:
U * V + (W – Z ) / X (2018 )

Postfix= XYZ+U/V*-

4. Convert the following Infix expression to its


equivalent Postfix expression, showing the stack
contents for each step of conversion. (2016) 2
P/(QR)*S+T

OR

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 109 PRAISE THE LORD


OR

6) Convert the following infix expression to its


equivalent postfix expression showing stack contents for
the conversion: X–Y /(Z + U) * V (D2009)2
Ans) X - Y / (Z + U) * v = (X - ((Y / (Z + U)) * v))
OR

5.Convert the following infix expression to its equivalent


Postfix expression, showing the stack contents for each
step of conversion. (2015) OR
U * V + R/ (ST)
Ans)

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 110 PRAISE THE LORD


7) Convert the following infix expression to its 9 ( (/ ( ( P Q -
equivalent postfix expression showing stack contents for 10 R (/ ( ( P Q - R
11 * (/ ( ( * P Q - R
the conversion: A + B * (C – D) / E (OD2009)2 12 ( (/ ( ( * ( P Q - R
Ans) A + B * (C - D) / E = (A+ ( (B* (C-D) ) / E) ) 13 S (/ ( ( * ( P Q - R S
14 - (/ ( ( * ( P Q - R S
-
15 T (/ ( ( * ( P Q - R S T
-
16 ) (/ ( ( * P Q - R S T -
17 ) (/ ( P Q - R S T - *
18 + (/ ( + P Q - R S T - *
19 U (/ ( + P Q - R S T - * U
20 ) (/ P Q - R S T - * U +
21 ) P Q - R S T - * U + /

Postfix Form: PQ-RST-*U+/

9)Write an algorithm to convert an infix expression to


postfix expression. (2001)
Ans) The following algorithm transforms the infix
expression X into its equivalent postfix expression Y. The
algorithm uses a stack to temporarily hold operators and left
parentheses. The postfix expression Y will be constructed
from left to right using the operands from X and the
operators which are removed from STACK. We begin by
pushing a left parenthesis onto STACK and adding a right
OR parenthesis at the end of X. The algorithm is completed
when STACK is empty.
Algorithm:
Suppose X is an arithmetic expression written in infix
notation. This algorithm finds the equivalent postfix
expression Y.
1. Push “(“ onto STACK, and add “)” to the end of X.
2. Scan X from left to right and REPEAT Steps 3 to 6 for
each element of X UNTIL the STACK is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it onto STACK.
5. If an operator is encountered, then:
(a) Repeatedly pop from STACK and add to Y each
operator(on the top of STACK) which has the same
precedence as or higher precedence than operator.
(b) Add operator to STACK.
/* End of If structure */
6. If a right parenthesis is encountered, then:
(a) Repeatedly pop from STACK and add to Y each
operator (on the top of STACK) until a left Parenthesis is
encountered.
(b) Remove the left parenthesis. (Do not add the left
parenthesis to Y).
/* End of If structure */
7. End.
8) Obtain the postfix notation for the following infix
notation of expression showing the contents of the stack MODEL 5: Write the equivalent infix expression
and postfix expression formed after each step of 1) Write the equivalent infix expression for
conversion : (P—Q)/(R*(S—T)+U)(2004) a, b, AND, a, c, AND, OR. (D 2006)
Ans) ((P-Q)/((R*(S-T))+U)) Ans) a, b, AND, a, c, AND, OR
S Symbol Stack Expression Y (a AND b), (a AND c), OR
No Scanned (a AND b) OR (a AND c)

1 ( (
2 ( ((
3 P (( P
4 - ((- P
5 Q ((- P Q
6 ) ( P Q -
7 / ( / P Q -
8 ( (/ ( P Q -

XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 111 PRAISE THE LORD


2) Write the equivalent infix expression for
10, 3, *, 7, 1, --,*, 23, + (OD2006)
Solution: 10, 3, *, 7, 1, - , *, 23, +
This is in Postfix form
(ie Operator will come after the operand(s));.
Infix form means Operator must come in between the
operands. 10, 3, *, 7, 1, - , *, 23, +
Prefix: 10 * 3, 7 – 1,*,23,+
(10 * 3) * (7 – 1),23,+
(10 * 3) * (7 – 1) + 23
(Infix form)
OR
10*3*(7-1)+23
3) Change the following infix expression into postfix
expression. (A+B)*C+D/E-F (2002) 3
Ans) Children, Try this answer as an assignment.

Dear Student/Reader, I have prepared


this material with the good intention to
make the XIIth class computer students to
understand all the important models. By
practicing this material students may get
good marks. But to get full marks, one
must prepare all the syllabus prescribed by
CBSE.
As I have prepared the above
material through my own answers,
marking schemes from CBSE, copied
material from various sources, etc, there
might be some spelling mistakes, or any
other errors. So reader should read
carefully. I am not responsible for any
errors that creep in this material.
**ALL THE BEST**
Your Ever….Dear….
Faculty, Friend & Well Wisher:
MRK
Email: ptlspecialsolutions@gmail.com
XII Computer – PART 1 (Refer mrkcomputer.blogspot.in ) 112 PRAISE THE LORD
11.DATA BASE CONCEPTS (2M) M001 JAYA SCIENCE
M002 ADITYA HUMANITIES
Model 1:For a given table, key/cardinality/ etc M003 HANSRAJ SCIENCE
M004 SHIVAK COMMERCE
1. Observe the following table and answer the
TABLE : RESULT
parts(i) and(ii) accordingly . 2019SP2
Table:Product NO MNAME STREAM
M002 ADITYA HUMANITIES
Ans) (i) SELECTION
Degree=3 Cardinality=1
4.Observe the table „Club‟ given below:(2017MP)
CLUB

Answer: (i) Write the names of most appropriate


columns, which can be considered as candidate
keys.
Ans) Candidate Key: Pno, Name
(ii) What is the degree and cardinality of the
above table?
Ans) Degree:4 Cardinality:5 i. What is the cardinality and degree of the above given
table?
2) Observe the following tables VIDEO and MEMBER ii. If a new column contact_no has been added and three
carefully and write the name of the RDBMS operation more members have joined the club then how these changes
out of (i) SELECTION (ii) PROJECTION (iii) UNION will affect the degree and cardinality of the above given
(iv) CARTESIAN PRODUCT, which has been used to table.
produce the output as shown below. Also, find the A) i. Cadinality: 4 Degree: 5
Degree and Cardinality of the final result. ii. Cardinality: 7 Degree: 6
2018
5.The following STUDENTS and EVENTS tables
TABLE: VIDEO
carefully and write the name of the RDBMS operation
VNO VNAME TYPE which will be used to produce the output as shown in
F101 The Last Battle Fiction
LIST ? Also, find the Degree and Cardinality of the
C101 Angels and Devils Comedy
LIST. (2016 D)
A102 Daredevils Adventure
TABLE : MEMBER
MNO MNAME
M101 Namish Gupta
M102 Sana Sheikh
M103 Lara James
TABLE : FINAL RESULT
VNO VNAME TYPE MNO MNAME
F101 The Last Battle Fiction M101 Namish
Gupta
F101 The Last Battle Fiction M102 Sana Sheikh
F101 The Last Battle Fiction M103 Lara James
C101 Angels and Comedy M101 Namish
Devils Gupta
C101 Angels and Comedy M102 Sana Sheikh
Devils
C101 Angels and Comedy M103 Lara James
Devils A) Cartesian Product
A102 Daredevils Adventure M101 Namish Degree = 4 Cardinality = 6
Gupta
A102 Daredevils Adventure M102 Sana Sheikh
6) Observe the following table carefully and write
A102 Daredevils Adventure M103 Lara James the names of the most appropriate columns, which
Ans) Cartesian Product can be considered as (i) candidate keys and (ii)
Degree = 5 Cardinality = 9 primary key. (2015)
3. Observe the following table MEMBER carefully and
write the name of the RDBMS operation out of (i)
SELECTION (ii) PROJECTION (iii) UNION (iv)
CARTESIANPRODUCT, which has been used to
produce the output as shown in RESULT. Also, find the
Degree and Cardinality of the RESULT. (2017)
MEMBER Ans) Candidate keys : Code, Item
No MNAME STREAM Primary keys : Code
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 1 PRAISE THE LORD
MODEL 2: THEORY QUESTION Keys. Out of the Candidate keys, one is selected as
KEYS Primary Key. while the rest are the Alternate Keys.
1) What do you understand by Primary Key? Give Ex: Table: Stock
a suitable example of Primary Key from a table Ino Item Qty
containing some meaningful data. (OD 2010) 2 101 Pen 560
Ans. An attribute or set of attributes which are used to 102 Pencil 780
identify a tuple uniquely is known as Primary Key. 104 CD 450
Table: Item 109 Floppy 700
105 Eraser 300
103 Duster 200
Here: Ino, Item – Candidate Keys,
Ino – Primary Key
Item – Alternate Key
Explain the concept of candidate key with the help
2) What is the importance of a primary key in a
of an appropriate example. (2013)(2010D)(D2009)2
table? Explain with suitable example. (OD 2007) 5) What is the purpose of a key in a table? Give an
Ans:Primary Key: A primary key is a set of one or more example of a key in a table. (OD 2009)2
attributes that can uniquely identify tuples within the Ans) An attribute/group of attributes in a table that
relations. A primary key comprises a single column
identifies each tuple uniquely is known as a Key.
or set of columns. No two distinct rows in a table can have
the same value (or combination of values) in those columns. OR
Depending on its designing, a table may have arbitrarily Any correct definition of Key / Primary Key /
many candidate keys but at most one primary key. The Candidate Key / Alternate Key
primary key is non redundant. Ie it does not have duplicate
values in the same relation.
Eg: Consider a table consists the following attributes:
AdmnNo,FirstName,LastName,SirName, M1, M2, M3,
Total,Avg,FName
Here we can uniquely identify the rows in the relation with
following key combinations:
a)AdmnNo
b)FirstName,LastName,SirName
c)FirstName,LastName,FName, etc.
We can set any one of the above candidate keys as primary
key, others are called as alternate keys.
3) Give a suitable example of a table with sample 6) Differentiate between Candidate key and
data and illustrate Primary and Candidate Keys in Primary key in context of RDBMS. (D2008)
it.(2012 D) Differentiate between Candidate Key and alternate
Ans A table may have more than one such Key in context of RDBMS. (OD 2008)
attribute/group of attribute that identifies Differentiate between primary key and alternate
a row/tuple uniquely, all such attribute(s) are known key. (D2007)
as Candidate Keys. Out of the Candidate keys, one is What is an alternate key? (D2006)
selected as Primary Key. What do you understand by the terms primary key
Ex: Table: Stock and degree of a relation in relational data base?
Ino Item Qty (D2005)
101 Pen 560 What do you understand by the candidate key and
102 Pencil 780 cardinality of a relation in relational data base?
104 CD 450 (OD 2005)
109 Floppy 700 What is primary key in a table? (2003)
105 Eraser 300
103 Duster 200 Ans) Candidate Key: All attribute combinations
Here: Ino – Primary Key inside a relation that can serve primary key are
Ino, Item – Candidate Keys, Candidate Keys as they are candidates for the primary
4) Give a suitable example of a table with sample key position.
data and illustrate Primary and Alternate Keys in Primary Key: A primary key is a set of one or more
it. (2012OD) attributes that can uniquely identify tuples within the
Ans A table may have more than one such relations.
attribute/group of attribute that Identifies a row/tuple Alternate Key: A candidate key that is not the
uniquely, all such attribute(s} are known as Candidate primary key is called an Alternate Key.

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 2 PRAISE THE LORD


(Where Candidate Key: All attribute combinations StudentN StudentName Hosteler
inside a relation that can serve primary key(uniquely umber
identifies a row in a relation) are Candidate Keys as 1 Ravi Y
they are candidates for the primary key position.) 2 Robert N
Table: Stock 3 Raheem Y
Ino Item Qty Relation 2: Instructor
101 Pen 560 InstructorName Subject
102 Pencil 780 K.Suman Computer Science
104 CD 450 P.Pavan Electronics
109 Floppy 700 The Cartesian product of these two relations, Student
105 Eraser 300 X Instructor, will yield a relation that have a degree of
103 Duster 200 5(3+2:sum of degrees of Student and Instructor) and a
Here: Ino, Item – Candidate Keys, cardinality 6 (3 X 2: Product of cardinalities of two
Ino – Primary Key relations).
Item – Alternate Key The resulting relation is as follows:
Stude Student Ho Instructor Subject
7) What is a relation? What is the difference between a
nt Name ste Name
tuple and an attribute? (1998)
Numb ler
Ans: In relational data model, the data is organized er
into table (rows and columns). These tables are called 1 Ravi Y K.Suman Computer
relations. A row in a table represents a relationship Science
among a set of values. 1 Ravi Y P.Pavan Electronics
Rows of the relations are called as tuples and 2 Robert N K.Suman Computer
columns of the relations are called as attributes. Science
2 Robert N P.Pavan Electronics
8) What do you understand by Degree and Cardinality 3 Raheem Y K.Suman Computer
of a table? (MP109-10) (MP108-09)2 Science
Ans) Degree: Number of Columns in a table 3 Raheem Y P.Pavan Electronics
Cardinality: Number of rows in a table Resultant Relation = Relation1 X Relation2
Ex: TABLE : MEMBER The resulting relation contains all possible
MNO MNAME combinations of tuples of the two relations.
M101 Namish Gupta 10) What do you understand by Union & Cartesian
M102 Sana Sheikh
Product operations in relational algebra?(2011D)2
M103 Lara James
Ans) Union (binary operator): It operates on two
Here, Cardinality = 3, Degree = 2 relations and is indicated by U.
What do you understand by the candidate key and For example, R= R1 U R2 represents union operation
cardinality of a relation in relational data base? between two relations R1 and R2. The degree of R is
(OD 2005) equal to degree of R1. The cardinality of R is sum of
OPERATIONS cardinality of R1 and cardinality of R2.
9. Explain the concept of Cartesian Product Following have to be considered for the operation R1
between tables, with the help of appropriate U R2.
example. (2014)(2001) Degree of R1 = Degree of R2
Answer) Cartesian Product (binary operator): It jth attribute of R1 and jth attribute of R2
operates on two relations and is denoted by X. must have a common domain.
The Cartesian product of two relations Example : Relation R1
yields a relation with all possible combinations of Student_ID Name
the tuples of the two relations operated upon. S120 Raju
All tuples of first relation are concatenated S121 Nani
with all the tuples of second realtion to form the
tuples of the new relation. Relation R2
The Cartesian product of two relations A and Student_Code Student_Name
B is written as AXB. The Cartesian product yields a K550 Chinna
new relation which has a degree (number of attributes) K551 Munna
equal to the sum of the degrees of the two relations Resultant Relation : R = R1 U R2
operated upon. Student_ID Name
The number of typles (cardinality) of the new relation S120 Raju
is the product of the number of tuples of the two S121 Nani
relations operated upon. K550 Chinna
Eg: There are two relations as follows: K551 Munna
Relation 1: Student

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 3 PRAISE THE LORD


11) What do you understand by Selection & Example: To create a table consisting the Admnno,
Projection operations in relational algebra? SName, Sub1, Sub2, Sub3, Total,Avg,Divison
(2011 OD)2 attributes.
Ans Selection for selecting the rows of table CREATE TABLE Student (AdmnNo integer,SName
char(20), Sub1 number(5,2), sub2 number(5,2),
Projection for selecting the columns of table
sub3 number(5,2), Total number(5,2),Avg
Ex: Table MEMBER number(5,2), Div Char(10));
No MNAME STREAM 2.Constraints:
M001 JAYA SCIENCE (i) NOT NULL : The attribute that contains this
M002 ADITYA HUMANITIES constraints should not be vacant.
M003 HANSRAJ SCIENCE (ii) Unique constraints: This constraint ensures that
M004 SHIVAK COMMERCE no two rows have the same value in the specified
column(s).
TABLE : TABSEL
(iii) Primary key constraints: This constraint declares
NO MNAME STREAM a column as the primary key of the table.(
M002 ADITYA HUMANITIES Primary keys cannot allow NULL values)
TABLE : TABPROJ (iv) Default constraints: A default value can be
No STREAM specified for a column using DEFAULT clause.
M001 SCIENCE When a user does not enter a value for the
M002 HUMANITIES column, automatically the defined default value
M003 SCIENCE is inserted in the field.
(v) Check constraints: this constraint limits values
M004 COMMERCE that can be inserted into a column of a table.
Here, Above table can be created using the constraints as
Table TABSEL is result of Selection operation follows:
Table TABPROJ is result of projection operation CREATE TABLE Student (AdmnNo number(4) NOT
NULL PRIMARY KEY, SName char(20), Sub1
DDL & DML number(5,2) CHECK(Sub1<=100.0), Sub2 number(5,2)
12) What are DDL and DML? (OD 2006) CHECK(Sub2<=100.0), Sub3 number(5,2)
(Differentiate between data definition language and data CHECK (Sub3<=100.0), Total number(5,2),Avg
manipulation language.(2002)) number(5,2),Div char(10));
Ans: DDL means Data Definition Language. SQL 3.INSERT Command:
DDL provides commands for defining relation INSERT INTO <tablename>[<column list>]
schemas, deleting relations, creating indexes and VALUES(<value>,<value>…);
modifying relation schemas. (Provides statements for Eg:
the creation and deletion of tables and indexes.) i) To insert our desired attributes only:
DML Means Data Manipulation Language. SQL INSERT INTO Student
DML provides statements to enter, update,delete data (Admnno,SName,Sub1,Sub2,Sub3)
Values (1000,‟pradeep‟,75.5,90.5,57.0);
and perform complex queries on these tables. ii) To insert all the attributes:
(includes a query language to insert, delete and INSERT INTO Student Values (1001,
modify tuples in the database) ‟sudeep‟,77.50,95.0,68.50, 41.0,80.33,‟First‟);
DML is used to put values and manipulate (for inserting number of rows in a easy way…)
them in tables and other database objects and DDL is INSERT INTO STUDENT(Admnno,SName,Sub1,Sub2,
used to create tables and other database objects. Sub3) VALUES (&Admnno, &SName, &Sub1, &Sub2,
&Sub3);
12.STRUCTURED QUERY LANGUAGE Then it will ask first student data….Enter the data…then
(6 Marks) press / at command prompt. It will ask you next student
STUDENT MARKS TABLE data, etc.)
In the following section many of the commands is Sample Data Inserted
explained through the example “Student marks table”. Adm SNam Sub Sub Sub Tot Avg Di
S.no Attribute Type n No e 1 2 3 al v
1000 Pradee 75.5 95.0 57.0
1 AdmnNo Integer
p
2 SName Character 1001 Sudee 77.5 95.0 68.5 241. 80.3 Firs
3 Sub1 Real Number p 0 3 t
4 Sub2 Real Number 1002 Philip 32.5 60.0 59.5
5 Sub3 Real Number 1003 Pradee 45.5 65.5 70.0
6 Total Real Number p
7 Avg Real Number 1004 Naidu 77.5 25.5 65.5
8 Divison Character 1005 Sudee 80.5 72.5 67.0
p
1. Create Table:
CREATE TABLE <table-name> (<column name><data 4.Select command: Select command of SQL lets you make
queries on the database. A query is a command that is given
type>[(size>)],<column name><data
type>[(size>)],…); to produce certain specified information from the database
table(s).
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 4 PRAISE THE LORD
Simple Form: Pradeep
SELECT<column name>[,<column name>…] FROM Sudeep
<table name>; Pradeep
Eg: Select AdmnNo,SName from Student. Sudeep
(Will display only AdmnNo and SName attributes of the 8. Condition based on a Range using BETWEEN:
table student.) Eg: SELECT AdmnNo, SName FROM Student
Select * from Student. WHERE AdmnNo BETWEEN 1003 AND 1005;
(Will display all the attributes of the table Student.) AdmnNo SName
5.DISTINCT Keyword: This keyword eliminates 1003 Pradeep
duplicate rows from the results of a SELECT statement. 1004 Naidu
Eg: Select DISTINCT SName from Student 1005 Sudeep
Sname 9.ORDER BY:
Pradeep SELECT AdmnNo, SName from student ORDER BY
Sudeep SName ASC;
Philip Admn No SName
Naidu 1004 Naidu
6.ALL Keyword: This keyword will not eliminate 1002 Philip
duplicate rows from the results of a SELECT statement. 1000 Pradeep
Eg: Select ALL SName from student 1003 Pradeep
SName 1001 Sudeep
Pradeep 1005 Sudeep
Sudeep SELECT AdmnNo, SName from student ORDER BY
Philip AdmnNo DESC;
Pradeep
Naidu Admn No SName
Sudeep 1005 Sudeep
7. Selecting specific rows using WHERE clause with 1004 Naidu
SELECT: 1003 Pradeep
Syntax: SELECT <column name>[< column name>,…]
1002 Philip
FROM <table name> WHERE <condition>;
1001 Sudeep
Eg:
1000 Pradeep
SELECT Admnno,SName FROM Student WHERE
Sub1>=40 AND Sub2>=40 AND Sub3>=40; 10. UPDATE COMMAND:
SELECT SName FROM Student WHERE UPDATE Student SET Total= Sub1+Sub2+Sub3;
SName=‟Sudeep‟ OR SName=‟Philip; UPDATE Student SET Avg=Total/3;
SName UPDATE Student SET Div=‟First‟ WHERE (Avg>=60.0);
Sudeep UPDATE Student SET Div=‟Second‟ WHERE
Philip (Avg>=50.0 AND Avg<60.0);
Sudeep UPDATE Student SET Div=‟Third‟ WHERE (Avg>=35.0
SELECT SName FROM Student WHERE AND Avg<50.0);
SName<>‟Naidu‟ UPDATE Student SET Div=‟Fail‟ WHERE (Sub1<35.0
OR OR Sub2<35.0 OR Sub3<35.0);
SELECT SName FROM Student WHERE (NOT After the execution of the above commands, the sample
SName=‟Naidu‟) data will be as follows:
SName Admn SName Sub1 Sub2 Sub3 Total Avg Div
Pradeep No
1000 Pradeep 75.5 95.0 57.0 227.5 75.85 First
Sudeep 1001 Sudeep 77.5 95.0 68.5 241.0 80.33 First
Philip 1002 Philip 32.5 60.0 59.5 152.0 50.66 Fail
Pradeep 1003 Pradeep 45.5 65.5 70.0 181 60.3 First
Sudeep 1004 Naidu 77.5 25.5 65.5 168.5 56.16 Fail
SELECT Sname from student WHERE SName 1005 Sudeep 80.5 72.5 67.0 220 73.3 First
in(„Pradeep‟,‟Sudeep‟); 11. ALTER TABLE:
SName ALTER TABLE student MODIFY (Div Char(6));
Pradeep ALTER TABLE student ADD(CNo NUMBER(10));
Sudeep 12. Functions:
Pradeep SELECT Min(Sub1) FROM Student;
Sudeep (Will give the Minimum marks of Subject1)
SELECT SName FROM Student WHERE SName NOT Min(SUB1)
IN(„Sudeep‟,‟Pradeep‟); 32.5
SName SELECT Max(Sub2) FROM Student;
Philip (Will give the Maximum marks of Subject2)
Naidu MAX(SUB2)
SELECT SName FROM Student WHERE SName LIKE 95
„%eep‟ SELECT Sum(Sub3) FROM Student;
SName (Will give the Sum of marks of Subject3)

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 5 PRAISE THE LORD


SUM(SUB3) WRITE SQL QUERIES
387.5
SELECT Avg(Sub1) FROM Student; i) To Display the Trainer name, City from table
(Will give the Average of Subject1) Trainer.
AVG(SUB1) A) SELECT TNAME, CITY from TRAINER;
64.83 ii) Display all details of table COURSE
SELECT Count(DISTINCT SName) FROM Student; A) SELECT * FROM COURSE;
( Will display 4)
iii) Display the Trainer Name, City & Salary in
COUNT(DISTINCT SNAME)
4 descending order of their Hiredate.
SELECT Count(SName) FROM Student; Ans:
( Will display 6) SELECT TNAME, CITY, SALARY FROM
COUNT(SNAME) TRAINER ORDER BY HIREDATE DESC;
6 iv) To display all the details of those trainers whose
Count – To count non-null values in a column
name ends with „A‟
Count(*) – To count total number of rows in a table.
13. Creating table from Existing Table:
A) select * from Trainer where Tname like „%A‟
CREATE TABLE PassStudent as (SELECT AdmnNo, v) Display all details from the table COURSE in
SName FROM Student WHERE (Sub1>=40.0 AND ascending order of their STARTDATE
Sub2>=40.0 AND Sub3>=40.0)); Ans:
14. Inserting the Results of a Query: SELECT * FROM COURSE ORDER BY
INSERT INTO PassStudent(admnno,sname)
SELECT AdmnNO, SName FROM Student
STARTDATE ASC;
WHERE (Sub1>=40.0 AND Sub2>=40.0 AND vi) To display CName and Fees of those Courses Whose
Sub3>=40.0); Fees range in between 10000-15000.
15. CREATE VIEW: A) select CName, Fees from Course where Fees
CREATE VIEW FailStudent AS SELECT * FROM between 10000 and 15000;
Student WHERE Div=‟Fail‟;
16. DELETE:
vii) To display total salary of trainers from city
DELETE FROM Student WHERE AdmnNo=1004; name ends with “I”.
(To delete a record, whose AdmnNo=1004) A) SELECT SUM(SALARY) FROM TRAINER
DELETE FROM Student; WHERE CNAME LIKE ‟%I‟;
(To delete all records of student)
17.DROP TABLE: viii) To display all Trainer Details from city “Mumbai”
DROP TABLE Student; Ans: SELECT * FROM TRAINER WHERE
18. DROP VIEW: CITY = ' Mumbai ' ;
DROP VIEW Failstudent;
19.Commit (To save the changes) ix) To display CName, Fees and StartDate of all
20.Rollback (for Undo) Courses which are started before 15th July 2018
Ans)
MODEL 1(VERY IMP) : TWO TABLES SELECT CNAME,FEES,STARTDATE FROM
1.Write SQL queries for (i) to (iv) and find COURSE WHERE STARTDATE< ' 2018-07-15;
outputs for SQL queries (v) to (viii), which are
based on the tables. 2019SP6 x) To display the last date (recent most) HIREDATE
from the table TRAINER
TRAINER
Ans: SELECT MAX(HIREDATE) FROM
TRAINER;
xi) To display the TNAME and CITY of Trainer
who joined the Institute in the month of
December 2001.
Ans:
SELECT TNAME, CITY FROM TRAINER
WHERE HIREDATE BETWEEN „2001-12-01‟
COURSE AND „2001-12-31‟;
OR
SELECT TNAME, CITY FROM TRAINER
WHERE HIREDATE >= „2001-12-01‟ AND
HIREDATE<=„2001-12-31‟;
OR
SELECT TNAME, CITY FROM TRAINER
WHERE HIREDATE LIKE „2001-12%‟;

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 6 PRAISE THE LORD


xii) To display TNAME, HIREDATE, CNAME, (h) select TNAME, CITY, SALARY from
STARTDATE from tables TRAINER and TRAINER T, COURSE C where T.TID!=C.TID;
COURSE of all those courses whose FEES is less A) TNAME CITY SALARY
than or equal to 10000. ManiPrabha Chennai 69000
Ans:
SELECT TNAME,HIREDATE,CNAME, Note: 3 to 4 recent questions models are
STARTDATE FROM TRAINER, COURSE merged in the above question.
WHERE TRAINER.TID=COURSE.TID AND 2.Write SQL queries for (i) to (iv) and find outputs
FEES<=10000; for SQL queries (v) to (viii), which are based on the
xiii) To display CNAME, Fees, TName,City from tables (2016)
tbales Trainer and Course of all those persons
whose Hiredate Before Year 2000.
Ans) SELECT CNAME, FEES, TNAME, CITY
from TRAINER, COURSE WHERE
TRAINER.TID=COURSE.TID AND
HIREDATE<‟2000-01-01‟;
(XiV) To display number of Trainers from each
city.
Ans)SELECT CITY,COUNT(*) FROM TRAINER;
WRITE SQL OUTPUTS
(a) SELECT TID, TNAME, FROM TRAINER
WHERE CITY NOT IN(„DELHI‟,„MUMBAI‟);
Ans:
TID TNAME
103 DEEPTI
106 MANIPRABHA
(b) SELECT DISTINCT TID FROM COURSE;
Ans: DISTINCT TID
101 (i) To display CNO, CNAME, TRAVELDATE from
103 the table TRAVEL in descending order of CNO.
102 Ans SELECT CNO, CNAME, TRAVELDATE
104
105
FROM TRAVEL ORDER BY CNO DESC;
c) SELECT TID, COUNT(*), MIN(FEES) (ii) To display the CNAME of all the customers from
FROM COURSE GROUP BY TID HAVING the table TRAVEL who are traveling by vehicle with
COUNT(*)>1; code V01 or V02.
Ans: Ans SELECT CNAME FROM TRAVEL WHERE
TID COUNT(*) MIN(FEES) VCODE=„V01‟ OR VCODE=‟V02‟;
101 2 12000 OR
d) SELECT COUNT(*), SUM(FEES) FROM SELECT CNAME FROM TRAVEL WHERE
COURSE WHERE STARTDATE< „2018-09-15‟; VCODE IN („V01‟, „V02‟);
Ans: (iii) To display the CNO and CNAME of those
COUNT(*) SUM(FEES) customers from the table TRAVEL who
4 65000 travelled between „2015-12-31‟ and „2015-05-01‟.
(e) SELECT MIN(STARTDATE) FROM Ans SELECT CNO, CNAME from TRAVEL
COURSE; WHERE TRAVELDATE >=„2015-05-01‟
Ans) MIN(STARTDATE) AND TRAVELDATE <= „2015-12-31‟;
2018-07-02 OR
(f). SELECT MAX(STARTDATE), MIN(FEES) SELECT CNO, CNAME from TRAVEL
WHERE TRAVELDATE BETWEEN „2015-05-01‟
FROM COURSE;
A) max(StartDate) min(Fees) AND „2015-12-31‟ ;
2018-10-01 9000 OR
SELECT CNO, CNAME from TRAVEL
(g) SELECT CITY, SUM(SALARY) FROM
WHERE TRAVELDATE <= „2015-12-31‟
TRAINER GROUP BY CITY HAVING
AND TRAVELDATE >= „2015-05-01‟ ;
COUNT(*)>1 ;
OR
A) CITY SUM(SALARY)
SELECT CNO, CNAME from TRAVEL
MUMBAI 18,5000
WHERE TRAVELDATE BETWEEN „2015-12-31‟
DELHI 15,8000
AND „2015-05-01‟;
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 7 PRAISE THE LORD
(iv) To display all the details from table TRAVEL for Ans SELECT Eno,Name FROM Employee
the customers, who have travel distance more than WHERE DOB BETWEEN „1987-01-01‟ AND „1991-12-01‟
120 KM in ascending order of NOP. OR
Ans SELECT * FROM TRAVEL SELECT Eno,Name FROM Employee
WHERE DOB >=„1987-01-01‟ AND DOB <=„1991-12-01‟ ;
WHERE KM > 120 ORDER BY NOP; OR
(v) SELECT COUNT(*),VCODE FROM TRAVEL SELECT Eno,Name FROM Employee
GROUP BY VCODE HAVING COUNT(*)>1; WHERE DOB >„1987-01-01‟ AND DOB <„1991-12-01‟;
Ans COUNT(*) VCODE (iv) To count and display FEMALE employees who
2 V01 have joined after '1986‐01‐01'.
2 V02 Ans SELECT count(*) FROM Employee
(vi) SELECT DISTINCT VCODE FROM TRAVEL; WHERE GENDER=‟FEMALE‟ AND DOJ > „1986-01-01‟;
Ans DISTINCT VCODE OR
V01 SELECT * FROM Employee
V02 WHERE GENDER=‟FEMALE‟ AND DOJ > „1986-01-01‟;
V03 (v) SELECT COUNT(*),DCODE FROM
V04 EMPLOYEE
V05 GROUP BY DCODE HAVING COUNT(*)>1;
vii) SELECT A.VCODE,CNAME, VEHICLETYPE Ans COUNT DCODE
FROM TRAVEL A,VEHICLE B WHERE 2 D01
A.VCODE=B.VCODE AND KM<90; 2 D05
Ans VCODE C NAME VEHICLETYPE (vi) SELECT DISTINCT DEPARTMENT FROM
V02 Ravi Anish AC DELUXE BUS DEPT;
V04 John Malina CAR Ans Department
(viii) SELECT CNAME,KM*PERKM INFRASTRUCTURE
FROM TRAVEL A,VEHICLE B MARKETING
WHERE A.VCODE=B.VCODE AND MEDIA
A.VCODE=‟V05‟; FINANCE
Ans CNAME KM*PERKM HUMAN RESOURCE
Sahanubhuti 2700 (vii) SELECT NAME, DEPARTMENT FROM
3. Consider the following DEPT and EMPLOYEE EMPLOYEE E, DEPT D WHERE
tables. Write SQL queries for (i) to (iv) and find E.DCODE=D.DCODE AND EN0<1003;
outputs for SQL queries (v) to (viii). (2015) Ans NAME DEPARTMENT
Table: DEPT George K INFRASTRUCTURE
Ryma Sen MEDIA
(viii) SELECT MAX(DOJ), MIN(DOB) FROM
EMPLOYEE;
Ans MAX(DOJ) MIN(DOB)
2014-06-09 1984-10-19
4.Answer the question (b) and (c) on the basis of
the following tables SHOPPE and ACCESSORIES.
(2014)
Table: SHOPPE
ID SName Area
S01 ABC Computronics CP
S02 All Infotech Media GK II
S03 Tech Shopee CP
S04 Geeks Techno Soft Nehru Place
S05 Hitech Store Nehru Place
Table: ACCESSORIES
ID Iname Price Sno
(i) To display Eno, Name, Gender from the table A01 Mother Board 12000 S01
EMPLOYEE in ascending order of Eno. A02 Hard Disk 5000 S01
Ans SELECT Eno,Name,Gender FROM Employee A03 Keyboard 500 S02
ORDER BY Eno; A04 Mouse 300 S01
A05 Mother Board 13000 S02
(ii) To display the Name of all the MALE employees
A06 Keyboard 400 S03
from the table EMPLOYEE. A07 LCD 6000 S04
Ans SELECT Name FROM Employee WHERE A08 LCD 5500 S05
Gender=‟MALE‟; A09 Mouse 350 S05
(iii) To display the Eno and Name of those employees A10 Harddisk 4500 S03
from the table EMPLOYEE w ho are born between
'1987‐01‐01' and '1991‐12‐01'.
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 8 PRAISE THE LORD
Write a SQL query (1 to 4) 4 Table: SUPPLIERS
1. To display Name and Price of all the Accessories in SUPCODE SNAME CITY
ascending order of their Price. S01 GET ALL INC KOLKATA
A) Select Name, Price from ACCESSORIES order by
S03 EASY MARKET DELHI
Price.
CORP
2. To display Id and Sname of all Shopee located in Nehru S02 DIGI BUSY CHENNAI
Place; GROUP
A) Select Id, Sname from SHOPPE where Area = (b) To display the details of all the products in ascending
„Nehru Place; order of product names (ie PNAME)
3. To display Minimum and Maximum price of each Name A) SELECT * FROM PRODUCTS ORDER BY
of Accessories. PNAME;
A) Select Min(Price), Max(Price) from ACCESSORIES (c) To display product name and price of all those products
group by Name; whose price is in range of 10000 and 15000 (both values
inclusive).
4. To display Name, Price of all the Accessories and their A) SELECT PNAME, PRICE FROM PRODUCTS
respective SName where they are available. WHERE PRICE >=10000 AND PRICE >=15000;
A) Select Name, Price, SName from SHOPPE, (d) To display the number of products, which are supplied
ACCESSORIES where SHOPPE.Id= supplier. Ie, the expected output should be
ACCESSORIES.ID; S01 2
Write the output of the following SQL command S02 2
(1 to 4) ( 2014 ) 2 S03 1
1. SELECT DISTINCT NAME FROM A) SELECT SUPCODE, COUNT(SUPCODE) FROM
ACCESSORIES WHERE PRICE>=5000; PRODUCTS GROUP BY SUPCODE;
(E) To display the price, product name and quantity (ie qty) of
INAME those products which have quantity more than 100
Mother Board A) SELECT PRICE,PNAME, QTY FROM
Hard Disk PRODUCTS WHERE QTY>100;
LCD (f) To display the names of those suppliers, who are either
from DELHI or from CHENNAI.
2.SELECT AREA, COUNT(*),FROM SHOPPE A) SELECT SNAME FROM SUPPLIERS WHERE
GROUP BY AREA; CITY=”DELHI” OR CITY=”KOLKATA”;
AREA Count(*) (g) To display the name of the companies and the name of
CP 2 the products in descending order of company names.
GK II 1 A) SELECT COMPANY, PNAME FROM PRODUCTS
ORDER BY COMPANY DESC.
Nehru Place 2
3. SELECT COUNT(DISTINCT AREA) FROM (h) Obtain the outputs of the following SQL queries
based on the data given in tables PRODUCTS and
SHOPPE;
SUPPLIERS above.
COUNT(DISTINCT AREA) (h1) SELECT DISTINCT SUPCODE FROM PRODUCTS;
3 A)
SUPCODE
4. SELECT NAME, PRICE*0.05 DISCOUNT FROM S01
ACCESSORIES WHERE SNO IN(„S02‟,‟S03‟); S02
INAME DISCOUNT S03
Keyboard 25
(h2) SELECT MAX(PRICE), MIN(PRICE) FROM
Motherboard 650 PRODUCTS;
Keyboard 20 A)
Hard Disk 225 MAX (PRICE) MIN(PRICE)
5.Write SQL queries for (b) to (g) and write the outputs 28000 1100
for the SQL queries mentioned shown in (h1) to (h4) on (h3) SELECT PRICE*QTY AMOUNT FROM
basis of tables PRODUCTS and SUPPLIERS. (2013) PRODUCTS WHERE PID=104;
Table: PRODUCTS A)
PI PNAME QT PRIC COMPA UPC AMOUNT
D Y E NY ODE 55000
101 DIGITIAL 120 12000 RENIX S01 (h4) SELECT PNAME, SNAME FROM PRODUCTS P,
CAMERA 14X SUPPLIERS S WHERE P.SUPCODE=S.SUPCODE AND
102 DIGITAL PAD 11i 100 22000 DIGI POP S02 QTY>100;
104 PEN DRIVE 16 GB 500 1100 STOREKI S01
NG PNAME SNAME
106 LED SCREEN 32 70 28000 DISPEX S02 DIGITAL CAMERA 14X GET ALL INC
PERTS PEN DRIVE 16GB GET ALL INC
105 CAR GPS 60 12000 MOVEON S03
SYSTEM

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 9 PRAISE THE LORD


6) Constider the following tables CARDEN and COUNT(*) Make
CUSTOMER and answer (b) and (c) parts of this 2 SUZUKJ:
question: (2012) 1 TATA
Table: CARDEN 1 TOYOTA
1 MERCEDES
Ccode CarName Make Color Cap Char
acit ge (iv) SELECT CarName FROM CARDEN WHE~ Capacity = 4;
y Ans CarName
501 A-Star Suzuki RED 3 14 Sx4
503 Indigo Tata SILVER 3 12 C Class
502 Innova Tovota WHITE 7 15 7) Consider the following tables EMPLOYEE and
509 SX4 Suzuki SILVER 4 14 SALGRADE and answer (b) and (c) parts of this
510 C Class Mercedes RED 4 35 questions. (2011)
Table: CUSTOMER
CCode Cname Ccode
1001 Hemant Sahu 501
1002 Raj Lal 509
1003 Feroza Shah 503
1004 Ketan Dhal 502
(b) Write SQL commands for the following
statements: 4
(i) To display the names of all silver colored Cars.
Ans SELECT CarName FROM CARDEN
WHER Color = „SILVER';
(ii) To display name of car, make and capacity of cars in
descending order of their sitting capacity.
Ans SELECT CarName, Make, Capacity FROM
CARDEN ORDER BY Capacity DESC;
(iii) To display the highest charges at which a vehicle can
be hired from CARDEN.
Ans SELECT MAX(Charges) FROM CARDEN ; (b) Write SQL commands for the following statements:
OR (i) To display the details of all EMPLOYEEs, in descending
SELECT CarName, MAX(Charges)FROM CARDEN order of DOJ
GROUP BY CarName; Ans SELECT * FROM EMPLOYEE ORDER BY DOJ
(iv) To display the customer name and the corresponding DESC;
name of the cars hired by them. (ii) To display NAME and DE51G of those EMPLOYEEs,
Ans SELECT CName, CarName FROM CUSTOMER, whose 5ALGRADE is either 502 or 503
CARDEN WHERE CUSTOMER.Ccode = Ans SELECT NAME, DESIG FROM EMPLOYEE
CARDEN.Ccode; OR WHERE SGRADE = 'S02' OR SGRADE= 'S03';
SELECT CUSTOMER. CName, CARDEN. CarName OR
FROM CUSTOMER, CARDEN WHERE SELECT NAME, DESIG FROM EMPLOYEE
CUSTOMER.Ccode = CARDEN.Ccode; WHERE SALGRADE ='S02' OR SALGRADE='S03';
OR (iii) To display the content of all the EMPLOYEEs table,
SELECT CName, CarName FROM CUSTOMER A, whose DOJ is in between'09-Feb-2006' and '08-Aug-2009'.
CARDEN B WHERE A.Ccode = B.Ccode; Ans SELECT * FROM EMPLOYEE
OR WHERE DOJ BETWEEN '09-Feb-2006'and '08-Aug-
SELECT A. CName, B. CarName FROM CUSTOMER 2009'; OR
A, CARDEN B WHERE A.Ccode = B.Ccode; SELECT * FROM EMPLOYEE WHERE DOJ > = '09-
Fab-2006' and DOJ <='08-Aug-2009';
(c) Give the output of the following SOL queries:
(i) SELECT COUNT (DISTINCT Make) FROM OR
CARDEN; SELECT * FROM EMPLOYEE
Ans COUNT (DISTINCT Make) WHERE DOJ > '09-Feb-2006' and DOJ <' 08-Aug-
4 2009" ;
(iv) To add a new row with the following:
(ii) SELECT MAX (Charges), MIN (Charges) FROM 109, 'Harish Roy', 'HEAD-IT', 'S02', '09-Sep-2007, '21-Apr-
CARDEN; 1983'
Ans MAX (Charges) MIN (Charges) Ans INSERT INTO EMPLOYEE
35 12 VALUES(109,'Harish Roy' ,'HEAD-IT' ,'S02' ,'09-Sep-
(iii) SELECT COUNT (*), Make FROM CARDEN; 2007' ,'21-Apr-1983' ) ;
Ans (Ignoring Make for display)
COUNT (*) (c) Give :the output of the following SQL queries: 2
5 (i) SELECT COUNT (SGRADE),SGRADE FROM
OR EMPLOYEE GROUP
(assuming the presence of GROUP By Make) BY SGRADE;
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 10 PRAISE THE LORD
Ans COUNT (SGRADE) SGRADE b2)Give the output of the following SQL queries:2
1 S01 Note: In all output Questions ignore Column
2 S02 Headings
2 S03 (i) SELECT COUNT(DISTINCT Scode) FROM
(ii) SELECT MIN(DOB), MAX (DOJ) FROM Store;
EMPLOYEE; Ans. COUNT(DISTINCT Scode)
Ans MIN (DOB) MAX (DOJ) 3
13-Jan-1980 12-Feb-2010
(ii) SELECT Rate*Qty FROM Store WHERE
(iii) SELECT NAME , SALARYFROM EMPLOYEE E, ItemNo=2004;
SALGRADE S WHERE Ans. RATE*QTY
E.SGRADE= S.SGRADE AND E.ECODE<103; 880
Ans Name Salary (iii) SELECT Item,Sname FROM Store S, Suppliers P
Abdul Ahmad 24000
WHERE S.Scode=P.Scode AND ItemNo=2006;
Ravi Chander 32000
Ans. ITEM SNAME Gel Pen Classic Premium
(iv) SELECT SGRADE, SALARY+HRA ET:)M Stationers
SALGRADE WHERE SGRADE= 'S02'; (iv) SELECT MAX(LastBuy) FROM Store;
Ans SGRADE SALARY+HRA Ans. MAX (LASTBUY)
S02 44000
24-Feb-10
8) Consider the following tables STORE and
9) Consider the following tables GARMENT and FABRIC.
SUPPLIERS and answer (bl) and (b2) parts of this Write SQL commands for the statements (i) to (iv) and give
question: (D 2010) outputs for SQL queries (v) to (viii) (D2009)6

b1)Write SQL commands for the following


statements:4 (i) To display details of all the items in
the Store table in ascending order of LastBuy.
Ans. SELECT * FROM STORE ORDER BY
LastBuy;
(i) To display GCODE and DESCRIPTION of each
(ii) To display ItemNo and Item name of those items
GARMENT in descending order of GCODE
from Store table whose Rate is more than 15 Rupees. Ans SELECT GeODE, DESCRIPTION FROM
Ans. SELECT ItemNo, Item..In FROM STORE GARMENT ORDER BY GCODE DESC;
WHERE Rate >15; (ii) To display the details of all the GARMENTs, which
(iii) To display the details of those items whose have READYDA TE in between 08-DEC-07 and 16-JUN-
Supplier code (Scode) is 22 or Quantity in Store (Qty) 08(inclusive of both the dates).
is more than 110 from the table Store. Ans) SELECT * FROM GARMENT WHERE READYDATE
Ans. SELECT * FROM STORE WHERE Scode = BETWEEN‟ 08-DEC-07‟AND , 16-JUN-08‟ ;
OR
22 OR Qty >110; SELECT * FROM DRESS WHERE LAUNCHDATE >= „08-
(iv) To display Minimum Rate of items for each DEC-07‟ AND LAUNCHDATE<=‟16-JUN-08‟;
Supplier individually as per Scode from the table (iii) To display the average PRICE of all the GARMENTs,
Store. which are made up of FABRIC with FCODE as F03.
Ans. SELECT Scode, MIN(Rate) FROM STORE Ans) SELECT AVG (PRICE) FROM GARMENT
GROUP BY Scode; WHERE FCODE = „F03‟;
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 11 PRAISE THE LORD
(iv) To display FABRIC wise highest and lowest price of Ans SELECT * FROM DRESS WHERE
GARMENTs from GARMENT table. (Display FCODE of LAUNCHDATE BETWEEN „05-DEC-07‟ AND ‟20-
each GARMENT along with highest and lowest price) JUN-08‟ OR
Ans SELECT FCODE, MAX (PRICE), MIN(PRICE) SELECT * FROM DRESS WHERE LAUNCHDATE
FROM GARMENT GROUP BY FCODE; >= „05-DEC-07‟ AND LAUNCHDATE<= ‟20-JUN-08‟
(v) SELECT SUM (PRICE) FROM GARMENT WHERE (iii) To display the average PRICE of all the dresses which
FCODE = „F01‟ ; are made up of material with MCODE as M003.
Ans SUM (PRICE) Ans SELECT AVG(PRICE) FROM GARMENT
2600 WHERE MCODE = „M003‟
(vi) SELECT DESCRIPTION, TYPE FROM GARMENT, (iv) To display materialwise highest and lowest price of
FABRIC WHERE GARMENT.FCODE = dresses from DRESS table. (Display MCODE of each dress
FABRIC.FCODE AND GARMENT. PRICE > = 1260 ; along with highest and lowest price)
Ans) DESCRIPTION TYPE Ans SELECT MCODE, MAX(PRICE), MIN (PRICE)
INFORMAL SHIRT COTTON FROM DRESS GROUP BY MCODE
INFORMAL PANT COTTON (v) SELECT SUM(PRICE) FROM DRESS WHERE
FORMAL PANT TERELENE MCODE=„M001‟;
Ans SUM(PRICE)
(vii) SELECT MAX (FCODE) FROM FABRIC;
2700
Ans MAX (FCODE)
(vi) SELECT DESCRIPTION, TYPE FROM DRESS,
F04
MATERIAL WHERE DRESS.DCODE =
(viii) SELECT COUNT (DISTINCT PRICE) FROM
MATERIAL.MCODE AND DRESS.PRICE>=l250;
GARMENT ;
Ans DESCRIPTION TYPE
Ans COUNT(DISTINCT PRICE)
(NO OUTPUT)
7
(vii) SELECT MAX(MCODE) FROM MATERIAL;
(10) Consider the following tables DRESS and Ans MAX (MCODE)
MATERIAL. Write SQL commands for the statements MOO4
(i) to (iv) and give outputs for SQL queries (v) to (viii). (viii) SELECT COUNT(DISTINCT PRICE) FROM
(2009 OD) 6 DRESS;
Ans COUNT(DISTINCT PRICE)
6
11) Consider the following tables Product and Client.
Write SQL commands for the statement (i) to (iv) and
give outputs for SQL queries (v) to (viii) (D 2008)
Table: PRODUCT
P_ID Product Name Manufact Price
urer
TP01 Talcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
Table: CLIENT
C_ID Client Name City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
16 Dreams Banglore TP01
(i) To display the details of those Clients whose city is
Delhi.
Ans: Select all from Client where City=”Delhi”
(ii)To display the details of Products whose Price is in the
range of 50 to 100 (Both values included).
Ans: Select all from product where Price between 50
and 100
(i) To display DCODE and DESCRIPTION of each dress in
ascending order of DCODE. (iii) To display the ClientName, City from table Client, and
Ans SELECT DCODE. DESCRIPTION FROM DRESS ProductName and Price from table Product, with their
ORDER BY DCODE ; corresponding matching P_ID.
(ii) To display the details of all the dresses which have Ans: Select ClientName,City, ProductName, Price
LAUNCHDATE in between 05-DEC‟-07 and 20-JUN-08 from Product,Client where Product.P_ID= Client.P_ID.
(inclusive of both the dates). (iv) To increase the Price of all Products by 10
Ans: Update Product Set Price=Price +10

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 12 PRAISE THE LORD


(v)SELECT DISTINCT Address FROM Client. (iii)To display the CustomerName, City from table
Ans: ( The above question may consist DISTINCT City. If Customer, and ItemName and Price from table Item, with
it is DISTINCT City, the following is the answer) their corresponding matching I_ID.
City Ans: SELECT CUSTOMERNAME,CITY,
----- ITEMNAME, PRICE FROM ITEM,CUSTOMER
Delhi WHERE ITEM.I_ID=CUSTOMER.I_ID.
Mumbai (iv) To increase the Price of all Items by 1000 in the table
Bangalore Item.
Ans: UPDATE ITEM SET PRICE=PRICE+1000
(vi)SELECT Manufacturer, MAX(Price), Min(Price),
Count(*) FROM Product GROUP BY Manufacturer; (v)SELECT DISTINCT City FROM Customer.
Ans: Ans: City
Manufacturer Max(Price) Min(Price) Count(*) Delhi
LAK 40 40 1 Mumbai
ABC 55 45 2 Bangalore
XYZ 120 95 2 (vi)SELECT ItemName, MAX(Price), Count(*) FROM
(vii)SELECT ClientName, ManufacturerName FROM Item GROUP BY ItemName;
Product, Client WHERE Client.Prod_Id=Product.P_Id; Ans: ItemName Max(Price) Count(*)
Ans: ClientName ManufacturerName Personal Computer 37000 3
Cosmetic Shop ABC Laptop 57000 2
Total Health ABC (vii)SELECT CustomerName, Manufacturer FROM
Live Life XYZ Item, Customer WHERE Item.Item_Id=Customer.Item_Id;
Pretty Woman XYZ Ans: CustomerName ManufacturerName
Dreams LAK N.Roy PQR
(viii)SELECT ProductName, Price * 4 FROM Product. H.Singh XYZ
ProductName Price*4 R.Pandey COMP
Talcom Poweder 160 C.Sharma PQR
Face Wash 180 K.Agarwal ABC
Bath Soap 220 (viii)SELECT ItemName, Price * 100 FROM Item
Shampoo 480 WHERE Manufacturer = „ABC‟;
Face Wash 380 Ans: ItemName Price*100
Personal Computer 3500000
12) Consider the following tables Item and Customer. Laptop 5500000
Write SQL commands for the statement (i) to (iv) and
give outputs for SQL queries (v) to (viii) (OD 2008) 13) Consider the following tables Consignor and
Consignee. Write SQL command for the
Table: ITEM statements(i)to(iv) And give outputs for the SQL quries
I_ID Item Name Manufa Price (v) to ( viii). (OD2007) 6
cturer TABLE : CONSIGNOR
PC01 Personal ABC 35000 CnorI CnorNa CnorAddress City
Computer D me
LC05 Laptop ABC 55000 ND01 R singhal 24,ABC New Delhi
PC03 Personal XYZ 32000 Enclave
Computer ND02 Amit 123,Palm New Delhi
PC06 Personal COMP 37000 Kumar Avenue
Computer MU15 R Kohil 5/A,South,Street Mumbai
LC03 Laptop PQR 57000 MU50 S Kaur 27-K,Westend Mumbai
TABLE : CONSIGNEE
Table: CUSTOMER Cnee CnorI CneeNam CneeAddress Cnee
C_I Customer Name City I_ID ID D e City
D MU0 ND01 Rahul 5,Park Avenue Mum
01 N.Roy Delhi LC03 5 Kishore bai
06 H.Singh Mumbai PC03 ND08 ND02 P Dhingra 16/j,Moore New
12 R.Pandey Delhi PC06 Enclave Delhi
15 C.Sharma Delhi LC03 KO19 MU15 A P Roy 2A,Central/av Kolka
16 K.Agarwal Banglore PC01 enue ta
(i) To display the details of those Customers whose city is MU3 ND02 S mittal P 245, AB Mum
Delhi. 2 Colony bai
Ans: SELECT ALL FROM CUSTOMER WHERE ND48 MU50 B P jain 13,Block New
CITY=”DELHI” d,a,viha Delhi
(ii)To display the details of Item whose Price is in the range (i)To display the names of all consignors from Mumbai.
of 35000 to 55000 (Both values included). Ans: SELECT CNORNAME FROM CONSIGNOR
Ans: SELECT ALL FROM ITEM WHERE WHERE CITY=”MUMBAI”;
PRICE>=35000 AND PRICE <=55000 (ii)To display the cneeID, cnorName, cnorAddress,
CneeName, CneeAddress for every Consignee.

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 13 PRAISE THE LORD


Ans: SELECT CNEEID, CNORNAME, Ans: SELECT * FROM SENDER ORDER BY
CNORADDRESS, CNEENAME, CNEEADDRESS SENDERNAME;
FROM CONSIGNOR,CONSIGNEE WHERE (iv)To display number of Recipients from each city.
CONSIGNOR.CNORID=CONSIGNEE.CNORID; Ans: SELECT RECCITY,COUNT(*) FROM
(iii)To display the consignee details in ascending order of RECIPIENT GROUP BY RECCITY;
CneeName.
Ans: SELECT * FROM CONSIGNEE ORDERBY (v) SELECT DISTINCT SenderCity FROM Sender;
CNEENAME ASC; Ans: DISTINCT(SENDERCITY)
(iv)To display number of consignors from each city. NewDelhi
Ans: SELECT CITY, COUNT(*) FROM Mumbai
(vi) SELECT A.SenderName A, B.RecName FROM
CONSIGNORS GROUP BY CITY;
Sender A, Recipient B WHERE A.SenderID=B. SenderID
(v)SELECT DISTINCT City FROM CONSIGNEE; AND B.RecCity=‟Mumbai‟;
Ans: CneeCity Ans: SenderName RecName
Mumbai R.Jain H.Singh
New Delhi S.Jha P.K.Swamy
Kolkata (vii)SELECT RecName,RecAddress FROM Recipient
(vi) SELECT A.CnorName A, B.CneeName B FROM WHERE RecCity Not IN („Mumbai‟, Kolkata‟);
Consignor A, Consignee B WHERE A.CnorID=B.CnorID Ans: RecName RecAddress
AND B.CneeCity=‟Mumbai‟; S Mahajan 116, A Vihar
S Tripati 13, B1 D, Mayur Vihar
(viii) SELECT RecID, RecName FROM Recipient
WHERE SenderID = „MU02‟ OR SenderID = „ND50‟;
Ans) Ans: RecID RecName
(vii)SELECT CneeName,CneeAddress FROM Consignee ND08 S Mahajan
WHERE CneeCity Not IN („Mumbai‟, „Kolkata‟); ND48 S Tripathi
Ans:
CneeName CneeAddress 15) Study the following tables FLIGHTS and FARES
P Dhingra 16/J,Moore Enclave and write SQL commands for the questions (i) to (iv)
B P Jain 13,Block D,A Vihar and give outputs for SQL quires (v) to(vi). (OD 2006)
(viii) SELECT CneeID, CneeName FROM Consignee TABLE: FLIGHTS
WHERE CnorID = „MU15‟ OR CnorID = „ND01‟;
Ans: CneeID CneeName
MU05 Rahul Kishore
KO19 A P Roy
14)Consider the following tables. Write SQL command
for the statements (i)to(iv)and give outputs for the SQL
quries (v) to (viii). (D2006) 6
TABLE : SENDER
SenderI SenderNa Sender Sender
D me Address City
ND01 R jain 2,ABC Appts New Delhi
MU02 H sinha 12, Newton Mumbai
MU15 S haj 27/ A,Park Street New Delhi TABLE:FARES
ND50 T Prasad 122-K,SDA Mumbai
TABLE :RECIPIENT
Sender ReCName RecAddress ReCCit
RecID ID y
KO05 ND01 R Bajpayee 5,Central Avenue Kolkata
ND08 MU02 S Mahajan 116, A Vihar New
Delhi
MU19 ND01 H sing 2A,Andheri East Mumbai
MU32 MU15 P K swamy B5, CS Terminus Mumbai
ND48 ND50 S Tripathi 13, B1 D,Mayur New
Vihar Delhi (i) Display FL_NO and NO_FLIGHTS from “KANPUR”
(i)To display the names of all senders from Mumbai. TO “BANGALORE” from the table FLIGHTS.
Ans:SELECT * FROM SENDER WHERE Ans: SELECT FL_NO, NO_FLIGHTS FROM
SENDERCITY=‟MUMBAI‟; FLIGHTS WHERE STARTING=”KANPUR” AND
(ii)To display the recID, senderName, senderAddress, ENDING=”BANGALORE”
RecName, RecAddress for every recipt. (ii) Arrange the contents of the table FLIGHTS in the
Ans: SELECT RECID, SENDERNAME, ascending order of FL_NO.
SENDERADDRESS, RECNAME, RECADDRESS Ans: SELECT * FROM FLIGHTS ORDER BY FL_NO;
FROM SENDER, RECIPIENT WHERE (iii) Display the FL_NO and fare to be paid for the flights
SENDER.SENDERID=RECIPIENT.RENDERID; from DELHI to MUMBAI using the tables FLIGHTS and
(iii)To display the sender details in ascending order of FARES, where the fare to be paid =
SenderName. FARE+FARE+TAX%/100.
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 14 PRAISE THE LORD
Ans: SELECT FL_NO, FARE+FARE+(TAX%/100) (iv) Display the highest consultation fee among all male
FROM FLIGHTS, FARES WHERE doctors.
STARTING=”DELHI” AND ENDING=”MUMBAI” Ans: SELECT MAX(CONSULATION) FROM
(iv) Display the minimum fare “Indian Airlines” is offering DOCTOR,SALARY WHERE SEX=”M” AND
from the tables FARES. DOCTOR.ID=SALARY.ID
Ans: SELECT MIN(FARE) FROM FARES WHERE
AIRLINES=”INDIAN AIRLINES” (v) SELECT count (*) from DOCTOR where SEX = “F”
Ans: 4
v)Select FL_NO,NO_FLIGHTS, AIRLINES from
FLIGHTS, FARES Where STARTING = “DELHI” AND (vi) SELECT NAME, DEPT , BASIC from DOCTOR,
FLIGHTS.FL_NO = FARES.FL_NO SALRY Where DEPT = “ENT” AND DOCTOR.ID =
Ans: SALARY.ID
Ans: Name Dept Basic
Jonah Ent 12000
17) Consider the following tables EMPLOYEES and
EMPSALARY. write SQL commands for the
Statements (i) to (iv) and give outputs for SQL quires (v)
(vi) SELECT count (distinct ENDING) from FLIGHTS. to (viii).(D2005)
Ans: 7 EMPLOYEES
16) Study the following tables DOCTOR and SALARY
and write SQL commands for the questions (i) to (iv)
and give outputs for SQL queries (v) to (vi) (D2006):
TABLE: DOCTOR

EMPSALRAY

TABLE: SALARY

(i) To display Firstname, Lastname, Address and City of


(i) Display NAME of all doctors who are in “MEDICINE” all employees living in Paris from the table
having more than 10 years experience from the Table EMPLOYEES.
DOCTOR. Ans: SELECT FIRSTNAME, LASTNAME,
Ans: SELECT NAME FROM DOCTOR WHERE ADDRESS,CITY FROM EMPLOYEES WHERE
DEPT=”MEDICINE” AND EXPERIENCE>10 CITY=”PARIS”
(ii) Display the average salary of all doctors working in (ii) To display the content of EMPLOYEES table in
“ENT”department using the tables DOCTORS and descending order of FIRSTNAME.
SALARY Salary =BASIC+ALLOWANCE. Ans: SELECT * FROM EMPLOYEES ORDER BY
Ans: SELECT AVG(BASIC+ALLOWANCE) FROM FIRSTNAME DESC
DOCTOR,SALARY WHERE DEPT=”ENT” AND
DOCTOR.ID=SALARY.ID (iii) To display the Firstname, Lastname, and Total Salary
(iii) Display the minimum ALLOWANCE of female of all managers from the tables, where Total Salary is
doctors. calculated as Salary+Benifts.
Ans: SELECT MIN(ALLOWANCE) FROM Ans: SELECT FIRSTNAME, LASTNAME,
DOCTRO,SALARY WHERE SEX=”F” AND SALARY+BENEFITS FROM EMPLOYEES,
DOCTOR.ID=SALARY.ID EMPSALARY WHERE DESIGNATION =

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 15 PRAISE THE LORD


”MANAGER” AND EMPLOYEES.EMPID (ii) To display the content of workers table in ascending
=EMPSALARY.EMPID order of LASTNAME.
(iv) To display the Maximum salary among Managers and Ans:SELECT * FROM WORKER ORDER BY
Clerks from the table EMPSALARY. LASTNAME ASC
Ans: SELECT DESIGNATION,MAX(SALARY) (iii) To display the FIRSTNAME, LASTNAME and Total
FROM EMPSALARY WHERE Salary of all Clerks from the tables WORKERS And
DESIGNATION=”MANAGER” OR DESIG, where Total
DESIGNATION=”CLERK” salary is calculated as Salary + benifts.
(v) SELECT FIRSTNAME,SALARY FROM Ans: SELECT FIRSTNAME, LASTNAME,
EMPLOYEES,EMPSALARY WHERE DESTINATION SALARY+BENEFITS WHERE WORKER.W_ID=
=‟Salesman‟ AND DESG.W_ID AND DESIGNATION=”CLERK”
EMPOLYEES.EMPID=EMPSALARY.EMPID; (iv) To display the minimum salary among managers and
Ans: Firstname Salary Clerks from the tables DESIG.
Rachel 32000 Ans:
Peter 28000 SELECT MIN(SALARY), DESIGNATION FROM DESIG
(vi) SELECT COUNT (DISTINT DESIGNATION ) WHERE DESIGNATION IN ('MANAGER'.'CLERK')
FROM EMPSALARY GROUP BY DESIGNATION;
Ans: 4 OR
SELECT MIN(SALARY), DESIGNATION FROM DESIG
(vii) SELECT DESIGNATION , SUM(SALARY)
WHERE DESIGNATION= „MANAGER‟ OR
FROM EMPSALARY GROUP BY DESIGNATION DESIGNATION='CLERK' GROUP BY DESIGNATION;
HAVING COUNT(*)>2; OR
Ans: Designation Sum(Salary) SELECT MIN(SALARY) FROM DESIG WHERE
Manager 215000 DESIGNATION=„MANAGER‟ OR
Clerk 135000 DESIGNATION='CLERK';
(viii)SELECT SUM (BENEFITS) FROM EMPSALARY OR
WHERE DESIGNATION=‟Clerk‟; SELECT MIN(SALARY) FROM DESIG WHERE
Ans: 32000 DESIGNATION IN („MANAGER‟,„CLERK‟);

18) Consider the following tables WORKERS and (v) SELECT FIRSTNAME, SALARY FROM WORKERS,
DESIG. Write SQL commands for the statements (i) to DESIG WHERE DESIGINATION = “MANAGER” AND
(iv) and give outputs for SQL queries (v) to (viii).(OD WORKERS.W_ID = DESIGN.W_ID
2005) Ans: FIRSTNAME SALARY
WORKERS Sam 75000
Manila 70000
George 75000
(vi)SELECT COUNT(DISTINCT DESIGNATION)
FROM DESIGN ;
Ans: 4
(vii) SELECT DESIGNATION, SUM(SALARY) FROM
DESIG GROUP BY DESIGNATION HAVING COUNT
(*) < 3;
Ans: Designation Sum(Salary)
Director 85000
Salesman 60000
(viii) SELECT SUM(BENIFTS) FROM DESIG WHERE
DESIGINATION=”salesman”;
Ans: 15000
DESIG 19. Give the following table for database a LIBRARY.
(2004)
TABLE : BOOKS

(i) To display W_ID Firstname, address and City of all


employees living in New York from the Table WORKERs
Ans: SELECT W_ID , FIRSTNAME,ADDRESS, CITY
FROM WORKERS WHERE CITY=”NEW YORK”

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 16 PRAISE THE LORD


TABLE:ISSUED TABLE:NEWONES

Write SQL queries from b to g.


(b)To show Book name, Author name and Price of books of
EPB publisher. (b) To show all information about the sofas from the
Ans: SELECT BOOK_NAME,AUTHOR_NAME, INTERIORS table.
PRICE FROM BOOKS WHERE PUBLISHER =”EPB” Ans: SELECT * FROM INTERIORS WHERE TYPE=
(c) To list the names of the books of FICTIONS type. “SOFA”
Ans: SELECT BOOK_NAME FROM BOOKS (d) To list ITEMNAME and TYPE of those items, in which
WHERE TYPE=”FICTION” DATEOFSTOCK is before 22/01/02 from the INTERIORS
(d) To display the names and prices of the books in table in descending order of ITEMNAME.
descending order of their price. Ans: SELECT ITEMNAME,TYPE FROM
Ans: SELECT BOOK_NAME, PRICE FROM BOOKS INTERIORS WHERE DATEOFSTOCK<‟22/01/02‟
ORDER BY PRICE DESC; ORDER BY ITEMNAME
(e) To increase the price of all books of First Pub.by 50. (e) To display ITEMNAME and DATEOFSTOCK of those
Ans: UPDATE BOOKS SET PRICE= PRICE+50 items in which the Discount percentage is more than 15
WHERE PUBLISHERS = “FIRST PUBL” from INTERIORS.
(f) To Display the Book_ID, Book_Name and Quantity Ans: SELECT ITEMNAME,DATEOFSTOCK FROM
Issued for all books Which have been issued. INTERIORS WHERE DISCOUNT>15
Ans:SELECT BOOK_ID, BOOK_NAME, (f) To count the number of items whose type is “Double
QUANTITY_ISSUED FROM BOOKS,ISSUED bed”;
WHERE BOOKS.BOOKID= ISSUED.BOOKID; Ans: SELECT COUNT(*) FROM INTERIORS
(g) To insert a new row in the table Issued having the WHERE TYPE=”DOUBLE BED”
following data: “F0002”,4 (g) To insert new row in the NEWONES table with the
Ans: INSERT INTO ISSUED VALUES(“F0002”,4) following data: 14, “True Indian “, “Office Table “,
{28/03/03},15000,20
(h) Give the output of the following queries on the above Ans: INSERT INTO NEWONES VALUES (14,”TRUE
tables INDIAN”,”OFFICE TABLE”,‟28/03/03‟,15000,20)
(i) Select Count(Distinct Publishers) From Books
(h) Give the outputs for the following SQL statements.
Ans: 3
(ii) Select Sum(Price) From Books Where Quantity>5 (i) Select COUNT (distinct TYPE) from INTERIORS;
Ans: 1350 Ans: 5
(iii) Select Book_Name,Author_Name From Books Where (ii) Select AVG(DISCOUNT)from INTERIORS where
Price<500 TYPE =”Baby cot”;
Ans: Book_Name Author_Name Ans: 13
My First C++ Brian & Brooks (iii) Select SUM(price)from INTERIORS where
C++ Brainworks A.W.Rossaine DATEOFSTOCK<{12/02/02};
Fast Cook Lata Kapoor Ans: 53000
(iv) Select Count(*) From Books 21)Consider the following tables ACTIVITY and
Ans: 5 COACH and answer (b) and (c) parts of this question:
20.Write SQL commands for (b) to (g) and write the (MP109-10)
outputs for (h) on the basis of tables TNTERIORS and
NEWONES. (2003)
TABLE: INTERIORS

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 17 PRAISE THE LORD


b)Write SQL commands for the flowing statements:4 Ans) SELECT * FROM Games ORDER BY
(i) To display the names of all activities with their Acodes ScheduleDate;
in descending order. (iv) To display sum of PrizeMoney for each Type of
Ans) SELECT Acodes, ActivityName FROM GAMES
ACTIVITY ORDER BY Acode DESC; Ans) SELECT SUM(Prizemoney),Type FROM Games
(ii) To display sum of PrizeMoney for the Activities played GROUP BY Type;
in each of the Stadium separately.
c) Give the output of the following SQL queries: 2
Ans) SELECT SUM(PrizeMoney), Stadium FROM
(i) SELECT COUNT(DISTINCT Number) FROM
ACTIVITY GROUP BY Stadium;
GAMES;
(iii) To display the coach's name and ACodes in ascending
Ans) 2
order of ACode from the table COACH
Ans) SELECT Name, Acode FROM COACH ORDER (ii) SELECT MAX(ScheduleDate), MIN(ScheduleDate)
BY Acode; FROM GAMES;
(iv) To display the content of the Activity table whose Ans) 19-Mar-2004 12-Dec-2003
ScheduleDate earlier than 01/01/2004 in ascending order of (iii) SELECT Name, GameName FROM GAMES G,
ParticipantsNum. PLAYER P WHERE G.Gcode=P.Gcode AND
Ans) SELECT * FROM ACTIVITY WHERE G.PrizeMoney>10000;
SchduleDate<'01-Jan-2004' ORDER BY Ans) Ravi Sahai Lawn Tennis
ParticipantsNum; (iv) SELECT DISTINCT Gcode FROM PLAYER;
Ans) 3
c) Give the output of the following SQL queries:2
(i) SELECT COUNT(DISTINCT ParticipantsNum) FROM 23)Consider the following tables ACTIVITY and
ACTIVITY; COACH. Write SQL commands for the statements (i) to
Ans) 3 (iv) and give outputs for SQL queries (v) to (viii)
(ii)SELECT MAX(ScheduleDate), MIN(ScheduleDate) (MP108-09) 6
FROM ACTIVITY;
Ans) 19-Mar-2004 12-Dec-2003
(iii) SELECT Name,ActivityName FROM ACTIVITY
A,COACH C WHERE A.Acode= C.Acode AND
A.ParticipantsNum = 10;
Ans) Ravinder Discuss Throw
(iv) SELECT DISTINCT Acode FROM COACH;
Ans) 1001
1003
1008

22) Consider the following tables GAMES and PLAYER


and answer (b) and (c) parts of this question (MP209-10)

i)To display the name of all activities with their Acodes in


descending order.
Answer: SELECT ActivityName, ACode FROM
ACTIVITY ORDER BY Acode DESC;
(ii) To display sum of PrizeMoney for each of the Number
of participants groupings (as shown in column
ParticipantsNum 10,12,16)
Answer: SELECT SUM(PrizeMoney), ParticipantsNum
FROM ACTIVITY GROUP BY ParticipantsNum;
(iii) To display the coach‟s name and ACodes in
ascending order of ACode from the table COACH
Answer: SELECT Name, ACode FROM COACH
ORDER BY ACode;
(iv) To display the content of the ACTIVITY table whose
ScheduleDate earlier than 01/01/2004 in ascending order of
ParticipantsNum.
b)Write SQL commands for the flowing statements:4
Answer: SELECT * FROM ACTIVITY WHERE
(i) To display the name of all GAMES with their GCodes
ScheduleDate<‟01-Jan-2004‟ ORDER BY
Ans) SELECT GameName,Gcode FROM GAMES;
ParticipantsNum;
(ii) To display details of those GAMES which are having
PrizeMoney more than 7000. v)SELECT COUNT(DISTINCT ParticipantsNum) FROM
Ans) SELECT * FROM Games WHERE ACTIVITY;
Prizemoney>7000; Answer: 3
(iii) To display the content of the GAMES table in (vi)SELECT MAX(ScheduleDate), MIN(ScheduleDate)
ascending order of Schedule Date. FROM ACTIVITY;
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 18 PRAISE THE LORD
Answer: SUM(PERIODS) SUBJECT
19-Mar-2004 12-Dec-2003 51 ENGLISH
(vii) SELECT SUM(PrizeMoney) 76 PHYSICS
FROM ACTIVITY; 24 MATHS
Answer: 54000 27 CHEMISTRY
(viii) SELECT DISTINCT (vi) SELECT TEACHERNAME, GENDER FROM
ParticipantsNum FROM ACTIVITY; SCHOOL, ADMIN WHERE DESIGNATION
Answer: 16 =‟COORDINATOR‟ AND
10 SCHOOL.CODE=ADMIN.CODE;
12 TEACHERNAME GENDER
24) Consider the following tables SCHOOL and PRIYA RAI FEMALE
ADMIN. Write SQL commands for the statements LISA ANAND FEMALE
(i) to (iv) and give outputs for SQL queries (v) to (vii) SELECT DESIGNATION, COUNT(*) FROM
(viii). ADMIN GROUP BY DESIGNATION HAVING
TABLE: SCHOOL COUNT(*)>1;
COD TEACHE SUBJECT DOJ PERI EXP DESIGNATION COUNT(*)
E RNAME ODS ERI COORDINATOR 2
ENC HOD 2
E
1001 RAVI ENGLISH 12/03/2000 24 10 SENIOR TEACHER 2
SHANKAR (viii) SELECT COUNT(DISTINCT SUBJECT) FROM
1009 PRIYA PHYSICS 03/09/1998 26 12 SCHOOL;
RAI COUNT(*)
1203 LISA ENGLISH 09/04/2000 27 5
ANAND 4
1045 YASHRAJ MATHS 24/08/2000 24 15
1123 GAMAM PHYSICS 16/07/1999 28 3 MODEL 2 : SINGLE TABLE
1167 HARISH B CHEMISTRY 19/10/1999 27 5 25. Given the following Teacher Relation. (2002)
Write SQL Commands fro (b) to (g)
1215 UMESH PHYSICS 11/05/1998 22 16

TABLE: ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD
(i) To decrease period by 10% of the teachers of
English subject.
UPDATE SCHOOL SET PERIOD = (b) To select all the information of teacher in computer
PERIOD*0.90; department
(ii) To display TEACHERNAME, CODE and Ans: Select * from Teacher where
Department=”Computer”
DESIGNATION from tables SCHOOL and ADMIN
whose gender is male. (c ) To list the name of female teachers in History
SELECT S.TEACHERNAME,S.CODE, Department.
A.DESIGNATION FROM SCHOOL, ADMIN A Ans: Select Name from Teacher Where Sex=”F” And
Department=”History”
WHERE GENDER=‟MALE‟ AND (d) To list all names of teachers with date of admission in
S.CODE=A.CODE; ascending order.
(iii) To display number of teachers in each subject. Ans: Select Name from Teacher Order By Dateofjoining
SELECT SUBJECT, COUNT(*) FROM SCHOOL Asc
GROUP BY SUBJECT; (e) To display Teacher's Name, Department, and Salary of
(iv) To display details of all teachers who have joined female teachers
the school after 01/01/1999 in descending order of Ans: Select Name,Department,Salary from Teacher
experience. Where Sex=”F”
SELECT S.CODE,S.TEACHERNAME, (f)To count the number of items whose salary is less than
S.SUBJECT, S.DOJ,S.PERIODS, 10000
Ans: Select Count(*) from Teacher Where
S.EXPERIENCE,A.GENDER,A.DESIGNATION
Salary<10000
FROM SCHOOL S, ADMIN A WHERE (g) To insert a new record in the Teacher table with the
DOB>‟01/01/1999‟ AND S.CODE=A.CODE following data:
ORDER BY EXPERIENCE DESC; 8,”Mersha”,”Computer”,(1/1/2000),12000,”M”.
(v) SELECT SUM(PERIODS), SUBJECT FROM Ans: Insert into Teacher values ,”Mersha”,
SCHOOL GROUP BY SUBJECT; ”Computer”,{1/1/2000),12000,”M”);
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 19 PRAISE THE LORD
26) Write the SQL commands for (i) to (vii) on the basis (d) To display a report, showing coachname, pay, age and
of the table SPORTS (2001) bonus(15% of pay) for all coaches.
TABLE: SPORTS Ans:
Select Coachname,Pay,Age,Pay*0.15 from Club
(e) To insert a new row in the CLUB table with following
data: 11,”PRAKASH”,37,”SQUASH”,
{25/02/98},2500,”M”
Ans: Insert into Club Values
(11,”PRAKASH”,37,”SQUASH”,{25/02/98}, 2500,”M”)
(f) Give the output of the following SQL statements:
(i) select COUNT (distinct SPORTS)from CLUB;
Ans: 4
(ii) select MIN(AGE) from CLUB where
SEX =”F”;
Ans: 34
(i) Display the names of the students who have grade „C‟ in (iii) select AVG(PAY) fromCLUB where SPORTS =
either Game1 or Game2 or both. “KARATE”;
Ans: Select Name From Sports Where Grade1=”C” OR Ans: 1100
Grade2=”C” (iv) select SUM(PAY) from CLUB where
(ii) Display the number of students getting grade „A‟ in DATAOFAPP>{31/01/98};
Cricket. Ans: 7800
Ans: Select Count(*) from Sports Where (G) Assuming that there is one more table COACHES in
(Game1=”Cricket” and Grade1=”A”) or the database as shown below:
(Game2=”Cricket” and Grade2=”A”) TABLE:COACHES
(iii) Display the names of the students who have same game
for both game1 and game2
Ans: Select Name From Sports Where Game1=Game2
(iv) Display the games taken up by the students, whose
name starts with „A‟.
Ans: Select Game1,Game2 From Sports Where Name
Like “A%”
(v) Add a new column named „marks‟. What will be the output of the following query:
Ans: Alter Table Sports Add Marks Number(5); SELECT SPORTS PERSON, COACHNAME
(vi) Assign a value 200 for marks for all those who are FROM CLUB,COACHES
getting grade „B‟ or „A‟ in both Game1 and Game2. WHERE COACH_ID=COACH_NO
Ans: (Children, Try This Answer as an assignment)
(vii) Arrange the whole table in the alphabetical order of
name.
Ans: Select * from Sports Order By Name
Ans)
27. Write SQL commands for the (b) to (e) and write the
28) Given the following Teacher relation: Write SQL
outputs for (g) on thse basis of table CLUB. (2000)
commands for questions (b) to (g). (1999)
TABLE: CLUB
TEACHER

(b) To show all information about the swimming coaches in (b)To show all information about the teachers of history
the club. department.
Ans: Select * from Club where SPORTS= ”SWIMMING” Ans:select * from teacher where department=‟history‟;
(c) To list names of all coaches with their date of (c) To list names of female teacher who are in math
appointment (DATOFAPP) in descending order. department.
Ans: Select COACHNAME,DATEOFAPP from Club Ans: select name from teacher where sex=‟female‟ and
order by DATEOFAPP desc; department=‟maths‟;

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 20 PRAISE THE LORD


d) To list names of all teacher with their date of joining in 13. BOOLEAN ALGEBRA
ascending order. Laws:
Ans:Select Name From Teacher order by dateofjoing; (1)Properties of 0 and 1:
(f) To count the number of teachers with age >23. 0 + X = X, 1 + X = 1,
Ans: Select count(name) from teacher where age>23; 0.X = 0, 1.X = X
(g) To insert a new row in the teacher table with the (2) Idempotence Law:
following data: (a)X +X = X (b)X.X = X
9, “raja‟, 26, “computer”, {13/5/95 }, 2300, “M”.
Ans: Insert into Teacher values(9,”raja”,26, (3) Involution Law: =A
”computer”, {13/05/95},2300,”M”); (4)ComplementaryLaw:
(a)X + =1 (b)X. =0
29. Write SQL commands for (b) to (g) and write (5)Commutative Law:
the outputs for (h) on the basis of (a) X+Y =Y+X (b)X.Y=Y.X
table HOSPITAL (1998) (6) Associative Law:
(a)X + (Y+Z)=(X+Y)+Z
(b)X.(Y.Z)=(X.Y).Z
(7) Distributive Law:
(a) X(Y+Z)=XY+XZ (b) X+YZ=(X+Y)(X+Z)
(8) Absorption Law:
(a) X+XY=X (b)X(X+Y)+X
(c)X+X‟Y = X+Y (d) X.(X‟+Y) = X.Y
X+X‟Y = X+Y is also known as third distributive law.
(9) Demorgan‟s Theorems
(a) (b)

Model 1: Boolean Laws (2 Marks)

Model 1A: Boolean Laws (Truth Table) (2M)


(b) To select all the information of patients of all cardiology
department. 1.State any one Distributive Law of Boolean
Ans: Select all from Hospital where Algebra and Verify it using truth table.
department=”Cardiology” 2019MP (2007D) (D2006) (2002)(1999) 2
(c) To list the names of female patients who are in ent
department. Ans) Distributive Law:
Ans:select name from Hospital where (i)A (B+C) = AB + AC (ii) A+BC=(A+B)(A+C)
Department=”Ent” and Sex=”F” Verification of first distributive law using Truth
(d) To list names of all patients with their date of admission Table: A (B+C) = AB + AC
in ascending order.
Ans: Select name,dateofadm from Hospital dateofadm.
(e) To display patients name, charges, age, for only female
patients.
Ans: Select Name,Charges,age from Hospital where
sex=”F”
(f) To count the number of patients with age <30.
Ans: Select count(*) from hospitals where age<30
(g) To insert the new row in the hospital table with the
following data: 11, “aftab”, 24, “surgery”, {25/2/98}, 300,
“M”. Comparing Column 5 and 8, Distributive law is
Ans: insert into Hospital values(11, “aftab”, 24, verified
“surgery”, {25/02/98}, 300, “M”) OR
(h) Give the output of the following SQL statements: Verification of second distributive law using
(i) Select count (distinct charges)from hospital; Truth Table:
Ans: 5
(ii) Select min(age) from hospital where sex = “f‟;
Ans: 16
(iii) Select sum(charges) from hospital where department =
“ent”;
Ans: 750
(iv) Select avg(charges) from hospital where date of
admission is <{12/02/98};
Ans:380

Comparing Column 5 and 8, Distributive law is


verified
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 21 PRAISE THE LORD
2) Yerify the following using Truth Table: 2 5.State DeMorgan‟s Laws of Boolean Algebra and
X+Y. Z=(X+Y).(X+Z) verify them using truth table.
(2017) (OD2007) (2003)(1998)
Ans)(i) (X+Y)‟ = X‟.Y‟ (ii) (X.Y)‟ = X‟+Y‟

3) State any one Absorption Law of Boolean


Algebra and verify it using truth table
(2018)(OD2009)(OD2008)(OD2005)(2002) 2
Ans) Absorption Laws:
(a) X+XY=X (b)X(X+Y)=X
(c)X+X‟Y = X+Y (d) X.(X‟+Y) = X.Y

State and verify De Morgan‟s law in Boolean


Algebra. (D2008) (MP108-09 2
6)State and verify AssociativeLaw. (OD2006) 2
Ans) (D2005)

OR

7) Verify the following using truth table: (2012)2


(i) X,X' = 0

4. Name the law shown below and verity it using a


truth table. (2014)

This is absorption law (In some books it is written as as 8) Verify X‟Y + X.Y‟ + X‟Y‟ = (X‟ + Y‟) using
third distributive law.) truth table. (D2009) 2
Ans)
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 22 PRAISE THE LORD
= X‟.Y‟.(Z+Z‟) + X‟.Y.(Z+Z‟) + X.Y‟.Z
= X‟.Y‟ + X‟.Y + X.Y‟.Z
= X‟.(Y‟+Y) +X.Y‟.Z
= X‟ + X.Y‟.Z
= (X‟ + X).(X‟ + Y‟.Z)
= X‟ + Y‟.Z
= LHS
4.Verify the following using Boolean Laws.
Model 1B: Boolean Laws – Algebraic Method U‟+ V= U‟V‟+U‟.V +U.V (2015)
(2Marks) L.H.S =U‟+ V
1) State and verify De Morgan‟s law in Boolean =U‟.(V+V‟)+ V.(U‟+ U)
Algebra. (MP109-10) (D2008) 2 =U‟.V + U‟.V‟ + U‟.V + U.V
=U‟.V+U‟.V‟+U.V
Ans) (i) (X+Y)‟= X‟.Y‟ (ii) (X.Y)‟= X‟+Y‟ =R.H.S
Verification OR
(X+Y)'.(X+Y) = X'.Y'.(X+Y) R.H.S =U‟V‟+U‟.V +U.V
0 = X'.Y'.X + X'.Y'.Y =U‟.(V‟+ V)+ U.V
0 = X'.X .Y'+ X'.0 =U‟.1 + U.V
0 = 0 .Y'+ 0 =U‟+ U.V
0=0+0 =U‟+ V =L.H.S
0=0 5) Verify the following using Boolean Laws
L.H.S = R.H.S X+Z = X + X‟.Z + Y.Z (2013) 2
2) State and verify Absorption Law in Boolean Ans: RHS X + X‟.Z + Y.Z
= X + Z + YZ (X + X‟Y = X+Y)
algebra.(OD2008) (OD2005)(2004) (MP208-09)2 = X + Z.1 + Z.Y
Ans)(a) X+XY = X (b)X(X+Y) = X = X + Z (1 + Y)
(c)X+X‟Y = X+Y (d) X.(X‟+Y) = X.Y = X + Z.1
Algebraic Verification: =X+Z LHS
(a) X+XY = X 6)Verify the following algebraically 2
LHS X+X.Y = X.1+X.Y (A‟+B‟).(A +B)=A‟.B+A.B‟ (2011)
= X.(1+Y)
=X.1
Ans. LHS
=X RHS (A‟ +B‟ ) . (A+B)
Verified = A‟.A + A‟.B + A.B‟ + B‟.B
OR = 0 + A‟.B + A.B‟+ 0
(b)X(X+Y) = X = A‟.B + A.B‟
LHS X.(X+Y) = XX+X.Y = RHS (Verified)
= X.1+X.Y 7)Verify the following algebraically:(OD 2010)2
= X.(1+Y)
= X.1 X‟.Y + X.Y‟ = (X‟+Y‟).(X+Y)
=X RHS Ans. R. H . S
Verified (X‟+y‟).(x+y)
OR = x‟.(x+y)+y‟.(x+y)
(c)X+X‟Y = X+Y = x.x‟+X‟.y+y‟.x+y‟.y
LHS X+X‟. Y = (X+X‟)(X+Y) = x‟.y+y‟.X
= 1.(X+Y) = x‟.y+x.y‟
= X+Y RHS
So L.H.S=R.H.S
Verified
OR OR
(d) X.(X‟+Y) = X.Y L.H.S.
LHS X(X‟+Y) = XX‟+X.Y X‟.Y + X.Y‟
= 0+X.Y = (X‟.Y+X) (X‟.Y+Y‟)
= X.Y RHS = (X‟+X).(Y+X).(X‟+Y‟).(Y+Y‟)
Verified = 1.(X+Y).(X‟ +Y‟).1 = (X+Y).(X‟+Y‟) = R.H.S.
3. Verify the following using Boolean Laws. (2016)2 8) Verify X.Y‟Z+X.Y‟Z‟+X‟.Y‟Z = X.Y‟ + Y‟.Z
X‟+ Y‟Z = X‟.Y‟.Z‟+ X‟.Y.Z‟+ X‟Y.Z+ X‟.Y‟.Z+ algebraically. (2003)
X.Y‟.Z 9) Prove XY + YZ + Y‟Z =XY + Z, algebraically.
Ans LHS =X‟ + Y‟.Z (2002) 2
= X‟.(Y + Y‟).(Z + Z‟) + (X + X‟).Y‟.Z 10) Prove algebraically:
= X‟.Y.Z + X‟.Y.Z‟ + X‟.Y‟.Z + X‟.Y‟.Z‟ + X.Y‟.Z
x‟y‟z‟+x‟y‟z+x‟yz‟+x.y‟z=x‟+y‟ (2001)
+ X‟.Y‟.Z
= X‟.Y.Z + X‟.Y.Z‟ + X‟.Y‟.Z + X‟.Y‟.Z‟ + X.Y‟.Z
11) Prove X‟.Y+Y‟.Z= X‟.Y.Z+X‟.Y‟.Z‟+
= X‟.Y‟.Z‟ + X‟.Y.Z‟ + X‟.Y.Z + X‟.Y‟.Z + X.Y‟.Z X.Y‟.Z+X‟.Y‟.Z algebraically. (2000)
= RHS 12) Prove x+x'y=x+y algebraically. (1999)
OR 13) Prove X+Y'Z=(X+Y'+Z')(X+Y'+Z)(X+Y+Z)
RHS=X‟.Y‟.Z‟ + X‟.Y.Z‟ + X‟.Y.Z + X‟.Y‟.Z + X.Y‟.Z algebraically. (1998)
= X‟.Y‟.Z + X‟.Y‟.Z‟ + X‟.Y.Z + X‟.Y.Z‟ + X.Y‟.Z
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 23 PRAISE THE LORD
Model 1C: Correct the Boolean Laws/Statements 1) Derive a canonical POS expression for a
(2Marks) Boolean function FN, represented by the
Correct the following boolean statements: following truth table. (2018)
1. X+1 = X 2. (A')'=A' X Y Z FN(X,Y,Z)
3. A+A'=0 4. (A+B)' = A.B (2017 MP) 0 0 0 1
A) 1. X+1 =1 or X+0=X 2. ((A‟)‟) = A 0 0 1 1
3. A + A‟= 1 or A . A‟=0 4. (A+B)‟ = A‟ . B‟ 0 1 0 0
Model 2A: Write SOP Form (1 Mark) 0 1 1 0
(Consider Only 1‟s combinations from the Result Column.
Here Variable Value is 1 ) 1 0 0 1
1.Derive a Canonical SOP expression for a 1 0 1 0
Boolean function F(X,Y,Z) represented by the 1 1 0 0
following truth table: 2019MP1 1 1 1 1
Ans: FN(X,Y,Z)=
(X+Y‟+Z).(X+Y‟+Z‟).(X‟+Y+Z‟).(X‟+Y‟+Z)
OR
FN(X,Y,Z)= Π (2,3,5,6)
2. Write the POS form of a Boolean Function F,
which is represented in a truth table as follows:
(2017 MP)
P Q R F
Ans: F(X,Y,Z)= X‟Y‟Z‟+X‟Y‟Z+XY‟Z‟+XYZ 0 0 0 0
OR 0 0 1 1
F(X,Y,Z)=Σ(0,1,4,7) 0 1 0 1
2) Write the SOP form of a Boolean Function F, 0 1 1 1
Which is represented by the following truth table: 1 0 0 0
(D2005)1 1 0 1 1
1 1 0 0
1 1 1 1
A) F(P,Q,R) = (P+Q+R).(P‟+Q+R).(P‟+Q‟+R)
3) Write the POS form of a Boolean function H,
which is represented in a truth table as follows:
(D2009) 1
Ans) A'.B'.C' + A'.B.C + A.B.C' + A.B.C
3) Write the SOP form of a Boolean function G,
which is represented in a truth table as follows:
(MP208-09)1

Ans) H(A,B,C) = (A+B+C).(A‟+B+C‟).(A‟+B‟+C)


OR
H(A,B,C) = (0, 5, 6)
Ans) G(P,Q,R) = P‟.Q.R‟+P.Q‟.R‟+P.Q.R‟+P.Q.R 4) Try following:
4) Try following:

Model 2B: Write POS Form (1 Mark) Model 3A: Write the Equivalent Boolean
(Consider Only 0‟s combinations from the Result Column. Expression (2 Marks)
Here Variable Value is 0 )

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 24 PRAISE THE LORD


1.Write the Boolean Expression for the result of
the Logic Circuit as shown below: (2016)

OD200
P.Q‟ + P.R + Q.R‟ 6
2) Write the equivalent expression for the following
Logic Circuit : (OD2005) 2

MP10
Ans) U.V‟+U‟.V+U‟.V 9-10
3) Write the equivalent Boolean expression for the
following Logic Circuit: (D2005) 2

Model 3B: Draw the Logic Circuit (2 Marks)


Ans) (X+Y‟)(X‟+Y)(X‟+Y‟) 1.Draw the Logic Circuit of the following
4)Write the equivalent Boolean Expression for the Boolean Expression:
following Logic Circuit (MP108-09) 2 ((U + V‟).(U + W)). (V + W‟) 2019MP2

Ans) F(P,Q)=(P‟+Q).(P+Q‟)
2014
2) Draw the Logic Circuit of the following Boolean
Expression: (U‟+V).(V‟+W‟) (2018)2

2013

3.Draw the equivalent logic circuit for the following


OD201 Boolean expression: (A.B)+C (2017MP)
0

OD200
7 4. Draw the Logic Circuit for the following Boolean
Expression : (X‟+Y).Z+W‟ (2015)

D2007

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 25 PRAISE THE LORD


5) Draw a logical circuit diagram for the following
Boolean Expression: (OD2008) 1
A.(B+C‟)

Ans) Answer: X‟Z‟+Y‟W‟+Y‟Z+XZW‟


6) Draw a Logical Circuit Diagram for the
2) Reduce the following Boolean Expression to
following Boolean Expression. (D2008) 1
X‟.(Y‟+Z) its simplest form using K-Map:2018 (3)
G(U,V,W,Z) = ∑ (3,5,6,7,11,12,13,15)

7) Draw a logical circuit diagram for the following


Boolean expression: A‟.(B+C) 1
Model 3B: Draw the Logic Circuit Using NAND or
NOR gates (2 Marks)
1. Draw the Logic Circuit of the following Boolean
Expression using only NOR Gates:
F(U,V,W,Z)= VZ + WZ + UVW‟+ U‟VW
( A+B).(C+D) (2017) 2 3. Reduce the following Boolean expression to its
simplest form using K-Map: (2017)
E(U,V,Z,W)= Σ (2,3,6,8,9,10,11,12,13)

2) Represent the Boolean expression X‟Y+Y‟Z with


the help of NAND gates only. (2000)
3) Represent the Boolean expression
(X+Y)(Y+Z)(X+Z) with help of NOR gates only.
(2002) 1
4) Represent the Boolean expression (x+y)(y+z)(z+x)
with the help of NOR gates only. (1999) E(U,V,Z,W) = UZ‟ + V‟Z + U‟ZW‟
5) Represent the Boolean expression X+Y.Z' with the K-MAP (SOP) Year
help of NOR gates only. (1998) F(A,B,C,D) = Σ (0,1,3,5,6,7,9,11,13,14,15) 2017
REPRESENT X‟Y‟ + X‟Z + Y‟Z‟ using NAND gates only F(P,Q,R,S) = ∑ (0,4,5,8,9,10,11,12,13,15) 2016
F(X,Y,Z,W) = Σ(0,1,4,5,6,7,8,9,11,15) 2015
F(A,B,C,D) = Σ(1,3,4,5,6,7,12,13) 2014
F(U,V,W,Z) = Σ (0,1,2,3,6,7,8,9,10,13,15) 2013
F(A, B, C, D) = Σ (2, 3, 4, 5, 6, 7, 8, 10, 11) 2012, D2010
F(A, B,C, D) =(0,1, 2, 4, 5, 6, 7, 8, 10) 2011
F(U, V, W, Z) = (3, 5, 7, 10, 11, 13, 15) D2010
F (A,B,C,D) = (3,4,5,6, 7,13,15) OD2010
F(P,Q,R,S) = ∑ (1,2,3,5,6,7,9,11,12,13,15) D2009
H(U,V,W,Z) = ∑( 0,1,4,5,6,7,11,12,13,14,15) OD2009
F(A,B,C,D) = ∑(0,1,2,,4,5,8,9,10,11) OD2008
F(A,B,C,D) = ∑(0,2,3,4,6,7,8,10,12) D2008
F(U, V, W, Z) = ∑(0,1,2,3,4,10,11) D2007
F(P, Q, R, S,) = ∑(0,3,5,6,7,11,12,15) D2006
Model 4A: Reduce the Boolean Expression using
F(A, B, C, D,) = ∑(0,1,2,3,4,5,10,11,15) OD2005
K-Map (3 Marks)
F(a,b,c,d) = ∑(0,1,2,4,5,7,8,9,10,11,14) 2004
1.Reduce the following Boolean Expression to its F(U,V,W,Z,)=∑(0,2,3,4,7,9,10,13,14,15) 2003
simplest form using K-Map: 2019SP3 F(w,x,y,z)=∑(2,3,6,10,11,14) 2002
F(X,Y,Z,W)= Σ (0,1,2,3,4,5,8,10,11,14) F(x,y,z,w)= ∑ (1,3,4,5,7,9,11,12,13,15) 2000
F ( w,x,y,z) = ∑ (0,4,8,12 1999
F( U, V, W,Z) = ∑(0,1,3,5,7,9,10,11,12,13,14,15) 1998
F(A,B,C,D)=  (0,1,2,4,5,6,8,10) MP108-09

F(A,B,C,D)=(0,1,2,4,5,6,8,10) MP109-10

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 26 PRAISE THE LORD


Model 4B: Reduce the Boolean Expression using Model 5B: Convert the expression into POS
K-Map Π (3 Marks) (1Mark)
1) Reduce the following Boolean expression using K
1) Convert the following Boolean expression into
– Map : (OD2006) 3
its equivalent Canonical Product of sum form
F(P, Q, R, S,) = Π (0,3,5,6,7,11,12,15)
(POS): A.B‟C + A‟.B.C + A‟.B.C‟. (OD200) 2
Ans) A.B‟C + A‟.B.C + A‟.B.C‟
= m5 + m3 + m2
= ∑(2,3,5)
=  (0,1,4,6,7)
= (A+B+C)((A+B+C’)(A’+B+C)(A’+B’+C)(A”+B’+C’)
2) Write the equivalent canonical product of sum
expression for the following sum of product
expression: (OD2007) 2
F(X, Y,Z) = ∑ (0, 2,4,5)
Ans)F(X, Y, Z) =  (1, 3, 6, 7)
OR
F=(X+Y+Z‟)(X+Y‟+Z‟)(X‟+Y‟+Z)(X‟+Y‟+Z‟)
2) Reduce the following Boolean expression using
K – Map : (D2005) 3 Model 6A: Express the following in SOP (1 Mark)
F(A, B, C, D,) = Π (0,1,2,3,4,5,10,11,15)
Ans) F(A, B, C, D,) = Π (0,1,2,3,4,5,10,11,15) 1) Express P +Q‟R in canonical SOP form.
(D2006)1
(P + Q‟R) = P.1.1 + 1.Q‟.R
= P ( Q+Q‟)(R+R‟) + (P+P‟)Q‟R
= (PQ +PQ‟) (R + R‟) + PQ‟R + P‟Q‟R
= PQR + PQ‟R + PQR‟ + PQ‟R‟ + PQ‟R+ P‟Q‟R
= PQR + PQ‟R + PQR‟ + PQ‟R‟ + P‟Q‟R

Model 6B: Express the following in POS (1 Mark)


1) Express P +Q‟R in POS form. (OD 2006)1
P +Q‟R = (P+Q‟).(P+R)
K-MAP (POS) Year = (P+Q‟+0).(P+0+R)
OD2007 = (P+Q‟+RR‟).(P+QQ‟+R)
F(A, B, C, D,) = Π (5, 6, 7, 8, 9, 12, 13, 14, 15)
= (P+Q‟+R) (P+Q‟+R‟) (P+Q+R)(P+Q‟+R)
F(a,b,c,d) = Π (0,1,3,4,5,7,8,9,11,12,13,15) 2001
= (P+Q‟+R).(P+Q‟+R‟).(P+Q+R)
F(U,V,W,Z)=  (0,1,2,4,5,6,8,10) MP208-09
Model 7: Mislleneous Models
F(A,B,C,D)=  (1,3,4,5,7,9,11,12,13,14) Write the dual of the followins Boolean Expression
F(U,V,W,Z)=  (0,1,2,4,5,6,8,10) MP209-10
(B’+C).A 2003
Model 5A: Convert the expression into SOP (x+y).(x'+y') 1999
(1Mark) (U+W)(V'U+W) 1998
1) Convert the following Boolean expression into 2) Seven inverters are cascaded one after another.
its equivalent Canonical Sum of Product Form What is the output if the input is 1? (2001)
(SOP): (D2008) 2 3) Given the following circuit:
(X‟+Y+Z‟).(X‟+Y+Z).(X‟+Y‟+Z).(X‟+Y‟+Z‟)
Ans) F(X,Y,Z) =  (4,5,6,7)
= ∑ (0,1,2,3) What if the output if (i) both inputs are FALSE(0)
=X’Y’Z’ + X’Y’Z + X’YZ’ + X’YZ (ii) one is FALSE and the other is TRUE.
4) State and verify Duality Principle. (2001)
Write equivalent Canonical SOP for Year
following
F(X, Y,Z) = Π (1,3,6,7) D2007
(U‟+V‟+W‟).(U+V‟+W‟).(U+V+W).

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 27 PRAISE THE LORD


14.COMMUNICATION AND 2) Daniel has to share the data among various
NETWORK CONCEPTS computers of his two offices branches situated in
the same city. Name the network (out of LAN,
Theory Question: Fundamental Concepts WAN, PAN and MAN) which is being formed in
this process. (2017MP)1
1) Mention one advantage of networking(2001). 1 Ans : MAN
Ans: Advantages/Need for networking or
3.Differentiate between PAN and LAN types of
Network Goals:
(i) Resource Sharing: Hardware Resources like networks. (2016) 1
printers, Softwares can be shared between all PAN (Personal Area LAN (Local Area Network)
computers in the network. Network)
(ii) Reliability: A file can have copies in two or more A personal area LAN interconnects a high
computers. network PAN is a number of access or node
(iii) Cost Factor computer network points or stations within a
(iv) Communication Medium: Using a network, it is organized around an confined physical area
possible for managers, working far apart, to prepare individual person. upto a kilometer
financial report of the company, etc 4. Which type of network (out of LAN, PAN and
MAN) is formed, when you connect two mobiles
2) What was the role of ARPANET in the
using Bluetooth to transfer a Video. 2013
Computer Network? (D2010)1m
Ans: PAN (Personal Area Network)
OR
What is the significance of ARPANET in the 5 In networking, what-is WAN? How is it
network? (MP108-10) 1 different from LAN? (2011) 1
Ans) The first evolution of network was jointly Ans A WAN (wide area network), is not restricted to
designed by The Advanced Research Projects Agency a geographical location, although it might be confined
(ARPA) and Department of Defence (DoD) of united within the bounds of a state or country. A WAN
states in 1969 and was called ARPANET. It was an connects several LANs, and may be limited to an
experimental project, which connected a few enterprise (a corporation or an organization) or
computers of some of the reputed universities of USA accessible to the public. The technology is high speed
and DoD. ARPANET allowed access and use of and relatively expensive. The Internet is an example
computer resource sharing projects. This ARPANET of a worldwide public WAN.
was handed over to Defence Communication Agency A LAN (local area network) is a group of
(DCA) for further development. computers and network devices connected together,
usually within the same building or campus.
3) What is NFS? (2001) 1 6) What is the difference between LAN and WAN?
4) Differentiate between Internet and Intranet (OD2009) 1
(D2006) 1 Ans LAN (Local Area Network):
Ans)Internet is a network of computer networks Interconnects a high number of access or node points
which operates world-wide using a common set of or stations within a confined physical area. An
communications protocols. example is the territory covered in a single office
Intranet is an inter-connected network within one building that houses various departments/offices. All
organization that uses Web technologies for the these areas are interconnected using a LAN.
sharing of information internally.
5) What do you understand by a backbone
network? (1998)1
Ans: A backbone is central interconnecting structure
that connects one or more networks just like the trunk
of a tree or the spine of a human being.
WAN (Wide Area Network)
LAN,MAN,WAN,PAN It is used to connect systems with no limitation of
1.Assume that 50 employees are working in an geographical area. It is used to serve many locations
organization. Each employee has been allotted a distributed over a large geographical area. A system of
separate workstation to work. In this way, all overnight teller machines used by a banking
computers are connected through the server and organisation covering the North of India is an example
all these workstations are distributed over two of a WAN. Internet is also an example of the same.
floors. In each floor, all the computers are 7) What is the difference between MAN and WAN?
connected to a switch. Identify the type of (2003)(1999) 1m
network? 2019MP1 8) What is the difference between LAN and WAN?
Ans: LAN(Local Area Network) (2000) 1m

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 28 PRAISE THE LORD


LAN WAN Optical Fibre Ethernet Cable
Diameter of not more Span entire countries Very Fast Slower as compared to Optical
than a few kilometers. Fiber
A total data rate of Data rate less than 1 Expensive Less Expensive as compared to
atleast several Mbps Mbps(Megabits per Optical Fiber
Second) Immune to Prone to electromagnetic
Complete ownership by a Owned by multiple electromagnetic interference
single organization organization interference
Very low error rates Comparatively higher 3. Out of the following, which is the fastest (i) wired
error rates and (ii) wireless medium of communication? (2015)1
Infrared, Coaxial Cable, Ethernet Cable, Microwave,
9) What is the difference between LAN and MAN? Optical Fiber
(1998) 1
Ans (i) Wired - Optical Fiber
SWITCHING TECHNIQUES (ii) Wireless ‐ Infrared OR Microwave
1) Name two switching techniques used to transfer 4. Write two advantages of using an optical fibre
data between two terminals(computers). cable over an Ethernet cable to connect two service
(D2009)1 stations, which are 200m away from each other.
Ans Circuit Switching , Message Switching and (2014) 1
Packet Switching Ans: Two advantages of using an optical fibre
2) What is the difference between Message cable over an Ethernet cable:
Switching technique and Packet Switching Provides high speed
technique? (2015) (D2005)(2002) 1m Electrical and magnetic interference does not affect
Ans: the transmission.
Message Switching Packet Switching 5. How is Coaxial cable different from Optical
The source computer The source computer Fibre? (D2008) (OD2005) 1
sends data (message) to sends data (message) in Ans) Coaxial Cable: Comparatively Slow, Economic,
the switching office, a fixed size of Packet to convenient to lay down, used in Bus topology of
which stores data in a the switching office, networks
buffer. It then looks for which stores data in Optical Fibre: Very fast, expensive, reliable, no
a free link to another main memory. It then interference
switching office and looks for a free link to 6) Write one difference between Coaxial and
sends data to that another switching office optical cable? (2004) 1
office. This process and sends data to that 7) Write an advantage and a disadvantage of using
continues until data is office. This process optical fibre cables? (2003) 1
delivered to the continues until data is
destination computer delivered to the 8) Name two transmission media for networking.
(OD2006) 1m
destination computer
Ans) Optical Fiber,Ethernet Cable or twisted pair
Message Switching Packet Switching cable or UTP or STP,Co-axial Cable,,Infrared, Radio
follows store and follows store and Link OR Radiowave, Microwave link OR Microwave,
forward principle for forward principle for Satellite Link
complete message. fixed packets
9) Name two communication channels used in
No limit on block size. Fixes an upper limit for networking and explain any one. (2001) 2
packet size
3) Define Packet switching? (2004) 1m TOPOLOGIES:
4) Compare any two Switching techniques. MP109-10)1 1) Differentiate between Bus Topology and Star
Topology of Networks. What are the advantages
GUIDED & UNGUIDED MEDIA and disadvantages of Star Topology over Bus
1. Your friend wishes to install a wireless Topology? (2018)(D2009)(D2006)
network in his office. Explain him the difference Ans:
between guided and unguided media. (2019MP)1 Bus Topology: It is characterised by common
Answer: Guided media uses cables to connect transmission medium shared by all the connected
computers, whereas unguided media uses waves. hosts, managed by dedicated nodes. It offers
2.Differentiate between communication using simultaneous flow of data and control.
Optical Fiber and Ethernet Cable in context of
wired medium of communication technologies.
(2017)2
Ans)
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 29 PRAISE THE LORD
Star Topology: It is characterised by central Ans Cable length required for this topology is the
switching node (communication controller) and least compared to other networks.
unique path (point to point link) for each host. It is Illustration of 4 computers connected with each
easy to add and remove additional hosts by upgrading other using star topology of network.
the centralised node.

Advantages of Star Topology over Bus Topology: ●


Faster communication as compared to Bus topology
● Independent line of connection allows freedom of
removing or adding nodes from the network
Theory Question : Communication Devices
*Fault detection is easy.
*Fault isolation is easy. 1)What is the purpose of using a repeater in the
Disadvantages of Star Topology over Bus context of networking? (2003)1
Topology: ● Expensive as compared to Bus topology 2) What are repeaters? (1998)1
● Long cable length A) A repeater is a network device that amplifies and
restores signals for long distance transmission.
2) Write two advantages and two disadvantages for It is used in long network lines, which exceed the
STAR topology? (2004)1 maximum rated distance for a single run.
3) Write one advantage and one disadvantage of the Repeaters are of two types:
following topologies in network: (2003)2 (i)Amplifier : amplifies all incoming signals over the
i)STAR Topology ii)BUS Topology network. (it amplifies both the signal and any
4) Mention one difference between Linear and Star concurrent noise)
topologies in networking. (2001)1 (ii) Repeater : collected inbound packet and then
5) Write the two advantages and two disadvantages of retransmits the packet as if it were starting form the
BUS Topology in network? (2000)2 source station.
6) Write two advantages and disadvantages of the 3) What is a Hub? (D2008)1
following topologies in a Network. (2002)1 Ans)A Hub is used for a central connection between
i) BUS ii)RING two or more computers on a network.
7) Give two advantages and disadvantages of OR
following network topologies: (1999)2 A Hub is a network device used to connect two or
i)BUS ii) Tree more computers. OR
8) Identify the type of topology on the basis of the A Hub is an unintelligent network device to connect
following: (2017MP) computers.
a. Since every node is directly connected to the server, Hubs are of two types:
a large amount of cable is needed which increases the (i) Active hubs: electrically amplify the signal as it
installation cost of the network. moves from one connected device to another.
b. It has a single common data path connecting all the (ii) Passive hubs: allow the signal to pass from one
nodes. 2 computer to another without any change.
Ans: a. Star Topology b. Bus Topology 3) What is a Modem? (OD2008)1
9. Illustrate the layout for connecting 5 computers Ans) Modem is a Modulation Demodulation device
in a Bus and a Star topology of Networks. that converts analog signal to digital signal and vice
(2015) 2 versa.
4) What is the purpose of using a MODEM?(2000)1
5) What is a Modem? (2002)1
6) What is a bridge? (1999)1
A) A bridge is a device that lets you link two networks
together. Bridges are smart enough to know which
computers are on which side of the bridge, so they
only allow those messages that need to get to the other
side to cross the bridge. This improves performance
on both sides of the bridge.
10) Write one advantage of Bus Topology of As a packet arrives at the bridge, the bridge
network. Also, illustrate how 4 computers can be examines the physical destination address of the
connected with each other using star topology of packet. The bridge then decides whether or not to let
network. (2012)2 the packet cross.
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 30 PRAISE THE LORD
OR information from internet using an internet browser is
A bridge is a network device that establishes an :TCP/IP OR HTTP
intelligent connection between two local networks 3) What is protocol? Which protocol is used to
with the same standard but with different types of copy a file from/to a remotely located server?
cables. (OD2009)1
7) What are Routers? (2000)1 Ans A protocol is the set of rules for governing
A) A router is a network device that is used to communication between two communication devices.
separate different segements in a network to improve It also infers documentation, negotiations and
performance and reliability. A router works like a establishment of rules. Protocol used to copy a file
bridge but can handle different protocols. from/to a remotely located server is FTP (File
Compared to hubs and switches, routers are smarter Transfer Protocol)
still. Routers use a more complete packet address to
determine which router or workstation should receive 4. What is the difference between HTTP and FTP.
each packet next. Based on a network road map (2013) 1
called arouting table routers can help ensure that Ans:
packets are travelling the most efficient paths to their
destination. If a link between routers fails, the
sending router can determine an alternate route to
keep traffic moving.
DATA TRANSFER UNITS
1) Define the term Bandwidth. Give any one unit of
Bandwidth. (MP208-10)(MP209-10)1
Ans) The amount of data that can be transmitted in a
fixed amount of time is known as bandwidth. 5) What is the purpose of using FTP? (1999) 1
For digital devices, the bandwidth is usually expressed
in bits per second(bps) or bytes per second. For analog SECURITY
devices, the bandwidth is expressed in cycles per
second, or Hertz (Hz) 1.Arun opened his e-mail and found that his
OR inbox was full of hundreds of unwanted mails. It
Bandwidth is referred to the volume of information took him around two hours to delete these
per unit of time that a transmission medium (like an unwanted mails and find the relevant ones in his
Internet connection) can handle. inbox. What may be the cause of his receiving so
2 ) Which of the following is not an unit for data many unsolicited mails? What can Arun do to
transfer rate? (D2010) 1 prevent this happening in future?
(i) bps (ii) abps (iii) gbps (iv) kbps 2019MP2
Ans. (ii)abps Ans: Arun‟s email has been attacked with spam.
These may be promotional mails from different
2) Which of the following is not a unit for data advertisement groups. Arun must have checked
transfer rate? (OD2010)1
some promotional offers while surfing the Internet.
(i) mbps (ii) kbps (iii) sbps (iv) gbps
Ans. (iii) sbps
He should create filters in his email to stop
3) Which of the following unit measures the speed receiving these unwanted mails.
with which data can be transmitted from one node to 2. Janish Khanna used a pen drive to copy files
another node of a network? Also, give the expansion from his friend‟s laptop to his office computer.
of the suggested unit. (D2007)1 Soon his office computer started abnormal
i) Mbps ii) KMps iii) MGps functioning. Sometimes it would restart by itself
Ans) Mbps (Mega Bits Per Second) and sometimes it would stop different applications
running on it. Which of the following options out of
Theory Question : Protocols (i) to (iv), would have caused the malfunctioning of
1.Which protocol helps us to transfer files to and from the computer? Justify the reason for your chosen
a remote computer? (2016)1 option:
Ans FTP OR Telnet OR TCP (i) Computer Virus (ii) Spam Mail
2) What is protocol? Which protocol is used to (iii) Computer Bacteria (iv) Trojan Horse (2017)
search information from internet using an internet Ans) (i) Computer Virus OR (iv) Trojan Horse
browser? (D2009) 1 Justification:
Ans A protocol is the set of rules for governing ● Pen drive containing Computer Virus / Trojan Horse
communication between two communication devices. was used before the abnormal functioning started,
It also infers documentation, negotiations and which might have corrupted the system files.
establishment of rules. Protocol used to search
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 31 PRAISE THE LORD
● Computer Virus/ Trojan Horse affects the system Ans. TROJAN HORSE: “Malware” computer
files and start abnormal functioning in the computer programs presented as useful or harmless in order to
3. Ms. Raveena Sen is an IT expert and a induce the user to install and run them.
freelancer. She recently used her skills to access the VIRUS: Virus is a malicious program that damages
Admin password for the network server of Super data and files and causes harm to computer system.
Dooper Technology Ltd. and provided confidential 11) What is the difference between Virus and
data of the organization to its CEO, informing him Worms in the computers? (OD2010)1
about the vulnerability of their network security. Ans.Virus: Virus is a malicious program that
Out of the following options (i)to (iv), which one damages data and files and causes harm to computer
most appropriately defines Ms.Sen? system.
Justify the reason for your chosen option: Worms: Worms disrupt services and create system
(i) Hacker (ii) Cracker management problems. In some cases worms can
(iii) Operator (iv) Network Admin (2017)2 install viruses that cause damage to system.
Ans) (i) Hacker : A Hacker is a person who breaks
into the network of an organization without any 12) How Trojan Horses are different from Worms?
malicious intent. Mention any one difference. (MP209-10)1
Ans)A Trojan horse is a term used to describe
4) Who is a hacker? (2017MP)1 malware that appears, to the user, to per form a
Ans: A computer enthusiast, who uses his computer desirable function but, in fact, facilitates unauthorized
programming skills to intentionally access a computer access to the user's computer system.
without authorization is known as A computer worm is a self-replicating computer
hacker. A hacker accesses the computer without the program. It uses a network to send copies of itself to
intention of destroying data or maliciously harming other nodes (computers on the network) and it may do
the computer. so without any user intervention.
5)How is a Hacker different from a Cracker? 13) What term we use for a software/hardware
(OD2008)1 device, which is used to block, unauthorized access
Ans)Hackers are the ones who get into someone‟s while permitting authorized communications. This
code or computer without any malicious intentions, term is also used for a device or set of devices
where as Crackers are the one‟s who get into configured to permit, deny, encrypt, decrypt, or
someone‟s code or computer with malicious proxy all (in and out) computer traffic between
intentions. different security domains based upon a set of rules
6) Difference between Hackers and Crackers? and other criteria. (D2010)1
(OD2006)1 Ans. Firewall
Ans)Hackers: Computer enthusiasts who enjoy Firewall: Any of a number of security schemes
learning about computer systems and get into other (hardware/software) that
system/network for gaining more knowledge or may prevent unauthorized users from gaining access to a
find flaws in the system for rectification purposes. computer network or that monitor transfers of
Crackers: Malicious programmers who break into information to and from the network.
secure systems for stealing and corrupting/spoiling
14)Define the term firewall. (MP208-10)1
data.
Ans) Firewall is a feature used for Network Security.
7) What is the basic difference between Computer In a Network there is always danger of information
Worm and Trojan Horse? (2016)1 leaking out or leaking in. Firewall is a feature which
Trojan Horse Computer Worm forces all information entering or leaving the network
It is a ‘Malware’ It is a self replicating to pass through a check to make sure that there is no
computer program computer program unauthorized usage of the network.
presented as useful or which uses a network to 15) How firewall protect our Network? (MP209-10)1
harmless in order to send copies of itself to Ans)A firewall is a part of a computer system or
induce the user to other computers on the network that is designed to block unauthorized access
install and run them. network and it may do while permitting authorized communications. It is a
so without any user device or set of
intervention. devices configured to permit, deny, encrypt, decrypt,
or proxy all (in and out) computer traffic between
8) What is Trojan Horse? (2015) 1 different security domains based upon a set of rules
Ans A Trojan Horse is a code hidden in a program, and other criteria.
that looks safe but has hidden side effects typically
causing loss or theft of data, and possible system 16) What do you mean by IP Address? How is it
harm. useful in Computer Security? 1
Ans) An Internet Protocol (IP) address is a numerical
10) What is the difference between Trojan Horse identification and logical address that is assigned to
and Virus in terms of computers? (D2010)1 devices connected in a computer network.An IP
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 32 PRAISE THE LORD
Address is used to uniquely identify devices on the URL‟s have three parts: the protocol , the
Internet and so one can quickly know the location of DNS name of the machine on which the page is
the system in the network. located and a local name uniquely indicating the
17) What do you mean by Spam Mails? How can specific page(generally the filename).
you protect your mailbox from Spams? (2000) 6) Write two advantages of 3G over 2G Mobile
Ans) Spam mails, also known as junk e-mail, is a Telecommunication Technologies in terms of speed
subset of spam that involves nearly identical messages and services? (2016)1
sent to numerous recipients by e-mail. Ans Speed ‐
We can protect our mailbox from spams by creating ● Faster web browsing
appropriate filters. ● Faster file transfer
Service ‐
18)Give two major reasons to have network ● Better video clarity
security. (MP108-10)1 ● Better security
Ans)Two major reasons to have Network Security are
(i) Secrecy: Keeping information out of 7. What is WEB2.0? (2011)1
the reach of unauthorized users. Ans The term Web 2.0 is associated with web
(ii) Authentication: Determining the authorized applications that facilitate participatory
user before sharing sensitive information with or information sharing, interoperability, user-centered
entering into a business deal. design, and collaboration on the World Wide Web.
Web 2.0 is also used for social networking. Example:
INTERNET : OTHERS Social Networking Sites, Blogs, Facebook, Video
1. What is the difference between E-Mail and Sharing Sites, Video Conferencing Applications etc.
Chat? (2014)1 8. Write two characteristics of Web 2.0. (2016) 1
Ans: In Email, it is not necessary that receiver should Ans ● Makes web more interactive through online
be present online when the receiver is sending the E- social medias
mail, whereas in Chat, it is must that the ● Supports easy online information exchange
communicators should be online at the time of ● Interoperability on the internet
communication. ● Video sharing possible in the websites
2) Name any two common Web browsers. (OD2010)1 9. Write two characteristics of Wi-Fi. 2014 (1)
Ans. Internet explorer,Firefox,Netscape Navigator, Ans: The characteristics of Wi-Fi are as follows:
Google Chrome, Opera, Safari 1. It allows the devices to connect with the netwok
3)What is the purpose of using a Web Browser? without any wire.
Name any one commonly used Web Browser. 2. Group of devices can be connected with single
(MP108-10)1 internet connection.
Ans) The Web Browser fetches the page requested, 10. Write any two important characteristics of
interprets the text and formatting commands that it Cloud Computing. 2014
contains, and displays the page properly formatted on Ans:Two characteristics of Cloud Computing are:
the screen. (i) It is controlled by entity and restricted to their
Example of a Web Browser: authorized user.
Mozilla Firefox OR Internet Explorer OR Netscape (ii) It is delivered through internet 24 X 7.
Navigator OR Safari OR OPERA 11. Describe the following in brief:2m (1998)
4) Give one suitable example of each URL and i)MOSAIC ii)Usenet
Domain Name (2012)1
Ans URL Example: http://www.w3schools. Theory Question : Cyber Crimes
com/htmlldefault.asp OR (1) Out of the following, which all comes under
www.youtube.com cyber crime? (2015)1
Domain Name Example: w3schools.com (i) Stealing away a brand new hard disk from a
OR showroom.
Any other correct URL and Domain Name Examples (ii) Getting in someone's social networking account
Note: Domain names in both the examples may/may without his consent and posting on his behalf.
not be same (iii) Secretly copying data from server of a
organization and selling it to the other organization.
5) What is the importance of URL in networking? (iv) Looking at online activities of a friends blog.
(MP208-10) (MP209-10)1 Ans (ii) & (iii)
Ans) URL stands for Uniform Resource Locator. 2) Which out of the following comes under Cyber
Each page that is created for Web browsing is Crime? (2012)1
assigned a URL that effectively serves as the page‟s (i) Operating someone's Internet banking account, without
worldwide name or address. . A URL is also referred his knowledge.
to as a Web address. (ii) Stealing a keyboard from someone's computer.

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 33 PRAISE THE LORD


(iii) Working on someone's computer with his/her restricted to a limited set of tags defined by
permission. proprietary vendors.
Ans (i) Operating someone's Internet banking account, Rather than waiting for standards bodies to adopt tag
without his knowledge. set enhancements (a process which can take quite
3) What is the significance of Cyber law? some time), or for browser companies to adopt each
(OD2007) (D2007)1 other's standards (yeah right!), with XML, you can
Ans) Cyber law encompasses a wide variety of create your own set of tags at your own pace.
political and legal issues related to the Internet and
other communications technology, including Theory Question : Scripts & Cookies
intellectual property, privacy, freedom of expression, 1) Classify each of the following Web Scripting as
and jurisdiction. Client Side Scripting and Server Side Scripting:
OR (2018)
Cyber law helps prevent Cyber Crime, Hacking, Data (i) Java Scripting (ii) ASP
theft, Software Piracy and protects rights of Cyber (iii) VB Scripting (iv) JSP
Users. Ans: (i) Client Side Scripting / Server Side Scripting
OR (ii) Server Side Scripting
Restricting unauthorized access to user accounts. (iii) Client Side Scripting
Promoting, coordinating and controlling e-business. (iv) Server Side Scripting
4) Write two application of Cyber Law. (D2005)1 2)Categories the following under Client side and
Ans)Cyber law encompasses a wide variety of Server Side script category? (2016)(2011)
political and legal issues related to the Internet and (i) Java Script (ii) ASP
other communications technology, including (iii) VB Sript (iv) JSP
intellectual property, privacy, freedom of expression, Client Side Scripts Server Side Scripts
and jurisdiction. VB Script ASP
Java Script JSP
5) If someone has hacked your Website, to whom 3) Name one server side scripting language and one
you lodge the Complain? (MP1 09-10)1 client side scripting language. (2012)1
Ans) The complaint has to be lodged with the Police Ans
under IT Act.
Ex. Of Client Side Ex. Of Server side
Theory Question : XML & HTML Scripts Scripts
1. Differentiate between XML and HTML. (2011) VB Script ASP
(OD2005) 1 Java Script JSP
HTML XML Peril Tcl PHP
Full form is Hyper Text Full form of XML is TK CGI
Mark Up Language extensible mark up REXX Perl
language 4) Which of the following is not a Client Side
It contains predefined tags It contains user defined script: (MP109-10)1
tags (i) VB Script (ii) Java Script
(iii) ASP (iv) PHP
predominant markup Initially visualized as a Ans)(iii)ASP and (iv) PHP are not client side scripts
language for the creation language for defining new 5.What are cookies? (2011)
of web pages. document formats for the Ans A small piece of information that a server sends
World Wide Web to a client. When a person visits a Web site with
It provides a means to XML is textbased formats cookie capabilities, its server sends certain
describe the structure of that provide mechanisms information about him/her to the browser, which is
text-based information in for describing document stored on his/her hard drive as a text file. At some
a document by denoting structures with the help of later time (such as returning to the site the next day),
certain text as headings, user defined Tags. the server retrieves the cookie.
paragraphs, lists, and to
6) What kind of data gets stored in cookies and
supplement that text with
how is it useful? (2015)1
interactive forms,
Ans When a Website with cookie capabilities is
embedded images, and
other objects using
visited , its server sends certain information about the
predefined Tags.
browser, which is stored in the hard drive as a text
file. It's a way for the server to remember things about
2) When do you prefer XML over HTML and
the visited sites.
why? (MP209-10)1
Ans) The first benefit of XML is that because you are 7) What do you understand by the terms Cookies
writing your own markup language, you are not and Firewall? (OD2005)1

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 34 PRAISE THE LORD


Ans)Cookies: A small piece of information that a Ans)Open Source's proponents often claim that it offers
server sends to a client When you visit a Web site significant benefits when compared to typical Proprietary
with cookie capabilities, its server sends certain Software. Proprietary Software typically favour visible
information about you to your browser, which is features (giving marketing advantage) over harder-to
measure qualities such as stability,security and similar less
stored on your hard drive as a text file. At some later
glamorous attributes.
time (such as returning to the site the next day),the Open Source Software developers are evidently motivated
server retrieves the cookie. It‟s a way toi the server to by many factors but favouring features over quality is not
remember things about you. noticeable amongst them. For many developers, peer review
and acclaim is important, so it's likely that they will prefer
Theory Question : Open Source Softwares to build software that is admired by their peers. Highly
1. Write the name of any two popular Open Source prized factors are clean design, reliability and
Software which are used as operating systems. 2014 maintainability, with adherence to standards and shared
Ans: Linux and Unix are two open source operating community values preeminent.
systems. 8)Compare freeware and Shareware. (MP209-10)1
Ans)Freeware, the name derived from words "free"
(2) Write two advantages of using open source and"software". It is a computer software that is available for
software over proprietary software. 2013 use at no cost or for an optional fee. Freeware is generally
A) Two advantages of using open source software proprietary software available at zero price, and is not free
over proprietary software are: software. The author usually
Open Source Software is software whose source code restricts one or more rights to copy, distribute, and make
derivative works of the software.
is available to customer and it can be modified and
Shareware is usually offered as a trial version with certain
redistributed without any limitations whereas source features only available after the license is purchased, or as a
code of proprietary software is not available. full version, but for a trial period. Once the trial period
Open Source software may come free of cost or with has passed the program may stop running until a license is
payment of normal charges whereas proprietary purchased. Shareware is often offered without support,
software is neither open nor freely available. updates, or help menus, which only become available with
the purchase of a license. The words "free trial" or "trial
(3) Name two Proprietary softwares along with version" are indicative of shareware.
their application. (2012)1 Mislleneous
Ans Microsoft Office - For office applications 1) The following is a 32 bit binary number usually
Adobe Photoshop - For design related works represented as 4 decimal values, each representing 8
Autocad - For professional Design bits, in the range 0 to 255 (known as octets) separated by
MAYA - For professional animations & Movie decimal points. 140.179.220.200
making 3D Studio - For 3 dimensional objects What is it? What is its importance? (2017MP)1
Tally - For accounting Ans: It is an IP Address.It is used to identify the computers
Oracle Database - For database management on a network.
2) What out of the following, will you use to have an
(4) Compare Open Source Software and audio-visual chat with an expert sitting in a far-away
Proprietary Software. (2011)1 place to fix-up a technical issue? 2012
Ans Open source software refers to a program or (i) VolP(ii) Email(iii) FTP
software in which the source code (the form of the Ans (ii) VolP
program when a programmer writes a program in a
particular programming language) is available to the
general public for use and/or modification from its
original design free of charge.
Proprietary software is software that is owned by an
individual or a company (usually the one that
developed it). There are almost always major
restrictions on its use, and its source code is almost
always kept secret.
6) Write one advantage of each for Open Source
Software and Proprietary Software. 1
Ans. An Open Source Software is freely and liberally
licensed because of which users have right to study,
change. and improve its design and source code. A
Proprietary Software has a copyright owner, who can
restrict the user's control over the software, its
modification, or restrictions in publishing of modified
or unmodified versions.
7) Mention any two advantages of Open Source
Software over Proprietary Software. (2000)
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 35 PRAISE THE LORD
NETWORKS FULL FORMS AUI – Attachment Unit Interface
ARPANET - Advanced Research Projects SNA – Systems Network Architecture
Agency Network VFIR – Very Fast Infrared
URI – Uniform Resource Identifier
CDMA – Code Division Multiple Access URN – Uniform Resource Name
FTP - FILE TRANSFER PROTOCOL P-P - Point to Point
FSF - FREE SOFTWARE FOUNDATION MIME – Mail and Multipurpose Internet Mail
Extensions
GPRS – General Packet Radio Service POP – Post Office Protocol
GNU - GNU‟s not Unix NNTP – Network News Transfer Protocol
GSM – Global System for Mobile HTTP – Hyper Text Transfer Protocol
(communication) NTP – Network Time Protocol
IMAP – Internet Mail Transfer Protocol
HTML - Hyper Text Markup Language SLIP – Serial Line Internet Protocol
HTTP – Hyper Text Transfer Protocol SIP – Session Initiation Protocol
MAN - Metropolitan Area Network PPP - Point to Point Protocol
MODEM - Modulator - Demodulator IPCP – IP Control Protocol
NCP – Network Control Protocol
PPP - Point To Point Protocol LCP – Link Control Protocol
SMS - Short Message/Messaging Service ITU – International Telecommunications Union
SMTP – Simple Mail Transfer Protocol PC – Personal Computer
TCP/IP - Transfer Control Protocol/Internet ISP – Internet Service Provider
SIM – Subscriber Identity Module
Protocol TDMA – Time Division Multiple Access
URL – Uniform Resource Locator TDM – Time Division Multiplexing
VoIP - Voice Over Internet Protocol IDEN – Integrated Digital Enhanced Network
WAN - Wide Area Network WCDMA –Wideband CDMA
PSTN – Public Switched Telephone Network
WLL(WiLL) – Wireless in Local Loop 1G, 2G, 3G, 4G, 5G – Fifth Generation
WWW - World Wide Web UMTS – Universal Mobile Telecommunications
XML – eXtensible Markup Language System / Universal Mobile Telephone System
EDGE – Enhanced Data rates for Global Evolution
SMSC – Short Message Service Center
THE ABOVE FULL FORMS ARE HLR – Home Location Register
PREVIOUSLY ASKED QUESTIONS Email – Electronic Mail
Fax – Fascimile
NSFNET - National Science Foundation Network VSNL – Videsh Sanchar Nigam Limited
LAN - Local Area Network DNS – Domain Name Server
PAN - Personal Area Network DHTML– Dynamic Hyper Text Markup Language
NIU - Network Interface Unit DECnet – Digital‟s family of communication protocols
NIC - Network Interface Card IE – Internet Explorer
TAP - Terminal Access Point(NIU = NIC = TAP) WiFi - Wireless Fidelity
bps - Bits Per Second LTE – Long Term Evolution
Bps - Bytes Per Second HDTV – High Definition Television
Kbps – Kilo bits Per Second WiMAX -Worldwide Interoperability for Microwave Access
KBps – Kilo Bytes Per Second ISD - International Subscriber Dialing
Mbps - Mega Bits Per Second ISDN - Integrated Services Digital Network
MBps – Mega Bytes Per Second IRC - Internet Relay Chat
Gbps - Giga Bits Per Second BWA – Broadband Wireless Access
GBps – Giga Bytes Per Second PHP - Hypertext Preprocessor
KHz – Kilo Hertz (earlier called,Personal Home Page)
MHz – Mega Hertz UNCITRAL – United Nation‟s Commission for
GHz – Giga Hertz International Trade related laws.
THz – Tera Hertz IT Act – The Information Technology Amendment Act
NFS – Network File System IP – Intellectual Property
VGM – Voice Grade Medium FAT – File Allocation Table
DGM – Data Grade Medium
STP – Shielded Twisted Pair “If wealth is lost, nothing is lost,
UTP – Unshielded Twisted Pair
LED – Light Emitting Diode If health is lost, something is lost,
LD – Laser Diode If character is lost, everything is lost”
OFC – Optic Fiber Cable, Fiber Optic Cable
PDA – Personal Digital Assistants
AM – Amplitude Modulation “THE FEAR OF THE
FM - Frequency Modulation
PM –
A/F –
Phase Modulation
Audio Frequency LORD
(Txd – Transmit, Rxd – Receive,
RTS – Request to Send, CD –Carrier Detect, IS THE BEGINNING
DSR – Data Set Ready, CTS – Clear to Send
DTR – Data Terminal Ready)
RJ45 – Registered Jack – 45 OF WISDOM”
BNC – Bayone – Neill – Concelman
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 36 PRAISE THE LORD
4Marks Problem : Model 1(All in a single city) (ii) Name the most suitable wing where the Server
should be installed. Justify your answer.
1. Multipurpose Public School, Bangluru is Answer:
Setting up the network between its Different Wing Senior(S)- Because it has maximum number
Wings of school campus. There are 4 wings of computers.
Named as SENIOR(S),JUNIOR(J), ADMIN(A) (iii) Suggest a device/software and its placement
and HOSTEL(H). 2019MP4 that would provide data security for the entire
network of the School.
Multipurpose Public School, Bangluru Answer: Firewall - Placed with the server at Senior
(iv) Suggest a device and the protocol that shall be
needed to provide wireless Internet access to all
smartphone/laptop users in the campus of
Multipurpose Public School, Bangluru.
Answer:
Device Name: WiFi Router OR WiMax OR RF
Router OR Wireless Modem OR RFTransmitter
Protocol : WAP OR 802.16 OR TCP/IP OR VOIP
OR MACP OR 802.11
Distance between various wings are given below: 2) CASE STUDY BASED QUESTION: (2018)
Ayurveda Training Educational Institute is setting up
its centre in Hyderabad with four specialized
departments for Orthopedics, Neurology and
Pediatries along with an administrative office in
separate buildings. The physical distances between
these department buildings and the number of
computers to be installed in these departments and
administrative office are given as follows. You, as a
network expert, have to answer the queries as raised
by them in (i) to (iv)
Number of Computers installed at various wings are Shortest distances between various locations in
as follows: meters:
Administrative office to Orthopedics 55
Unit
Neurology Unit to Administrative 30
Office
Orthopedics Unit to Neurology Unit 70
Pediatrics Unit to Neurology Unit 50
Pediatrics Unit to Administrative 40
Office
Pediatrics Unit to Orthopedics Unit 110
(i) Suggest the best wired medium and draw the Number of Computers installed at various locations
cable layout to efficiently connect various wings of are as follows:
Multipurpose PublicSchool, Bangluru. Pediatrics Unit 40
Answer: Administrative Office 140
Best wired medium: Optical Fibre OR CAT5 OR Neurology 50
CAT6 OR CAT7 OR CAT8 OR Ethernet Cable Orthopedics Unit 80

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 37 PRAISE THE LORD


(i) Suggest the most suitable location to install the As a network expert, provide the best possible answer
main server of this institution to get efficient for the following queries:
connectivity. i) Suggest a cable layout of connections between the
Ans: Administrative Office buildings.
(ii) Suggest the best cable layout for effective network
connectivity of the building having server with all the
other buildings.
Ans:

OR
Administrative Office is connected to Orthopedic,
Radiology, Pediatrics units
directly in a Star Topology
(iii) Suggest the devices to be installed in each of ii) Suggest the most suitable place (i.e. buildings) to
these buildings for connecting computers installed house the server of this organization.
within the building out of the following: Ans) The most suitable place/ building to house the
* Gateway * Modem * Switch server of this organization would be building Research
Ans: Switch Lab, as this building contains the maximum number of
(iv)Suggest the topology of the network and network computers.
cable for efficiently connecting each computer iii) Suggest the placement of the following device
installed in each of the buildings out of the following: with justification: a) Repeater b) Hub/Switch
Topologies: Bus Topology, Star Topology a) For layout1, since the cabling distance between
Network Cable: Single Pair Telephone, Coaxial Accounts to Store is quite large, so a repeater would
Cable, Ethernet Cable. ideally be needed along their path to avoid loss of
Topology : Star Topology signals during the course of data flow in this route.
Network Cable: Ethernet Cable / Coaxial Cable For layout2, since the cabling distance between Store
3) Rehaana Medicos Center has set up its new to Recresearch Lab is quite large, so a repeater would
center in Dubai. It has four buildings as shown in ideally be placed.
the diagram given below: (2017MP) b) In both the layouts, a Hub/Switch each would be
needed in all the buildings to interconnect the group of
cables from the different computers in each building.
iv) Suggest a system (hardware/software) to prevent
unauthorized access to or from the network.
A) Firewall

4) 2014

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 38 PRAISE THE LORD


(ii) Suggest the most appropriate layout to connect all
three blocks for efficient communication.

(iii) Which type of network out of the following is


formed by connecting the computers of these three
blocks?
LAN MAN WAN
A)LAN
(iv) Which wireless channel out of the following
should be opted by RCI to connect to students from all
over the world?
Infrared Microwave Satellite
A) Satellite.
6.Great Studies University is setting up its
Academic schools at Sunder Nagar and planning to
set up a network. The university has 3 academic
schools and one administration center as shown in
the diagram below: (2011) 4
5)2013

Expected computers to be installed in each block


Block Computers
Administrative Block 30
Finance Block 20
Faculty Recording 100
Block
(i) Suggest the most appropriate block, where RCI
should plan to install the server.
A) Faculty Recording Block is most appropriate block
(i) Suggest the most suitable place (i.e. School/
to install the server.
Center) to install the server of this university with a
suitable reason. 1
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 39 PRAISE THE LORD
Ans Option 1 : Admin center as it has the most
number of computers
Option 2.Business School as it will require minimum
cable length to connect other blocks
(ii) Suggest an ideal layout for connecting these
schools/ center for a wired connectivity. 1
Ans Option 1:

Option 2:

(e2) Suggest the most suitable place (i.e. building) to


house the server for this NGO. Also, provide a
suitable reason for your suggestion.
Ans. Training Building as it contains maximum
number of computers.
(e3) Suggest the placement of the following devices
(iii) Which device will you suggest to be placed/installed in with justification:
each of these schools /
(i) Repeater(ii) Hub/Switch
center to efficiently connect all the computers within these
Ans. (i) A Repeater should be placed when the
schools / center? 1
Ans Switch distance between any two connecting buildings
(iv) The university is planning to connect its admission exceeds 70 m.
office in the closest big city, which is more than 350 km (ii) Every building will need one Hub / Switch, to
from the university. Which type of network out of LAN, send signals to all of the workstations connected to it
MAN or WAN will be formed? Justify your answer.1 (e4) The NGO is planning to connect its International
Ans WAN as the distance is more than the range of LAN or office situated in Delhi. Which out of the following
MAN. 1 wired communication links, will you suggest for a
7) “Vidya for All” is an educational NGO. It is setting very high speed connectivity ?
up its new campus at Jaipur for its web-based activities. (i) Telephone Analog Line(ii) Optical Fiber
The campus has four buildings as shown in the diagram
(iii) Ethernet Cable
below: (2010 OD) 4
Ans. (ii) Optical Fibre
8) “Hindustan Connecting World Association “is
planning to start their offices in four major cities in
India to provide regional IT infrastructure support in
the field of Education & Culture. The company has
planned to set up their head office in New Delhi in
three locations and have named their New Delhi
offices as “Sales Office “,”Head Office “and “Tech
Office “.The company‟s regional offices are located at
“Coimbatore”,”Kolkata”and “Ahmadabad”. A rough
layout of the same is as follows: (2007OD) 4

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 40 PRAISE THE LORD


Approximate distance between these offices as per 9) INDIAN PUBLIC SCHOOL in Darjeeling is
network survey team is as setting up the network between its different wings.
follows There are 4 wings named as SENIOR(S),
JUNIORS (J), ADMIN (A) and HOSTEL (H).
(2006OD)
Distance between various wings is given below:
Number of Computers
Wing A 10
Wing S 200
In continuation of the above, the company experts Wing J 100
have planned to install the following number of
computers in each of their offices: Wing H 50
Head Office 100 i) Suggest a suitable Topology for networking the
Sales Office 20 computer of all wings.1
Tech Office 50 Ans)Star Topology OR Bus Topology
Kolkata Office 50 ii) Name the wing where the server to be installed.
Ahmadabad Office 50 Justify your answer. 1m
Coimbatore Office 50 Ans)Wing S
1) Suggest network type(out of LAN,MAN,WAN) for as it has the maximum number of computers
connecting each of the following set of their offices: OR
Head Office and Tech Office WingA as it is placed in the Admin Wing (for security
Head Office and Coimbatore Office reasons)
Ans) Head Office and Tech Office: LAN iii) Suggest the placement of Hub/Switch in the
Head Office and Coimbatore Office: WAN network.
2) Which device you will suggest to be produced by Ans) Inside all the four wings
the company for connecting all the computers with in iv) Mention in economic technology to provide
each of their offices out of the following devices? internet accessibility to all wings.
Modem Telephone Switch/Hub 1m
Ans) Switch / Hub Ans:Any one of the following:
3) Which of the following communication media, will Dialup, TCP/IP, DSL, Modem, Broadband, Cable,
suggest to be procured by the company for connecting ISDN, Telephone Line, Co-axial, Ethernet Cable,
their local offices in New Delhi for very effective and Radiowave
fast communication?
Ethernet Cable, Optical Fibre,Telephone Cable 10) The Cyber Mind Organization has set up its
Ans) Optical Fibre new Branch at Mizoram for its office
O and web
4) Suggest a cable/writing layout for connecting the based activities. It has 4 Wings of buildings as
company‟s local offices located in New Delhi. Also, shown in the diagram: (OD 2005)
suggest an effective method /technology for
connecting the company‟s regional offices at
“Kolkata”,”Coimbatore”and “Ahmadabad”.
Ans) Optical Fiber/Star Topology
Wireless

Center to center distances between various blocks

Wing X to Wing Z 40 m
Wing Z to Wing Y 60 m
Wing Y to Wing X 135 m
Wing Y to Wing U 70 m
OR Wing X to Wing U 165 m
Wing Z to Wing U 80 m
Number of computers
Wing X 50
Wing Z 130
Wing Y 40
Wing U 15
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 41 PRAISE THE LORD
1) Suggest a most suitable cable layout of connections
between the Wings, and topology. 1m
2) Suggest the most suitable place (i.e., Wing) to house the
server of this organization with a suitable reason, with
justification. 1m
Ans) Wing Z as it has largest number of computers
3) Suggest the placement of the following devices with
justification:1m
(i)Repeater (ii) Hub/Switch
4) The organization is planning to link its head office
situated in Delhi with the offices at Srinagar.1m Suggest an e2) Suggest the most suitable place (i.e. block) to
economic way to connect it; the company is ready to house the server of this organization with a suitable
compromise on the speed of connectivity. Justify your reason.
answer. 2m Ans) The most suitable place / block to house the
Ans)TCP/IP Dial Up (Most Suitable answer 1)
server of this organisation would be Block C, as this
OR
Telephone Link (Most Suitable answer 2) block contains the maximum number of computers,
OR thus decreasing the cabling cost for most of the
Microwave computers as well as increasing the efficiency of the
OR maximum computers in the network.
Radio Link/Radio Wave e3) Suggest the placement of the following devices
OR with justification
Satellite Link (i) Repeater (ii) Hub/Switch
OR Ans) (i) For Layout 1, since the cabling distance
WAN between Blocks A and C, and that between B and C
11)Knowledge Supplement Organisation has set up its are quite large, so a repeater each, would ideally be
new center at Mangalore for its office and web based
activities. It has 4 blocks of buildings as shown in the
needed along their path to avoid loss of signals during
diagram below: (MP109-10)4 the course of data flow in these routes.

For layout 2, since the distance between Blocks A and


C is large so a repeater would ideally be placed in
between this path.

(ii) In both the layouts, a hub/switch each would be


needed in all the blocks, to interconnect the group of
cables from the different computers in each block.

e1) Suggest a cable layout of connections between the


blocks.

Ans)
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 42 PRAISE THE LORD
e4) The organization is planning to link its front office
situated in the city in a hilly region where cable
connection is not feasible, suggest an economic way
to connect it with reasonably high speed?
Ans)The most economic way to connect it with a
reasonable high speed would be to use radio wave
transmission, as they are easy to install, can travel
long distances, and penetrate buildings easily, so they
are widely used for communication, both indoors and
outdoors. Radio waves also have the advantage of e2) Suggest the most suitable place (i.e. building) to
being omni directional, which is they can travel in all house the server of this organization with a suitable
the directions from the source, so that the transmitter reason.
and receiver do not have to be carefully aligned Ans)The most suitable place / block to house the
physically. server of this organisation would be Raj Building, as
this block contains the maximum number of
12) Ravya Industries has set up its new center at computers, thus decreasing the cabling cost for most
Kaka Nagar for its office and web based activities. of the computers as well as increasing the efficiency
The company compound has 4 buildings as shown of the maximum computers in the network.
in the diagram below: (MP209-10) 4 e3) Suggest the placement of the following devices
with justification:
(i) Internet Connecting Device/Modem
(ii) Switch
Ans)(i)Raj Building
(ii) In both the layouts, a hub/switch each would be
needed in all the buildings, to interconnect the group
of cables from the different computers in each block
e4) The organisation is planning to link its sale
counter situated in various parts of the same city,
which type of network out of LAN, MAN or WAN
will be formed? Justify your answer.
Ans)The type of network that shall be formed to link
the sale counters situated in various parts of the same
city would be a MAN, because MAN (Metropolitan
Area Networks) are the networks that link computer
facilities within a city.

13)Knowledge Supplement Organisation has set up


its new center at Mangalore for its office and
web based activities. It has 4 blocks of
buildings as shown in the diagram below:
(MP108-09)

e1) Suggest a cable layout of connections between the


buildings.
Ans)

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 43 PRAISE THE LORD


e1) Suggest a cable layout of connections between
the blocks.1
Ans)Layout 1:

Layout Option 2:
Since the distance between Block A and Block B is
quite short e4) The organization is planning to link its front office
situated in the city in a hilly region where cable connection
is not feasible, suggest an economic way to connect it with
reasonably high speed? 1
Ans) The most economic way to connect it with a
reasonable high speed would be to use radio wave
transmission, as they are easy to install, can travel long
distances, and penetrate buildings easily, so they are widely
used for communication, both indoors and outdoors. Radio
e2) Suggest the most suitable place (i.e. block) to waves also have the advantage of being omni directional,
house the server of this organisation with a suitable which is they can travel in all the directions from the
reason. 1 source, so that the transmitter and receiver do not have to be
Ans) The most suitable place / block to house the carefully aligned physically.
server of this organisation would be Block C, as this 4Marks Problem : Model 2 (Between 2 distant places)
block contains the maximum number of computers, 1)Hi Standard Tech Training Ltd is a Mumbai based
thus decreasing the cabling cost for most of the organization which is expanding its office set-up to
computers as well as increasing the efficiency of the Chennai. At Chennai office compound, they are
maximum computers in the network. planning to have 3 different blocks for Admin,
e3) Suggest the placement of the following Training and Accounts related activities. Each block
devices with justification 1 has a number of computers, which are required to be
i)Repeater ii)Hub/Switch connected in anetwork for communication, data and
Ans) For Layout 1, since the cabling distance resource sharing.
between Blocks A and C, and that between B and C As a network consultant, you have to suggest the best
are quite large, so a repeater each, would ideally be network related solutions for them for issues/problems
needed along their path to avoid loss of signals during raised by them in (i) to (iv), as per the distances
the course of data flow in these routes between various blocks/locations and other given
parameters. (2017)

For layout 2, since the distance between Blocks A


and C is large so a repeater would ideally be placed in
between this path

In both the layouts, a hub/switch each would be


needed in all the blocks, to interconnect the group of
cables from the different computers in each block
XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 44 PRAISE THE LORD
i) Suggest the most appropriate block/ location to Number of Computers installed at various
house the SERVER in the CHENNAI Office (out of locations are as follows:
the 3 blocks) to get the best and effective connectivity.
Justify your answer. (1)
Ans)Training Block - Because it has maximum
number of computers.
ii) Suggest the best wired medium and draw the cable
layout (Block to Block) to efficiently connect various Note: In Villages, there are community centers, in which
blocks within the CHENNAI office compound. 1 one room has been given as training center to this
Ans) Best wired medium: organization to install computers.The organization has got
Optical Fibre OR CAT5 OR CAT6 OR CAT7 OR financial support from the government and top IT
companies.
CAT8 OR Ethernet Cable (i) Suggest the most appropriate location of the SERVER in
the YHUB (out of the 4 locations), to get the best and
effective connectivity. Justify your answer. 1
Ans YTOWN
Justification
● Since it has the maximum number of computers.
● It is closest to all other locations.
(ii) Suggest the best wired medium and draw the cable
layout (location to location) toefficiently connect various
locations within the YHUB. 1
Ans Optical Fiber
iii) Suggest a device/software and its placement that
would provide data security for the entire network of
the CHENNAI office. (1)
Ans) Firewall - Placed with the server at the Training
Block OR
Any other valid device/software name
iv) Suggest a device and the protocol that shall be
needed to provide wireless Internet access to all
smartphone/laptop users in the CHENNAI office(1)
A)Device Name: WiFi Router OR WiMax OR RF (iii) Which hardware device will you suggest to connect all
the computers within each location of YHUB? 1
Router OR Wireless Modem OR RF Transmitter
Ans Switch OR Hub
Protocol : WAP OR 802.16 OR TCP/IP OR VOIP (iv) Which service/protocol will be most helpful to conduct
OR MACP OR 802.11 live interactions of Experts from Head Office and people at
YHUB locations? 1
2)Intelligent Hub India is a knowledge community Ans Videoconferencing OR VoIP OR any other correct
aimed to uplift the standard of skills and knowledge in service/protocol
the society. It is planning to setup its training centers in
multiple towns and villages pan India with its head 3) Xcelencia Edu Services Ltd. is an educational
offices in the nearest cities.They have created a model of organization. It is planning to set up its India campus at
their network with a city, a town and 3 villages as Hyderabad with its head office at Delhi. The Hyderabad
follows: (2016) 4 campus has 4 main buildings ‐
As a network consultant, you have to suggest the best ADMIN, SCIENCE, BUSINESS and MEDIA.
network related solutionsfor their issues/problems
raised in (i) to (iv), keeping in mind the distances You as a network expert have to suggest the best
between various locations and other given parameters. network related solutions for their problems raised in (i)
to (iv), keeping in mind the distances between the
buildings and other given parameters. (2015)

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 45 PRAISE THE LORD


(i) Suggest the most suitable place (Le. building) to
house the server of this organization. Also give a
reason to justify your location.
(i) Suggest the most appropriate location of the server Ans Building "RED", since it contains maximum
inside the HYDERABAD campus (out of the 4 buildings), number of computers OR
to get the best connectivity for maximum no. of computers. Building "BLUE", since it is closest to "GREEN" and
Justify your answer.1 "RED"
Ans ADMIN (due to maximum number of computers) (ii) Suggest a cable layout of connections between the
(ii) Suggest and draw the cable layout to efficiently connect buildings inside the campus.
various buildings 'within the HYDERABAD campus for
Ans Layout 1:
connecting the computers.

(iii) Which hardware device will you suggest to be


procured by the company to be installed to protect and Layout 2
control the intemet uses within the campus?1
Ans Firewall OR Router
(iv) Which of the following will you suggest to establish
the online face‐to‐face communication between the people
in the Admin Office of HYDERABAD campus and DELHI
Head Office?
(a) E‐mail (b) Text Chat (c) Video Conferencing
(d) Cable TV 1
Ans Video Conferencing

4)Workalot Consultants are setting up a secured


network for their office campus at Gurgaon for
their day-to-day office and web-based activities. (iii) Suggest the placement of the following devices
They are planning to have connectivity between 3 with justification:
buildings and the head office situated in Mumbai (1) Switch (2) Repeater
Answer the questions (i) to (iv) after going through Ans (1) Switch:
the building positions in the campus and other In each of the buildings, since a network switch is a
details, which are given below: (2012) 3 networking device that joins multiple computers
together within one local area network (LAN).
(2) Repeater:
For the Layout 1 drawn in (e2)- Between buildings
"GREEN" and "RED", since distance between these
two buildings is greater than 70 m which will
otherwise lead to loss of signal intensity for data to be
transferred.
For the Layout 2 drawn in (e2): Repeater is not
needed, since distance between both the buildings
connected to "Ganga" is less than 70 m, not leading to
any signal loss OR

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 46 PRAISE THE LORD


Any other placement of Repeater with proper (E2) Suggest the most suitable place (i.e. building) to house
justification the server of this organisation, with a suitable reason. 1
(iv) The organization is planning to provide a high Ans Academic Building as it contains maximum number of
speed link with its head office situated in the computers.
(E3) Suggest an efficient device from the following to be
MUMBAI using a wired connection. Which of the
installed in each of the buildings to connect all the
following cable will be most suitable for this job? computers : 1
(i) Optical Fibre (ii) Co-axial Cable (iii) Ethernet (i) GATEWAY (ii) MODEM (iii) SWITCH
Cable Ans SWITCH
Ans (i) Optical Fibre (E4) Suggest the most suitable (very high speed) service to
provide data connectivity between Admission Building
5) Eduminds University of India is starting its first located in Delhi and the campus located in Par am pur from
campus in a small town Parampur of Central India the following options: 1
with its center admission office in Delhi. The _ Telephone line
university has 3 major buildings comprising of _ Fixed-Line Dial-up connection
_ Co-axial Cable Network
Admin Building, Academic Building and Research
_ GSM
Building in the 5 KM area Campus. As a network _ Leased line
expert, you need to suggest the network plan as per _ Satellite Connection
(E1) to (E4) to the authorities keeping in mind the Ans Satellite Connection OR Leased line
distances and other given parameters. (2009 OD)
6)”China Middleton Fashion” is planning to expand their
network in India, starting with two cities in India to provide
infrastructure for distribution of their product. The company
has planned to setup their main office in Chennai at three
different locations and have named their offices as
“Production Unit”, “Finance Unit” and “Media Unit “.The
Company has its corporate unit in Delhi. A rough layout of the
same is as follows: (2008 OD)

Approximate distance between these Units is as follows:

In continuation of the above, the company experts have planned to


install the following number of computers in each of their offices:

(E1) Suggest to the authorities, the cable layout amongst


various buildings inside the university campus for
connecting the buildings. 1 1) Suggest the kind of network required (out of LAN, MAN,
WAN) for connecting each of the following office units: i)
Production Unit and Media Unit
ii) Production Unit and Finance Unit
Ans) Production Unit and Media Unit : MAN
Production Unit and Finance Unit : LAN
2) Which one of the following devices will you suggest for
connecting all the computers with in each of their office units? i)
Switch/Hub ii) Modemii) Telephone
Ans) Switch / Hub
Ans)

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 47 PRAISE THE LORD


3) Which of the following communication media, you will suggest
to be procured by the company for connecting their local office
units in Chennai for very effective (High Speed) communication?
i) Telephone cable ii) Optical Fibre iii) Ethernet Cable
Ans) Optical Fibre
4) Suggest a cable/wiring layout for connecting the company‟s
local office units located in Chennai. Also, suggest an effective
method/technology for connecting the company‟s office unit
located in Delhi.
Ans)

For Any Doubts or for good


suggestions……….
Please feel free to contact:
MRK
ptlspecialsolutions@gmail.com

VERY IMPORTANT NOTICE


DEAR READER,
This material is meant only for slow learners
to give an idea of questions pattern. If any
student systematically practice these models,
will get good marks (but not full marks).
Especially we cannot guess the theory
questions. Theory questions will come from
any corner of the syllabus. (Some times only
theory questions were asked from the previous
questions)
BUT STUDENTS ARE ADVISED TO
READ ENTIRE SYLLABUS TO GET FULL
MARKS.
As I collected this material from various
sources, there might be some typing errors or
technical errors, etc.

XII Computer – PART 2 (Refer mrkcomputer.blogspot.in ) 48 PRAISE THE LORD

S-ar putea să vă placă și