0% found this document useful (0 votes)
2K views184 pages

CS 1 TPS Computer Science PDF Guide

The document provides an overview of C++ programming, including its advantages, data types, and key concepts such as object-oriented programming principles. It discusses the differences between traditional procedural programming and object-oriented programming, as well as various operators and memory management techniques in C++. The content serves as a review for understanding C++ fundamentals and programming practices.

Uploaded by

soham7587
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views184 pages

CS 1 TPS Computer Science PDF Guide

The document provides an overview of C++ programming, including its advantages, data types, and key concepts such as object-oriented programming principles. It discusses the differences between traditional procedural programming and object-oriented programming, as well as various operators and memory management techniques in C++. The content serves as a review for understanding C++ fundamentals and programming practices.

Uploaded by

soham7587
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Welcome to tpspoint.

com
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Thank You for Visiting
[Link]
Welcome to [Link]
Chapter 3> [Link]

Probable marks:41

Syllabus
Scope of the
Review of C++
references,
strings
pointers,
Arrays, programming
oriented
rinciple of
object
Classes and objects
Constructors and destructors

conversions

overloading
and type
Operator
Inheritance
and polymorphism
Virtual functions
Working with files

REVIEW OF C++
(March 2003,13
Q.1 What is C++? What are the advantages of C++ ?
Ans.
C+t is an object oriented programming language. Initially C++ was named as t witt
classes". C++ Was developed by Bjarne Stroustrup at AT & T Bell Laboratories, USA
the early eighties.
The advantages of C++ over C are :
(i)
) C++ is an incremented version of C. It is
a
r a m s can s

in C++ superset of C. Almost all C progran


run
Compiler.
() The important facilities added in C++
classes, function overloaau6
operaa
are
overloading.
(iii) C++ allow user
to create abstract data XIStingd
types. types, to inherit properties front
(iv) C++
supports polymorphism.
(V) Any real lite
application
systems can be built by C++systems such as editor, compiler, cati

(vi) Object oriented ibrares can be databases,


(viil C++
programs can be easily built by C+.
implemented, maintained and
expanded
[Link]
Science -I C+
TPS Computer 3-2

Q.2 Differentiate between


traditional procedural programming approach and
object
oriented programming approach. Oct. 2002, 2005; March 2011, March 2018)
Ans.
The differences between traditional procedural programming approach and object
oriented programming approach are as follows
Traditional Procedural Object Oriented
Programming Approach Programming Approach
1 In this approach, the problem is 1 In this approach, the problem is
viewed as a sequence of things to be decomposed into a number of entities
done. called objects and then builds data
and function around these entities.
the data rather tharn
2 Emphasis is on doing things. 2 Emphasis is on

procedure.
3 Large programs are divided into 3 Programs aré divided into entities
smaller programs known as functions. known as objects.
4 Data move openly around the system| 4 Data is hidden and cannot be accessed
from by external functions.
in 5 Follows bottom-up approach in
Employs top-dowm approach
program design. program design.
and Object Oriented
Q.3 What do you mean by Object Based Programming Language
Programming Language ? State the relationship between theselanguages.
(Oct. 2008,March 2010, 3)
Ans
Object Based Programming Language:
with objects are said to be object based
1) Language that supports programming
programming languages.
2) lt is a style of programming that primarily supports
encapsulation & object or identity.
3) Major features are
a) Data encapsulation
mechanism
b) Data hiding & access

c) Automatic initalization & clean-up objects


d) operator overloading
.& dynamic binding
They do not support inheritance
5) For eg-Ada.

Object Oriented Programming Language inheritance and


