Ans : (i) goto : A goto statement can transfer the program control anywhere in the program.

(ii) break : A break statement enables a program to terminate of the loop/block, skipping anycode in between.

(iii) continue : A break statement enables a program to force the next iteration to take place,skipping any code in between.

(iv) return : A return statement is used to return from a function.

Q10. How are the following related to one another?

(i) array and structure

(ii) structure and class

Ans: (i) Array is a group of items of the same data types whereas structure brings together a groupof related data items of any data types.

(ii) Structure is actually a class (in C++) declared with keyword struct. By default, allmembers are public in a structure; on the other hand all members are private by default ina class.

Questions based onProgram Errors

Short Answer Questions

( 2 marks)

Note : Errors are explained in the solutions. While solving such type of question, a student shouldcarefully go through correctness of each statement and the logic of the whole program.

Students are advised to practice

various questions to develop the skill of finding the errors.

Q1. Rewrite the following program after removing the syntactical errors (if any). Underline eachcorrection.

#include<iostream.h>

int func(int

y =10, int &x)

{

if(x%y = 0) return ++x ; else return y--

;

}

void main()

{

int p = 20, q = 23;

r = func(p,q);

cout>>p>>q>>r;

}

Ans: #include<iostream.h>

int func(int y

, int &x) // violating the rule of Default argument

{

if(x%y= =

0) return ++x ; else return y--

;

// = = relational operator

}

void main()

{

int p = 20, q = 23;

Page7

/63

intr = func(p,q);

// r should be declared

cout << p << q << r;

// << operator for cout

}

Q2. . Rewrite the following program after removing the syntactical errors (if any). Underline eachcorrection.

#include<iostream.h>

void main()

{

int X[ ]={60,50,30,40},Y; count=4;

cin>>Y;

for(i=count-1;i>=0;i--)

switch(i)

{

case 1;

case 2: cout<<Y * X; break;

case 3: cout<<Y+ Y;

}

}

Ans: #include<iostream.h>

void main()

{

int X[ ]={60,50,30,40},Y, count=4;

// multiple declaration separated by comma

cin>>Y;

for(int i=count-1; i>=0; i--)

// i should be declared

switch(i)

{

case 1:;

// case should follow by :

case 2:cout<<Y*X[i]; break;

// Lvalue required for X

case 3: cout<<Y + Y;

}

}

Q3. Rewrite the following program underlining the syntactical errors (if any) and its explanations.

#include<iostream.h>

void main()

{

int n = 44;

int *ptr = &n;

++(*ptr);

int *const cptr = &n;

++(*cptr);

++cptr;

const int kn=88;

const int *ptrc = &kn;

++(*ptrc);

++ptrc;

const int *const cptrc =&kn;

++(*cptrc);

++cptrc;

}

Ans:

#include<iostream.h>

void main()

{

int n = 44;

int *ptr = &n;

++(*ptr);

int *const cptr = &n;

Page8

/63

++(*cptr);

//cannot modify the constant value of *cptr

++cptr;

const int kn=88;

const int *ptrc = &kn;

++(*ptrc);

//cannot modify the constant value of *ptrc

++ptrc;

const int *const cptrc =&kn;

++(*cptrc);

//cannot modify the constant value of *cptrc

++cptrc;

//cannot change the constant address of cptrc

}

Q4. Rewrite the following program after removing the syntactical errors (if any). Underline eachcorrection.

#include <iostream.h>

struct Pixels

{

int Color,Style;}

void ShowPoint(Pixels P)

{

cout<<P.Color,P.Style<<endl;}

void main()

{

Pixels Point1=(5,3);

ShowPoint(Point1);

Pixels Point2=Point1;

Color.Point1+=2;

ShowPoint(Point2);

}

Ans:

#include <iostream.h>

struct Pixels

{

int Color,Style;};

// Definition of structure Pixels must be ended with ;

void ShowPoint(Pixels P)

{

cout<<P.Color<<

P.Style<<endl;} // In cascading of cout, << to be used

