Академический Документы
Профессиональный Документы
Культура Документы
Q6. What are key words? How these are different from identifiers?
Ans. The keywords are the reserved words. The keywords are identifiers but cannot be user
defined. It is mandatory that all the keywords should be in lower case letters. For example
for, while, do, if, continue, break etc.
There are 32 keywords in C and 48 in C++.
Identifier can be defined as name of variable and some other program elements using the
combination of following characters.
Alphabet: a to z, A to Z
Numerals: 0 to 9
Underscore: _
Q7. Differentiate between compiler and interpreter? Also give the name of the various
compilers of C and C++.
Ans. Compiler and interpreter both are used to convert the high-level language program into the
object source code. Differences are:
Interpreter: - Interprets the program line by line. It is slow
Compiler: - Compiles the whole program at a time. It is fast.
Also, interpreter can be more easily designed than compilers.
Name of the C and C++ compilers: Borland C, ANSI C, Turbo C.
Q9. Define array. How will you declare and store values in an array?
Ans. Arrays are subscripted variables. They are used to give a common name to different memory
locations of same data type. In an array, group of elements can share the same name.
Syntax to declare array is: -
storgeclass datatype arrayname [size];
Example
int a[5];
Main Program
statements
}
Q15. Why are functions created in ‘C++’? What is the difference between library functions
and user-defined functions?
Ans. Functions: - A function is a self-contained program segment that carries out some specific,
well-defined task. A function is also known as sub program that can be executed in the
program. The functions are used to make the program modular.
Function basically are classified in two categories
Library functions: - These are needed in every program. They are stored in the library files
known as header files. Commonly used functions are printf() and scanf(). It is to be included
at the beginning of the program using header file. Examples of library files: stdio.h,
iostream.h etc.
User defined functions: - These functions are defined by the users according to their
requirements. Example: functions to calculate factorial, prime number etc.
Ans. Abstraction: In OOP data abstraction is defined as a collection of data and methods
(functions). In a class we define the data members as well as the functions, which can access
and use these data members.
Polymorphism: In OOP, polymorphism is defined as how to carry out different processing
steps by a function having the same name. Polymorphism allows you to create definitions for
operators and functions and at run-time depending on the context a particular definition will
be used.
Q18. What is a structure? What is the difference between a structure and a union?
Ans. Structure constitutes a super data type, which represents several different data types in a
single unit. It is a collection of dissimilar data type. Structure can be initialized if it is static or
global. A structure variable contains each of the named members, and its size is large enough
to hold all the members.
A union contains one of the named members at a given time and is large enough to hold the
largest member.
Arithmetic operators
* Multiplication
/ Division
% Modulus
+ Addition
- Subtraction
Relational operators
Logical operators
! Logical Not
&& Logical And
|| Logical Or
Example
static int a[10] = {1,2,5,4,7,90,-3,4,5,6};
2 dimension
storageclass datatype arrayname[dimension1][dimension2] = {element1, element2….,
element n};
Example
static int ch[2][2] = {
{2,3},
{4,1}
};
Q24. What are the advantages of using identifier with long names?
Ans. C++ allows using long names for identifiers. Its advantages are:
1. Long name describe identifier clearly.
2. Readability and understandability of identifier is increased by using long names
Q25. Is cascading of input and output operators possible? If yes explain how?
Ans. The multiple uses of insertion or extraction operators in one statement is called cascading.
Cascading is possible in C++
For example
Cascading of input using cin:
cin>>a>>b>>c;
Cascading of output using cout:
cout<<a<<b<<c;
Q30. What is object oriented programming? What is the difference between an object and a
class?
Ans. Object oriented programming treat data as a critical element in program development and
does not flow freely around the system. It ties data more closely to functions that operate on it
in a data structure called Class. Objects are instances of Class. Class is a template from which
objects take their shape. A Class can have more than one object. Collection of number of
entities is called as objects. Class is also defined as collection of data members and member
functions.
Concepts of OOP are:
• Objects
• Classes
• Data abstraction and Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Ans. Yes. By putting the conditional operator within parenthesis we can write as many conditions.
Example:
(a>b &&a >c)?cout<<a: ((b>c)?cout<<b:cout<<c);
• Objects
• Classes
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message passing
Q39. What are the various output statements used in C++? Explain with examples.
Ans. cout: It can display data of any type. It can print integer, float, character, double type. It is a
member of the iostream class.
Example: cout<<a<<b;
put: It is used to display a line of text, character by character. It is a member of the ostream
class
Example: cout.put(ch);
write: The write() function displays an entire line and has he following form.
Example: cout.write(string1, 10);
Q41. How does C++ help to produce flexible and extensible software?
Ans. Using C++ we can create software that can represent real life entities. The systems design
using C++ has open interfaces. It provides facility of inheritance using which class can be
extended by keeping its previous form as it is and adding new features to it. C++ is flexible
because it industrializes software development.
Ans. While programming, we store the variables in our computer's memory. For it, the compiler
needs to know the datatype of the variable, so that it could allocate memory to the variables.
Various data types are:
1. Character data type: any character belonging to the ASCII character set is considered as a
character data type whose maximum size is 8 bits long. The ‘char’ keyword is used to
represent character data type in C++. Character constants are always represented within single
quotes. An array of characters is called a string.
2. Integer data: the keyword ‘int’ stands for the integer data type in C++ and its size is either
16 or 32 bits. A 16-bit integer falls in the range of -215 to 215 -1, while 32 bit integers fall in
the range of -231 to 231 - 1.
Various integer data types are:
a) Short integer data type: Normally the short int is used to declare the short integer data
type in C++. Its maximum size is 16 bits long. It falls in the range between
-32768 to 32767. When we write int in our program, it is considered as short int.
b) Long integer data type: The long int stands for the long integer data type used in C++. Its
size is 32 bits. It may fall in the range of -2147483648 to 2147483647.
3. Floating point data type: The numbers which are stored in the form of floating point
representation are known as floating point numbers. They can be declared as ‘float’ in C++
whose maximum size is a rational number approximately between -3.4E-38 to 3.4E+38
4. Double data type: ‘double’ is a keyword that is used to represent double precision floating
point numbers in C++. The size of double data type varies from -1.7E-308 to 1.7+308
5. Void: void is a special data type used in C++. Uses of void are:
• To specify the return type of a function when it is not returning any value.
• To indicate an empty argument list to a function.
• It is also used in context of pointers
OR
In how many ways can we represent an integer?
Integer data: the keyword ‘int’ stands for the integer data type in C++ and its size is either 16
or 32 bits. A 16-bit integer falls in the range of -215 to 215 -1, while 32 bit integers fall in the
range of -231 to 231 - 1.
Various integer data types are:
a) Short integer data type: Normally the short int is used to declare the short integer data
type in C++. Its maximum size is 16 bits long. It falls in the range between
-32768 to 32767. When we write int in our program, it is considered as short int.
b) Long integer data type: The long int stands for the long integer data type used in C++. Its
size is 32 bits. It may fall in the range of -2147483648 to 2147483647.
Q2. What are pre processors? Write a program to define a macro with parameters using
#define pre-processor.
Ans. Preprocessor is a directive that modifies the C++ source program according to conditions
given by users. To instruct the compiler that we are using a library defined function we
specify the header file containing the prototype for the function related to their input or
output. These header file are included into your source code using “#” symbol and known as
preprocessors directives. They make the compiler to include the contents of specified file.
Using preprocessor we can also specify the macros. They commonly useable preprocessors
are #include and #define.
The preprocessor carries out the following actions:
• Replacement of identifiers by some values.
• Conditional execution of parts of the source file.
• Inclusion of other file.
• Renumbering of source file and renaming of the source file itself.
Program with definition of macro with parameter:
#define SQUARE (x) x*x
#include <iostream.h>
void main( )
{
int a=SQUARE (5);
int b=SQUARE(6);
cout<< a<<b;
}
Q3. What do you mean by manipulators? Explain some inbuilt I/O manipulators.
Ans. Manipulator functions are special stream functions that change certain characteristics of the
input and output. They change the format flags and values for a stream. They facilitate
formatting the input and output streams. The input and output manipulators can be used in the
program by including the file <iomanip.h>.
Endl. The endl is an output manipulator. It generate carriage return or line feed.
Setbase( ). It is used to convert the base of numeric value into another base.
Dec – decimal base (base=10)
Hex - hexadecimal base (base=16)
Oct – octal base (base =8)
Setw ( ) The setw( ) stands for set width. It is used to specify the minimum number of
character positions on the output field a variable will consume.
Setfill( ) The setfill( ) manipulator function is used to specify a different character to fill the
unused field width of the value.
Q4. What are the different control structure available in ‘C++’? Explain with example.
Ans. Control statements are used to make decision. These statements are required to take an action
according to the condition. The various control statements are as under: -
1. if statement 2. if – else statement 3. nested if
1. if statement :- Executes the statements if condition is true.
Syntax: -
if (condition)
{
statements;
}
2. if–else statement: - Executes the block of statements if condition is true. Otherwise
execute else block.
if (condition)
{
statements;
}
else
{
statements;
}
3. Nested if :- Executes one block out of number of blocks of statements which specify
the condition other wise executes else block statements.
if (condition)
{
statements;
}
else if(condition)
{
statement;
}
else
{
statements;
}
Case statements :- These statements are used to make decision from the number of choices.
In “C++” case control instruction is the switch statement.
Switch statement :- switch statement provide better alternative for series of if –else
statements, because any part of the code can be executed on the value of an expression.
Syntax: -
switch(expression)
{
case value:
statement1;
case value:
statement2:
default:
statements
}
Default statement is used as optional.
Branching statements: These statements transfer the control to another part of the program.
There are three types of branching statement.
(a) Continue statement
(b) Break statement
(c) Goto statement
i. continue :- The continue statement takes the control at the beginning of the
loop and remaining statements skipped and control move to the last stub.
ii. break :- The break statement is used to terminate the loop or a sequence of
statement in a switch statement. A break statement enforces immediate
termination of program.
iii. goto :- The goto statement is used to alter the normal sequence of program
execution by transferring the control to some of the defined level in the
program.
Syntax
goto label;
label :
statements;
Iterations statements/Loop statements: - Loops are used execute a set of statements
repeatedly until desired condition is meet. There are different types of loops in C++
1. while
2. do while
3. for
While loop: -
This statement is used to execute the loop till the condition true.
while (expression or condition)
{
statements
}
Do while: -
Statements will execute when the condition is true but in this loop the statements will execute
first then condition checked.
do
{
statements
}while (expression);
For loop: -
In the for loop the initialization , condition and increment or decrement can be done at one
place.
for (initial value; expression; increment/decrement)
{
statements ;
}
Q5. Write a program to calculate the Q6. Write a program to input a word.
sum of all odd numbers between 1 and Display on screen “Hello” as many times
1000. as, the number of a’s present in the
Ans. word.
#include<iostream.h> Ans.
#include<conio.h> #include<iostream.h>
void main( ) void main( )
{ {
int i; char str[20];
long int sum=0; int k;
for(i=1;i<=1000;i+=2) cout<<”Enter a string”;
sum+=i; cin>>str;
cout<<”Sum of odd numbers between 1 k=0;
and 1000 is : “<<sum; while(str[k] !=’\0’)
getch( ); {
} if(str[k]==’a’)
cout<<endl<<”hello”;
k++;
}
}
4. Reusability of code
Functions once defined can be used any number of times just by calling them by their
name.
Example:
int square ( int a) {
statements;
---------
return ; }
Here square is the user-defined function getting one parameter of type int. The function is
also returning a value of type int.
Q10. What is recursion? Why recursion is used? Write a program to calculate sum of first
five numbers using recursion.
Ans. A function, which calls itself directly or indirectly again and again, is known as the recursive
function. Recursive functions are very useful while constructing the data structures like trees.
The recursive function will be invoked by itself as long as the given condition is satisfied.
Program to calculate the sum of first five numbers:
int sum(int x)
{
if (x==1)
return 1;
else
return ( x+ sum(x-1));
}
void main( )
{
cout<< sum(5);
getch( );
}
Q11. Create a function to find whether Q12. WAP to pass array as parameter in
the character is in uppercase or the function and to find the greatest
lowercase. number from the list of array.
Ans. Ans.
#include<stdio.h> int greatest (int a[ ] , int n )
#include<conio.h> {
void letter(char); int j , max ;
void main() max = a[0];
{ for ( j=1; j<n;j++)
char c; {
clrscr(); if (max <a[j])
cout<<”enter any letter”; max= a[j];
cin>>c; }
letter(c); return max;
getch(); }
} void main ( ) {
void letter(char c) int a [ 50 ], n , j ;
{ cout<<”Enter the range”;
if((c>'a')&&(c<'z')) cin>> n;
cout<<"letter is in lower case"; for (j=0;j<n; j++)
else {
cout<<"letter is in upper case"; cout<<”Enter the array element “;
} cin>> a[j];
}
cout<<”The greatest element in array is”;
greatest( a, n);
}
Q13. WAP to pass a structure in the function as parameter and return the structure from the
function.
Ans. struct complex {
float real;
float imag;
};
complex add (complex a, complex b)
{
complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return c;
}
void main( )
{
complex a,b,c;
cin>>[i][j]; cin>>b[i][j];
} for(i=0;i<3;i++)
} {
for(i=0;i<2;i++) for(j=0;j<3;j++)
{ {
for(j=0;j<2;j++) c[i][j]=0;
{ for(k=0;k<3;k++)
cout<<a[i][j]); c[i][j] + = a[i][k] * b[k][j];
} }
cout<<endl; }
} for(i=0;i<3;i++)
getch(); {
} cout<<endl;
for(j=0;j<3;j++)
{
cout<<”\t”<<c[i][j];
}
}
getch( );
}
Q17. What is pointer? WAP to display the values of single dimensional array using pointer.
Ans. Pointer:
Pointer is an indirection operator, which refers to any other variable. Pointers are variables,
which store the address of another variable. That variable may be a scalar (including another
pointer), or an aggregate (array or structure). The pointer to object may be part of a larger
object, such as a field of a structure or an element in an array.
Program to show the elements of an array-using pointer:
#include<iostream.h>
#include<conio.h>
#define MAX 100
void show( int * a, int n)
{
int j;
for(j=0;j<n;j++)
cout<<endl<<*(a+j);
}
void main( )
{
int arr[MAX], n, k;
cout<<”Enter the no. of elements to be entered in array”;
cin>> n;
cout<<”Enter the array”;
for(k=0;k<n;k++)
{
cout<<”Enter the array element”;
cin>>arr[k];
}
show(arr, n);
getch( );
}
Q18. What is the difference between array of pointers and pointers to an array?
Ans. A pointer to an array contains the address of the first element. In a one-dimensional array, the
first element is &[0]. In two-dimensional array, it is &value[0][0].
The address of the zeroth row and the zeroth column of the two-dimensional array value is
assigned to the pointer variable value.
For example:
int a[ ] [ ];
int *ptr;
ptr=&a[0][0]; // or ptr= a;
Array of pointers:
The pointer may also declared like any other data type. The declaration of an integer pointer
array of size 10 is
int *ptr[10];
Where ptr is an array of pointers. It can hold the addresses of various arrays.
Q19. What is the difference between call by value and call by reference? WAP to swap the
value of two parameters using pointers.
Ans. Pass by reference passes a pointer to the value. This allows the caller to modify the variable
directly. Pass by value gives a copy of the value to the caller. This allows the caller to modify
the value without modifying the variable. (In other words, the caller simply cannot modify the
variable, since it lacks a reference to it.)
Program to swap two numbers using pointers:
#include<iostream.h>
#include<conio.h>
void swap( int * x, * y)
{
int temp;
temp=* x;
*x= * y;
*y=temp;
}
void main( )
{
int first, second;
cout<<”Enter the first number”;
cin>>first;
cout<<”enter the second number”;
cin>>second;
swap(&first, & second); // call by reference
cout<<”After swapping values are :”;
cout<<”First : “<<first;
cout<<”Second: “<<second;
getch( );
}
Q20. Write a function that will round Q21. Write a c++ program to compute
floating-point number to an indicator the size of union.
decimal place. Ans.
Ans. union stu
#include<manip.h> {
void main() int a,b;
{ };
float a=5,b=3,c d; void main()
c=a/b; {
cout<<”enter d”; union stu q;
cin>>d; int j;
cout<<setprecision(d)<<c; j=sizeof(q);
} cout<<j;
}
Q22. What is a header file? What is the purpose of using these files?
Ans. A file with extension .h is called header file. It is a library, which contains the definition of
various functions. These functions assist the programmer to prepare the program in an
efficient manner. These standard libraries come along with the complier as a utility
software .The term include is used to include a certain library in your program. As these
libraries contain several inbuilt functions, we don't need to redeclare these functions
ourselves. we can include a library and use its functions by just calling them with their
appropriate parameter.
Most C ++ compliers support the following standard library facilities:
1) Operations on characters 2) Operations on strings.
2) Mathematical operation 4) Storage allocation procedures
5) Input /Output operations
Q23. Using pointer write a program to add Q24. Program to convert decimal into
two matrixes. [IN EXAM] hexadecimal.
Ans. Ans.
#include<iostream.h> # include <iostram.h>
#include<conio.h> # include <conio.h>
void main( ) #include <string.h>
{ void main ()
int a[3][3], b [3] [3], c [3] [3], i, j, k; {
int *p1[3], *p2[3],*p3[3]; long int n, m; char res[20]; int r,i;
cout<<”Enter the first array”; for (i =o; i<20;c++)
for (i=0;i<3;i++) res [i] =\;; // to initialize string
for(j=0;j<3;j++) i=0;
cin>>a[i][j]; cont<<' counter the number ; cin >> n;
cout<<”Enter the second array”; m=n;
for (i=0;i<3;i++) while (m >0)
for(j=0;j<3;j++) {
cin>>b[i][j]; r= m%16;
p1=&a[0][0]; if (r<=a)
p2=&b[0][0]; {
p3=&c[0][0]; res[i] = r +'0'
for(i=0;i<3;i++) {
{ res[i]= r+'0';
for(j=0;j<3;j++) }
{ else
p3[i][j] = p1[i][j] + p2[i][j]; {
} switch (a)
} {
for(i=0;i<3;i++) case 10: res[i] ='a';
{ break;
cout<<endl; case 11: res[i] ='b' ; break;
for(j=0;j<3;j++) case 12; res[i] ='c' break;
{ case13: res [i] ='d' break
cout<<”\t”<<c[i][j]; case 14: res[i] ='e' break
} case 15: res[i] ='f' break
} }
getch( ); }
} i++i
m/16;
}
straw (res);
cout <<' Hexadecimal equivalent of "<<n<< is
<< res;
getch ();
}
Q25. WAP to sort an array using Q26. Write a program to count number
pointer. of vowels, consonants, blank spaces and
words in a line of text.
Ans. Ans.
# include<iostream.h> #include<iostream.h>
#include<conio.h> #include<stdio.h>
#define MAX 100 #include<conio.h>
void sort( int * a, int n) void main()
{ {
int i, temp, j; int cons=0, vow=0, bsp=0, w=1, I=0;
for( i=n;i>0;i--) chat str[50];
{ cout<<”Enter a string”;
for( j=0;j<i;j++) gets(str);
{ while(str[I] !=’\0’)
if (a[j]>a[j+1]) {
{ if((str[I]>=’a’ && str[I]<=’z’) ||(str[I]>=’A’
temp=*a[j]; && str[I]<=’Z’))
*a[j]=*a[j+1]; {
*a[j+1]=temp; if((str[I] ==’a’ || str[I]==’e’ || str[I]==’i’ ||
} str[I]==’o’ || str[I]==’u’)||(str[I] ==’A’ ||
} str[I]==’E’ || str[I]==’I’ || str[I]==’O’ ||
} str[I]==’U’))
} {
void main( ) vow++;
{ }
int arr[MAX], n , index; else
cout<<”Enter the size of array”; cons++;
cin>>n; }
for(index=0;index<n;index++) }
{ else if( str[I]==’ ‘)
cout<<”Enter the array elements”; {
cin>>arr[index]; bp++;
} w++;
sort( &arr[0],n); // function called and }
reference to the array is passed I++;
cout<<”Sorted array is “; }
for(index=0;index<n;index++) cout<<”Number of vowels are”<<vow;
cout<<endl<<arr[index]; cout<<endl<<”Number of consonants
getch( ); are”<<cons;
} cout<<endl<<”Number of blank spaces are
“<<bsp;
cout<<endl<<”Number of words are”<<w;
getch();
}
if (condition)
{
statements
}
if ..... else
if (Condition)
{
statement
:
}
else
{
statements
:
}
If ladder
if (Condition)
{
if (condition)
{
statements
}
else
{
statements
}
}
else
{
statements
}
Q29. Program to add all odd no's Q30. Program to maintain student
between 10-1000. record using structure.
Ans. Ans.
Q31. Program to print string in reverse Q32. Write a program, which solves the
order. following expression:
Ans. c=a+b (b) c=a-b (c) c=a*b
#include<string.h> (d) c=a/b
void main() Ans.
{ void main()
char n[20],n1[20]; {
int c=0,i; int a,b,c;
clrscr(); cout<<”enter a and b”;
cout<<"enter string"; cin>>a>>b;
gets(n); c=a+b;
for(i=0;n[i]!=NULL;i++) cout<<c;
{ c=a-b;
c++; cout<<c;
} c=a*b;
for(c=c-1,i=0;c>=0;c--,i++) cout<<c;
{ c=a/b;
n1[i]=n[c]; cout<<c;
} }
n1[i]='\0';
char *p;
i=0;
while(n1[i]!='\0')
{
p=&n1[i];
cout<<*p;
i++;
p++;
}
}
Q33. What do you mean by string handling? Explain all the string handling functions with
examples?
Ans. String library functions are the functions, which are used regularly and stored in library file
and whenever these functions are needed, you need to include the required header file in your
program.
There are different types of functions
Strlen(): This function is used to count the characters in a string. It calculate the length of the
string.
Syntax:
strlen(array variable);
strcpy(): This function copies the contents of one string into another
Syntax:
strcpy(target,source);
strcat(): This function is used to concatenate the source string at the end of the target string.
Syntax:
strcat(target,source);
strcmp(): This function compares the two strings to find out whether they are same or
different. The two strings are compared character by character until there is a mismatch or
end of the string. These function returns 0 if both the strings are identical.
Syntax:
strcmp(string1,string2);
Q34. Write various paradigms, tools, notations and graph used in object oriented system
development.
OR
What are characteristic of object oriented languages?
Ans. Definition:
Using object oriented programming language we can represent information as series of
objects. Object will be of class type. Once class is created, any number of objects of that class
type can be created.
PARADIGMS:
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on data of an object are tied together in the data structure.
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary.
8. It follow bottom up approach in program design.
TOOLS
1.Rational rose
2. Reqisite pro
4. State Diagram
5. Activity Diagram
6. Physical Diagram
7. Deployment Diagram
8. Component Diagram
Q35. Write a program to display the Q36. Write a program to print the
characters line by line. pascal triangle.
Ans. Ans.
#include< fstream.h> void main()
#include<string.h> {
int main() int i,j,l,m,n;
{ cout<<”enter no of rows”
char string[80]; cin>> n;
cout <<”enter string”; m=1;
cin>> string; for(i=1;i<n;i++)
int len=strlen(string); {
fstream file; for(i=40-3*l;i>0;i--)
fileopen(“TEXT”, ios::in | ios::out); cout<<” “;
for(int i=0;i<len;i++) for(j=0;j<=l;j++)
file.put(string[i]); {
file.seekg(0); if((j==0)|| (l==0))
char ch; m=1;
while(file) else
{ m=(m*(l-j+1))/j;
file.get(ch); cout<<m;
cout<<ch; }
} cout<<endl;
return 0; }
} getch();
}
Q4. What are classes? How classes are different from structures?
Ans. A class is a user defined data type, which holds both the data and functions. The internal data
of a class is called member data and the functions are called member functions. The member
functions mostly manipulate the internal data of a class. The member data of a class should
not normally be addressed outside a member function. The variables of a class are called
objects or instances of a class.
Structure contains one or more data item, which are grouped together as a single unit. On the
other hand class not only contain the data members but also the functions to manipulate that
data. Secondly, in a structure, all elements are public by default, while in a class they are
private.
Q6. A friend function cannot be used to overload the assignment operator =. Explain why?
Ans. Although the friend function cannot directly access the members that are declared as private,
still the friend function has the right to access these members. In other words, there is nothing
a class can hide from its friend.
But the friend function is not within the scope of any class. And it is defined out of class.
Also when the function is called, it is called without any object reference. The only need is to
pass the object of class as parameters in to the function. So it can not be used to
overload=operator
The class C is derived from both classes A and B. In multiple inheritance a class is derived to
inherit the properties of two or more parent classes. Multiple inheritance can combine the
behavior of multiple base classes in a single derived class. It has advantages over single
inheritance .It can combine the behavior of multiple base classes in a single derived class. It
has advantages over single inheritance such as rich semantics and ability to directly express
complex structures.
Q10. What are the various access labels used in the declaration of classes?
Ans. Three types of labels are used:
1. public
2. private
3. protected
By converting data from one type to another accuracy is reduced .If we convert float data
into an integer then rounding of all digits after decimal reduces accuracy.
Q14. What is late binding? What is early binding? How these bindings are implemented?
OR
What is static polymorphism? What is dynamic polymorphism?
Ans. Early binding: Choosing a function in normal way, during compilation time is called as
early binding or static binding or static linkage or static Polymorphism. During
compilation time, C++ compiler determines which function is used based on parameters
passed to the function or function return type. The compiler then substitutes the correct
function for each invocation.
By default, c++ follows early binding. C++ supports late binding also. Late binding is
called as run time binding or execution time binding or dynamic polymorphism. Late
binding is implemented using virtual function.
class2 class3
Class4
Q16. How pointer to a class is declared?
Ans. The pointer will hold address of object of class .The pointer to object of class can be accessed
using following syntax:
Objectname -> membername=variable;
Or
(*Objectname).membername=variable;
Q17. How inheritance works in different labels? Explain with suitable example.
Ans. In public inheritance:
• Each public member in the base class is public in the derived class.
• Each protected member in the base class is protected in the derived class.
• Each private member in the base class is private in the derived class.
In private inheritance:
• Each public member in the base class is private in the derived class.
• Each protected member in the base class is private in the derived class.
• Each private member in the base class is private in the derived class.
In protected inheritance:
• Each public member in the base class is public in the derived class.
• Each protected member in the base class is protected in the derived class.
• Each private member in the base class is private in the derived class.
Q1. Write a program to create a class Q2. Write a program using classes to
that can store the data of two find the roots of quadratic equation.
employees. Ans.
Ans. #include<iostream.h>
#include<iostream.h> #include<conio.h>
#include<conio.h> #include<math.h>
class employee{ class Quad{
char name[20],design[20]; int a,b,c;
long int bsal, age; float d, alpha, beta;
public: public:
void getdata( ) void getabc( )
{ {
cout<<”Enter the name of employee”; cout<<”Enter the values of a, b & c”;
cin>>name; cin>>a>>b>>c;
cout<<”Enter the age of employee”; }
cin>>age; void calc( )
cout<<”Enter the designation”; {
cin>>design; d=b*b – 4*a*c ;
cout<<”Enter the basic salary”; if (d==0)
cin>>bsal; {
} cout<<”Roots are same “;
void showdata( ) alpha= -b/2*a;
{ cout<<alpha;
cout<<”\nName : “<<name; }
cout<<”\n Age : “<<age; else if (d<0)
cout<<”\n Designation : “<<design; cout<<”Roots are imaginary”;
cout<<”\n Basic Salary ”<<bsal; else
} {
}; alpha= (-b + sqrt(d)) /2*a;
void main( ) beta= (-b - sqrt(d)) /2*a;
{ cout<<”alpha : “<<alpha;
employee e1,e2; cout<<endl<<”beta : “<<beta;
e1.getdata( ); }
e2.getdata( ); }
e1.showdata ( ); };
e2.showdata( ) ; void main( )
} {
Quad obj;
obj.getabc( );
obj.calc( );
getch( );
}
-The derived class can add data and function members to the class without affecting
the
-Base class behavior.
-Code reusability
Types: - 1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hybrid inheritance.
4. Hierarchical inheritance
Q6. What is the use of static keyword in ‘C++’? Why are static members created in a class?
Ans. The main characteristic of the static variables is that the static variables are automatically
initialized to zero unless it has been initialized by some other value explicitly. In C++, static
member of a class can be categorized into two types, static data member and static member
function. Whenever a data or function member is declared as a static type, it belongs to a
class, not to instances or objects of the class.
Q7. What are the different types of friend functions? Explain each with example.
Ans. Friend function is a special mechanism for letting non- member functions access private data.
A friend function may be either declared or defined within scope of a class definition. The
keyword friend informs the compiler that it is not a member function of the class.
Accessing private data by non member function through friend
The friend function can access the private members of a class. When it is necessary to access
the private data by non- member functions, then a class may have a friend function.
Example:
#include<iostream.h>
class sample
{
private :
int x;
public:
void getdata( )
{
cout<<”Enter the value of x”;
cin>>x;
}
friend void display( sample);
};
void display(sample abc)
{
cout<<”entered number is “<<abc.x;
}
void main( )
{
sample obj;
obj.getdata( );
display(obj);
}
public:
void disp (first a);
};
inline void second::disp(first a)
{
cout<<”Entered number is “<<a.x;
}
void main( )
{
first objx;
second objy;
objx.getdata( );
objy.disp(objx);
}
Q9. Write a program to define two classes having the same friend.
Ans. A non-member function may have friendship with one or more classes. When a function has
declared to have friendship with more than one class, the friend classes should have forward
declaration. It implies that it needs to access the private members of both classes.
Example:
class second;//forward declaration
class first
{
private:
int x;
public:
void getdata( )
{
cout<<”enter the value for x”;
cin>>x;
}
void disp( )
{
cout<<”Entered number is (x)”<<x;
}
friend int sum(first , second);
};
class second{
private:
int y;
public:
void getdata( )
{
cout<<”Enter the value for y”;
cin>>y;
}
void display( )
{
cout<<”Entered number is (y) “<<y;
}
friend int sum(first, second);
};
int sum( first one , second two)
{
int c;
c=one.x+two.y;
return c;
}
void main ( )
{
first a;
second b;
a.getdata( );
b.getdata( );
a.disp( );
b.display( );
int c=sum(a,b);
cout<<”Sum of the two private data variables is “<<c;
}
Q10. What is function overloading? How the compiler will decide which function to use?
Explain with example.
Ans. Function overloading is a logical method of calling several functions with different arguments
and data types that perform basically identical things by the same name.
The compiler classifies the overloaded function by its name and the number and type of
arguments in the function declaration. The function declaration and definition is essential for
each function with the same function name but different arguments and data types.
In this example, a function ‘ Add ‘ is overloaded to find the sum of integer variables.
if we pass a&b then Add(int ,int) is executed.
if we pass a,b&c then Add(int ,int,int) is executed.
If we pass a,b,c,d then Add(int ,int,int,int) is executed.
#include<iostream.h>
void Add(int,int);
void Add(int,int,int);
void Add(int,int,int,int);
void main( )
{
int a=4,b=5,c=6,d=7;
Add(a,b);
Add(a,b,c);
Add(a,b,c,d);
}
void Add(int a,int b)
{
cout<<“sum of a&b=“<<a+b;
}
void Add(int a,int b,int c)
{
cout<<“sum of a,b,c=“<<a+b+c ;
}
void Add(int a,int b,int c,int d)
{
cout<<“a+b+c+d=“<<a+b+c+d;
}
Q11. What is operator overloading? How ‘+’ can be overloaded with matrix addition?
Ans. C++ has the ability to overload operators. Objects derived from composed types can accept
operators, which would not be accepted otherwise, and we can even modify the effect of
operators that they already admit. Here is a list of all the operators that can be overloaded:
+ - * / = < > += -= *= /= << >>
<<= >>= == != <= >= ++ -- % & ^ ! |
~ &= ^= |= && || %= [] () new delete
To overload an operator we only need to write a class member function whose name is
operator followed by the operator sign that we want to overload, following this prototype:
type operator sign (parameters);
#include <iostream.h>
class dis {
private :
int feet ;
float inch;
public :
dis( int f,float I)
{
feet = ft;
inch=I ;
}
void getdist( )
{
cout<<“Enter feet :”;
cin>>feet;
cout<<“Enter inch :”;
cin>>inch;
}
void showdist( )
{
cout <<feet<<“-”<<inch;
}
dis operator + (dis);
};
dis dis::operator + (dis d2)
{
int f=feet+d2.feet ;
float I =inch+d2.inch;
while(I>=12)
{
I - =12 ;
f++ ;
}
return dis(f,I)
}
void main( )
{
dis dist1 ;
dist1.getdist( ) ;
dis dist2 ;
dist2.getdist( ) ;
dis dist3 = dist1+dist2;
cout<<“dist=“;
dist3.showdist( ) ;
}
Q12. What is single inheritance? Write a program to show the concept of single
Inheritance.
Ans. Single inheritance:
Single inheritance is the process of creating new classes from an existing base class. The
existing class is known as the direct base class and the newly created class is called as a
singly derived class.
Single inheritance is the ability of a derived class to inherit the member functions and
variables of the existing base class.
Example:
#include<iostream.h>
class basic_info{
private:
char name[20];
long int rollno;
char sex;
public:
void getdata( )
{
cout<<”Enter the name of student”;
cin>>name;
cout<<”Enter the rollno”;
cin>>rollno;
cout<<”Enter the sex”;
cin>>sex;
}
void display( )
{
cout<<name<<’\t’<<rollno<<’\t’<<age;
}
};
class physical :public basic_info{
private:
float height, weight;
public:
void getdata( )
{
basic_info::getdata( );
cout<<”Enter height and weight”;
cin>>height<<weight;
}
void display( )
{
basic_info::display( );
cout<<height<<’\t’<<weight;
}
};
void main( )
{
physical a;
a.getdata( );
cout<<”\nName \t Rollno \t Sex \t Height \t Weight”;
a.display( );
}
Example:
class base A
{
-----------
-----------
};
class derivedB:public baseA
{
-----------
-----------
};
Multiple inheritance
A derived class could inherit from more than one base classes. When this is done it is called
multiple inheritance.
Example:
class A {
-----
};
class B{
------
};
class C:public A, public B{
-------
};
The class C is derived from both A and B.
Q14. What is ambiguity in ‘C++’? Write a program to show the ambiguity in multiple
inheritance.
Ans. Whenever a data member and member function are defined with the same name in both the
base and the derived classes, these names must be without ambiguity. The scope resolution
operator may be used to refer to any base member explicitly. This allows access to a name
that has been redefined in the derived class.
Example to show how ambiguity occurs in both base class and derived class:
#include<iostream.h>
class baseA{
public:
int a;
};
class baseB{
public :
int a;
};
class derivedC: public baseA, baseB{
public :
int a;
};
void main( )
{
derivedC obj;
obj.a=10;// local to the derived class
}
The object of derived class can directly access to its own member rather than the members of
the base classes.
If one wants to access the members of base classes then the code can be written like
void main( )
{
derivedC obj;
obj.a=10;
obj.baseA::a=20; // accessing the base class A member
obj.baseB::a=90;// accessing the base class B member;
}
Q15. What are virtual functions? Give types, rules. Explain with example.
Ans. It would be nice if the appropriate member function could be selected while the program is
running. This is known as runtime polymorphism. C++ support a mechanism known as
virtual function to achieve runtime polymorphism. At runtime, when it is known what class
object are under consideration, the appropriate version of the function is called. Since the
function is linked with a particular class much later after the compilation, this binding is
termed as late or dynamic binding.
Types
1. Simple virtual function(as shown in example below)
2. Pure virtual function(A pure virtual function is a virtual function with no body).
Rules
1. Virtual keyword is necessary with virtual function.
2. Its body can be outside or inside class.
3. Pure virtual function is without body.
}
};
class derivedC:public derivedB
{
public:
virtual void display ( )
{
cout<<”\nThree”;
}
};
void main( )
{
baseA obja;
derivedB objb;
derivedC objc;
baseA *ptr[3];
ptr[0]=&obja;
ptr[1]=&objb;
ptr[2]=&objc;
for(int i=0;i<3;i++)
{
ptr[i]->display( );
}
}
Q16. Describe the importance of destructor functions and write a program that illustrates the
working of destructor function.
Ans. A destructor is a function that automatically executes when an object is destroyed. A
destructor function gets executed whenever an instance of the class to which it belongs goes
out of existence. The primary usage of the destructor function is to release space on the heap.
}
}
Q17. What are inline functions? How are they created in ‘C++’? Explain with Example.
Ans. The inline specifier is a hint to the compiler that inline substitution of the function body is to
be preferred to the usual function call implementation.
The size of the object code is considerably reduced with the use of inline function.
The use of inline function increases the execution speed of program.
Program to input date and display it using inline functions:
#include<iostream.h>
#include<conio.h>
class date
{
private:
int day,month,year;
public:
void setin(int dayin,int monthin,int yearin);
void show();
};
inline void date ::setin(int dayin,int monthin,int yearin)
{
day=dayin;
month=monthin;
year=yearin;}
inline void date::show()
{
cout<<day<<"-"<<month<<"-"<<year<<endl;
}
void main()
{
date d1,d2,d3;
d1.setin(24,5,2000);
d2.setin(30,7,98) ;
d3.setin(13,7,99);
cout<<"first date=";
d1.show();
cout<<"second date";
d2.show();
cout<<"third date";
d3.show();
getch();
}
Q18. Write a program to calculate the area of a triangle, rectangle, circle and square using
inheritance.
Ans.
Class Common void showarea ()
{ {
protected : res= 3.14 * a*a;
int a,b; cout <<” Area of cirlce " << res
float res ; }
}; };
Class triangle : public common class square : public common
{ {
public : public
Area operator – ( )
{
ar = a*b;
return * this;
}
Area show()
{
cout<<ar;
}
};
Void main ()
{
Area Rect , Cir;
Rect.input (20, 30);
Rect ++;
Cir.input (10) :
Cir --;
Rect . Show ();
Cir . show ( ) ;
}
getch();
}
Q23. Write a program to read a set of floating point numbers using concept of overloading.
Ans.
#include<iostream.h>
#include<conio.h>
void getdata(int x,int y);
void getdata(int x,int y,int z);
void main()
{
float i,j,k;
clrscr();
cout<<"enter data";
cin>>i>>j>>k;
getdata(i,j);
getdata(i,j,k);
getch();
}
Q24. Write a C++ program that declares a class called employee with data members: name,
father name, residence address.
Ans.
class employee
{
private:
char name[10];
char fname[20];
char address[20];
public:
void getdata();
{
cout<<”enter data”
cin>>name;
cin>>fname;
cin>>address;
}
void display()
{
cout<<name;
cout<<fname;
cout<<address;
}
};
void main()
{
employee e;
clrscr();
e.getdata();
e. display();
getch();
}
Q25. What are different types of membership functions? Explain structure of class.
Ans. Membership functions:
1. Constructor
2. Friend function
3. Destructor.
4. Static member function
5. Virtual function
6. Inline member function
STRUCTURE OF CLASS
Class <classname>
{
private:
datamember 1;
datamember 2;
datamember 3;
public:
member function1();
member function2();
member function3();
};
Example:
#include <iostream>
using namespace std;
class alpha
{
int x;
public:
alpha(int I)
{
x = i;
cout<< ”alpha initialized \n”;
}
void show_x(void)
{
cout<< “x = “<<x << “\n”;
}
};
class beta
{
float y;
public:
beta(float j)
{
y = j;
cout<< “ beta initialized \n”;
}
void show_y(void)
{
cout<< “ y = “ <<y << “\n”;
}
};
class gamma: public beta, public alpha
{
int m, n;
public:
gamma(int a, float b, int c, int d): alpha(a), beta(b)
{
m = c;
n = d;
cout<< “gamma initialized \n”;
}
void show_mn(void)
{
cout<< “ m = “<<m <<”\n”;
cout<<” n = “<<n <<”\n”;
}
};
int main( )
{
gamma g(5, 10.75, 20, 30);
cout<< “\n”;
g.show_x( );
g.show_y( );
g.show_mn( );
return 0;
}
struct student
{
char name [20] ;
int age ;
int fee;
};
struct student s[ ];
void main()
{
----------------------
----------------------
fi (struct student s[ ] )
}
struct student fi (struct student s[ ] )
{
-
-
-
-
}
Q28. Using operator overloading, write a program for floating point number operation like
‘+’ and ‘-‘.
Ans.
#include<iostream.h>
struct complex
{
float real;
float imag;
};
void main( )
{
complex a,b,c;
cout<<”Enter the first complex number”;
cin>>a.real>>a.imag;
cout<<”Enter the second complex number”;
cin>>b.real>>b.imag;
cout<<”\nComplex number operations”;
cout<<endl<<” a - > add”<<endl<<”s - > subtract “;
cout<<endl<<”Enter your choice”;
char ch;
cin>>ch;
switch ( ch)
{
case ‘a’ : c=a+b;
cout<<endl<<”Addition of two complex numbers is :”;
cout<<c.real<<”+I”<<c.imag;
break;
case ‘s’: c=a-b;
cout<<endl<<”subtraction of two complex numbers is :”;
cout<<c.real<<”+I”<<c.imag;
break;
}
}
Q29. Differentiate between abstraction and data hiding. Why classes in C++ are abstract?
Ans. OOP encapsulates data and functions into packages called objects. The data & functions of an
object are intimately tied together. Objects have the property of information hiding. This
means that although objects may know how to communicate with each other, they normally
do not know how other objects are implemented. That is, implementation details are hidden
within the objects themselves.
Abstraction is very close to data hiding. Abstraction refers to the act of representing essential
features without including the background details or explanations. Data abstraction is
concerned with separation the behaviour of data object from its representation or
implementation.
Abstract class: An abstract class is one that is not used to create object. Classes that declare a
pure virtual function is called an abstract class. It is used as a base class for deriving. It
defines properties common to other classes derived from it. Since an abstract class contains
one or more functions for which there is no definition, no objects can be created using an
abstract class.
Q5. What are the functions available in C++ to manipulate the file pointers? Explain.
Ans. Open (): This is the function used to open a file. A string parameter, which is actually
the name of the file to be opened, is passed to the function.
Close (): This is the function used to close the already opened file.
Eof (): this function is used to check whether a file pointer has reached at end of the file.
Fail (): The function return true if it failed to open the file requested.
1000 is the location of the first element of the array. As the int data type takes two bytes of
the memory so the next element is stored at 1002 and so on.
Q3. What is a random access file? Explain the syntactic rule for the following random access
file member function?
a) seekp
b) seekg
c) tellg
d) tellp
Ans. RANDOM FILE: In random access file the file pointer can be moved to any location in the
file instead of moving it sequentially. This approach is used with database files.
Q4. Write an algorithm for Bubble sort & explain with an example.
Ans. Algorithm BUBBLE (DATA, N)
Here DATA is an array with n elements. This algorithm sorts the elements in DATA.
Example: 32 51 27 85 66 23 13 57
A1 A2 A3 A4 A5 A6 A7 A8
This is pass 1
Similarly, in every pass the greater element will be moved towards the end.
Since the array has 8 elements, it is sorted after the seventh pass i.e. (n-1) in pass.
Q5. Write non-recursive & recursive procedures to find the factorial of a given number.
Ans.
Procedure: FACTORIAL (FACT, N)
This procedure calculates N! & returns the value of the variable FACT in a non-recursive
manner.
Q6. Explain the basic operations on stack. Write procedures to implement these operations.
Ans. A stack is a list of elements in which an element may be inserted or deleted only at one end
called the top of the stack.
Hire DATA is a linear array with N elements & ITEM is a given item of information. This
algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search is
unsuccessful.
Q12. What are the operations that can be performed on a queue? Write procedures to
implement these operations.
Ans. A queue is linear list of elements in which deletions can take place only at one end, called the
“front” & insertions can take place only at the other end called the “rear”.
1. [Overflow?]
If R≥N then write (OVERFLOW)
Return.
2. [Increment rear pointer]
R: =R+1
3. [Insert element]
Q[R]: =Y
4. [Is front pointer properly set?]
If F=0
Then F:=1
Return.
1.) [Underflow]
If F=0
Than write (‘underflow’)
Return (0) [0 deviates an empty queue]
2.) [Delete element]
Y ←Q[F]
3.) [Queue empty?]
If F=R then F: =R: =0
Else F: =F+1
4.) Return element]
Return (Y)
Q13. Write an algorithm for transforming infix expression into postfix expression with
example.
Ans. POLISH (Q, P)
Suppose Q is an arithmetic expression written in infix mutation. This algorithm finds the
equivalent postfix expression P.
a) Repeatedly pop from STACK & add to P each operator, which has the same
precedence as or higher precedence than Q.
b) Add Q toy STACK
[End of If structure]
6. If a right parenthesis is encountered
a) Repeatedly pop from STACK & add to P each operator until a left parenthesis is
encountered.
b) Remove the left parenthesis [Do not add the left parenthesis to P]
[End of If structure]
[End of step 2 Loop]
7. Exit
Q14. Write procedure for performing insertion & deletion operations on a circular queue.
Ans. A circular queue is the same as a queue but the front & rear ends of a queue are joined
together to form a circular ring.
Q16. What are linked lists. How do they overcome the drawbacks of arrays.
Linear Linked Lists
Ans. Linked List
List means to a linear collection of data items. Till now we are storing elements in array.
Arrays has some disadvantages like:
1.Wastage of memory, because total space allocated must be known in advance, otherwise
enough space can be wasted.
2.Some operations like Insertion and Deletions require extra time, because insertion and
deletion requires enough shifting of elements.
Due to these disadvantages we use dynamic memory allocation i.e., using Linked List.
A linked list is a linear collection of data elements, called nodes. Pointers give the linear
order. Each node is divided into two or more parts. Concept of linked list uses dynamic
memory allocation. A linked can be of the following type.
• Linear linked list or one-way list
• Double linked list or two way list
Head
Q17. Define pointer. Write an algorithm to create a linked list & insert an item into a linked
list.
Ans. A pointer is a variable that stores the address of another variable.
Algorithm: INFIRST (INFO, LINK, START, AVAIL, ITEM). This algorithm inserts ITEM
as the first mode in the list.
1. [Overflow?] If AVAIL = NULL
then: Write overflow L Exit
2. Remove first mode from AVAIL list]
Set NEW: = AVAIL and AVAIL:= LINK [AVAIL]
3. Set INFO [NEW]: = ITEM [Copies new data into new mode.
4. Set LINK [NEW]: =START [New mode points to original first mode].
5. Set START: = NEW [Changes START so it points to the new mode].
6. Exit.
void main()
{
ofstream ofile;
ifstream ifile;
char fname1[10],fname2[10];
char ch;
cout<<”Enter the source file name”;
cin>>fname1;
cout<<”Enter the target file name”;
cin>>fname2;
ifile.open(fname1);
if( ifile.fail())
{
cerr<<”File not found”;
return;
}
ofile.open(fname2);
if (ofile.fail())
{
cout<<”can not make file”;
return;
}
while( ! ifile.eof())
{
ch=(char) ifile.get();
ofile.put(ch);
}
ifile.close();
ofile.close();
}
Q20. Using classes write a program to copy text from one file to another.
Ans.
#include<iostream.h>
#include<fstream.h>
class student
{
private:
char name[20];
int age;
public:
void getdata( )
{
cout<<”Enter the name and age of the student”;
cin>>name>>age;
}
void show( )
{
cout<<”Name : “<<name;
cout<<endl<<”Age :”<<age;
}
};
void main( )
{
student s;
fstream infile, outfile;
outfile.open(“stucopy”,ios::out); // file opened in write mode
infile.open(“stu”,ios::in); // file opened to read data from
while (! infile.eof( ))
{
infile.read((char *) &s, sizeof( s));
outfile.write((char *) &s, sizeof(s));
}
infile.close( );
outfile.close ( );
outfile.open(“stucopy”,ios::in); // file in which data was copied is opened in read mode
while (! outfile.eof( ))
{
outfile.read((char *) &s, sizeof( s));
s.show( );
}
outfile.close( );
}