1) all the object based features along with
his language incorporates
dynamic binding.
2) For eg. C++, Smalltalk.
The relation between them characterized by following statement:
features + inheritance + dyrnamic
programming =. object-based
Object oriented
bindin
[Link]
3-3 Ct+
-
TPS Computer Science I
Oriented programming.
of Object
Q.4 State any six principal
advantages
(March 2012,3
Ans.:
Oriented Programming:
Advantage of Object and extend the
use of existing classec
ses.
eliminate redundant code
1. Through, inheritance,
to build secure program.
the programmer
2 The principle of data hiding helps
co-exist without any interferenoo
ence.
instances of an object to
3. It is possible. to have multiple
in a; project based on object.
4. It is easy to partition the work
OOP system can be upgraded from small to
easily large system.
5.
6. Software complexity can,be easily managed.
in the program.
objects in the problem domain objects
to
7. It is possible to map
communication between objects.
8. Good message passing technique for

Q.5 What are the different data types in C++ ? (Oct.2015


Ans.
1) Data types in C++ are shown in figure below:

C+ data types

|User defined type Built in Type Derived type


i. Structure
ii. Union i. Array
ii. Class ii. Function
iv Enumeration ii. Pointer

Integral type Void


Floating type

int
Char Float double
2) C++ allows user to
create new abstract data types, which
data type. These are can behave like uit-in
called user-defined any D
and enumeration. data types. These
3)
include structure, unio
class

C++
provides three built-in data
4) Integral includes integer and types which are integral, void and
double. character (string) while floating
5) In floating type includes
includes float
i
addition to these data types, C++
which are referred as provides user with arrays,
derived data types. functions and
inter
Science I
TPS Computer
-

3-4 [Link] C+

Q.6 Enlist the basic data types used in C++ with size of data in terms of bytes for each.
March 2002, 2006, October 2006)
OR Enlist different built in data types in C++ with their sizes.
(Oct. 2009
Ans.: There are three main basic built-in data types used in C++ viz. integral type, voia ana
floating type.
Built-in type
or
Basic data type

Integral type Void Floating

int char float double

i) Integral data type:


It includes integer (int) and character (char).
variable requires 1 byte.
An int variable requires 2 bytes to store, while a character
short int and (b) long int. Long integer
Integer variables are also of two types (a)2
requires 4 bytes, while short integer requires bytes.
ii) Void data type:
Void data type is used:
value.
of a function when it is not returning any
(a) to specify the return type
function.
empty argument list to
a
(6) to indicate an

c) to declare generic pointers.


ii) Floating type:
July 2019)
4
float and double. A float variable requires
variables are of two types;
Floating type 8 bytes to store in memory.
bytes, while double requires which requires 10 bytes to store in
kind of double namely long double,
There is another
data types, size and range
table shows all basic
memory. The following
Bytes Range
Sr. No. Type
1 128 to 127
char (Signed char)
1 0 to 255
unsigned char
2
2 32768 to 32767
signed int)
-

3 int (short int or

unsigned int
2 0 to 65535
4 3.4 x 10-38 to 3.4 x 10-38
float
1.7x 10308
8 1.7x 10-308 to
6 double
3.4 x 10-4932
7 long double 10 3.4 x 10-4932 to
3-5
TPS Computer Science -I
[Link]

Q.7 Explain insertion and extraction operátors


in C++.
(Mar. 2012
Ans.
(i) Insertion operator:
It is also called as "put to" on
The operator "<<" is called as insertion operator.
inserts the contents of the variables on its right
to the object on its left. perator.i
generally
It is used in output statement in C++.
e.g. (i) Coút <<a;
(i) Cout << "program";
In first example, the value of variable 'a' is printed on screen, while in second exam.
example
the word "program" is printed on screen.
(ii) Extraction operator:
The operator ">>" is called as extraction operator. It is also called as get from' operato
tor.
It extracts or takes the value from keyboard and assigns it to a variable on its right. It
used in input statement in C++
e.g. cin >> a;
This instruction will extract a value from keyboard and assign it to the variable a. C+
allows us to redefine insertion and extraction operators by overloading them.
Q.8 Write a short note on scope resolution operator. (Oct. 2014; Mar.16
Ans.
1) The operator:: is called as scope resolution operator.
2) C++ is block structured language i.e. a C++
a

another block.
program may contain one block withir
3) When a variable is declared in
program, scope extends from the point of declaration tili
the end of the block in which it is
defined.
4) The same variable name can be used to
have different meaning in different blocks.
5) Consider the following
segment
of
program.
*****

int x =10;
*****

int x =
1; Block 2 Block 1

****