void main()

{

Pixels Point1 ={5,3};

// { } to be used to initialise of

members of the object

ShowPoint(Point1);

Pixels Point2=Point1;

Point1.Color+=2;

// member to followed by the object using . operator

ShowPoint(Point2);

}

Q5. Rewrite the following program after removing the syntactical errors (if any). Underline eachcorrection.

#include <iostream.h>

class sum

{

int x, y, total;

public :

sum(int a, b)

{

x=a ; y = b * 2 ; total = 0 ;

}

void display()

{

c = x + y ;

Page9

/63

total += c ;

cout << total ;

}

}

void main()

{

sum s(20, 10);

display();

}

Ans : #include <iostream.h>

class sum

{

int x, y, total;

public :

sum(int a,int b)

// argument b should be declared separately

{

x=a ; y = b * 2 ; total = 0 ;

}

void display()

{

int c = x + y ;

// local variable c should be defined

total += c ;

cout << total ;

}

};

// class definition must terminate with;

void main()

{

sum s(20, 10);

s.display();

// member function must be invoked using . operator

}

Questions based onFinding Outputs using random()

Short Answer Questions

( 2 marks)

Note: random(n) generates the numbers randomly from 0 to n–1. For example: random(20)generates randomly from 0 to 19.

Explanations are given at the end of each solution.

Q1. In the following program, if the value of N given by the user is 50, what maximum andminimum values the program could possibly display?

#include <iostream.h>

#include <stdlib.h>

void main()

{

int N,Guessme;

randomize();

cin>>N;

Guessme=random(N) + 5;

cout<<Guessme<<endl;

}

Ans : Minimum : 5

Maximum : 54

Explanation : Since random(50) gives a number randomly from 0 to 49. If it returns 0 i.e.minimum for random(50), the minimum value for Guessme will be 0 + 5 = 5. If it returns49 i.e. maximum for random(50), the maximum value for Guessme will be 49 + 5 = 54.

Page10

/63

Q2. In the following program, write the correct possible output(s) from the options (i) to (iv).

Explanation : Since random(2) gives either 0 or 1, Fly value will be either 1 or 2.

City[1] is “CHN” and City[2] is “KOL” . Since I value from 0 to 2 (<3), 3 iterations willtakes place. So the possible output consists 3 strings separated by :, each of them may beeither “CHN” or “KOL”.

Q3. Study the following program and select the possible output from it:

#include<iostream.h>

#include<stdlib.h>

const int Max=3;

void main( )

{

randomize();

int Number;

Number=50 + random(Max);

for(int P=Number; P>=50; P-

-)

cout<<P<<”#”;

cout<<endl;

}

(i)

53#52#51#50#

(ii)

50#51#52#

(iii)

50#51#

(iv)

51#50#

Ans:51#50#

Q4. In the following program, if the value of Guess entered by the user is 65, what will be the

expected output(s) from the following options (i), (ii),

(iii) and (iv)?

#include <iostream.h>

#include <stdlib.h>

void main()

{

int Guess;

randomize();

cin>>Guess;

for (int I=1;I<=4;I++)

{

New=Guess+random(I);

cout<<(char)New;

Explanation : Since random(3) gives a numberrandomly from 0 to 2. So, the values of Numberranges from 50 (50+0) to 52 (50+2)

and theNumber should be displayed in descending orderaccording to the programme. 53 is not possible, sothe answer is (iv).

Page11

/63

}

}

(i) ABBC

(ii) ACBA

(iii) BCDA

(iv) CABD

Ans:(i) ABBC

Q5. In the following program, if the value of N given by the user is 20, what maximum andminimum values the program could possibly display?

#include <iostream.h>

#include <stdlib.h>

void main()

{

int N,Guessnum;

randomize();

cin>>N;

Guessnum= random(N–

10)+10;

cout<<Guessnum<<endl;

}

Ans :Maximum Value: 19

Minimum Value: 10

Questions based onFinding Outputs

Short Answer Questions

( 2 marks)

Note : While solving such type of question, a student should carefully go through the

logic of thewhole program

and concepts used in it.

Various patterns of questions are given below.Students are advised to practice

various questions to develop the skill of finding the output.

Q1. Find the output of the followingprogram:

#include <iostream.h>

struct Game

{

char Magic[20];int Score;

};

void main()

{

Game M={“Tiger”,500};==c桡爠⩃桯楣rX==C桯楣h=䴮䵡g楣i==Choice[4]=’P’;==Choice[2]=’L’;==䴮jc潲oH=㔰R==c潵琼o䴮䵡g楣YY䴮jc潲oYYe湤氻=䝡浥⁎=䴻==N.Magic[0]=’A’;N.Magic[3]=’J’;==丮卣潲eJ=ㄲ〻==c潵琼o丮kag楣iY丮卣k牥YYe湤氻=}=Ans:

Explanation : In first iteration I = 1 and random(I) gives 0. So, New =65 + 0, hence output is A. In first iteration I = 1, So,

New = 65 + 0,hence output is A. In second iteration I = 2 and random(I) gives 0 or1. So, New = 65 or 66, hence output is A or B. In third iteration I=3and random(I) gives 0 to 2. So, New = 65 or 66 or 67, hence output isA or B or C. In fourth iteration I=4 and random(I) gives 0 to 3. So,New = 65 or 66 or 67 or 68, hence output is A or B or C or D. Option(i) satisfies all the above only, so it is the answer.

Ans. Data hiding is a property whereby the internal data structure of an object is hidden from therest of the program. Data hiding is implemented in C++ by private and protected members ofclass.

Q11. How data abstraction can be implemented in C++?

Ans. Data abstraction can be implemented in C++ by using public members of class.

Q12. What is programming paradigm?

Ans. A programming paradigm defines the methodology of designing and implementing

programs using the key features and building blocks of a programming language.

Q13. What is procedural programming paradigm?

Ans. In procedural programming paradigm, data is shared

among all the functions. Its emphasis ison doing things rather than using the data.

Page16

/63

Q14. What are the advantages of OOP?

Ans : The advantages of OOP are Reusability of code, Ease of comprehension, ease of fabricationand maintenance, ease of redesign and extension.

Q15. What do you understand by functional overloading? Give an example illustrating its use in aC++ program.

Ans: A function name having several definitions that are differentiable by the number or types oftheir arguments is known as functional overloading. For example:

float volume(float a )

{ return a * a * a; }

float volume(float a, float b )

{ return a * a * b; }

float volume(float a, float b, float c)

{ return a * b * c; }

CLASSES AND OBJECTS

SOME

MPORTANT

QUESTIONS

TO

REFRESH

THE

CONCEPT

Q1.

Write four attributes associated with declaration of classes.

Ans.

The attributes associated with declaration of classes are Data Members, Member Functions,Program access levels and Class Tagname.

Q2.

Define data members andmember functions.

Ans. Data members are exactly like the variables in a structure. They are normally made Memberfunction is function defined within a class that acts on the data members in the class. Theyare normally made public.

Q3.

Write the scope rules of members of a class.

Ans.Scope rules ofmembers of aclass are:-

Private

These members can be accessed only by the member functions &friend functions of the class. It can not be inherited.

Protected

These members can be accessed only by the member functions &friend functions of the class. It can be inherited.

Public

These members can be directly accessed by any function.

Q4.

How many types of functions are used in a class?

Ans.

1. Accessor function 2. Mutator functions 3. Manager functions

Q5.

When will you make a function inline?

Ans.

A function is made inline when it is very small and does not return any value. Also it doesnot contain any loop and static variables.

Q6.

What is scope resolution operator?

Ans.

This operator(::) is used in situations where a global variable exists with the same name as alocal variable. This is

also used when the member functions are declared outside the classdefinition; the function name is preceded by the class name and the binary scope resolutionoperator( :: ).

Q7.

Define static data members.