Here Block 2 is
hides the contained in Block 1. Note
declaration of the same that declaration of a variable in an è rbloo
variable in an outer in
block.
TPS Computer
Science -I [Link]
3-6 C+
Scope resolution operator is used to uncover a hidden
6)
It takes the form variable.
:variable namee
e.g

intx= 10;

int x =
1;
cout << "Local x is" << x;

cout << "\n Global x is" << :: x;

The output will be as follows


Local x is1
Global x is 10
of scope resolution operator and memory management operators in
Q.9 Explain the use

C++ with examples. (March 2004,16, 17


Ans.: Scope resolution operator:
from function
is used to access a global variable
a
1) In C++, scope rèsolution operator (::) same name as a global
variable.
in which a local variable is defined with the
2) For example: variable num and also the
In following program, the function main ( ) access the global
local variable with the same name.

int num = 20

void main ()

variable
intnum 10;// local
=

cout <<"Local =" << num;


cout<"Global =" <<::num;

The output is as5:


Local = 10
Global = 20
Memory management operator
two memory management oper
C++ provides following
ii) delete
3-7 [Link] CH
TPS Computer Science - I

block from operating system


arnd returns a pointe
(2) The new operator obtains memory allocation is unsuccescf
returns NULL, if memory al.
its starting point. The new operator

The general format of new operator is


DataType
*
new DataType |size in integerl
allocated by the new operator back .
(3) The delete operator is used to return the memory to
of the program
the memory pool. Thus released memory will
be reused by other parts
The general format of delete operator is:
delete pointervariable;
(4) Forexample:
void main ()
char str= ""COMPUTER";
*

int len = strlen (str);

char ptr
ptr = new char [len + 1];
strcpy (ptr, str);
cout <<"ptr =" << ptr;

delete ptr;

In above example, the new operator returns a pointer that point to a memory section
large enough to hold the string str plus an extra byte for null character. Thern after use of
memory delete operator released memory.
Q. 10 What are the different selection (conditional) statements in C++? Give syntax for
each.
Ans.
The program has to be able to evaluate conditions and select alternative path in
programn.
In C++, there are two ways in which selection may be made:
1) The if statement 2) The switch statement
1) The if statement:
The if statement has two forms:
i) Simple if statement ii) if else statement
i) Simple if statement

Syntax if (condition)

action 1;

action 2;

1) Depending the
on
condition value,
direction or another. program execution proceeds
2) If the condition is
true, then action I will be
done.
Science II [Link] C+
s
T P S
Computer
3-8

ii) if.. else statement:

Syntax if (condition)

action 1;

else

action 2

action 3; will
otherwise action 2
If the condition is true, then and then only action 1 will be done,
be done.
The switch statement:
2)
1) This is a multiple branching statement.
only one module out of several. If no

Depending on certain condition, it executes


2) module will be executed.
condition is satisfied, then default
terminate switch statement.
3) The break statement is used to
int or char value.
4) Expression must have
Syntax: switch (expression)

case 1:

action 1;
break;

case2:

action 2;
break;

default

action x
[Link]
CH
3-9
TPS Computer Science - I
each.
Give syntax for
structures in C++ ?
Q.11 What are the different looping

Ans.: inC++:
structures
Following are the differentlooping
3) Do-while loop
2) While loop
1) For loop
1) The for loop: when action is
to be repeate
entry-controlled loop.
It is used
The for loop is an
predetermined number of times.
Syntax: increment / decrement expression)
for (initial expression; test expression;

action;
***°

where
starts.
(a) Initial expression is executed only once, when the loop
(6) Test-expression evaluated each time through the loop, before the body of the loop-
b)
is executed.

(c) Increment/ Decrement expression changes the value of the loop variable at the
end of the loop.
2) The while loop:
The while loop is an entry-controlled loop and it repeats the action until the condition
becomes false. When condition is false, that time loop is terminated.

Syntax: while (condition)

action 1;

action 2;
3) The do-while loop:
The do-while loop is an exit-control loop used to carry out
Syntax conditional looping.
do

action 1;

while (condition);
action 2;
In do-while, condition is not tested
even if until the body of the
the condition is false the loop has been executed
after the first loop is executed at
iteration, the loop is terminated. least once. If the
o1
conditiOT is
Q.12
What is function prototyping? [Link]

Ans. :

Function prototyplng 1s one of the major


1)
The prototype describes the function
improvements added to C++ functions.
2 interface to the compiler by giving details such as
the number and the type of
arguments and the type of return values.
With function prototyping, a template is always used when declaring and defining a
3)
function.

When function is called, the compiler uses the template


a
to ensure that proper
arguments are passed, and the return value is treated correctly.
Any violation in matching the arguments and the return type will be caught by the
compiler at the time of compilation itself.
6) Function prototype is a declaration statement in the calling program and is of the
following form
return-type function-name (argument-list);
The argument list contains the types and names of arguments that must be passed to the
function.
e.g
float volume (int x, float y, float z);
Note that each argument variable should be declared independently. The conmbined
declaration like:
float volume (int x, float y, z); is invalid.
7) In function declaration, the names of arguments are the dummy variables and therefore,
they are optional i.e. the declaration:-
float volume (int, float, float); is valid.
Q.13 Write a short note on inline functions.
Ans.
1) When a function is called, a lot of time is spent in executing series of instructions, for
tasks such as jumping to the function, saving registers, pushing arguments into stack
and returning to the calling function.
2) Ct+ proposes a solution of inline functions to this problem. Inline flunction makes a
program run faster because the overhead of a function call and return is eliminated.

3)9However, it makes program to take up more memory, because the statements that
define inline function are reproduced at each point where the function is called.

4) "An inline function is a function that is expanded inline when it is invoked". ie. the
Compiler replaces function call with the corresponding function code.
5)
Theinline functions are defined as follows:
inline function header

function body
[Link]

3-11
TPS Computer Science - I

eg. inline int area (int a, int b)

return (a*b);

when they are small enough to be defin ed in


6 The functions are generally made inline,
one or two lines.
7) The keyword inline is not a command, but
it is a request to the compiler.
request
8) Following are some situations in which compiler may ignore inline
statemernt exists.
i) For functions returning value, if loop, switch or goto
ii) For functions not returning value, if a return statement exists.
ii) If functions contain static variables.
iv If inline functions are recursive.
Q.14 What are default arguments? Give the advantages of using default arguments.
Ans.
1) C++ allows to call a function without specifying all its arguments. In such cases, the
function assigns default value to the
a
parameter, which does not have a matching
argument in the function call.
2) Default values are
specified when the function is declared.
3) Consider a
function area declared as follows,
float area (int r, float Pi 3.14); =

The above
prototype declares default value 3.14 to the argument Pi. A
function call like - subsequent
A =area(7); //one argument
missing
passes the value 7 tor and lets the function
use default
The call A area (7, 2.5)
=
value 3.14 for' Pi
passes an explicit value 2.5 to. Pi.
4 Only trailing arguments have
default value cannot provide to an default values.
can
i.e. add defaults
argument in the middle of
from right to lenft. A
5) Advantages of using default arguments: list.
i These are useful in
situations, where some
ii It
provides better flexibility to arguments have same values.
arguments that are meaningful to programmers by allowing to use rticula

ii) Use default particular solution. pa


arguments to add new
iv) Default parameters to the existing functions.
arguments can be used to combine
Q.15 Explain the
concept of function similar functions into a ction

single T
Ans.
overloading with example. 2000

1) The use of same March 2008, 15, 17; Octs


tasks is called as function name to create
function
overloading. functions that
2) Overloading perform varietY
f feren

orfunction
refers the use
to
of same
a

polymorphism, is an thing for different


example of
compile timepurposes. Function
overload.

polymorphism. polymorphism.
TPs Computer Science I
-

3-12
[Link] C+
3 Using the concept of function
name but with different overloading, create
argument lists. a family of functions with one function
4) The function would
call.
pertorm different operation.
depending on argument list in functionn
5) The correct function to be
of the arguments and not invoked is determined by checking the number
on the and the type
function type.
6) eg #include siostream.h>
int area (int
s);
int area (int 1, int //prototype declaration
b) //for overloading area()
main ()

cout <<area (10);


cout <<area
//function calls
(5, 10);