Ans.

Static data members are initialized tozero when the first object of its class is created. Noother initialization is permitted. Only one copy of that member is created for the entire classand is shared by all the objects for that class.

Q8.

How is memory allocated to a class and its objects?

Ans.

When a class is defined, memory is allocated for its member functions and they are stored inthe memory. When object is created, separate memory space is allocated for its datamembers. All objects work with the same copy of member function shared

A member function CALCNTR() to calculate and return the number of centers as(NoCandidates/100+1)

Public Members

•

A function SCHEDULE() to allow user to enter values for TestCode, Description,NoCandidate & call function CALCNTR() to calculate the number of Centres

•

A function DISPTEST() to allow user to view the content of all the data members

Ans:

class TEST

{

int TestCode;

char Description[20];

int NoCandidate,CenterReqd;

void CALCNTR();

public:

void SCHEDULE();

void DISPTEST();

};

void TEST::CALCNTR()

{

CenterReqd=NoCandidate/100 + 1;

}

void TEST::SCHEDULE()

{

cout<<”Test Code :”;cin>>TestCode;

cout<<”Description :”;gets(Description);

cout<<”Number

:”;cin>>NoCandidate;

CALCNTR();

}

void TEST::DISPTEST()

{

cout<<”Test Code :”<<TestCode<<endl;

cout<<”Description :”<<Description<<endl;

cout<<”Number :”<<NoCandidate<<endl;;

cout<<”Centres :”<<CenterReqd<<endl;;

}

Page20

/63

Q5.

Define a class

in C++ with following description:

Private Members

•

A data member Flight number of type integer

•

A data member Destination of type string

•

A data member Distance of type float

•

A data member Fuel of type float

•

A member function CALFUEL() to calculate the value of Fuel as per the followingcriteria

Distance

Fuel

<=1000

500

more than 1000 and <=2000

1100

more than 2000

2200

Public Members

•

A function FEEDINFO() to allow user to enter values for Flight Number,Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel

•

A function SHOWINFO() to allow user to view the content of all the data members

Ans:

class FLIGHT

{

int Fno;

char Destination[20];

float Distance, Fuel;

void CALFUEL();

public:

void FEEDINFO();

void SHOWINFO();

};

void FLIGHT::CALFUEL()

{

if (Distance<1000)

Fuel=500;

else

if (Distance<2000)

Fuel=1100;

else

Fuel=2200;

}

void FLIGHT::FEEDINFO()

{

cout<<”Flight No :”;cin>>Fno;

cout<<”Destination :”;gets(Destination);

cout<<”Distance:”;cin>>Distance;

CALFUEL();

}

void FLIGHT::SHOWINFO()

{

cout<<”Flight No :”<<Fno<<endl;

cout<<”Destination :”<<Destination<<endl;

cout<<”Distance :”<<Distance<<endl;;

cout<<”Fuel :”<<Fuel<<endl;;

}

Page21

/63

CONSTRUCTOR AND DESTRUCTOR

SOME

MPORTANT

QUESTIONS

TO

REFRESH

THE

CONCEPT

Q1. What is constructor?

Ans. A member function with the same name as its class is called

constructor and it isused toinitialize the objects of that class type with a legal initial value.

Q2. What is destructor?

Ans.A destructor is a member function having same name as its class but preceded by ~ sign andit deinitialises an object before it goes out of scope.

Q3. What are different types of constructors?

Ans. The different types of constructors are Default constructor, Parameterized constructor andCopy constructor.

Q4. What is default constructor?

Ans. A constructor that accepts no parameter is called the default constructor.

Q5. What is parameterized constructor?

Ans. A constructor that accepts parameters for

its invocation is known as parameterized

constructor.

Q6. What is copy constructor?

Ans. A copy constructor is a constructor that defines and initializes an object with another object.It takes the form classname(classname). For a copy constructor there must be a defaultconstructor or a parameterized constructor.

BOARD

PATTERN

QUESTIONS

-

Short Answer Questions ( 2 marks)

Note : Two options with the following pattern are generally

asked in the Board Exam. Variousoptional questions

are givenbelow.

Q7. Answer the following questions after going through the following class:

class Seminar

{

int Time;

public:

Seminar();

//Function 1

void Lecture()

//Function 2

{cout<<”Lectures in the seminar on”<<end1;}

Seminar(int);

//Function 3

Seminar(Seminar &abc);

//Function 4

~Seminar()

//Function 5

{ cout<<”Vote of thanks”<<end1;}

};

(i) In Object Oriented Programming, what is Function 5 referred as and when does it getinvoked/called?

Ans : Function 5 is referred as destructor and

it is invoked as soon as the scope of theobject gets over.

(ii) In Object Oriented Programming, which concept is illustrated by Function 1, Function3 and Function 4 all together?

How does the access of inherited members depend upon their access specifiers and thevisibility modes of the base class?

Ans.

public inheritance

protectedinheritance

private inheritance

public

member in base class

public

in derived class

protected

inderived class

private

in derivedclass

protected

member in baseclass

protected

in derivedclass

protected

inderived class

private

in derivedclass

private

member in baseclass

hidden in derived class

hidden in derivedclass

hidden in derivedclass

Q4.Write the different ways of accessibility of base class members.

Ans.

Access Specifier

Accessible from

own class

Accessible from derived

class (Inheritable)

Accessible from objects

outside class

public

Yes

Yes

Yes

protected

Yes

Yes

No

private

Yes

No

No

Q5.How is the size of a derived class object calculated?

Ans.

The size of a derived class object is equal to the sum of sizes of data members in base classand the derived class.

Q6.

In what order are class constructors

and class destructors called when a derived class object iscreated or destroyed?

Ans.

When the object of a derived class is created, firstly the constructor of the base class isinvoked and then, the constructor of the derived class is invoked.

On the other hand, when the object of a derived class is destroyed, firstly the destructor of thederived class is invoked and then, the destructor of the base class is invoked.

Note : Observe the following questions and their solutions. The above concepts are implemented.Practice of such questions will definitely clear your doubts and improve your confidencelevel.Discussion with your friends and distinguish the varieties of these questions.

Access specifier

Visibility mode

Page24

/63

BOARD

PATTERN

QUESTIONS

Long

Answer Questions

(4 Marks)

Q1. Answer

the questions (i) to (iv) based on the following:

i) Write the member(s) that can be accessed from the object of bus.

ii) Write the data member(s) that can be accessed from the function displaydata( ).

iii) How many bytes are requiredby an object of bus and heavyvehicle classes respectively?

iv) Is the member function outputdata( ) accessible to the objects of the class heavyvehicle?

Ans :

(i) fetchdata(), displaydata()

(ii) make, load, passanger

(iii) for the object of bus–

28 bytes, for the object of heavyvehicle–

8 bytes

(iv) No

Q2. Answer the questions (i) to (iv) based on the following:

(i)

Write the members which can be accessed from the member functions of class human.

(ii)

Write the members, which can be accessed by an object of class human.

(iii)

What is the size of an object (in bytes) of class human?

(iv)

Write the class(es) which objects can access read() declared in livingbeing class.

Ans :

(i) race, habitation, iq_level, readhuman(), showhuman(), readape(),

showape()

(ii) readhuman(), showhuman(), readape(), showape()

(iii) 78 bytes

(iv) livingbeing

Q3. Answer the questions (i) to (iv) based on the following:

(i)

In case of the class father, what is the base class of father and what is the derived class of father?

(ii)

Write the data member(s) that can be accessed from function dispdata().

(iii)

Write the member function(s), which can be accessed by an object of mother class.

(iv)

Is the member function outputdata() accessible to the objects of father class?

Ans :

(i) base class of father–

parent, derived class of father–

mother

(ii) child, baby, son

(iii) fetchdata(), dispdata(), readdata(), writedata()

(iv) No

class vehicle