int area (int s) //function definition


return (s*s);

int area (int 1, int b)

return (1b);

n above example the function area( ) is overloaded. The first function is used to
calculate area of square. It has one integer parameter.
The second function is used to calculate area of rectangle. It has two integer parameters.
7) When a function is called, the compiler first matches the prototype having same number
and types of arguments and then calls appropriate function for execution. A best match
must be unique.
Q.16 Explain the structure of a general C++ program. March 2019
Ans.
1) A typical C++ program contains 4 sections as shown in following figure These sections
may be placed in different code files and then compiled independently or jointly.
Include files
Class declaration
Class functions definitions

Main function program


Structure of C++ program

2) t is a common practice to organize a program


into three separate files.
in
3 The class declarations are placed in a header file and the definitions of the member go
other file.
[Link]

3-13
interface from the
TPS Computer Science - I

the
abstract of the
to separate
approach enables the prograr
4) This
implementation details.
that uses the class is placed in third
file, which
chudes the
inchsd

the main program


5 Finally
well as any other
files required.
previous two files as t h r e e numbers.
number among
in C++ that finds
larger
Q.17 Write a program
number
Ans. /Program to find largest
#include <iostream.h>
void main( )

int a, b, c, max;
cout<"Enter three numbers" <<endl;
cin>>a>>b>>c;
if (b>c)
max = b;}

else
max c
if (a>max)
max a;}
cout<<"The larger number is:-";
cout<<max;

Q.18 Write a program in C++ to display a fibonacci series of 15 terms.


March 2004, 2007,2009, 2017; Oct.20
OR Write a program in C++ to display a Fibonacci series of 20 terms (use n < = 18 in tna
case)

Ans.: #include<iostream.h>
void main()
int f0, f1, f, n;
f0 = 0;
f1 =1;
clrscr();
cout<<"Fibbonacci series \n";
cout<"\n" <<f0<<"\n"<<f1;
for (n=1;n<=13; n++)

f f0+ f1;
cout<"\n"<<f;
f0 = f1;
f1 =f;
Science -

I
TPS Computer 3-14 [Link] C+

Q 19 Write a program in C++ to calculate and print factorial of first 10 numbers.


Ans.;

//C++ program to calculate and print factorial of first 10 numbers


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

int fact, n,i;


clrscr( );
cout<<"Number"<<"\t"<<"Factorial";
for (n=1;n<=10; n++)

fact 1;
for (i = 1; i<=n; i++)

fact facti;

coutecendlk<n«<"\t"<cfact;

Q. 20 Write a C++ program to find factorial of a natural number input during program
execution. March 2004, 08, 17, Oct. 2002,04,12)
number
Ans. //Program to find factorial of a
#include<iostream.h>
#include<conio.h>
void main ()

int fact, numberi;


clrscr ();
fact 1;
cout << "Enter the
number" <<endl;
cin >> number;
for (i =1;i<=number; i++)

fact f a c t * i;

inputted number is:"


<< fact;
cout<< "The factorial of a

whether the given integer is palindrome or not.


Q.21 Write a program in C++ to check (Oct.2012)
not
find whether the given integer is palindrome or
Ans. //C++ program to
#includeiostream.h>

#include<conio.h>
TPS Computer Science - I 3-15
[Link]
void main()

int n, dn, temp=-0, d;


clrscr();
cout<<"Enter a number";
cin>>n;
dn=n;
while (dn!=0)

d=dn%10;
temp-(temp*10)+d;
dn=dn/10;

if (n==temp)

cout<<"The number"<<n<<"is palindrome";

else

cout<<"The number"<<n<<"is not


palindrome";

Q. 22 What is an armstrong number ?


Write a program C++
number is armstrong or not. in to check whether the gve
Ans.: Armstrong number
"If sum of the cubes of digits of
number is said to be an
a number is equal to the
armstrong number". original number, then
e.g. 153 is an
armstrong number.
//C++ Program to find whether the
#include<iostream.h>> number is
armstrong or not.
#include<conio.h>
void main()
int n, dn, temp, d;
cout<<"Enter anumber";
cin>>n;
dn = n;

temp=0;
while (dn!=0)