{

int wheels;

protected:

int passenger;

public:

void inputdata( );

void outputdata( );

};

class bus : private heavyvehicle

{

char make[20];

public:

void fetchdata( );

void displaydata( );

};

class livingbeing

{

char specification[20];

int averageage;

public:

void read();

void show();

};

class human : public ape

{

char race[20];

char habitation[30];

public:

void readhuman();

void showhuman();

};

class parent

{

char name[20];

protected:

int son;

public:

void inputdata();

void outputdata();

};

class mother : public

father

{

int child;

public:

voidfetchdata();

void dispdata();

};

class father : protected

parent

{

int daughter;

protected:

int baby;

public:

void readdata();

void writedata();

};

class heavyvehicle : protected vehicle

{

int diesel_petrol;

protected:

int load;

public:

void readdata(int, int);

void writedata( );

};

class ape : private livingbeing

{

int no_of_organs;

int no_of_bones;

protected:

int iq_level;

public:

void readape();

void showape();

};

Page25

/63

Q4. Answer the questions (i) to (iv) based on the following:

(i)

What type of inheritance is depicted by the above example?

(ii)

Write the member functions, which can be called by the object of class client.

(iii)

What is the size in bytes of the object of class doctor and client respectively?

(iv)

Write the data members, which can be used by the member functions of the class doctor.

Ans :

(i) Hierarchical Inheritance

(ii) get_resource(), free_resource()

(iii) size of object of class doctor = 62 and client = 44

(iv) speciality, x

Q5. Answer the questions (i) to (iv) based on the following:

(i)

Write the names of data members, which are accessible from object of class employee.

(ii)

Write the names of all the member functions which are accessible from object of class person.

(iii)

Write the data members which are accessible from member functions of class employee.

(iv)

How many bytes are required by an object belonging to class employee?

Ans :

(i) Nil

(ii) haveit(), giveit()

(iii) ecode, dept, salary

(iv) 76 bytes

Q6. Answer the questions (i) to (iv) based on the following:

(i)Write the names of data members, which are accessible from objects belonging to class AUTHOR.

(ii) Write the names of all the members which are accessible from member functions of class AUTHOR.

(iii) How many bytes are required by an object belonging to class AUTHOR?

(iv) Write the sequence of the constructors’ invocation when the object of author is created.

Ans:(i) Nil

(ii) Acode, Aname, Amount, Employees, Start(), Show(), Haveit(),

Giveit(), Register(), Enter(), Display()

(iii) 70 bytes

(iv) BRANCH(), PUBLISHER(), AUTHOR()

Q7. Answer the questions (i) to (iv) based on the following:

class person

{

char name[20], address[20];

protected:

int x;

public:

void enter_person();

void disp_person();

};

class doctor : public person

{

char speciality[20];

public:

void input();

void disp();

};

class author

{

char name[12];

double royalty;

protected:

void register();

public:

author(){};

void enter();

void display();

};

class employee : private

author, public person

{

int ecode;

char dept[30];

public:

employee(){};

void start();

void show();

};

class client : private

person

{

int resource;

public:

int get_resource();

void free_resource();

};

class person

{

char address[20];

protected:

float salary;

public:

person(){};

void havelt();

void givelt();

};

class PUBLISHER

{

char Pub[12];

double Turnover;

protected:

void Register();

public:

PUBLISHER();

void Enter();

void Display();

};

class BRANCH

{

char CITY[20];

protected:

float Employees;

public:

BRANCH();

void Haveit();

void Giveit();

};

class AUTHOR:

private BRANCH,

public PUBLISHER

{

int Acode;

char Aname[20];

float Amount;

public:

AUTHOR();

void Start();

void Show();

};

class CUSTOMER

{

int Cust_no;

char Cust_Name[20];

protected:

void Register();

public:

CUSTOMER();

void Status();

};

class SALESMAN

{

int Salesman_no;

char Salesman_Name[20];

protected:

float Salary;

public:

SALESMAN();

void Enter();

void Show();

};