d=dn%10;
[Link]
Sciernce -

I C+
TPS
Computer 3-16

temp=temp+(d*d*d);
dn=dn/10;

if(n==temP)

cout<<n<<"is armstrong no.";

else

cout<<n<<"is not an armstrong number";

Q. 23 Write aprogram in C++ to print the numbers in following manner.


1
2 2
3 3
4 4 4

n terms

Ans.
//C++ program to print given pattern
#include<iostream.h>

#includecconio.h>
void main()
int i, j, n
clrscr();
cout<<"Enter a number";

cin>>n;
cout<<endl;
for (i=1; i<=n; it+)

for =1;j<=i:j++)

cout<<i<<"\t";

cout<<endl;
numbers
Q. 24 Write a program in C++ to printthe
1 0 1 0 1
1 0 1 0
1 0 1
10
1
Ans.
//C++ program to print given pattern
#includeiostream.h>
#include<conio.h>
void main( )

clrscr( );
int i, j;
for (i=5; i>=1;i--)

for j=1;j<=i j++)

cout<j%2<<"\";

cout<<endl;

Q.25 Write a
program to
perform
arithmetic calculations such
multiplication division, depending
or
on choice
as
addition, subtractio
Ans. using switch statement.
//C++ program to
generate simple calculator
#include<iostream.h>
#include<conio.h>
void main()

float a, b, result;
int ch;
clrscr);
cout<"Enter two numbers";
cin>>a>>b;
cout<<"\nl-addition \n 2-subtraction
cout"Enter Your Choice:"; \n
cin>>ch; 3-multiplication \n 4-division
switch (ch)

[Link]
Science -

I [Link] C+
Computer 3-18
TPS
case 1:
result=a+b;
cout<<"Sum is""<<result;
break;
case 2:
result=a-b;
cout<<"Difference is"<<result;
break;
case 3:
result=a*b;
cout<"Product is"<<result;
break;
case 4:
result=a/b;
couts<"Division is"<<result;
break;
default
cout<<"invalid choice";
break;

recursive function ? Write a program


in C++ to calculate addition of firsttn
Q.26 What is a

numbers using recursive function.


Ans.: Recursive function :

of the function itself is called as

"A function which is called


within the body same

recursive function."
addition of first n numbers
//Program to calculate
#include<iostream.h>

#include<conio.h>
int add (int);
void main()

int n, sum;
cout<<"Enter a number \n";

cin>>n;
sum=add(n);
of
first"<<n<<"numbers is"<<sum;
cout<<"Addition

addition
//function to calculate
int add (int x)

int S = 0;

if (xl=0)
[Link]
3-19
TPS Computer Science - I

S=xtadd(x-1);

return(S);
cylinder and rectangula
of cube, r bo-
C++ to calculate volume
27 Write a program in
overloading.
function
depending on choice by using
Ans.: //Program using function overloading
#include<conio.h>

#includesiostream.h>
int volume (int s);
float volume (float r, float h);
int volume (int 1, int b, int h};
void main()
int ch;
do

clrscr();
cout<<"\nl:Volume of cube";
cout"n2:Volume of cylinder";
out<<"\n3:Volume of rectangular box";
cout<<"\n4:Quit";
cout<<"\n\n Enter Your Choice";
cin>>ch;
switch (ch)

case 1:

cout"Volume of cube is";


cout<<volume (5);
break;
case 2:

cout<<"Volume of cylinder is";


cout<volume (7.0, 2.0);
break;
case 3:

cout"Volume of
cout<<volume rectangular
(3,5, 7); box is";
break;
Science J [Link]
TPS Computer
-

3-20 C+

case 4: break;
default:
cout<<"Invalid choice";
cout<<"Reenter your choice";

while (ch!=4);

/function to calculate volume of cube


int volume (int s)

return (s*s*s);

//function to calculate volume of cylinder


float volume (float r, float h)

return (3.14*r*r*h);

//function to calculate volume of rectangular


int volume (int 1, int b, int h)

return (1'bh);

and Strings
Arrays, Pointers, References
onto a function.
What is ? Explain how array can be passed
Q.28 an array

Ans.
objects, which are stored in consecutive
"An array is collection of identical data
1) a
variable name."
locations under common
memory
multidimensional.
dimensional o r
2) Arrays may be o n e
declaration of one-dimensional arrayis
3 The general form for
data-type array-name lexpression];

eg. int al 10);


This declaration creates an array of 10 integers.
element has
based. i.e. in above examples, the first array
4) In general, C++ arrays are zero
is al1| and the last
al0|. Similarly, second array elenment
index 0 and it is referred as

i.e. 10th element is a[9].


3-21
I
Computer Science
-

TPS
onto a
function.
function
claration. No
declaration. No
subs
entire array
C t + allows to pass the for the
5) be used a s .a n
argument

An array name
can
function using arrays.
a
to invoke
bracketsare required array
(float bll, int c);
one 1s a n
e.g. float
rev
parameters,
out ofwhich
declares a function rev, with
two
March 11,19, July1 ,1
his of using pointerS.
the advantages
Q. 29 What are pointers ? Give
variable."
Ans. address of other
holds the memory

pointer is a variable, which the form


as.
1) A
in C++. It takes
declare pointer
2) operator is used to
datatype *variablename;
e.g. int "ptr; variable and whick
which is a pointer
create a variable ptr,
The above declaration will
data type is integer
will point to a variable, whose will point s
but data type, of
variable which ptr
3) The data type is not of ptr integer,
integer
4) Advantages of using pointers are as function
It allows to pass variables, arrays, functions, strings,
structures, objects as
i)
arguments.
It allows to return structured variables from functions.
ii)
ii) It supports dynamic allocation and deallocation of memory segments.
iv) By using pointers, variables can be swapped, without physically moving them.
iv)
v)It allows to establish link between data elements or objects.
Q.30 What are pointers in C++ ? Explain the use of pointer variables for
definitions using call by value and call by reference OR
March 2004,07,08,09, Oct. 2006
Explain 'Call by value' and 'Call by reference' with one
Ans.:
example of each.
1) Pointers in C++
A pointer is a variable which holds
the memory address
of another variable.
operator used to declare pointer in C++.
*
is
Forexample: int "ptr;
where ptr is a pointer variable and
integer. which will point to a variable whose dard type
2) The use of pointers in a
function definition
(1) Call by value (2) Call may be classified into two
3) Call by value: by reference. groups
(a) When
portion of the program invokes
a

function
the main
to
copied to the function.
the
calling functionfunction,
a
control will be transie transferred
and the value of actual argumen
(b) Within function the actual
value may be
altered or
changed.
TPS Computer Science I [Link] C++
-

3-22

()
(c) When the control is transferred back from function to the program,
are not transferred back. This type of passing formal argument to altered vauesis
a function
called as call by value
(d) For example:
main ()
void furnct (int X, int Y);

funct (X, Y); // Call by value

void funct (int a, int b)

4) Call by reference: Oct.2014


(a) In call by reference, when a function is called by a program the address of the
actual arguments are copied on to the formal arguments. ie. the formal and actual
arguments are referring to same memory location.
(b) Therefore change in value of formal argument affects the value of actual
arguments.
(c) The content of a variable that are altered within the function are return to calling
portion of a program in the altered form.
(d) For example:
main ()

v o i d f u n c t ( i n t * X, i n t * Y);

funct (&X, &Y); // Call by reference.

void funct (int * a, int* b )

Q.31 Explain how the memory address of a variable can beaccessed in C++
(March2004, 07,14;Oct.2004,12)
Ans.
1) Computer uses memory forstoring the values of variables and the memory is a
sequential collection of storage cell. Each cell has a number called address of the cell.
2) In C++, if declare a variable, then it gets associated with certain location where the value
of the variable is stored.
[Link]
3-23
TPS Computer Science - I

3) Consider the declaration


int p = 30;

then p Location name (variable)

30Value atlocation
7940 Location number (address) the value 30.
location to store
LOmputer has selected
7940 memory
"&t operator is used. m
of a particular variable
4) lo access the memory address
returns the memory address
of its operand.
operator
For example: a = &p; location add.
the
assigns the memory address of variable p to the a.
This address is
ddress
variable. The operator '& is "the address
of" operator
as that contains
the address. The Doin
The variable 'a' is declared as pointer variable pointe
variable declared in C++ as,
i n t * a;