class

SHOP : private CUSTOMER , public SALESMAN

{

char Voucher_No[10];

char Sales_Date[8];

public:

SHOP();

void Sales_Entry();

void Sales_Detail();

};

Page26

/63

(i)Write the names of data members which are accessible from objects belonging to class CUSTOMER.

(ii)

Write the member functionsthat

are accessible from objects belonging to class SALESMAN.

(iii)Write the names of all the members which are accessible from member functions of class SHOP.

(iv)

How many bytes will be required by an object belonging to class SHOP?

Ans : (i) None of data members are accessible from objects belonging to class CUSTOMER.

Formulae of Row Major & Column Major are used in the given questions. Kindly go through it.

Q1. An array x[30][10] is stored in the memory with each element requiring 4 bytes of storage. Ifthe base address of x is 4500, find out memory locations of x[12][8] and x[2][4], if thecontent is stored along the row.

Ans : Given, W = 4, N = 30, M = 10, Base(x) = 4500

Row Major Formula:

Loc(x[12][8])

= Base(x)+W*(M*I+J)

Loc(x[2][4])

= Base(x)+W*(M*I+J)

= 4500 + 4 * (10 * 12 + 8)

= 4500+ 4*( 10*2 + 4)

= 4500 + 4 * 128

= 4500 + 4 * 24

= 4500 + 512

= 4500 + 96

= 5012

= 4596

Q2. An array P[20][30] is stored in the memory along the column with each of the elementoccupying 4 bytes, find out the Base Address of the array, if an element P[2][20] is stored atthe memory location 5000.

Ans : Given, W=4, N=20, M=30,

Loc(P[2][20])=5000

Column Major Formula:

Loc(P[I][J]) =Base(P)+W*(N*J+I)

Loc(P[2][20]) =Base(P)+4*(20*20+2)

Base(P) =5000–

4*(400+2)

=5000–

1608

=3392

Q3. An array ARR[5][25] is stored in the memory with each element occupying 4 bytes of space.Assuming the base address of ARR to be 1000, compute theaddress of ARR[5][7], when thearray is stored as : (i) Row wise

(ii) Column wise.

Ans:

(i) Row wise :

Given, W = 4, N = 5, M = 25,

Base(ARR) = 1000

Row Major Formula:

Loc(ARR[5][7])= Base(ARR)+W*(M*I+J)

= 1000 + 4*( 25*5 + 7)

= 1000 + 4 * 132

= 1000 + 528

= 1528

(ii) Column wise :

Given, W = 4, N = 5, M = 25,

Base(ARR) = 1000

Column

Major Formula:

Loc(ARR[5][7])= Base(ARR)+W*(N*J+I)

= 1000 + 4*( 5*7 + 5)

= 1000 + 4 * 40

= 1000 + 160

= 1160

Q4.An array S[40][30] is stored in the memory along the row with each of the element occupying2 bytes, find out the memory location for the element S[20][10], if an element S[15][5] isstored at the memory location 5500.

Page27

/63

Ans.

Given,

W=2,

N=40,

M=30,

Loc(S[15][5])=5500

Row Major Formula:

Loc(S[I][J])

=Base(S)+W*(M*I+J)

Loc(S[15][5])

=Base(S)+2*(30*15+5)

5500

=Base(S) + 2*(450+5)

Base(S)

=5500–

910 = 4590

Loc(S[20][10])

=4590+2*(30*20+10)

=4590+2*(600+10)

=4590+1220 = 5810

Q5.

An array P[20][30] is stored in the

memory along the column with each of the elementoccupying 4 bytes, find out the memory location for the element P[5][15], if an elementP[2][20] is stored at the memory location 5000.

Ans.

Given,

W=4,

N=20,

M=30,

Loc(P[2][20])=5000

Column Major Formula:

Loc(P[I][J])

=Base(P)+W*(N*J+I)

Loc(P[2][20])

=Base(P)+4*(20*20+2)

5000

=Base(P)+4*(400+2)