where * indicates that a is a pointer variable.

What is call by reference ? What is the advantage of call by reference over call b
Q.32
value? (Mar. 2014
Ans.
A function can be called by two methods :
) Call by value
(i) Call by reference
1) When a function call passes arguments by value (call by value) the called funchar
creates a new set of variables and copies the values of
arguments into them.
2) The function does not have access to the actual
variables in the calling program and u
only work on the copies of values.
3) Provision of reference variables in C++
reference.
permits to pass parameters to the functiol
4)
4) When pass arguments by reterence
function become alises to the actual(callby reference) the formal arguments in tne calle
when the function is working with arguments
in the calling that

its
function. This mean n the
original data. own arguments, it is actually working
5) The mechanism of call
by value is good, if the function does not need to
of the original variables in the
Values

alter tue
6) But, if a situation to
calling program.
sort compare two
change the values of variables in the b u b b h

adjacent elements in the list and calling programn. e.g.


than second. In such interchange them if first i
1 Sg r e a t

situation, the
variables of calling program, whichfunction
is not
should be able to
interchange the be done
the call by reference method is
used. possible by call by value. But it
But it can can

7) e.g.//Program to interchange the values of


#include <iostream.h variable
void swap (int", int");
// function declaration
Computer Science
-

I [Link]
TPS 3-24 C+
void main()

int a, b;
cin>>a>>b;
swap (&a,&«b); //call by reference
cout<<"a="<<a;
cout"b="<<b;
void swap (int"a, int"b) //function definition
int t;
t=*a;/assign the value at address a tot.
*a=*b;//put the value at b into a.
*b=t;//put the value at t intob.

.33 Explain Library Functions (Oct.2015,4)


(i) Strcpy () (i) Stremp ()
Ans.
Strcpy ()
IF S, and S2 are string then strepy (S, S,) copies character string Sa into character string
S. It means it creates a duplicate of string S2.
Char * strcpy (Char *S1, const char *S,)

For example
int main ()

charS, []="ABCD"
char S2 []="XYZ"
cout << "Before strcpy (S, S) \n";
cout << " \ t S; = [ " < < S1 < < " ] , l e n g t h = " < < s t r e l n (S,) < < e n d l ;

cout " \ t S2 = ["<< S, «<"], length = " < < s t r l n (S,) < < e n d l ;

strcpy (S, S2)i


cout <<"After strcpy (S, S,) \n";
cout < < " \ t S2 = [ " < < S2 < < " ] , l e n g t h = " < < s t r l e n (S,) << e n d l ;

O/P-Before strcpy (S, S2)


S, = [ABCDEJ, length = 5

S= [XYZ]; length = 3
After strepy (S1, S2)
S =
[XYZ], length = 3

S=XYZ], length = 3
3-25
TPS Computer Science - I
[Link]

(ii) Strcmp (): ve integer accord


positive integer accord
Int strcmp (char *S, char * S};
integer,
zero or
Returns a negative
t compares S with S,
than S2.
1s less than equal to or grater

Example:
Char "S, = "ABCDE"

Char S2 ="
If (strcmp (S, S3) <0)
Cout< S << "<" <<S, << endl;
else

coutS< ">="<<S2 <<endl;


0/P is ABCDE>=
.34 Write C++ program
a to read 'n' numbers input from keyboard and sort them
em in
ascending order. Oct. 200
Ans.:/Program to sort numbers in ascending order
#include iostream.h>
voidemain ()
int a [100];
int n,i, j, temp;
cout << "How
many numbers ?" <<endl;
cin >> n;
cout << "Enter the elements:";
for (i=1; ik=n; i++)

cin >> a ;

for (i=1;i<=(n-1); it+)

for (j=1; j<=n-i; j++)


if (a[j]> alj+1])

temp =aijl;
alj] =alj+1]
alj+1] = temp;

cout<<"Ascendingorder is:\n";
Thank you for visiting
[Link]
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters
Visit [Link] for all Chapters

You might also like