Base(P)

=5000–

1608

Base(P)

=3392

Loc(P[5][15])

=3392+4*(20*15+5)

=3392+4*(300+5)

=3392+1220

=4612

Page28

/63

Static Allocation of Objects

Short Answer Questions

( 2 marks)

Note : Practice the way to write the function definition where array and its size are passed asarguments. Practice

with the concepts of accessing the elements of the one / two dimensionalarray. Apply the suitable logic to solve the given problem and write the coding of it.

Q1. Write a function in C++ to find sum of rows from a two dimensional array.

Ans : void MatAdd(int A[ ][ ],int N, int M)

{

for (int R=0;R<N;R++)

{

int SumR=0;

for (int C=0;C<M;C++)

SumR+=A[C][R];

cout<<SumR<<endl;

}

}

Q2.Write a function in C++ to find the sum of both left and right diagonal elements from a twodimensional array (matrix).

Ans : void DiagSum(int A[ ][ ], int N)

{

int SumD1=0,SumD2=0;

for (int I=0;I<N;I++)

{

SumD1+=A[I][I];

SumD2+=A[N-I-1][I];

}

cout<<”Sum of Diagonal 1:”<<SumD1<<endl;

cout<<”Sum of Diagonal 2:”<<SumD2<<endl;

}

Q3. Write a function in C++ which accepts an integer array and its size as arguments and replaceselements having even values with its half and elements having odd values with twice itsvalue. eg:

if the array contains :

3, 4, 5, 16, 9

then the function should be rearranged as 6, 2,10,8, 18

Ans: void calc(int x[ ], int m)

{

for(int i=0; i<m; ++i)

{

if(x[i]%2==0)

x[i]=x[i]/2;

else

x[i]=x[i]*2;

}

}

Q4. Write a user defined function in C++ which intakes one dimensional array and size of array asargument and display the elements which are prime.

If 1D array is 10 , 2 , 3 , 4 , 5 , 16, 17 , 23

Then prime numbers in above array are: 2 , 3 , 5, 17, 23

Ans: void primedisp(int x[ ], int m)

{

int nf;

for(int i=0; i<m; ++i)

Page29

/63

{

nf=0;

for(int j=1; j<=x[i]; j++)

if(x[i] % j == 0)

nf++;

if(nf == 2)

cout<<”\n”<<x[i];

}

}

Q5. Writea function in C++ which accepts an integer array and its size as arguments/parametersand exchanges the values at alternate locations.

example : if the array is 8,10,1,3,17,90,13,60 then rearrange the array as 10,8,3,1,90,17,60,13

Ans : void exchange(intx[ ], int m)

{

int y;

for(int i=0; i<m; i= i+2)

{

if(m-i == 1)

// if m (no. of element ) is odd last element

i = m;

// should not alter its position.

else

{

y= x[i];

x[i] = x[i+1];

x[i+1] = y;

}

}

}

Short Answer Questions ( 3 marks)

Q1. 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 resultantarray is required to be in ascending order.

Ans: voidMERGE(int A[ ], int B[ ], int C[ ], int M, int N, int &K)

{

int I,J, K;

for(I=0, J=N–

1, K=0; I<M && J>=0;)

{

if (A[I]<=B[J])

C[K++]=A[I++];

else

C[K++]=B[J--];

}

for (int T=I;T<M;T++)

C[K++]=A[T];

for(T=J;T>=0;T--)

C[K++]=B[T];

}

Q2. Given two arrays of integers x and y of sizes m and n respectively. Third array of integers zhas m+n size. These are passed as the arguments to the function EXCHANGE(). Write afunction named EXCHANGE() which will produce the elements to the third array named z,such that the following sequence is followed:

(i) All odds numbers of x from left to right are copied into z from left to right.

Page30

/63

(ii) All even number of x from left to right are copied into z from right to

left.

(iii) All odd numbers of y from left to right are copied into z from left to right.

(iv) All even number of y from left to right are copied into z from right to left.