You are on page 1of 61

Dept.of C.S.

,RMKMHSS - 601206

Namma Kalvi

11 www.nammakalvi.in

RMKMHSS

COMPUTER SCIENCE

GUIDE
VOLUME II

ELANGOVAN
M.Sc,B.Ed,M.Phill
rmkmhsselango.blogspot.com
9677515019

1
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

UNIT -III
INTRODUCTION TO C++ CHAPTER
9
Introduction to C++

6.Define Keywords.
1.History of C++  Keywords are the reserved words.
 It conveys specific meaning to the C++ compiler.
 C++ was developed by Bjarne Stroustrup at AT & T
Bell Laboratory during 1979  They are the essential elements to construct C++
programs.
 it was referred “New C” and “C with Classes”.
 Most of the keywords are common to C, C++ and
 In 1983, the name was changed as C++ by Rick
Java.
Mascitti.
2.Benefits of learning C++  All the keywords must be in lower case in C++.
 C++ is called as Hybrid Language.  keywords cannot be used as an identifier name.
Ex. if ,for ,this, cout , cin, while etc….
 C++ is for multi-device, multi-platform app
7.What are Identifiers?
development.
 Identifiers are the user-defined names given to
 C++ is an object-oriented programming language.
variables, functions, arrays, classes etc.,
 It includes classes, inheritance, polymorphism,
 These are the fundamental building blocks of a
data abstraction and encapsulation.
program.
 C++ has a rich function library.
 Every language has specific rules for naming the
 C++ allows exception handling, inheritance and
identifiers.
function overloading which are not possible in C.
8.What are the Rules for naming an identifier?
 C++ is a powerful, efficient and fast language.
 Only alphabets, digits and underscore(_) are
 It finds a wide range of applications.
permitted.
3.List the languages which are influenced by C++
 Other special characters ,space are not allowed.
 C# (C-Sharp), D, Java and newer versions of C
 The first character of an identifier must be an
4.What are the Character set in C++?
alphabet or an underscore (_).
 Character set is a set of characters which are
• C++ is case sensitive
allowed to write a C++ program. They are
• keywords cannot be used as an identifier name.
9.Define Literals /Constant? What is meant by literals?
 Literals are called as Constants.
 Literals are data items whose values do not change
during the execution of a program.
C++ has several kinds of literals:
 Numeric Constants:
 Boolean Literals
 Character constant
 String constant.
10.Numeric Constants: What are numeric constant and
its types.
The numeric constants are only numeric values,
They are,
5.What are Lexical units or Lexical elements or Tokens. 1. Integer Constants (or) Fixed point constants.
in C++? 2. Real constants (or) Floating point constants.
 The smallest individual unit in a program is known
as a Lexical unit or Lexical elements or Token. They
are Keywords • Identifiers • Literals • Operators
• Punctuators

2
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

11.How many types of integer literals(or) Fixed 17.What is the significance of null (\0) character in a
point constants available in C++? or string?
Explain the types of integer literals in C++.  String should be terminated with a ‘\0’ (NULL)
 Integers are whole numbers without a decimal character Ex. ,”ELANGO\0”
point. 18.What is Escape sequences (or) Non-graphic
 It may be signed (negative )or unsigned. Characters (or ) non- Printable Characters ?
 Commas and blank spaces are not allowed.  Non-printable characters cannot be typed directly
Three types : (i) Decimal (ii) Octal (iii) Hexadecimal from a keyboard .
Decimal  These non-printable characters can be represented
 Consists of digits (0 …. 9)Ex. 28 , -28 , 28.11 by using escape sequences.
Octal  An escape sequence is represented by a backslash
 Consists of digits (0.. 7)begins with 0 is considered ( \ ) followed by one or two characters.
as an Octal constant. Ex.022 , - 022
Hexadecimal
 Consists of digits (0…9 ,A..F)
 begins with 0x or 0X is considered as a Hexadecimal
constant. Ex. 0x28 , 0X3AC
13. What are Real constants (or) Floating point
constants
 It is a numeric constant having a fractional
component.
 It may be signed (negative )or unsigned with
decimal point
 It may be written in fractional or in exponent form.
 Exponent form consists of two parts:
(1) Mantissa and (2) Exponent.
 The mantissa followed by a letter E or e and the
exponent.
14. How to write 58000000 . 00 in Exponent form.?
It may be written as 0.58 × 10 8 or 0.58E8.
Other Example:
5.864 E-1 - 5.864 × 10 1 - 58.64 Ex.\a ,\n , \t etc…
5864 E-2 - 5864 × 10 -2 - 58.64
0.5864 E-2 - 0.5864 × 10 2 - 58.64 19.How to represent a long and unsigned constant ?
15.What is Boolean Literals?  The suffix L or l used to represent long constant
 Used to represent Boolean values(True (1) or Ex.25L
false(0)).  The suffix U or u used to represent unsigned
16.Differentiate between Character constant and constant. Ex. 25U
String constant? Evaluate Yourself
Character constant 1.What is meant by literals? How many types of integer
 It must contain one character literals available in C++? Ref.9 & 11
 must be enclosed within a single quote. 2. What kind of constants are following?
Ex. ‘p’ , ‘6’ , ‘+’ i) 26 ii) 015 iii) 0xF iv) 014.9
3. What is character constant in C++? Ref.16
 Each single character constant has an equivalent
4. How are non graphic characters represented in
ASCII value. For ‘A’ is 65.
C++? Ref.18
String Literals
5. Write the following real constants into exponent
 Set of characters are called String literals.
form: i) 32.179 ii) 8.124 iii) 0.00007
 It enclosed within double quotes (“ “ ) .
Ans : i)32.179E3 ii)8.124E3 iii)0.7E-4
 String should be terminated with a ‘\0’ (NULL)
6. Write the following real constants into fractional
character..
form: i) 0.23E4 ii) 0.517E-3 iii) 0.5E-5 iv)5E-5
 Size of “welcome” is not 7 but 8 including \0 . Ans: i)2300 ii) 0.000517 iii) 0.000005 iv) 0.00005
Ex. “S” , “Elango” , “123” ,”ELANGO\0” 7. What is the significance of null (\0) character in a
string? Ref.17.

3
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

20.What are Operators and Operands Example:


 The symbols which are used to do some let n=2
mathematical or logical operations are called as Prefix Postfix
“Operators”. a=++n a=n++
 The values that the operators act upon are called as First increment the First a gets the value of n,
“Operands”. value of n by 1 and then increment it by 1
A + B : + operator A , B - Operands then a gets the value.
21.How are the operators classified based on operand value of a=3 , n=3 value of a=2 , n=3
requirements? a=--n a=n- -
1. Unary Operators - Require only one operand *First decrements the *First a gets the value of
2. Binary Operators - Require two operands value of n by 1 n,
3. Ternary Operators - Require three operands *then a gets the value *then decrement it by 1
22.How are the C++ Operators are classified based on *value of a=1 ,n=1` *value of a=2, n=1
their function? 27. Assume that R starts with value 35. What will be the
(1)Arithmetic Operators value of S from the following expression? S=(R--)+(++R)
(2) Relational Operators Result: S = 70
(3) Logical Operators 28. What will be the value of j = - - k + 2k. if k is 20
(4) Bitwise Operators initially ? Result j = 57
(5) Assignment Operators 29. What will be the value of p = p * ++j where j is 22
(6) Conditional Operator and p = 3 initially? Result is 69
(7) Other Operators
23.Define Arithmetic Operators 30.Write short note on Relational Operators
 Arithmetic operators are binary operators  Relational operators are binary operators.
because it require two operands.  Relational operators are used to compare numeric
 It performs operations like addition, subtraction, values
multiplication, division etc.,  A relational expression is consists of any two
Ex .+ (Addition ) , - (subtraction ) *( Multiplication ) operands with a relational operator Ex. 10 > 5
/ (division – Quotient of the division)  The result will be a Boolean value(1(TRUE)or
% (Modulus – Remainder of the division ) 0(FALSE) ) They are > , < , <= , >= ,== ,!=
24.What does the modulus operator % do? 31.Write short note on Logical Operators
 It gives the remainder of the division  Logical operators combine the results of one or
Ex let x=5; x%2; the result is 1 more conditions.
25. What will be the result of 8.5 % 2?  C++ provides three logical operators.
 Ans: Error occurs because Modulus operator % 1. AND(&&), OR(||) are binary operators
cannot be used on floating point data. 2. NOT (!) is an unary operator
26.Write short note on Increment and Decrement AND(&&) – The result is 1 (TRUE) when all condition
Operators. are 1 (TRUE)
 Increment ( + + ) Operator and Decrement ( - - ) OR(||) - The result is 1 (TRUE) when atleast one
Operator are unary operators condition is 1 (TRUE)
 The Increment ( + + ) Operator adds 1 to its NOT (!) – it inverts , The result is 1 (TRUE ) when
operand condition is False and vice versa.
 The Decrement ( - - ) Operator subtracts 1 to its Ex. if a = 5, b = 6, c = 7;
operand. Expression Result
 x++ is the same as x = x+1; (a<b) && (b<c) 1 (True)
It adds 1 to the present value of x (a>b) && (b<c) 0 (False)
 ++ x is the same as x = x+1; (a<b) || (b>c) 1 (True)
It adds 1 to the present value of x !(a>b) 1 (True)
 x-- is the same as to x = x–1; 32. Write short note on Bitwise Operators
It subtracts 1 from the present value of x  Bitwise operators perform bit-by-bit operation.
 --x is the same as to x = x–1;  In C++, there are three kinds of bitwise operators,
It subtracts 1 from the present value of x which are:
(i) Logical bitwise operators
(ii) Bitwise shift operators
(iii) One’s compliment operators

4
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

33.Logical bitwise operators:


 & Bitwise AND (Binary AND)
The result is 1 (TRUE) when all operands are 1 (TRUE)
 | Bitwise OR (Binary OR)
The result is 1 (TRUE) when atleast one operand is 1
(TRUE)
 ^ Bitwise Exclusive OR (Binary XOR)
If both are same, it will return 0 (False).

34.Write the Truth Table for bitwise operators


38. The Bitwise one’s compliment operator:
 The bitwise One’s compliment operator ~ (Tilde)
 It inverts, that is, all 1’s become 0 and all 0’s
become
 It is an unary operator.
39.If a =15; find ~a.
Equivalent binary values of a is 0000 1111

35.If a = 65, b=15 find the value of &,| and ^


In binary 65 = 1000001 in 8 bits : 0100 0001
15 = 1111 in 8-bits = 00001111

40.Define Assignment Operator.


 It is used to assign a value to a variable.
 = is commonly used as the assignment operator.
 This operator copies the value at the right side to
the left side variable.
 It is also a binary operator.
Syntax : Variable = Value\ constant\ expression ;
Ex. a = 10;
41.What are Shorthand assignment operators?
 +=, -= ,*= , /= , %=
42.Define Conditional Operator:
 This is a Ternary Operator.
 ?: is a conditional Operator.
36. The Bitwise shift operators:
 In C++, there is only one conditional operator is
There are two bitwise shift operators in C++,
used.
1.Shift left (<<) 2. Shift right (>>).
 This operator is used as analternate to if … else
Shift left ( << ) :
Syntax :( Condition ) ? Statement 1 : Statement 2 ;
 The value of the left operand is moved to left by the
 If condition is TRUE Statement 1 is executed.
number of bits specified by the right operand.
 If condition is FALSE Statement 2 is executed
 Right operand should be an unsigned
43.Define comma operator.
(positive)integer. Ex a<<3;
 Comma ( , ) is an operator in C++ used to together
Shift right ( >> ) :
several expressions.
 The value of the left operand is moved to right by
 The group of expression separated by comma.
the number of bits specified by the right operand.
 It is evaluated from left to right.
 Right operand should be an unsigned
(positive)integer. Ex. a>>3;
37.If a =15;find a<<3 and a>>2
Equivalent binary value of a is 0000 1111

5
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

44.What is sizeof operator or Define compile time


operator Evaluate Yourself….
 This is called as compile time operator.
 It returns the size of a variable in bytes. 1.What is use of operators? 20.
 Ex. int x = 10; cout << sizeof(a); 2. What are binary operators? Give examples arithmetic
Output : 2 bytes binary operators.23.
45.What is Association or Define order of precedence. 3. What does the modulus operator % do? 24.
 Operators are executed in the order of precedence. 4. What will be the result of 8.5 % 2?
 The operands and the operators are grouped in a 8. Give that i = 8, j = 10, k = 8, What will be result of the
specific logical way for evaluation. following expressions?
 This logical grouping is called as an Association. (i) i < k (ii) i < j (iii) i > = k (iv) i = = j (v) j ! = k
Result: i) 0 ii)0 iii)1 iv)0 v)1
46.Order of precedence of C++ Operators 9. Write an expression involving a logical operator to
test, if marks are 75 and grade is 'A'.
 If (marks > 75) && ( marks == 75)
cout<<”Grade is A”;

10.Define order of precedence


 The order of precedence is used to determine how
an expression involving more than one operator is
evaluated.
11. What will be the order of evaluation for the
following expressions?
(i) i + 3 >= j - 9 (ii) a +10 < p - 3 + 2 q

I/O Operators

48. What is the use of a header file or Library file?


 A header file comprises of all standard declarations
and definitions for predefined functions
 One can include the header file in the program by
47.What is Punctuators ?
using a preprocessor directive (#) .
 Punctuators are symbols, which are used as
 It instructs the compiler to do the required job.
delimiters, while constructing a C++ program.
Syntax : # include <header file>
 They are also called as “Separators”. Ex #include<iostream.h>
{ } -curly braces indicate the start and the end of a 49.What are the pre processor operators?
block of code. Ex. {int a; a=10;}
 # and ## are pre processor operators
( ) Parenthesis indicate function calls and function
 The sysmbol # is a directive for the pre-processor.
parameter. Ex add(); main()
 These are processed before the compilation process
[ ] Suare brackets indicates arrays ex.int a[5];
begins.
, comma is used as separator ex, int a,b,c;
Ex. #include<iostream>
; every executable statement in C++ should
terminate with a semicolon ex. int a;
: colon is used to label a statement. Ex. private:
// single line comment
/* */ Multi line comment

6
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

50.Define Input operator or define Input statement . 52.What is the use of namespace std; or Define
 The operator >> is called as “Stream extraction” or namespace std;
“get from” operator.  It tells the compiler to use standard namespace.
 >> operator to perform input operation.  Namespace collects identifiers used for class ,object
 It extracts the value through the keyboard and and variables.
assigns it to the variable on its right.  Namespace provide a method of preventing name
 It is a binary operator. conflicts in large projects.
 The first operand is the pre-defined identifier cin  It is introduced by the ANSI C++ standards
that identifies keyboard as the input device. committee.
 The second operand must be a variable. 53.What are the importance of main() function?
Syntax : cin>>variable; ex. cin>>a;  Every C++ program must have a main function.
cin>>var1>>var2>>var3; ex. cin>>a>>b;  The main() function is the starting point where all
C++ programs begin their execution.
 The executable statements should be inside the
main() function.

Execute C++ program


51.Define Output Operator:or output statement?

 << is called the “Stream insertion” or “put to” 54.How to creating and executing a C++ program
operator. (1) Creating Source code
 << operator to perform output operation.
 Typing and editing the valid C++ code as per the
 It is used to send the string or the values of the rules followed by the C++ Compiler.
variables on its right to the object on its left. (2) Saving source code with extension .cpp
 << is a binary operator.  After typing, the source code should be saved with
 The first operand is the pre-defined identifier cout the extension .cpp
that identifies monitor as the standard output
object. (3) Compilation
 The second operand may be a constant, variable or  In compilation, compiler links the library files with
an expression the source code and verifies each and every line of
code.
 If any mistake or error is found, it will inform you to
make corrections.
Syntax : cout<<variable; Ex. cout<<a;
 If there are no errors, it translates the source code
into machine readable object file with an
For yourself:
extension .obj
 To display the contents of the variable:
(4) execution
Syntax : cout<<variable; Ex. cout<<a;
 In this stage, the object file becomes an executable
 To display the Message only
file with extension .exe.
Syntax : cout<<”Message”; Ex. cout<<”INDIA”;
 An executable file, can run your application without
 To display the Escape Sequence only
the help of any compiler or IDE.
Syntax : cout<<”\escape seq.”; Ex. cout<<”\n”;
55.What is IDE in C++?
 To display the Message with Escape Sequence
 Integrated Development Environment (IDE) makes
Syntax : cout<<”Message esc.seq.”;
it easy to create, compile and execute a C++
Ex. cout<<”INDIA\n”;
program.
 To display the result of expression
cout<<a+b;
 To display the constant or data.
cout<<7; or cout<< 2+3;
 To display Message escape sequence variable
cout<<”Message”<<’\n’<<variable;
ex. cout<< “ The Result is..”<< ‘\t’ << c;

7
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

List some Familiar C++ Compilers with IDE 1.Describe the differences between keywords and
identifiers? Ref. 6 and 7
2. Is C++ case sensitive? What is meant by the term
“case sensitive”?
 C++ is case sensitive as it treats upper and lower-
case characters differently.
3. Differentiate “=” and “==”.
4. Assume a=10, b=15; What will be the value of a^b?
5. What is the difference between “Run time error” and
“Syntax error”?
56.Explain how to work with Dev C++? 6. What are the differences between “Logical error”
 Double click Dev C++ icon to open IDE and “Syntax error”?
 To create a source file, 7. What is the use of a header file?
 Select File → New → Source file or Press Ctrl + N. 8. Why is main function special?
 After save, Click Execute → Compile and Run or 9. Write two advantages of using include compiler
press F11 key. directive.
 If your program contains any error, it displays the 10. Write the following in real constants.
errors under compile log. (i) 15.223 (ii) 211.05 (iii) 0.00025
 If your program is without any error, the display will
appear as follows.
 After successful compilation, output will appear in Data Types, Variables and Expressions
output console.
57.Define Syntax error 60.What are the categories of Data types?
 Syntax error occur when grammatical rules of C++ In C++, the data types are classified as three main
are violated. categories
 Ex. cout<<”INDIA” - it will throw an error because (1) Fundamental data types
this statement does not end with a semicolon. (2) User-defined data types and
58.Define semantic error or logical error . (3) Derived data types
 It may be happened by wrong use of variable /
operator /order of execution etc.
 Here program is grammatically correct but it
contains some logical error.
59.Define run time error.
 A run time error occurs during the execution of a
program.
 It occurs because of some illegal operation that
takes place.

Evaluate Yourself….

1.What is meant by a token? Name the token available 61.Write about Fundamental data types.
in C++. Ref.5  Fundamental (atomic) data types are predefined
2. What are keywords? Can keywords be used as data types available with C++.
identifiers?ref.6  There are five fundamental data types in C++: char,
3. The following constants are of which type? int, float, double and void.
(i) 39 (ii) 032 (iii) 0XCAFE (iv) 04.14 int data type:
5. Assume n=10; what will be result of n>>2;?  Integers are whole numbers without any fraction.
6. Match the following  Integers can be positive or negative.
A B  Integer data type accepts and returns only integer
(a) Modulus (1) Tokens numbers.
(b) Separators (2) Remainder of a division  .Ex. int a = 5; int x = -4 ;
(c) Stream extraction (3) Punctuators int a= 4.5 (it will accept only 4)
(d) Lexical Units (4) get from

8
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

char data type:  C++ compiler allocates specific memory space for
 Character data type accepts and returns all valid each and every data .
ASCII characters.  Every data is stored inside the computer memory in
 Character data type is an integer type. the form of binary digits
 All the characters are represented in memory by
their associated ASCII Codes.
Ex. ‘A’ represent 65
float data type:
 Float data type accepts floating point values with 6
digits of precision.
 It includes integer portion, a decimal
point ,fractional portion and an exponent.
Ex. float a =3.14;
There are two advantages of using float data types. 63.Write a short note on modifiers Or qualifiers .
(1) They can represent values between the integers.  Modifiers can be used to modify (expand or reduce)
(2) They can represent a much greater range of values. the memory allocation of any fundamental data
Disadvantage type.
 Floating point operations are slower than integer  They are also called as Qualifiers
operations. There are four modifiers used in C++. They are:
double data type (1) signed (2) unsigned (3) long (4) short
 double data type accepts double precision floating Integer type
point numbers with 14 digits of precision.
 This type occupies double the space than float type
Ex. double a=3.456744;
void data type
 It is used as a return type for functions that do not
return any value.
 The void data type specifies an empty set of values.
It is used as a return type for functions that do not
return any value.
 Ex. void main() , void add()
What are the advantages and disadvantages of float
data type ? Ref. above answer

Evaluate Yourself….

1.What do you mean by fundamental data types?Ref.61


2. The data type char is used to represent characters.
then why is it often termed as an integer type?
 Character data type accepts and returns all valid
ASCII characters.
 All the characters are represented in memory by
their associated ASCII Codes.
 ASCII codes are an integer type.
3. What is the advartage of floating point numbers over
integers? Ref. 61. integer type accepts only 2 bytes of data
4. The data type double is another floating point type. long accepts 2 bytes
Then why is it treated as a distinct data type?
 Because more fractions accommodated in double
than in float type
5. What is the use of void data type? Ref.61
62.What are the Memory representation of
Fundamental Data types in C++?

9
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

char type
Variables
65.Define variables.
 Variables are user-defined names.
 Variables are memory locations in which the values
are stored.
 Variables are also identifiers.
 These are called as symbolic variables because
these are named locations.
Floating point type
 There are two values associated with a symbolic
variable;
 They are R-value and L-value.
• R-value is data stored in a memory location
• L-value is the memory address .
 The memory addresses are in the form of
Hexadecimal values
 Ex.Let int a = 5 ; Here Variable name is a ;R value is
5 ; L value is 0x12b(for example)

66.How to Declare of Variables in C++?


 Every variable should be declared before they are
Memory allocation by Turbo C++ and Dev C++ actually used in a program.
 Declaration is a process to instruct the compiler to
allocate memory as per the data type along with
the variable name.
Syntax : Data type space variable name ;
Ex. int a;
Declaration of more than one variable:
Syntax : Data type space var1,var2,var3 ;
Ex. int a,b,c; (comma is used to separating the
variables).
67. What is meant by Junk” or “Garbage”?
 If you declare a variable without any initial value,
variable will be occupied with some unknown value.
 These unknown values are called as “Junk” or
“Garbage” values.

68.How to initialize the variable in C++?


 Assigning an initial value to a variable during its
declaration is called as “Initialization”.
Suntax: Data type space variable name = value;
Ex. int a = 10;
 Variables that are of the same type can be initialized
in a single statement.
int x1 = -1, x2 = 1;
64.What is Number Suffixes in C++? 69.What is Dynamic Initialization?
 There are different suffixes for integer and floating  A variable can be initialized during the execution of
point numbers. a program. It is known as “Dynamic initialization”.
 Suffix can be used to assign the same value as a For example, int c = a+b;
different type.
Ex.To store 45 in long int suffix letter L : 45L
Unsigned int : 45U for float : 3.14F

10
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

70.Define Access modifier or qualifier or const 2)setw ( )


qualifier. setw manipulator sets the width of the field assigned
 const is the keyword used to declare a constant. for the output.
 The const qualifier specifies that the value of a Syntax:
variable will not change during the run time of a setw(number of characters)
program. 3)setfill ( )
 Any attempt to alter the value, an error message  It is usually used after setw.
will be displayed as “Cannot modify the const cout << "\n H.R.A : " << setw(10) << setfill (0) << hra;
object” in Turbo compiler . from above example ,
 “assignment of read only memory num” in Dev  setw creates a field to show the presented value,
C++.  setfill is used to fill un-occupied spaces with 0
 if hra=1200,The output will be, 0000001200.
Evaluate Yourself…. 4)setprecision ( )
 This is used to display numbers with fractions in
1.What is modifiers? What is the use of modifiers?63. specific number of digits.
2.What is wrong with the following C++ statement: Syntax:
long float x; there is no long float setprecision (number of digits);
3.What is variable ? Why a varible called symblolic Ex.
varible? 65.  float hra = 1200.123;
4. What do you mean by dynamic initialization of a  cout << setprecision (5) << hra;
variable? Give an exmple.69  The output will be 1200.1(including fraction)
5. What is wrong with the following statement?  setprecision can also be used to set the number of
const int x; decimal places to be displayed.
 Error because const modifier should be used  In order to do this task, you will have to set an ios
during initialization. Here value is not initialized. flag within setf() manipulator.
 There are two types of flags i) fixed ii) scientific
71. What is References variable? Example
 A reference provides an alias for a previously cout.setf(ios::fixed);
defined variable. cout << setprecision(2)<<0.1;
 Declaration of a reference consists of base type and  In the above statements, ios flag is set to fixed type;
an & (ampersand) symbol;  It prints the floating point number in fixed notation.
 Reference variable name is assigned the value of a So, the output will be, 0.10
previously declared variable. cout.setf(ios::scientific);
Syntax: cout << setprecision(2) << 0.1;
Data type & reference_variable = original_variable;  In the above statements, ios flag is set to scientific
Ex. int a=10; int &b=a; type;
 The output of a is 10 and the output of b is 10  it prints the floating point number in scientific
72. What are Manipulators? notation. So, the output will be, 1.00e-001
 Manipulators are used to format the output of any 74. Explain the types of Expression in C++?
C++ program. There are seven types of expressions, and they are:
 Manipulators are functions specifically designed to (i) Constant Expression
use with the insertion (<<) and extraction(>>) (ii) Integer Expression
operators. (iii) Floating Expression
 Commonly used manipulators are: endl, setw, (iv) Relational Expression
setfill, setprecision and setf. (v) Logical Expression
 endl is a member of iostream header file. (vi) Bitwise Expression
 setw, setfill, setprecision and setf are members of (vii) Pointer Expression
iomanip header file. (i) Constant Expression
73. Explain some formatting output or Manipulators  Consist only constant value Ex.int a=10;
1)endl (End the Line) (ii) Integer Expression
 endl – Inserts a new line and clean the buffer  Consist of integer and character values\ variables \
expression
 ‘\n’ - Inserts only a new line.  Produce integer results
Ex.avg=sum/5;

11
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

(iii) Floating Expression 5. What is the use of setprecision ( ) ? 73


 Consist of floating point values\ variables
\ expression. 1. What is the difference between a keyword and
 Produce floating point results an identifier?
Ex. float a= 3.14*r*r; 2. What are literals in C++? How many types of
(iv) Relational Expression literals are allowed in C++?
 Consist of values\ variables with relational 3. How many ways are there in C++ to represent
operators. an integer constant?
 Produce either True(1) or False(0).ex. a>b 4. What is the different between ‘a’ and “a” in
(v) Logical Expression C+?
 Consist of values\ variables with Logical operators.  Character enclosed in single quotes are
 Produce either True(1) or False(0). character constant
 Ex. (a>b) && (a>c)  The size of ‘a’ is 1 character.
(vi) Bitwise Expression  Character enclosed in double quotes
 Consist of values\ variables with Bitwise operators are string constant
(vii) Pointer Expression  \0 (nul) used to terminate the string
 A Pointer is a variable that holds a memory  The size of “a” is 2 character.
address. 5. Who was developer of C++? Ref 1
 Pointer declaration statements: 6. What was the original name given to C++? Who
Syntax : Data type space *variable; ex. int *a; gave the name “C++”?
75.What is Type Conversion? Give examples 7. What is meant by token? Name the token
The process of converting one fundamental type available in C++.
into another is called as “Type Conversion”. 8. What are keywords? Can keywords be used as
C++ provides two types of conversions. identifiers?
(1) Implicit type conversion 9. What is an identifier ? what are the rules to
(2) Explicit type conversion. form an identifiers?
76.Define Implicit type conversion 10. What are literals ?how many types of integer
 An Implicit type conversion is performed by the literals are available in c++?
compiler automatically. 11. How are integer constants represented in C++?
 It is also called as “Automatic conversion”. Explain with example
 Compiler converts smaller type into wider type 12. What kind of constant are the following?
which is called Type Promotion 14 , 011 , 4.324, ‘a’ , “rmk” , 0X2A
Ex.int a=6; float b=3.14; cout << a+b; 13. How are nongraphic characters represented in
The output is 9.14(float is wider than int) c++?
77.Define Explicit type conversion ( What is Type 14. What kind of program element (token) are the
casting?) following? 28 , a , for , // , +
 Explicit conversion is performed by the 15. Which escape sequence represent the newline
programmer in the program itself. & null character?
16. Which character is automatically added to string
 Explicit conversion is converting of variables or
in C++?
expressions from one data type to another
17. What header file must you include with your
specific data type.
source file to use cout and cin?
 It is called as “type casting”.
18. What are the main data types of C++?
Syntax. : (type-name) expression;
19. Explain fundamental data types.
Ex. float varf=78.685; cout << (int) varf;
20. Why is char often treated as integer data type?
output is 78
21. Consider the following two C++ statements.
78. What is type promotion? Ref. 76.
Are they equivalent.. char g=65; char g=’A’;
Evaluate Yourself.. Yes both are equivalent ASCII code value of ‘A’ is
65
22. What is the different between 25L and 25
1. What is meant by type conversion? 77
25L - long integer constant
2. How implicit conversion different from explicit
25 - integer constant.
conversion? 76 , 77
3. What is difference between endl and \n? 73.
4. What is the use of references? 71

12
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

UNIT -III INTRODUCTION TO C++ CHAPTER


10
Flow of Control
1.Define statements. 7.What is Selection Statements?
 A computer program is a set of statements or  Here, the statement (s) are executed depends upon
instructions to perform a specific task. a condition.
There are two kinds of statements used in C++.  If a condition is true, a true block (a set of
(i) Null statement statements) is executed otherwise a false block is
(ii) Compound statement executed.
2.What is Null statement? What is the use of null or  This statement is also called decision statement.
empty Statements?  Two types of selection statements,
 The " null or empty statement" is a statement i) if ii)switch …case
containing only a semicolon ( ; ). 8.What is Iteration statement?
 Null statements are commonly used as placeholders  It is also called Looping Statement.
in iteration statements.  An Iteration statement is a set of statements that
3.What is Compound statement ? are repeatedly executed until a condition is
 C++ allows a group of statements enclosed by TRUE.
pair of braces {}.  These statements are also called as control flow
 This group of statements is called as a statements.
compound statement or a block.  C++ supports three types of iteration statements.
{  They are, i) for ii) while iii) do…while
Statement 1; 9.Explain if statement with an example.
Statement 2; Syntax:
… if (expression)
} {
4. Differentiate between sequential flow and control True – Block;
flow? }
Sequential flow control flow. Statement x ;
The Statements are The statements are
executed sequentially executed like branching,  It is a selection statement
Iteration, jumping and In if statement,
function calls  if the condition is true then a true block- is
executed, otherwise the true-block is skipped.
5.What is control statement.?  Statement x is executed.
 Control statements are statements that alter the #Include<iostream.>
sequence of flow of instructions. Using namespace std; Here,
 There are three kinds, They are int main() if condition is
1)Sequence Statement { True(Nonzero),
2) Selection Statement. clrscr(); Eligible for Vote
3)Iteration ( Loop) Statement. int a; Good Bye
6.What is Sequential Statements? cin>>a; will be Display.
 The sequential statement are executed one after if(a>=18) Otherwise control
another only once from top to bottom. cout<<”Eligible for Vote..”; jumps to Good Bye.
 These statements do not alter the flow of cout<<”\nGood Bye”;
execution. getch();
 They are always end with a semicolon (;). }

13
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

10.Explain if …else statement with an example. If condition 1 is TRUE and Condition 2 is FALSE
Syntax: False block 2 will be executed
if (expression) Case3
{ If Condition 1 is FALSE
True – Block; False block 1 will be executed.
}
else 2. Nested if inside else part
{ Syntax:
False- block; if(condition-1)
} {
Statement – x ; TRUE block 1;
}
 if the condition is true then a true block- is else
executed, False-block is skipped. {
 if the condition is False then a true block- is if (condition-2)
skipped, False-block is executed. { True block 2 }
#Include<iostream> else
Using namespace std; Here,if condition { False block 2 }
int main() is True(Nonzero), }
{ Eligible for Vote 3. Nested if inside both if part and else part
int a Good Bye if(condition-1)
cin>>a; will be Display. {
if(a>=18) Otherwise control if (condition-2)
cout<<”Eligible for Vote”; jumps to elseand { True block 2 }
else Not Eligible for else
cout<<”Not Eligible for Vote”; Vote { False block 2 }
cout<<”\nGood Bye”; Good Bye. }
} will be executed. else
11.Explain Nested if statements with suitable example. {
An if statement contains another if statement is called if (condition-3)
nested if statement. It has three forms. { True block 3 }
1.Nested if inside if part else
2. Nested if inside else part { False block 3 }
3. Nested if inside both if part and else part }
12.Explain if -else-if ladder statement with an example.
1. Nested if inside if part  The if-else ladder is a multi-path decision making
If(condition-1) statement.
{ In this type of statement,
if (condition-2)  'if' is followed by one or more else if statements
{ True block 2} and finally end with an else statement.
else Syntax:
{ False block 2} if(condition-1)
} { block – 1}
else else if (condition – 2 )
{ { block – 2}
False block 1; else if (condition – 3 )
} { block – 3}
else
{ default block}

 When the respective Condition becomes TRUE, the


Case 1 respective block is executed and skipped from
If condition 1 & condition 2 are TRUE ladder.
True Block 2 will be executed  If none of the conditions is true, then the final else
Case 2 statement will be executed.

14
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

Example.  When the expression is evaluated and if its value


#Include<iostream> matches against the case value,
Using namespace std;  that respective set of statements are executed.
int main()  Otherwise, the default statements are executed.
{ Example:
int a,b,c; #Include<iostream>
cin>>a>>b>>c; Using namespace std;
if (( a>b)&& (a>c)) int main()
cout<< " A is greater " ; {
else if (( b>a) &&( b>c)) int n;
cout<< " B is greater " ; cin >> n;
else switch (n)
cout<< " C is greater " ; {
} case 1 : cout << “\nONE”; break;
13.Explain conditional operator with an example. case 2 : cout << “\n TWO”; break;
 The conditional operator(?:) (or Ternary operator) default : cout << “\nEnter only 1 & 2”;
is an alternative for ‘if else statement’. }
 It takes three operands. }
Syntax: Condition ? expression 2 : expression 3 Working of a program
* If n=1
* case 1 statement will execute directly and terminated
by break;
* If switch expression gets other then the case value
 if the condition is true (Non-zero), default statement will execute
 then the control is transferred to expression 2,
otherwise, the control passes to expression 3. 15.Differentiate between switch and if…else
Example: statement.
#Include<iostream> if…else switch
Using namespace std; Expression decide whether Expression decide
int main() if block or else block is which case to execute
{ execute.
int a, b, l; Uses multiple expression Uses single expression
cout << "\n Enter any two numbers: "; for multiple choices. for multiple choices
cin >> a >> b; It checks equality or logical It checks only for
l = (a>b)? a : b; expression expression
cout << "\n Largest number : " << l; It evaluates It evaluate only
} integer ,char ,float,pointer char,int and enum
14.Explain switch statement with an example. or Boolean data type data type
 The switch statement is a multi-way branch If expression is false, else If expression is false,
statement. statement will be execute. default statement will
 Based on a condition, the control is transferred to be execute.
one of the many possible points. Difficult to edit Easy to Edit
 The switch statement replaces multiple if-else
statement.

Syntax:
switch (expression/variable) 16.Explain Nested switch statement.
{  When a switch statement contains another switch
case 1 : action block 1; break; statement is called as nested switch statement.
case 2 : action block 2; break;  The inner switch and the outer switch constant may
default : action block 3; or may not be the same.
}
In the above syntax,

15
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

Syntax Test-expression is placed Test-expression is placed


switch( Expression1) at the beginning of the at the end of the body of
{ body of the loop the loop
case 1 : { First the test-expression First the body of the loop
switch(Expression 2) is evaluated. is executed
case 1: statements1; break; The body of loop will be The body of loop will be
case 2: statement 2; break; executed only when executed at least one
…………………….. condition is true time
default : statement;
}; break: Ex.for , while do…while
case 2: statement; break;
………. 20.Explain for loop with an example
default: statement;  It is an Entry controlled loop.
}  The condition (Test –Expression) placed at the
beginning of the body of the loop.
17.Explain an Iteration or Loop statements ( or )  for loop contains initialization , test expression and
Define Iteration Statements update expression but these are optional.
 It is also called Looping Statement. Syntax:
 An Iteration statement is a set of statements that for(Initialization ; test-Expression ; update expression)
are repeatedly executed until a condition is {
TRUE. Statements;
 These statements are also called as control flow }
statements. Statement – x;
 C++ supports three types of iteration statements. General working for loop
 They are, i) for ii) while iii) do…while 1.First the control variable is initialized
18.Explain the Parts of a loop. 2. Then to condition.
Every loop has four elements .They are 3. If the condition is false, the control transferred to
• Initialization expression statement-x.
• Test expression 4. If the condition is true, the body of the loop is
• Update expression executed,
• The body of the loop 5. Next the control is to update expression.
Initialization expression(s): 6.After this, the control is again transferred to the
 The control variable(s) must be initialized before condition.
enters into loop. 7.Next the steps 3 to 5 is repeated.
 The initialization expression is executed only once in Example:
the beginning of the loop. #Include<iostream>
Test Expression: Using namespace std;
 The test expression is an expression or condition. int main()
 If condition is TRUE, the loop-body will be execute. )
otherwise the loop is terminated. {
Update expression: for(int n=1;n<5;n++)
 It is used to change the value of the control {
variable. cout <<n
}
The body of the loop: }
 A statement or set of statements forms a body of
the loop that are executed repetitively. In the above program,
Step 1 .Control Variable n gets1
19.What are the difference between Entry controlled Step 2.Next n is compared with 5,
loop and Exit controlled loop?. Step 3 conditions true so 1 is printed on screen
Step 4 n incremented by 1 so n is 2
Entry controlled Exit controlled Seep 2 to 4 is repeated. Till condition gets false.

16
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

21.Why always prefer prefix increment/decrement }


operator over postfix when to be used alone? }
 Because prefix operators are executed faster than In the above program,
postfix. Step 1 .Control Variable n gets 1
23.Give an example of infinity loop and empty loop Step 2.Next n is compared with 5,
for( int i=0 ;; i++) - infinity loop Step 3 condition true so 1 is printed on screen
for( ; ; ) - infinity loop Step 4 n incremented by 1 so n gets2
24.What is an empty loop? Seep 2 to 4 is repeated. Till condition gets false
 Empty loop means a loop has no statement in its
body is called an empty loop. 27.Explain do..while loop with an example.
Ex.for( int i=0 ; i<4 ; i++);  do.. while is an Exit controlled loop,
25.What is the output of the following code?  The condition placed at the end of the body of the
int i; loop.
for(i=0;i<=5;i++);  The body of loop will be executed at least one time.
{ cout<< “ We are Indians”; } Syntax:
 It is an infinity loop Initialization;
 In the above code, the body of a for loop enclosed do
by braces is not executed. {
26.Explain While loop with an example. statement;
 It is an Entry controlled loop. update expression;
 The condition (Test –Expression) placed at the } while (condition);
beginning of the body of the loop. Statement-x;
 A while loop may contain several variations.
 It can be an empty loop or an infinite loop. General working do..while loop
Syntax: 1.Firstthe control variable is initialized.
Initialization; 2.The body of the loop is executed, and update
while ( Test expression ) expression.
{ 3.Then to condition.
Body of the loop; 4 . If the condition is false, the control transferred to
Update expression; statement-x.
} 4. If the condition is true, the body of the loop is
Statement-x; executed, .
General working while loop Example
1.First the control variable is initialized the first time #Include<iostream>
2. Then to condition. Using namespace std;
3 . If the condition is false, the control transferred to int main()
statement-x. {
4. If the condition is true, the body of the loop is Int n=1;
executed, do
5. Next the control is to update expression. { cout <<n
6.After this, the control is again transferred to the n++;
condition. }while(n <3);
7.Next the steps 3 to 5 is repeated }
getch(); }
Example:
#Include<iostream> Output In the above program,
Using namespace std;  Control Variable n gets 1
int main() 1234  1 is printed on screen
{  n increment by 1
int n=1;  Next n is compared with 3,
while(n<5)  If it is true ,the body of loop is executed.
{  If it is False, exit from the loop.
cout <<n;
n++;

17
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

28.Explain Nesting of Loop with an example. int a,b;


 A loop which contains another loop is called as a cin>>a>>b;
nested loop. if(a>b)
 The inner loop must be completely nested inside goto true;
the body of the outer loop. else
 An outer loop and inner loop cannot have the same cout<<”B is greater”;
control variable, as it will lead to logical errors.
Syntax: Break Continue
Loop 1() for(int i = 1; i <= 3; i++) Break is used to exit continue statement
{ { the current loop only forces the loop to
Loop 2() int j = 1; . execute the next
{ while (j <= i) iteration following
block 2; { statements will be
} cout << “* “; skipped
block 1; j++; Break is used with loops Continue is only used
} } as well as switch case. in loops, it is not used
cout << ‘\n’; in switch case.
} true:
cout<<”A is greater”;
working of the above program: getch()}
The iterations of the nested loops are as follows;
For loop While loop 30.Difference between Break and Continue
I=1 Is executed once(j<=1)
I=2 Is executed twice (j=1,2) Answers to all the questions (2 Marks):
I=3 Is executed thrice(j=1,2,3) 1. What is a null statement and compound statement?
28A)Define jump statements 1
 Jump statements are used to interrupt the normal 2. What is selection statement? write it's types?7
flow of program. Types of Jump Statements are 3. Correct the following code segment:
• goto statement if (x=1)
• break statement p= 100;
• continue statement else
29.Explain goto statement with an example (or) p = 10;
explain unconditional statement in C++. correction : (x==1)
 The goto statement is a control statement. 4. What will be the output of the following code:
 It is an unconditional statement. int year;
cin >> year;
 It is used to transfer the control from one place to
if (year % 100 == 0)
another place without any condition in a program.
if ( year % 400 == 0)
Syntax: Syntax cout << "Leap";
goto label; Label: else
………………. ….. cout << "Not Leap year";
……………….. …….. If the input given is (i) 2000 (ii) 2003 (iii) 2010?
………………. goto Label; 5. What is the output of the following code?
Label:
for (int i=2; i<=10 ; i+=2)
cout << i;
Here ,
6. Write a for loop that displays the number from 21 to
 Label is an identifier.
30.
 When goto label; is encountered, the control of
7. Write a while loop that displays numbers 2, 4, 6,
program jumps to label: and executes the code
8.......20.
below it.
8. Compare an if and a ? : operator.
Example:
#Include<iostream>
Using namespace std;
int main()
{

18
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

UNIT -III INTRODUCTION TO C++ CHAPTER


11
Functions

1.Define Functions. What is functions ? What ate the puts()


advantage of functions in C++?  It prints the string read by gets() function in a
 A large program can be split into small sub- newline.
programs (blocks) called as functions. 5.Explain few Character functions(ctype.h) in C++.
 Functions are the executable segments in a  The header file ctype.h is to be included to use
program. Character functions in a program.
 Functions are the building blocks of C++ programs isalnum()
Advantage of function  It is used to check whether a character is an
 Reduce the size of the program. alphanumeric or not.
 Reusability of code  It returns 1 if a character is an alphanumeric.
Functions can be classified into two types. Otherwise it returns 0.
1.Pre - Defined or Build – in or Library functions. Syntax: int isalnum (char c);
2.User - Defined Functions. isalpha()
2.Differentiate between Pre - Defined and  It is used to check whether a character is an
User - Defined Functions. alphabet or not.
Pre - Defined User - Defined  It returns 1 if a character is an alphabet .
Functions. Otherwise it returns 0.
These are already Create new functions Syntax: int isalpha (char c);
written, debugged and to perform specific isdigit()
compiled for various task. task by the user.  It is used to check whether a character is a digit
Definition are stored in The name of task and or not.
Header Files. data required are  It returns 1 if a character is a digit.
decided by the user. Otherwise it returns 0.
Ex. gets(),strlen() Ex. int add(int r); Syntax :int isdigit (char c);
3.Define Header file. islower()
 Declaration and definitions for pre-defined  It is used to check whether a character is in
functions are grouped and stored in files called lower case or not.
Header files.  It returns 1 if a character is a lower case .
 It is also called as Library files. Otherwise it returns 0.
 Their file extension is .h Syntax: int islower (char c);
 A single header file may contain multiple pre isupper()
defined functions.  It is used to check whether a character is in
Ex.stdio.h , iostream.h ,conio.h , string.g , iomanip.h upper case or not.
4.Explain some Standard input/output(stdio.h)  It returns 1 if a character is a upper case .
predefined functions in C++. Otherwise it returns 0.
The header file stdio.h is to be included to use Syntax :int isupper (char c);
Standard input/output functions in a program 6.Explain some string functions in C++.(string.h)
getchar() strcpy()
 It is used to get a single character from keyboard  The strcpy() function takes two arguments: target
putchar() and source.
 It is used to to display a single character.  It copies the character string by the source to the
gets() memory location by the target.
 It reads a string from standard input and stores it  The null character (\0) is also copied.
into the variable. Syntax: strcpy(target,source);
 It treats spaces as part of string

19
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

strlen() 9.Define Function Definition.


 The strlen() returns length of a character.  A function must be defined before it is used
 The length does not include the null(\0) character. anywhere in the program.
Syntax: strlen(source);
strcmp() Syntax:
 It is used to compares(ASCII values are compared) Return_Data_Type Function_name(parameter list)
the two given strings. {
 if string1 = string2 (equal) it returns 0 Body of the function
 if string1 > string2 it returns 1(Positive) }
 if string1< string2 it returns -1 (Negative) 10.Define function prototype.
syntax: strcmp(string 1,string2);  Functions should be declared before they are used
strcat() in a program.
 It is used to merge two strings: target and source  function prototype is used to declare a function .
syntax: strcat(target,source);  The declaration statement may be given outside the
strupr() main() function.
 The strupr() function is used to convert the given  It helps the compiler to check the data requirement
string into Uppercase letters. of the function.
strlwr() syntax
 The strlwr() function is used to convert the given Return type function name(arguments);
string into Lowercase letters. 11.What are the information the prototype provides to
7.Explain some of Mathematical functions (math.h) in the compiler ?
C++. The prototype provides the following information to the
Mathematical functions are defined in math.h header compiler:
file . 1.Number and type of arguments
cos() 2.The type of return values
 The cos() function takes a single argument in 3.Name of the function.
radians. syntax
 It returns the value in the range of [-1, 1]. Return type function name(arguments);
 The returned value is either in double, float, or long 12.Write the information to the compiler from the
double. following prototype. long fact(int a ,double b);
sqrt()  The return data type is long.
 The sqrt() function returns the square root of the  fact is the name of the function.
given value of the argument.  The function is called with two arguments:
 It takes a single positive value only  The first argument is of int data type.
 otherwise , a domain error occurs.  The second argument is of double data type.
sin() 13.What are the uses of void ?
 The sin() function takes a single argument in  To indicate the function does not return a value
radians.  To declare a generic pointer.
 It returns the value in the range of [-1, 1]. Ex. void fun(void)
 The returned value is either in double, float, or long In above example, fun function neither receives
double. value from calling nor return value to the calling
pow() statement,
 The pow() function returns the power of exponent. 14.Differentiate between actual parameters and
 If any value passed to pow() is long double, the formal parameters.
return type is promoted to long double. Actual parameters Formal parameters
 If not, the return type is double. Parameters The parameters
 The pow() function takes two arguments: associated with call associated
1. base 2. exponent statement is called with function header is
Syntax: pow(base,exponent) ;Ex . pow(3,2); actual parameters. called formal parameter.
8.How to generate Random Numbers in C++ It is within calling It is within function
 strand() and rand() are used to generate Random statement. definition
Numbers. Only variables are The constant, variables or
 By default the seed for rand() is 1. used expressions are used.
 They are defined in <cstdlib.h> or <stdlib.h)

20
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

15.How to access a function? 19.Explain call by value in C++ with an example.


 A function can be called or invoked from another  In this method, the formal parameter creates new
function by using its name and the required variables and stores the value from actual
arguments. parameter
 The compiler refers to the function prototype to  This method copies the values of actual parameters
check whether the function has been called into the formal parameters
correctly.  Any change in the formal parameter is not reflected
 If the argument type does not match exactly with back to the actual parameter.
the prototype, the compiler will perform type Ex.
conversion, if possible. #include <iostream >
otherwise, the compiler generates an error using namespace std;
message. void swap (int a)
Ex . swap(x,y); ` { a=8;
16.Explain Default arguments with an example. cout << ‘\n’<< a;
 The default value is given in the form of variable }
initialization. Ex : void area (int n1=10, n2=100); int main ( )
 The default arguments facilitate the function call {
statement with partial or no arguments. int m1 = 10;
 The default values can be included in the function cout <<m1 ;
prototype from right to left, swap (m1);
 Default value cannot be include between the cout << ‘\n’<< m1;
argument list. }
Ex : void area (int n1=10, n2);//invalid prototype Note:
void area(int n1, n2 = 10);//valid prototype m1 -> Actual parameter
Example a -> Formal Parameter
#include <iostream > Output:
using namespace std; 20.Explain call by reference in C++ with an example
80
int area (int l = 10, int b=20)  In this method, formal parameters become alias to
{ return (l * b); } the actual parameters.
void main ( )  It is working on the original data.
{ int s1 = 4, s2 = 6;  Any change made in the formal parameter is
cout <<area (s1); reflected back in the actual parameter
} Ex.
17.Define constant argument. What is const modifier? #include <iostream >
 The constant variable can be declared using const using namespace std;
keyword.
Output:
 The constant variable should be initialized while void swap (int &a)
declaring. { a=8; 10
 The const modifier enables to assign an initial value cout << ‘\n’<<a;
to a variable that cannot be changed later inside } 8
the body of the function. int main ( )
Syntax : const datatype variable=value; { 8
Example: const int a=10; int m1 = 10;
cout <<m1 ;
18.Explain the Methods of calling functions. swap (m1);
What are the different ways of passing parameters in cout << ‘\n’<< m1;
C++ functions? }
 The call statement communicates with the function Note:
through arguments or parameters. m1 -> Actual parameter
 There are two ways of passing parameters in C++ a -> Formal Parameter
functions .
1.Call by value 2. Call by reference.

21
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

cout<<display();
21.Explain inline function with example }
 An inline looks like a normal function in the source  The name of the function is display(),
file but inserts the function’s code directly into the  its return type is int and it does not have any
calling program. argument.
 To make a function inline, insert the keyword  The return statement returns a value of a (10) to
inline in the function header the calling function .
(Ex inline void swap (int a)) 3. A Function without return value and with parameter
 inline keyword is just a request to the compiler #include <iostream >
Sometimes the compiler will ignore the request using namespace std;
Advantages of inline functions: void display( int a)
• Inline functions execute faster but requires more {
memory space. cout<<a;
• Reduce the complexity of using STACKS. cout<<"Without return value& with parameter ";
Ex. }
#include <iostream > int main()
using namespace std; {
inline void swap (int a) int x=10;
{ a=8; display(a);
cout << ‘\n’<< a; }
} The name of the function is display(),
int main ( ) its return type is void and it has one parameters (int
{ a).
int m1 = 10; 4. A Function with return value and with parameter
cout <<m1 ; #include <iostream >
swap (m1); using namespace std;
cout << ‘\n’<< m1; int display( int a)
} {
22.What are the different forms of user defined Int b=5
function ? Int c=a+b;
1. Function without return value and without cout<<"With return value& with parameter ";
parameter return c;
#include<iostream.h> }
void display() void main()
{ {
cout<<"No return value& without parameter "; int x=10;
} cout<< display(a);
void main() }
{ The name of the function is display(), its return type
display(); is int and it has one parameter.
} The return statement returns with c value to the
In the above program, The name of the function is calling statement.
display(), its return data type is void and it does not 23.Define return statement in C++.
have any argument.  The return statement is used to return from a
2.A Function with return value and without parameter function to the calling function.
#include <iostream >  It is a jump statement.
using namespace std;  A return may or may not have a value associated
int display() with it.
{  A return statement without parameter can be used
Int a =10; to terminate the function.
cout<<"With return value& without parameter "; Syntax: return expression/variable;
return a; Example : return(a+b); return(a); return;
}
void main()
{

22
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

24.Explain the returning value in C++? 2. Function scope


 The functions that return no value is declared as  The variable declared within a function
void.  The scope of variable is extended to the function
 Default return data type is int. block, and all sub-blocks.
 if no data type is explicitly mentioned, it is treated  The life time of a function scope variable, is the life
as int. time of the function block.
Ex. int add (int, int); add (int, int);  Formal parameters is a function scope
In both prototypes, the return value is int, 3. File scope
float area(float); float  The file scope variable is also called as global
char name(); char variable.
25.Explain the Returning by reference in C++?  The file scope of variable declared above main ( ).
#include <iostream >  The life time of a file scope variable is the life time of
using namespace std; a program.
int main() #include <iostream >
{ using namespace std;
int a=150; Int b=10;
int &b=a; void swap (int a)
cout<<a<<’\t’<<b; { int c = a+b;
b++; cout << c;
cout<<’\n’<<a<<’\t’<<b; }
} int main ( )
 The variable b is alias to a. {
 Hence the value of b is altered automatically int m1 = 10;
when the value of a is changed. cout <<m1 ;
 The two variables a,b shares same memory or swap (m1);
reference. cout << ‘\n’<< m1;
26.What is Recursive function ? }
A function that calls itself is known as recursive function. Here,
Example: a - Function scope variable b - File scope variable
int add(int a,int b) c - Local variable
{ 4. Class scope
……  A class is a new way of creating and implementing a
…..add(a,a+b); user defined data type.
 Access specifiers are , Private , protected and public.
} class name
void main() {
{ Private:
add(x,y); { declaration; }
} Protected:
27.Explain about the different scopes of a variable in { declaration; }
C++ with an example. Public:
 Scope refers to the accessibility of a variable. { declaration; }
There are four types of scopes in C++. };
They are: 1. Local scope, 2. Function scope, 3. File 28.Explain the use of scope operator with an example?
scope 4.Class scope  :: is called scope resolution operator
1. Local scope  It is used to refer variables declared at file level.
 A local variable is defined within a local block.  It is used when the local and file scope variables
 A local variable cannot be accessed from outside the have the same name.
block of its declaration. Example: #include <iostream >
 A block of code begins and ends with curly braces{ }. using namespace std;
 It is created upon entry into its block and destroyed int x=45;
upon exit . int main() {
int x = 10;
cout << ::x + x; } Output: 55

23
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

UNIT -III Introduction of C++ CHAPTER


12
Arrays and Structures
1.What is an Arrays? #include <iostream>
using namespace std;
 An array is a collection of variables of the same type int main()
that are referenced by a common name. {
 It is derived data type. int num[5];
There are different types of arrays used in C++. They for(int i=0; i<5; i++)
are: {
 One-dimensional arrays cin>>num[i];
 Two-dimensional arrays }
 Multi-dimensional arrays }
2.Define One-dimensional array In the above program, a for loop has been constructed
 This is the simplest form of an array. to execute the statements within the loop for 5 times.
 A one dimensional array represents values that are 6.How to Accessing array elements
stored in a single row or in a single column.  Array elements can be used anywhere in a
Declaration program like a normal variable.
Syntax:  The elements of an array are accessed with the
data type array_name [size]; array name followed by the subscript index within
Example: the square bracket.
int num[10]; Ex. cout<<num[3];
3.State the following array declaration are valid or The following for statement is used to display the
Invalid. values.
(a)int array [100.5]; - invalid for(int i=0; i<5; i++)
(b)int a [10]; - valid {
(c)char name [15]; - valid cin>>num[i];
(d)const j = 15; double val [ j ]; - valid }
(e)int d[ ] ={ 1, 2, 3, 4, 5, 6, 7 } - valid 7.What is Traversal in an Array?
4.Write a statement for the following.  Accessing each element of an array at least
(a) Read 6 th element = cin >> n [5] once to perform any operation is known as
(b)assigns the contents of the 4 th element of the array “Traversal”.
to its 5 th element = n [4] = n [3]  Displaying all the elements in an array is an example
(c) increments the value stored as 5 th element by 1 of “traversal”.
= n [4] ++ 8.What are strings? Give an example.What is Array of
5.Explain the types of Array Initialization Characters?
 An array can be initialized at the time of its  A string is defined as a sequence of characters
declaration. where each character may be a letter,number or a
 Unless an array is initialized, all the array elements symbol.
contain garbage values.  Each element occupies one byte of memory.
Syntax:  Every string is terminated by a null (‘\0’)
Datatype array_name [size] = {val-1,val-2,. ,val-n};  a string as an one-dimensional character array.
Ex. int a[3] = { 2,3,4); To declare Character array
a[1] = 5; a[0]= 10; Syntax: char array_name[size];
More examples of array initialization: #include <iostream>
float x[5] = {5.6, 5.7, 5.8, 5.9, 6.1}; void main()
char vowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'}; {
Accepting values to an array during run time : char country[6];
by using cin cin>>a[2] ;

24
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

cout<< "Enter the name of the country: "; Ex. int n [2] [3] = (2 x 3) x 2 = 12 bytes
cin>>country; 15.How to initialize a two dimensional array .
cout<<" The name of the country is "<<country;  The array can be initialized in more than one way at
} the time of 2-D array declaration.
OUTPUT Ex. int a [2][2] = { {1,2},{3,4}};
Enter country the name: INDIA  Array’s row size is optional but column size is
The country name is INDIA compulsory.
9.How to Initialize one dimension character array ?  Accessing the two-dimensional array
 The character array can be initialized at the time of A[0][1] = 10; assign 10 to 2nd element of first row
its declaration. The syntax is shown below: 16.Define Memory representation of 2-D array
char a_nam[size]={ list of characters separated by  A 2-D array is stored in sequential memory blocks.
comma or a string } ;  There are two types of 2-D array memory
char country[6]=“INDIA”; representations. They are:
char country[6]={‘I’, ‘N’, ‘D’, ‘I’, ‘A’, ‘\0’}; Row-Major order
char country[]=“INDIA”;  In row-major order, all the elements are stored row
char country[]={‘I’, ‘N’, ‘D’, ‘I’, ‘A’, ‘\0’}; by row in continuous memory locations,
Column-Major order
 During initialization, the array of elements cannot  In column-major order, all the elements are stored
be initialized more than its size. column by column in continuous memory locations,
char str[2]={'5','+','A','B'}; // Invalid 17.What is array of string?
 An array of strings is a two-dimensional character
10.Define cin.get(). array.
 In C++, cin.get() is used to read a line of text  The size of first index (rows) determines the number
including blank spaces. of strings and the size of second index determines
 This function takes two arguments. maximum length of each string.
 The first argument is the name of the string and Ex. char day[2][10] ={“Sunday \0”,“Monday\0”};
second argument is the maximum size of the array. S u N d a Y \0
char str[100]; M O N D A Y \0
cin.get(str, 100); 18.Write a C++ program to accept and print your
Name.
11.Define cin.getline() #include <iostream>
 In C++, getline() is also used to read a line of text using namespace std;
including blank spaces from the input stream. int main()
 It can read the characters till it encounters a newline {
character or a delimiter specified by the user. char n[]=”ELANGO”;
 This function is available in the <string.h> header. cout<<”Myname is …”<<n;
12.Define Two-dimensional array }
 Two-dimensional (2D) arrays are collection of 19.How will you pass two dimensional array to a
similar elements where the elements are stored in function explain with example?
certain number of rows and columns.  In C++, arrays can be passed to a function as an
ex.int arr[3][3]; argument.
13.How to Declare 2-D array in C++? Write the syntax  The actual parameter is passed only the array
of Declaration of 2-D array. name as an argument ignoring dimensions.
data-type array_name[row-size][col-size]; Passing a two-dimensional array to a function
Ex. int a[3][4]; #include <iostream>
 Array size must be Positive integer value using namespace std;
 In arrays, column size is compulsory but row size is int main()
optional. {
14.How to calculate the size of the array? int marks[5]={88, 76, 90, 61, 69};
one dimension array size = memory required (data display(marks);
type ) x No. of the elements in the array }
Ex. int n[5] = 2 x 5 = 10 bytes ( one integer is 2 bytes)
Two dimension array = Number of elements (Row x
column ) x memory required

25
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

void display (int m[5]) sum[i][j]=m1[i][j]+m2[i][j];


{ cout<<sum[i][j]<<’\t’;
for (int i=0; i<5; i++) }
{ }
cout << m[i]; getch();
} }
}
20.Write a C++ program to find the sum of two matrix.
#include <iostream>
Structures …
using namespace std;
int i;
22.What is Structure? Or Define Structure.
int main()
{  Structure is a user-defined data type.
int m1[10][10], m2[10][10], sub[10][10];  This allows to group of variables with different
cout<< "Enter the elements of first matrix:\n "; data types together into a single unit.
for (i = 0;i<2;i++ ) 23. Declaring and defining structures
for (j = 0;j<2;j++ ) Structure is declared using the keyword ‘struct’.
cin>>m1[i][j]; Syntax:
cout<< "Enter the elements of second matrix:\n "; struct structure_name
for (i = 0;i<2;i++ ) {
for (j = 0;j<2;j++ ) type member_name1;
cin>>m2[i][j]; type member_name2;
cout<<"Output: \n"; } object ;
for (i = 0;i<2;i++ )
for (j = 0;j<2;j++ ) 24.Define global objects.
{  Objects declared along with structure definition are
sub[i][j]=m1[i][j] - m2[i][j]; called global objects
cout<<sub[i][j]<<’\t’; 25.What is an Anonymous Structure?
}  A structure without a name/tag is called anonymous
} structure.
getch(); struct
} {
21.Write a C++ program to find the difference between long rollno;
two matrix. int age;
#include <iostream> float weight;
using namespace std; } student;
int i; 26.To store 100 integer number which of the following
int main() is good to use? Array or Structure
{ Array because Array is a set of variable of same data
int m1[10][10], m2[10][10], sum[10][10]; type
27.What is the error in the following structure
cout<< "Enter the elements of first matrix:\n "; definition.
for (i = 0;i<2;i++ ) struct employee
for (j = 0;j<2;j++ ) {
cin>>m1[i][j]; Int eno;
Char ename[20];
cout<< "Enter the elements of second matrix:\n "; char dept;
for (i = 0;i<2;i++ ) }
for (j = 0;j<2;j++ ) Employee e1,e2;
cin>>m2[i][j];  Structure is not terminated with ;
 Data type and variable name should be separate(int
cout<<"Output: \n"; eno; char ename;)
for (i = 0;i<2;i++ )  In Structure tag Employee e should be in small
for (j = 0;j<2;j++ )
{

26
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

Correct definition Ex. x.rollno , x.age .


struct employee 33.How pointer type elements reference in structure?
{  If the members are a pointer types then ‘->’ is used
int eno;  to access the members.
char ename[20];  Let name is a character pointer ins student like
char dept; char * name
};  It can be accessed student -> name
employee e1,e2; 34.What are the different ways to initialize the
28.Write a structure definition for the structure structure members?
student containing examno, name and an array for How values are assigned to structure elements?
storing five subject marks. How to Initializing structure elements?
struct student  Values can be assigned to structure elements similar
{ to assigning values to variables.
int examno; balu.rollno= “702016”;
char name; balu.age= 18;
int marks[5]; balu.weight= 48.5;
};  Also, values can be assigned directly as similar to
29.What is the size of the following highlighted assigning values to Arrays.
variable in terms of byte if it is compiled in dev c++ balu={702016, 18, 48.5};
struct A{ float f[3]; char ch[5];long double d;};  Structures can be assigned directly instead of
struct B{ A a; int arr[2][3];}b[3] assigning the values of elements individually.
struct A{ float f[3]; char ch[5];long double d;}; 35.Define Structure Assignments in c++
1.4x3 = 12  Structures can be assigned directly instead of
2.1x 5 =5 assigning the values of elements individually.
3.2+8 =10  Structure assignment is possible only if both
Total = 27 bytes structure variables/objects are same type.
struct B{ A a; int arr[2][3];}b[3] Ex.
4 x 6 = 24 struct student
24+24+24 =72bytes {
30.Is the following snippet is fully correct. If not I
identify the error. int age;
struct sum1{ int n1,n2;}s1; float height,weight;
struct sum2{int n1,n2}s2; } priya,usha;
cin>>s1.n1>>s1.n2; priya ={19,165.7,56.4};
s2=s1; usha=priya;
Error because s1,s2 are separate objects for two It will assign the same age,height and weight to usha.
separate structures. 36.Define nested Structures.
31.Differentiate array and structure.
 The structure declared within another structure is
Array Structure called a nested structure.
An array is a collection This allows to group of Ex.
of variables of the same variables with different struct student
type that are referenced data types together into {
by a common name a single unit. int age;
struct dob
It is a derived data type It is a user-defined data {
type. Int date;
char mon[4];
There are different Only one type int year;
types. }y;
}x;
32.How to referencing structure elements in C++? void main()
How to success members of a structure ?Give example. {
 The structure members can be accessed directly. cin>>x.age >>x.y.date;
 The syntax for that is using a dot (.) between the }
object name and the member name.
27
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

37.Explain Array of Structure with an example. employee p;


 An array of structures is declared in the same way as cout<< "\nEnter Full name: ";
declaring an array with built-in data types like int or cin>>p.name;
char. cout<< "\nEnter salary: ";
For example cin>>p.salary;
 If the class has 20 students, then 20 individual printdata(p);
structures are required. }
 For this purpose, an array of structures can be used. Output:
#include <iostream.h> Enter Full name: Kumar
struct student Enter salary: 34000.0
{ Display
int age; Name: Kumar
float height, weight; Salary: 34000.0
char name[30];  In the above example, a structure name is employee
};  The values are name, age and salary .
void main( )  A function printdata() used to display employee.
{ Call by reference
student std[20];  In this method, the address of a structure variable
int i; /object is passed to the function using address of(&)
for(i=0;i<20;i++) operator.
{  So Any change made to the contents of the
cout<< “ Enter the age:”<< ’\n’; cin>>std[i].age; structure affect the argument of the function.
cout<< “Enter the height:”<< ’\n’; cin>>std[i].height;  Structures are usually passed by reference
cout<< “Enter the weight:”<< ’\n’; cin>>std[i].weight; method because it saves the memory space and
} executes faster.
cout<< “To enter the value…<’\n’; #include <iostream>
for(i=0;i<20;i++) using namespace std;
cout<<”Student ”<<i+1<< “\t”<<std[i].age<< struct employee
“\t”<<std[i].height<< “\t”<<std[i].weight; } {
38.Explain call by value with respect to structure in c++ char name[50];
Explain call by reference with respect to structure in float salary;
c++ };
What are the method to pass structures to function? void printdata(employee &q)
A structure variable can be passed to a function in two {
types 1.call by value 2. Call by reference cout<<”\nDisplay..”;
Call by value. cout<< "\nName: " << q.name ’;
 When a structure is passed as argument to a cout<< "\nSalary: " <<q.salary;
function using call by value method, }
 Any change made to the contents of the structure void main() Output:
do not affect the argument of the function. { Enter Full name:
#include <iostream> employee p; Kumar
using namespace std; cout<< "\nEnter Full name: "; Enter salary:
struct employee cin>>p.name; 34000.0
{ cout<< "\nEnter salary: "; Display
char name[50]; cin>>p.salary; Name: Kumar
float salary; printdata(p); Salary: 34000.0
}; }
void printdata(employee q)
{
cout<<”\nDisplay..”;
cout<< "\nName: " << q.name ’;
cout<< "\nSalary: " <<q.salary;
}
int main()
{
28
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

UNIT -III Object Oriented


Programming with C++
CHAPTER
13
Introduction to Object Oriented Programming with Techniques
1.What is paradigm ?Mention the different types of 4.What are the Main Features of Object Oriented
paradigm? Programming? Advantages of oop.
 Paradigm means organizing principle of a program.  Data Abstraction
 It is an approach to programming  Encapsulation
 They are Procedural programming, Modular  Modularity
Programming and Object Oriented Programming  Inheritance
2.How is modular programming different from  Polymorphism
procedural programming paradigm? 5.How is encapsulation and abstraction are
interrelated? Or
Modular programming Procedural
6.Define encapsulation.
programming
 The mechanism by which the data and functions
Emphasis on algorithm This emphasis on doing
are bound together into a single unit is known
rather than data things.
as Encapsulation
Programs are divided Programs are organized
 It can also be called data binding.
into individual modules into subroutines or sub
7.Define Abstraction
programs
 Abstraction refers to showing only the essential
Each modules are All data items are global
features without revealing background details
independent and have
8.Define Data Hiding or information Hiding.
their own local data
 The members and functions declared under private
Modules can work with Difficult to maintain
are not accessible by members outside the class,
its own data and enhance the
this is referred to data hiding.
Ex.Pascal and C program code .
9.Differentiate classes and objects.
Ex.FORTRAN and COBOL.
Class object
3.Write the differences between Object Oriented
Class is a way to bind the Represents data and its
Programming and procedural programming
data and its associated associated function
functions together. together into a single
Modular programming Object Oriented
unit.
Programming
User defined data type They are instances of
Emphasis on algorithm Emphasizes on data
Class ( class variable)
rather than data rather than algorithm
Class represents a group Basically an object
Programs are divided Data and its associated
of similar objects is created from a class.
into individual operations are
10.What is polymorphism?
modules grouped in to single unit
 Polymorphism is the ability of a message or function
Each modules are Data abstraction is
to be displayed in more than one form.
independent and have introduced
11.What are the Advantages of OOP
their own local data
Re-usability:
Modules can work with Relationships can be
Code can be use any number of times.
its own data. created between similar
Redundancy:
Inheritance is the good feature for data redundancy.
Ex.Pascal and C Ex.C++, Java, VB.Net,
Easy Maintenance:
Python etc.
It is easy to maintain and modify existing code
Security:
Data hiding and abstraction are used to give the
security of data.

29
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

12.Write the disadvantages of OOP.


Size:
 Object Oriented Programs are much larger than
other programs.
Effort:
 Object Oriented Programs require a lot of work to
create.
Speed:
 Object Oriented Programs are slower than other
programs, because of their size.
13.What is Modularity ?
 Programs are divided into individual modules is
called Modularity.
14.Define Software re-use:
 A program can be composed from existing and
new modules

30
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

UNIT -IV Object Oriented


Programming with C++ CHAPTER 14
Classes and objects

1.Define Class in C++.


 Class is a way to bind the data and its associated  It cannot be accessed from outside the class.
functions together. The Public Members
 It is used to create user defined data type.  It can be accessed from within the class by class
2.Write the syntax of Declaration of a class or How to members.
Declare a class in C++?  It can be accessed from outside the class by
General Form using objects.
Class class_name 5.Differentiate between private and public specifier in
{ C++. ( ref. Q4)
private:
variable declaration 6.How to Define class members ?or .What are data
function declaration members and member functions of a class? or
protected: What does a class comprise of?
variable declaration What are class ( called )member?
function declaration Differentiate between Data Members and Member
public: functions.
variable declaration
function declaration  Class Members are classified as Data Members
}; and Member functions.
 A class is defined in C++ using the keyword class Data members
followed by the name of the class.  Data members are the data variables that represent
 The body of a class is enclosed within braces and is the features or properties of a class.
terminated by a semicolon ;  Data members are also called as attributes.
 The class body contains the declaration of  Separate space is allocated for member variables
variables(data) and functions when each object is created
 The class body has three access specifiers ( visibility Member functions
labels) viz., private , public and protected  Member functions are the functions that perform
3.What is the use of Data Hiding in C++? specific tasks in a class.
 The members and functions declared under private  Members functions are called as methods,
are not accessible by members outside the class,  No separate space is allocated for member
this is referred to data hiding. functions when the objects are created.
4.What are the three access specifiers of class 7.What are the methods of defining methods
members? (or) List out the accessibility levels in C++. (functions) in a class?
 The key words public, private, andprotected are Two types.
called access specifiers. (1) Inside the class definition (inline)
The Private Members (2) Outside the class definition (outline)
 It can be accessed only within the class by class (1) Inside the class definition (inline function)
members and friend functions.  A member function is defined inside a class,
 It cannot be accessed from outside the class.  It behaves like inline functions.
 It is a default access specifier.  These are called Inline member functions.
The Protected Members (2) Outside the class definition (outline function)
 It can be accessed from within the class by class  A Member function defined outside the class.
members and from the members of the inherited  It behaves like normal function definition .
classes.  It is called as outline member function or non-inline
member function.

31
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

 Scope resolution operator (::) is used for this


purpose. 11.How memory is allocated to the objects of a class.?
The syntax for defining the outline member function is The member functions are created and placed in the
return_typeclass_name::function_name (parameters) memory space only when they are defined as a part of
{ the class specification.
function definition No separate space is allocated for member functions
} when the objects are created.
Ex. Separate space is allocated for member
void add :: display() variables(data)when each object is created.
{  Separate memory allocations for the objects are
} essential because the member variables will hold
8.Differentiate structure and class though both are different data values for different objects.
user defined data type. 12.What is the size of the objects s1, s2?
structure Class class sum
User defined data type User defined data type { int n1,n2;
struct keyword used class keyword used public:
public as default private as default void add()
9.What is the difference between the class and object {int n3=10;n1=n2=10;
in terms of oop? } } s1,s2;
Class object
Class is a way to bind the Represents data and its
data and its associated associated function
functions together. together into a single
unit.
User defined data type They are instances of S1 = 4+4+4 = 12 Bytes S2 = 4+4+4 = 12 Bytes
Class ( class variable) How are the class members accessed? Or
Class represents a group Basically an object 13.How class members are referencing in C++?
of similar objects is created from a class.  The members of a class are referenced (accessed)
10.What are the methods of creating class object in by using the object of the class followed by the dot
C++? (membership) operator and the name of the
Objects can be created in two methods, member.
(1) Global object (2) Local object
Global Object The general syntax for calling the member function is:
 If an object is declared outside all the function Object_name .function_name(actual parameter);
bodies or Ex. stud.execute();
 Byplacing their names immediately after the closing 14.Define Array of objects.
brace of the class declaration then it is called as  An array which contains the class type of element is
Global object. called array of objects.
 These objects can be used by any function in the  It is declared and defined in the same way as any
program other type of array.
Ex. class xyz Class stu
{ {,…. ……
}a; } a[3];
Local Object Here,a[0],a[1] , a[2] are the array of object of the class
 If an object is declared with in a function then it is stu.
called local object. 15.What is nesting of member functions in C++?
 It cannot be accessed from outside the function.  A member function can call another member
Ex. function of thesame class directly without using
class xyz the dot operator.
{  This is called as nesting of member functions.
}; 16.What are the ways of objects can be passed as
main() arguments?
{ Objects can also be passed in both ways
xyz a; }

32
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

(1) Pass By Value


(2) Pass By Reference
17.Explain how the objects can be passed in pass by void print( )
value method. {
 When an object is passed as argument by cout<<num;
value ,new object is created in formal parameter. }
 The objects from actual parameter copied in to };
formal parameter. int main()
 Any changes made to the object inside the formal {
parameter ,do not affect the actual object. sample s1,s2;
#include <iostream> s2.pass(s1);
using namespace std; s1.print();
class sample return 0;
{ }
private: 19.What is nested class?
intnum;  When one class become the member of another
public: class then it is called Nested class.
void pass(sample obj) 20.What are the ways the classes can be nested?
{ Classes can be nested in two ways.
obj1.num=100; 1. Defining a class within another class
cout<<"\n\n Changed value of object1 "<<obj1.num; 2. Declaring an object of a class as a member to another
} class
void print( ) Defining a class with in another
{  When a class is declared with in another class,
cout<<num;  The inner class is called as Nested class .
}  The outer class is known as Enclosing class.
};  Nested class can be defined in private as well as in
int main() the public section of the Enclosing class.
{ #include<iostream>
sample s1,s2; using namespace std;
s2.pass(s1); class enclose
s1.print(); {
return 0; private:
} int x;
18.Explain how the objects can be passed in pass by class nest
reference method. {
 When an object is passed as argument by private :
reference ,object in formal parameter alias the int y;
object of actual parameter. public:
 The formal parameter works directly on the actual void prn()
object. {
 Any changes made to the object inside the formal y=3;
parameter ,affect the actual object. cout<<y;
#include <iostream> }
using namespace std; };
class sample nest n;
{ public:
private: void square()
intnum; {
public: n.prn();
void pass(sample &obj) x=2;
{ cout<< x * x;
obj1.num=100; }
cout<<"\n\n Changed value of object1 "<<obj1.num; };
}
33
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

int main() class add


{ {
enclose e; public:
e.square(); void add(int a, int b)
} {
cout<<a+b;
In the above program }
 The inner class nest is defined inside the outer class };
enclose. int main( )
 nest is accessed by enclose by creating an object of {
nest Int x,y;
cin>>x>>y;
Declaring an object of a class as a member to another add(x,y); // dynamic initialization
class }
 Whenever an object of a class is declared as a Introduction to Constructors& Destructors
member of another class it is known as a container
class.
23.What is a constructor?
 In the container-ship the object of one class is
 Classes include special member functions called as
declared in another class.
constructors.
#include<iostream>
using namespace std;  The name of the constructor must be same as that
class outer of the class
{  Used to allocate memory space and initialize the
int data; data member of the class object
public:  It has no return type
void get();  Constructor can have parameter list
};  Constructor can be overloaded
class inner  They cannot be inherited but a derived class can call
{ the base class constructor
int value; Syntax:
outer ot; Class class_name
public: {
voidgetdata(); public:
}; class_name()
Intmain() {
{ }
Inner x; };
} 24.What are the functions of constructors?
In the above program 1) To allocate memory space to the object .
 classouter and inner are defined separately. 2) To initialize the data member of the class object
 But both the classes areconnected by the object 25.What are the Characteristics of Constructors? Or
'ot' which is a member of class inner. What are the rules of constructors?
21.What is Container class?  The name of the constructor must be same as that
 Whenever an object of a class is declared as a of the class
member of another class it is known as a container  Used to allocate memory space and initialize the
class. data member of the class object
22.Write the example how will you dynamically  The constructor is executed automatically when the
initialize objects? object is created
 When the initial values are provided during runtime  No return type for constructor
is called dynamic initialization.  A constructor can have parameter list
Example  The constructor can be overloaded
#include<iostream>  They cannot be inherited but a derived class can call
using namespace std; the base class constructor
 Default constructor is public member function

34
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

26.Define constructor overloading. Types of 29.What are the ways to create an object using
constructor. parameterized constructor?
 Function overloading can be applied for There are two ways to create an object using
constructors, are called constructor overloading . parameterized constructor 1)Implicit call 2) Explicit call
Three types of constructors, they are Implicit call
1.Non-Parameterized constructor or default constructor  In this method ,the parameterized constructor is
2.Parameterized constructor invoked automatically whenever an object is
3.copy constructor created.
27.Define Non-Parameterized constructor or default For example simple s1(10,20);
constructor.  In this for creating the object s1 parameterized
 A constructor that accepts no parameter is called constructor is automatically invoked.
default constructor. Explicit call
 In the absence of user defined constructor, the  In this method , the object can be created and
compiler automatically generates default initialized
constructor when the object is created For example simple s1=simple(10,20);
 A default constructor implicitly as an inline public  An explicit call to constructor creates temporary
member. instance(object).
Advantage :
 Default constructors are very useful to create 30.Explain copy constructor with an example.
objects without having specific initial value.  Copy Constructor is a type of constructor which is
 It is also used to create array of objects. used to create a copy of an already existing object of
Ex. a class type.
class add  While defining copy constructor the argument
{ (object) should be passed only by reference not by
public: value method.
add(); Ex, simple (simple&x) - simple- class name.
{
} Calling copy constructors
}; A copy constructor is called
int main() 1.When an object is passed as a parameter to
{ any of the member functions
add x; Example:void simple::putdata(simple x);
} 2.When a member function returns an object
28.Define Parameterized Constructors Example:simple getdata() { }
 A constructor with arguments is called 3.When an object is passed by reference to an
parameterized constructor . instance of its own class
 This type of constructor helps to create objects with Example:simples1, s2(s1); // s2(s1) calls copy
different initial values. constructor
 This is achieved by passing parameters to the
function. 31.How constructors are executed (Order of
 Parameterized constructor can havedefault constructor invocation) ?
arguments.  The constructors are executed in the order of the
Ex. object declared.
class add For example
{ Test t1; Test t2;
public: The order of constructor execution is first for t1 and
add(int a) then for t2.
{ Sample s1,s2,s3 ; //The order of construction is s1 then
} s2 and finally s3
};
int main()  But if a class containing an object of another class as
{ its member then that class constructor is executed
add x(5); first.
}

35
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

32.Define Distructors. 36.Mention the differences between constructor and


 Classes include special member functions called as destructor.
destructor . Constructor Destructor
 The destructor has the same name as the class tag The name of the The destructor has the
prefixed by the ~ (tilde) constructor must be same same name as the
 The destructor is executed automatically when the as that of the class class tag prefixed by the
control reaches the end of class scope ~ (tilde)
 Destructor function removes the memory of an The constructor is The destructor is
object executed automatically executed automatically
when the object is when the control
Syntax: created reaches the end of class
class simple scope
{
Public: Used to allocatememory Destructor function
~simple() space and initialize the removes the memory of
{ data member of the class an object
object
}
}; It has no return type It has no return type
Constructor can have Destructor can nothave
33.What are the rules or Characteristics of parameter list parameter list
Destructors?
 The destructor has the same name as the class tag Constructor can be Destructor cannot be
prefixed by the ~ (tilde) overloaded overloaded
 The destructor is executed automatically when the
control reaches the end of class scope They cannot be inherited They cannot be
 Destructor function removes the memory of an but a derived class can call inherited
object the base class constructor
 It has no return type
 Destructor cannot have parameter list Default constructor is Destructor is public
 Destructor cannot be overloaded public member function member function
 They cannot be inherited
34.Write down the importance of Destructor. class class_name class simple
 The purpose of the destructor is to free the { {
resources. public: Public:
 A destructor function removes the memory of an class_name() ~simple()
object which was allocated by the constructor at the { {
time of creating a object. }
35. Why it is considered as a good practice to define a }; }
constructor though compiler can automatically };
generate a constructor ?
 Default constructors are automatically generate a
constructor
 It simply allocates memory for the object.
 It is also used to create array of objects.

******************

36
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

UNIT -IV Object Oriented


Programming with C++ CHAPTER 15
Polymorphism
1.What is Function overloading? 6.Does the return type of a function help in
 The ability of the function to process the message overloading a function?
or data in more than one form is called as function
overloading. No, The return type of overloaded functions are not
Ex. float area (float r); considered for overloading same data type
float area (float l,float b);
2.What is function's signature? 7.Define Constructor overloading.
 The number and types of a function's parameters  Function overloading can be applied for
are called the function's signature. constructors, called as Constructor overloading .
3.Define Overloaded resolution.  A class can have more than one constructor with
 The process of selecting the most appropriate different signature.
overloaded function or operator is called overload  Constructor overloading provides flexibility of
resolution. creating multiple type of objects for a class.
4.What are the advantages of function overloading? or
What is the use of overloading a function? 8.class add{int x; public: add(int)}; Write an outline
 Function overloading is used to reduces the number definition for the constructor.
of comparisons in a program add ::add(int y)
 It makes the program to execute faster. {
 It also helps the programmer by reducing the y=x;
number of function names to be remembered. }
5.Explain Function over loading with an example. 9.How does a compiler decide as to which function
 The ability of the function to process the message should be invoked when there are many functions?
or data in more than one form is called as function Give an example.
overloading. When you call an overloaded function,
Ex. float area (float r);  The compiler determines the most appropriate
float area (float l,float b); definition to use,
 by comparing the number of argument and their
Rules for function overloading types to call the function definitions.
 The overloaded function must differ in the number  The process of selecting the most appropriate
of its arguments or data types. overloaded function or operator is called overload
 The return type of overloaded functions are not resolution.
considered for overloading same data type area(float r)
 The default arguments of overloaded functions are {
not considered as part of the in function cout<<3.14*r*r;
overloading parameter list. }
Example: area( float l,float b)
#include <iostream> {
using namespace std; cout<<l*b;
float area ( float r ) }
{ return ( 22/7 * r * r );} void main()
float area ( float l, float b ) {
{ return ( l *b ) ;} area(4.6);
void main() area(5.7,4.3);
{ cout<<”circle”<<area(5.2); }
cout<<”Rectangle”<<area(5.3,8.2);

37
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

10.class sale ( int cost, discount ;public: sale(sale &); 15.Define and explain the operator overloading?
Write a non inline definition for constructor specified; Define :
sale :: sale(sale &a)  The mechanism of giving special meaning to an
{ operator is known as operator overloading.
cost=s.cost;  Operator overloading provides new definitions for
discount=s.discount; most of the C++ operators
} The definition of the overloaded operator is given using
the keyword 'operator' followed by an operator symbol.
11.Define Operator overloading Syntax:
 The mechanism of giving special meaning to an Inline:
operator is known as operator overloading. ReturnType operator operatorSymbol(argument)
 Operator overloading provides new definitions for {
most of the C++ operators }
12.List out the operators that cannot be overload in Ex. complex operator +( complex c2)
C++ {
 scope operator (:: ) }
 sizeof Outline:
 member selector ( . ) ReturnType classname : : operator operatorSymbol(argument)
 member pointer selector (* ) {
 ternary operator ( ?: ) }
13.How to define operator overload in C++ Rules or Restrictions on Operator Overloading
 The definition of the overloaded operator is given  Precedence and Associativity of an operator cannot
using the keyword 'operator' followed by an be changed.
operator symbol.  No new operators can be created,
Syntax:  Only existing operators can be overloaded.
Inline:  Cannot redefine the meaning of an operator’s
ReturnType operator operatorSymbol(argument) procedure.
{  Overloaded operators cannot have default
} arguments.
Ex. complex operator +( complex c2)  When binary operators are overloaded, the left
{ hand object must be an object of the relevant class
}
Outline:
ReturnType classname : : operator operatorSymbol(argument)
{
}

14. What are the Rules or Restrictions on Operator


Overloading?
 Precedence and Associativity of an operator cannot
be changed.
 No new operators can be created,
 Only existing operators can be overloaded.
 Cannot redefine the meaning of an operator’s
procedure.
 Overloaded operators cannot have default
arguments.
 When binary operators are overloaded, the left
hand object must be an object of the relevant class

38
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

UNIT - IV Object Oriented


Programming with C++
CHAPTER
16
Inheritance
3. Hierarchical inheritance
1.What is inheritance? What are the advantages of When more than one derived
inheritance? classes are created from a
 It is a process of creating new classes called single base class ,it is known as
derived classes, from existing or base classes. Hierarchical inheritance.
 Inheritance allows us to inherit all the code
(except declared as private) of one class to 4. Multilevel Inheritance
another class  The transitive nature of
The main advantage of inheritance is inheritance.
• It represents real world relationships well  In multilevel inheritance a
• It provides reusability of code derived class itself acts as a
• It supports transitivity base classto derive another
2.What is base class? class.
 A class that is used as the basis for inheritance is
called a superclass or base class. 5. Hybrid inheritance
3.Define derived class. Or why derived class is called A combination of more than
power packed class? one type of inheritance is
 A class that inherits from a superclass is called a known as hybrid inheritance.
subclass or derived class It may be a combination of
 The derived class is a power packed class, as it can Multilevel and Multiple or
add additional attributes and methods and thus Hierarchical and Multilevel or
enhance its functionality Hierarchical,
4.What are the types of Inheritance ?
 There are different types of inheritance viz., Single 6.What are the points to be
Inheritance, Multiple inheritance, Multilevel noted while deriving a new class?
inheritance, hybrid inheritance and hierarchical  The keyword class has to be used
inheritance.  The name of the derived class is to be given after
5.Explain the types of Inheritance. the keyword class
There are different types of inheritance viz., Single  A single colon
Inheritance, Multiple inheritance, Multilevel inheritance,  The type of derivation (the visibility mode ), namely
hybrid inheritance and hierarchical inheritance. private, public or protected.
Default visibility mode is private.
1. Single Inheritance  The names of all base classes(parent classes)
When a derived class inherits separated by comma.
only from one base class, it is class derived_class_name
known as single inheritance. :visibility_modebase_class_name
{
// members of derivedclass
2. Multiple Inheritance
};
When a derived class inherits Ex. Class boys : public student
from multiple base classes it is {
known as multiple inheritance
};

39
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

7.Differentiate between access specifier and visibility  When classes are inherited the private members of
modes the base class are not inherited they are only
 Access specifiers control the accessibility of the visiblei.e continue to exist in derived classes, and
class members with in the class cannot be accessed
 Visibility modes control the access of inherited 9.Differentiate between private and public visibility
members with in the class modes.
8.Explain the different visibility mode in inheritance. Ref.above ans.
 The accessibility of base class by the derived class is 10.What is the size of following class?
controlled by visibility modes. classx
 The three visibility modes are private, protected and {
public. };
 The default visibility mode is private.  A class without any declaration will have 1 byte size.
Private visibility mode So ,x occupies 1 byte.
When a base class is inherited with private visibility,
 The public and protected members of the base class 11.Explains the significance of different visibility modes
become ‘private’ members of the derived class from following program.
#include <iostream>
using namespace std;
class Shape
{
private:
int count;
protected:
int width;
Protected visibility mode int height;
When a base class is inherited with protected visibility. public:
 The protected and public members of the base class voidsetWidth(int w)
become ‘protected members ‘ of the derived class {
width = w;
}
voidsetHeight(int h)
{
height = h;
}
};
class Rectangle: public Shape
Public visibility mode {
When a base class is inherited with public visibility, public:
 The protected members of the base class will be intgetArea()
inherited as protected members of the derived {
class. return (width * height);
 The public members of the base class will be }
inherited as public members of the derived class. };
int main()
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
cout<< "Total area: "<<Rect.getArea() <<endl;
return 0;
}
Output
Total area: 35

40
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

The following table contain the members defined 13.Find the output of the following program.
inside each class before inheritance #include<iostream>
using namespace std;
classbase
{
public:
base()
{
cout<<"\nConstructor of base class...";
The following table contain the details of members }
defined after inheritance ~base()
{
In case the class rectangle is derived with private cout<<"\nDestructor of base class.... ";
visibility mode }
};
classderived:public base
{
public :
derived()
{
cout<< "\nConstructor of derived ...";
}
~derived()
Suppose the class rectangle is derived with protected {
visibility cout<< "\nDestructor of derived ...";
}
};
class derived1 :public derived
{
public :
derived1()
{
cout<< "\nConstructor of derived1 ...";
Suppose the class rectangle is derived with }
publicvisibility ~derived1()
{
cout<< "\nDestructor of derived1 ...";
}
};
int main()
{
derived1 x;
return 0;
12.WriteSome Facts about the execution of constructor }
in inheritance. Output:
 Base class constructors are executed first ,before Constructor of base class...
the derived class constructors execution Constructor of derived ...
 Derived class can not inherit the base class Constructor of derived1 ...
constructor. Destructor of derived1 ...
 If there are multiple base classes ,then its start
Destructor of derived ...
executing from the left most base class
 In multilevel inheritance, the constructors will be
Destructor of base class....
executed in the order of inheritance

41
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

14.How the size of derived class object is calculated? char address[25];


Size of derived class object = double turnover;
Size of all base class data members + size of all protected:
derived class data members. char phone[3][1O];
void register();
15.What do you mean by overriding /Shadowing? public:
 When a derived class member function has the publisher();
same name as that of its base class member ~publisher();
function , void enter data();
 The derived class member function shadows/hides voiddisp data();
the base class’s inherited function . };
 This situation is called function overriding
/Shadowing . class branch
 This can be resolved by giving the base class name {
followed by :: and the member function name charbcity[15];
Ex.employee :: display(); charbaddress[25];
protected:
16.Define“this” pointer intno_of_emp;
 this pointer used to refer the current objects public:
members charbphone[2][10];
 'this' pointer is a constant pointer that holds the branch();
memory address of the current object. . ~branch();
 It identifies the currently calling object. void have data();
 It is useful when the argument variable name in the void give data();
member function and the data member name are };
same. Syntax: this->data member name
class author: public branch, publisher
#include<iostream> {
using namespace std; Intaut_code;
class T Charaname[2O];
{ float income;
public: public:
int x; author();
void foo() ~author();
{
voidgetdata();
x = 6; // same as this->x = 6;
voidputdata();
this->x = 5; // explicit use of this->
cout<<endl<<x<<" "<<this->x; };
}
void foo(int x) a.Which type of Inheritance is shown in the program?
{ Multiple inheritance
this->x = x; // unqualified x refers to the b.Specify the visibility mode of base classes.
parameter.'this->' required for disambiguation public:
cout<<endl<<x<<" "<<this->x; c. Give the sequence of Constructor/Destructor
}}; Invocation when object of class author is created.
Constructor of publisher
17.Answer the following questions based on the given
Constructor of branch
program.
#include<iostream> Constructor of author
#include<string.h> Destructor of author
#include<stdio.h> Destructor ofbranch
usingnamespacestd; Destructor of publisher
class publisher d. Name the base class(/es) and derived class (/es).
{ Base class: publisher, branchDerived class:author
charpname[15]; e. Give number of bytes to be occupied by the object of
charhoffice[15]; the following class: (a) publisher (b) branch (c) author
publisher:93 bytes branch:64 bytes author: 28 bytes

42
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

f. Write the names of data members accessible from the Destructor


object of class author. Result()
Phone,no_of_emp, bphone,aut_code,aname,income Marks()
g. Write the names of all member functions accessible Personal()
from the object of class author. d. Name the base class(/es) and derived class (/es).
getdata(),putdata(),give data(),have data(),disp data(), Base :Personal,MarksDerived : Marks , Result
enter data(); e.Give number of bytes to be occupied by the object of
h. Write the names of all members accessible from the following class:
member functions of class author (a) Personal turbo 25bytes,devc++ 29bytes
getdata(),putdata(),give data(),have data(),disp data(), (b) Marks 25 bytes(c) Result 29bytes
enter data(),register()
Phone,no_of_emp, bphone,aut_code,aname,income f. Write the names of data members accessible from the
object of class Result.
18.Consider the following c++ code and answer the Name,Grade,total,Agg,FinalGrade.Commence
questions g. Write the names of all member functions accessible
class Personal from the object of class Result.
{ R calculate(),R display(),M entry(),M
Int Class,Rno; display(),personal();void pentry(); voidPdisplay();
char Section; h. Write the names of all members accessible from
protected: member functionsof class Result.
char Name[20]; R calculate(),R display(),M entry(),M
public: display(),personal();void pentry(); voidPdisplay();
personal();
void pentry(); 19.Write the output of the following program
void Pdisplay(); #include<iostream>
}; using namespace std;
Class Marks:private Personal class A
{ {
float M{5}; protected:
protected: int x;
char Grade[5]; public:
public: void show()
Marks(); {
void M entry(); cout<<"x = "<<x<<endl;
void M display(); }
}; A()
classResult:public Marks {
{ cout<<endl<<" I am class A "<<endl;
floatTotal,Agg; }
public: ~A()
charFinalGrade, Commence[20]; {
Result(); cout<<endl<<" Bye ";
void R calculate(); }
void R display(); };
}: class B : public A
a. Which type of Inheritance is shown in the program? {
Multilevel Inheritance {
b. Specify the visibility mode of base classes. protected:
private , public int y;
c Give the sequence of Constructor/Destructor public:
Invocation when object of class Result is created. B(int x, int y)
Constructor
Personal() {
Marks() this->x = x;
Result() this->y = y;

43
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

} int b1:b2:b3;
B() A::getdata[];
{ b1=a1;
cout<<endl<<" I am class B "<<endl; b2=a2;
} a3=a3;
~B() cout<<b1<<’\t’<<b2<<’t\’<<b3;
{ }
cout<<endl<<" Bye "; void main()
} {
void show() clrscr()
{ B der;
cout<<"x = "<<x<<endl; der1:func();
cout<<"y = "<<y<<endl; getch();
} }
}; To Know Yourself
int main() Define Pointer variable
{  A pointer is a variable that hold a memory address
AobjA; of other variable
B objB(30, 20);  In Pointer ,the memory location of a variable can be
objB.show(); directly accessed.
return 0;  The address of ( & ) and the value at operator (*)are
} deals with pointer.
Output: To declare
I am class A Syntax :data type *Variable name;
I am class B Ex. Int *abc;- Here The variable abc can only
X=30 store addresses.
Y=20 Initialization of pointer variable:
Bye Int *abc , n;
Bye n=10;
20.Debug the following program abc = &n;
Output  Pointer variable can store the address of other
------------- variables
15  Pointer variable and assigning variable should have
14 same data type.
13 ---------------------------------------------------
Program : For example
------------- Int *abc ; float n;
%include(iostream.h) n=10.5;
#include<conio.h> abc = &n;
Class A Compiler shows an error because,
{ Pointer variable and assigning variable should have
public; same data type
int a1,a2:a3; ==============================================
Void getdata[]
{
a1=15;
a2=13;a3=13;
}
}
Class B:: public A()
{
PUBLIC
voidfunc()
{

44
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

UNIT -V COMPUTER ETHICS AND


CYBER SECURITY 17
Computer Ethics And Cyber Security
1.What is cyber-crime? 9. Write a short note on cracking.
 A cyber-crime is a crime which involves computer  Cracking is where someone edits a program source
and network. so that the code can be exploited or modified. A
2.What is Computer ethics cracker (also called a black hat or dark side hacker)
 Computer ethics is set of moral principles that is a malicious or criminal hacker.
regulate the use of computers by users 10. What is a Cookie?
3. What are ethical issues? Name some.  A cookie is a small piece of data sent from a website
An Ethical issue is a problem or issue that requires a and stored on the user's computer memory (Hard
person or organization to choose between drive) by the user's web browser while the user is
alternatives browsing internet.
 Cyber crime  Type of cookies: HTTP cookie, web cookie, Internet
• Software Piracy cookie, browser cookie, or simply cookie
• Unauthorized Access 11.What is the role of firewalls?( layered security)
• Hacking  Firewalls also vary in type depending on where
• Use of computers to commit fraud communication originates, where it is intercepted,
• Sabotage in the form of viruses and the state of communication being traced.
• Making false claims using computers 12. Write about encryption and decryption.
4.What is Harvesting?  Encryption and decryption are processes that
 A person or program collects login and ensure confidentiality that only authorized persons
password information from a can access the information.
legitimate user to illegally gainaccess  Encryption is the process of translating the plain
to others’ account(s). text data (plaintext) into random and mangled data
5.What is Malware? (called cipher-text).
 Malicious programs that can perform a variety of  Decryption reverse process of converting the
functions including stealing, encrypting or cipher-text back to plaintext. Encryption and
deleting sensitive data, altering or hijacking core decryption are done by cryptography
computing functions and monitoring user’s 13. Explain symmetric key encryption.
computer activity without their permission  Symmetric encryption is a technique to use the
6.Write two types of cyber attacks. ref.above ans same key for both encryption and decryption.
Differentiate between scam and spam (Secret key)To exchange the key used to encrypt
Scam the data before they can decrypt it
 Tricking people into believing something that is 14. What are the guidelines to be followed by any
not true. computer user?
Spam  Honesty: Users should be truthful while using the
 Distribute unwanted e-mail to a large number of internet.
internet users  Confidentiality: Users should not share any important
7.What is spoofing? information with unauthorized people.
 It is a malicious practice in which communication  Respect: Each user should respect the privacy of other
is send from unknown source disguised as a users.
source known to the receiver  Professionalism: Each user should maintain
8.What are Warez? professional conduct.
 Commercial programs that are made available to  Obey The Law: Users should strictly obey the cyber law
the public illegally are often called warez. in computer usage.
 Responsibility: Each user should take ownership and
responsibility for their actions

45
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

15.Define software piracy.


 Software Piracy is about the copyright violation of
software created originally by an individual or an
institution
Type of Piracy Function
1 Unauthorized access
 Unauthorized access is when someone gains access
to a website, program, server, service, or other
system by breaking into a legitimate user account.
2 Hacking
 Hacking is gaining unauthorized access to s
computer system without the owner’s permission.
3 Cracking
 Cracking is where someone edits a program source
so that the code can be exploited or modified. A
cracker (also called a black hat or dark side hacker)
is a malicious or criminal hacker
Prevented Action:
 Stop to chat on Internet Relay Chat(IRC) or by
Instant messenger.
 e-mail can also be a source for them.
16.Explain the types of cyber attacks.
1. Virus
A virus is a small piece of computer code that can repeat
itself and spreads from one computer to another by
attaching itself to another computer file.
2. Worms
Worms are self- repeating and do not require a
computer program to attach themselves.
3. Spyware
Spyware can be installed on the computer automatically
when the attachments are open, by clicking on links or
by downloading infected software.
4. Ransom ware
Ransomware is a type of malicious program that
demands payment after launching a cyber-attack on a
computer system.

17.Define cyber law.


“Cyber law or Internet law is a term that encapsulates
the legal issues related to use of the Internet
18.Define digital signature.

 Digital signatures are based on asymmetric


cryptography and can provide assurances of
evidence to origin, identity and status of an
electronic document, transaction or message, as
well as acknowledging informed by the signer

46
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

UNIT -V COMPUTER ETHICS AND


CYBER SECURITY 18
Tamil Computing
1.What are Search Engines? Write the List of the search
engines supporting Tamil.
 Search Engines are portal or website .
 Used to search any information from the cyber space.
 Google and Bing provide searching facilities in Tamil.

2.Define e – Governance:
 Getting Government services through internet is known
as e-Governance.
 One can get important announcements, government
orders, and government welfare schemes from the web
portal of Govt.
 Ex.www.tn.gov.in\ta

3.Define e-Library
 E-Libraries are portal or website of collection of e-
books.
 E-Library services provide thousands of Books as e-books
mostly at free of cost.
 Ex.www.chennailibrary.com

4.What are the keyboard layouts used in Android?


 Sellinam and Ponmadal – are familiar Tamil keyboard
layouts that works on Android operating system

5.What are the Tamil keyboard interfaces softwares?


 NHM Writer, E-Kalappai and Lippikar – are familiar Tamil
keyboard interfaces software

6.Name and define Tamil Translation Applications


 Thamizpori is a Tamil translation application.
 Using this application, we can translate small English
sentences into Tamil.
7. Write a short note about Tamil Programming Language.
 Based on Python programming language, the first Tamil
programming language “Ezhil” is designed.
 It is used to write simple programs in Tamil.
8.What TSCII?
 TSCII (Tamil Script Code for Information Interchange) is
the first coding system to handle Tamil language easily in
computer and electronic devices, including non-English
computers.
 This encoding scheme was registered in IANA (Internet
Assigned Numbers Authority) unit of ICANN.
9. Write a short note on Tamil Virtual Academy.
 Tamil Virtual University was established on 17th
February 2001 by the Govt. of Tamilnadu.
 Now, it is called as “Tamil Virtual Academy”.
 This organisation offers different courses regarding Tamil
language, Culture, heritage etc., from kindergarten to
under graduation level.

47
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

www.nammakalvi.in

11
COMPUTER SCIENCE
PRACTICAL

9677515019
www,rmkmhsselango.blogspot.com

Elangovan M.Sc,B.Ed,M.Phil
Head of the Dept.
R.M.K.Matric.Hr.Sce.School,
R.S.M.Nagar,601206.

48
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

CS1 - GROSS SALARY cout<<setw(25)<<""<<setw(10)<<"--------


"<<'\n';
Write a C++ program to input basic salary of an cout<<setw(25)<<"Gross
employee and calculate its Gross salary according to
following:
Salary:"<<setw(10)<<g<<'\n';
Basic Salary <25000 : HRA = 20%, DA = 80% cout<<setw(25)<<""<<setw(10)<<"--------
Basic Salary >= 25000 : HRA = 25%, DA = 90%
"<<'\n';
Basic Salary >= 40000 : HRA = 30%, DA = 95%
AIM:
To input basic salary of an employee and calculate its }
Gross salary
CODING:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float b,g,d,h;
cout<<"Enter Basic Salary of an
Employee..\t"; cin>>b;
if (b<25000)
{
d=b*80/100;
h=b*20/100;
}
else if (b>=25000 && b<40000)
Output:
{
d=b*90/100; Enter basic salary of an employee: 25000
h=b*25/100; Basic : 25000
} DA : 22500
else if (b>=40000) HRA : 6250
------------------------
{
Gross Salary : 53750
d=b*95/100;
------------------------
h=b*30/100;
}
g=b+d+h;
cout<<setw(25)<<"Basic:"<<setw(10)<<b<<
'\n';
cout<<setw(25)<<"DA:"<<setw(10)<<d<<'
\n';
cout<<setw(25)<<"HRA:"<<setw(10)<<h<<'
\n';

49
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

CS2 - PERCENTAGE

Write a C++ program to check percentage of a


student and display the division (distinction, first,
second, third or fail) scored using switch case.
Percentage Division
>=80 Distinction
>=60 and <80 First division
>=50 and <60 Second Division
>=40 and <50 Third Division
<40 Fail
AIM: To check percentage of a student and display
the division
CODING:

#include<iostream>
using namespace std;
int main()
{
int p,x;
cout<<"Enter Your Percentage:\t";
cin>>p;
Output 1
cout<<"\n\n\nYou Scored "<<p<<"%\n"; Enter your percentage: 79
x=p/10; You scored 79%
First division
switch(x) Output 2
Enter your percentage: 39
{
You scored 39%
case 10: case 9: case 8: Sorry: You have failed

cout<<"\nDistinction";break;
case 7: case 6 : cout<<"\nFirst
division";break;
case 5:cout<<"\nSecond division";break;
case 4: cout<<"\nThird division";break;
default: cout<<"\nSorry , You have
Failed..";
}
}

50
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

CS3 - PALINDROME

Write a C++ program to enter any number and


check whether the number is palindrome
or not using while loop.
AIM: To enter any number and check whether the
number is palindrome
CODING:
#include<iostream>
using namespace std;
int main()
{ Output 1
int n,x,d,r=0; Enter a positive number: 1234
The Reverse number is: 4321
cout<<"Enter a Positive Number...\t"; NOT A PALINDROME
cin>>n;
Output 2
x=n; Enter a positive number: 1221
while(n!=0) The Reverse number is: 1221
PALINDROME
{
r=(r*10)+n%10;
n=n/10;
}
cout<<"\nThe Reverse Number is
\t"<<r<<'\n';
if(x==r)
cout<<"\nPALINDROME";
else
cout<<"\n NOT A PALINDROME";

51
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

CS4 NUMBER CONVERSION while(b!=0)


{
d+=b%10*pow(2,i);
Using do while loop create the following menu based b/=10;
C++ program i++;
1.Convert a Decimal to binary number
}
2.Convert a binary number to Decimal
3. Exit cout<<"\n\n Decimal..:"<<d<<'\t'; break;
Depending on the choice accept the value and display
the result .The program should continue till the user case 3: break;
select the third option default: cout<<"\nEnter only 1 / 2 / 3:";
AIM:To Convert a Decimal to binary number and To }
Convert a binary number to Decimal in menu based } while(c!=3);
method using do..while loop
}
CODING:
#include<iostream>
#include<math.h>
using namespace std;
int main() Output
{ MENU
int d=0,c,i; 1.Decimal to Binary number
long int b=0; 2.Binary to Decimal number
3.Exit
do Enter your choice(1/2/3)1
{ Enter a Decimal Number: 23
cout<<"\n\n\tMENU\n" In decimal … 10111
cout<<"\n1.Decimal to Binary\n2.Binary to MENU
Decimal\n3.Exit\n"; 1.Decimal to Binary number
cout<<"\nEnter Your Choice (1 / 2 / 3)..\t"; 10
cin>>c;
2.Binary to Decimal number
3.Exit
switch(c)
Enter your choice(1/2/3)2
{
Enter a Binary Number: 11001
case 1: cout<<"\nEnter a Decimal Number....:\t";
In binary … 25
cin>>d;
MENU
i=0; 1.Decimal to Binary number
while(d!=0) 2.Binary to Decimal number
{ 3.Exit
b+=d%2*pow(10,i); Enter your choice(1/2/3) 4
d/=2; Enter only 1 /2 /3:
i++;
}
cout<<"\n In Binary..:"<<b<<'\t'; break;

case 2: cout<<"\nEnter a Binary number...:\t";


cin>>b;
i=0;

52
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

CS5 - FIBONACCI PRIME SERIES }

Write a C++ program using a user defined function


to generate the Fibonacci series till n terms and
print if each term is prime or Composite.
AIM: To generate the Fibonacci series till n terms
and print if each term is prime or Composite
CODING:
#include <iostream>
#include <stdlib.h>
using namespace std;
void prime (int a )
{
int j;
if ( a == 0 || a == 1 ) { cout<< " NEITHER
PRIME NOR COMPOSITE ";}
else
{ Output
for (j = 2 ; j<a; j++) ENTER THE NUMBER OF TERMS 10
{ FIBONACCI SERIES
if (a%j==0) { cout<< 0 NEITHER PRIME NOR COMPOSITE
"\tCOMPOSITE" ;break ; } 1 NEITHER PRIME NOR COMPOSITE
} 1 NEITHER PRIME NOR COMPOSITE
if ( a==j ) {cout<< "\tPRIME" ;} 2 PRIME
} 3 PRIME
} 5 PRIME
void fib ( int n ) 8 COMPOSITE
{ 13 PRIME
int a = -1 , b = 1 ,c=0 ; 21 COMPOSITE
for ( int i = 1 ; i <= n ; i++) 34 COMPOSITE
{
cout<<endl;
c=a+b;
cout<<c;
prime(c);
a = b;
b=c;
}
}
int main ()
{
int n ;
cout << " ENTER THE NUMBER OF TERMS
";
cin >> n ;
cout<< "\n\tFIBONACCI SERIES\n " ;
fib (n) ;
return 0;

53
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

CS6 - INSERT / DELETE ELEMENTS IN AN ARRAY n=n+1;


cout<<"\n After deletion...\n";
dis();
Write a menu driven C++ program to Insert and
}
Delete elements in a single dimension array of void main()
integers and print the array after insertion or {
clrscr();
deletion.
int ch;
AIM: To Insert and Delete elements in a single cout<<"\nEnter the size of the Array:\t"; cin>>n;
dimension array of integers and print the array cout<<"\nEnter the element....\n";
after insertion or deletion for(int i=0;i<n;i++)
CODING: {
#include<iostream.h> cin>>a[i];
#include<conio.h> }
int p,e,n, a[20] , b[20] , c[20]; do
void dis() {
{ cout<<"\n\n\nMENU\n\n";
cout<<"The Elements are...\n"; cout<<"\n1.Insert\n2.Delete\n3.Exit\n";
for(int i=0;i<n;i++) cout<<"-----------------------";
{ cout<<"\nEnter Your Choice..\t";cin>>ch;
cout<<a[i]<<'\n'; switch(ch)
} {
} case 1: ins() ; break;
void ins() case 2: del() ; break;
{ case 3: break;
int e,p; default: cout<< "\nEnter only 1/2/3";
cout<<"\nEnter new element..\t";cin>>e; }
cout<<"\nEnter position \t";cin>>p; }while(ch!=3);
for(int i=n;i>=p-1;i--) getch();
{ }
a[i+1]=a[i];
}
a[p-1]=e;
n=n+1;
dis();
}
void del()
{
cout<<"Enter the Position:\t"; cin>>p;
e=a[p];
for(int i=p ;i<n-1; i++)
{
a[i]=a[i+1];
}

54
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

Output 1

Enter the size of the array elements: 5


Enter the elements for the array:
1
2
3
4
5
--------Menu-----------
1.Insert
2.Delete
3.Exit
-----------------------
Enter your choice: 1

Enter the position: 3


Enter the element to be inserted : 26
The array elements are:
1 2 26 3 4 5

Output 2
--------Menu-----------
1.Insert
2.Delete
3.Exit
-----------------------
Enter your choice: 2
Enter the position: 2
The deleted element is = 2
The array elements are:
1 3 26 4 5

55
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

CS 7 - Boundary Element of a Matrix

Write a C++ program to print boundary elements


of a matrix
AIM: To print boundary elements of a matrix
Coding
#include <iostream>
using namespace std; Output
void printBoundary (int a[][10], int m, int n) Enter more than 3 x3
{ 4 4
for (int i = 0; i < m; i++) { 1
for (int j = 0; j < n; j++) 2
{ 3
4
if (i==0|| j==0||i==m-1||j==n-1)
5
cout<<a[i][j]<<" ";
6
else 7
cout<<" "; 8
} 9
cout <<endl ; 0
} 1
} 2
int main() 3
{ 4
int a[10][10] ,i,j,m,n; 5
6
cout<<"Enter more than 3 x3 "<<endl;
cin>>m>>n;
Original Array
for (i=0;i<m;i++) 1 2 3 4
{ 5 6 7 8
for (j=0;j<n;j++) 9 0 1 2
{ 3 4 5 6
cin>>a[i][j];
} The Boundary element
} 1 2 3 4
system("cls"); 5 8
cout<<"\n\nOriginal Array\n"; 9 2
3 4 5 6
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"\n\n The Boundry element\n";
printBoundary(a, m, n);
return 0;
}

56
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

CS8 - ABC PUBLISHERS cout<<"\n==================================\n";


cout<<" Book Number : "<<Bookno<<endl;
cout<<"Title : "<<Title<<endl;
Define a class named Publisher in C++ with the cout<<"Author Name : "<<Author<<endl;
cout<<"Price Per Book : "<<Price<<endl;
following descriptions cout<<"Total Amount : "<<Totamt<<endl;
cout<<"\n==================================\n";
AIM: To create a class named Publisher with given }
descriptions. int main()
{
Coding int n,i;
#include<iostream> Publisher p[10];
#include<stdlib.h> cout<<"Enter the number of object to be
using namespace std; created";cin>>n;
int id=1001;21 for (i=0;i<n;i++)
class Publisher p[i].Readdata();
{ for (i=0;i<n;i++)
int Bookno; p[i].Displaydata();
char Title[20]; return 0;
char Author [10]; }
float Price; Output
float Totamt; Enter the number of object to be created 2
float calculate (int); Enter the Title name C++Programming
public: Enter the Author name Balaguru 23
Publisher() Enter the Price 500
{Bookno=id; Enter the Number of copies 3
Title[0]='\0'; Enter the Title name CoreJava
Author[0]='\0'; Enter the Author name Xavier
Price=0; Enter the Price 250
Totamt=0; Enter the Number of copies 5
id++;
} ABC PUBLISHERS
void Readdata(); ~~~~~~~~~~~~~~
void Displaydata(); INVOICE
}; ~~~~~~~
void Publisher::Readdata() ==================================
{ Book Number : 1001
int nocopies; Title : C++Programming
cout<<"Enter the Title name ";cin>>Title; Author Name : Balaguru
cout<<"Enter the Author name ";cin>>Author; Price Per Book : 500
cout<<"Enter the Price ";cin>>Price; Total Amount : 1500
cout<<"Enter the Number of copies ";cin>>nocopies; =================================
Totamt=calculate(nocopies); ABC PUBLISHERS
} ~~~~~~~~~~~~~~
float Publisher::calculate(int x) INVOICE
{22 ~~~~~~~
return x*Price; ==================================
} Book Number : 1002
void Publisher::Displaydata() Title : CoreJava
{ Author Name : Xavier
cout<<"\n\t\tABC PUBLISHERS\n"; Price Per Book : 250
cout<<"\t\t~~~~~~~~~~~~~~\n"; Total Amount : 1250
cout<<"\t\t INVOICE\n"; ==================================
cout<<"\t\t ~~~~~~~\n";

57
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

CS9 - EMPLOYEE DETAILS USING CLASS

void display()
Create a C++ program to create a class employee {
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<
containg the following members <hra<<"\t"<<da<<"\t"<<pf<<"\
t"<<np<<"\n";
AIM: To create a class employee containg the }
following members };
Coding int main(){
#include<iostream> int i, n;26
using namespace std; char ch;
class emp{ salary s[10];
public: cout<<"Enter the number of employee:";
int eno; cin>>n;
char name[20], des[20]; for (i =0; i < n; i++){
void get(){ s[i].get();
cout<<"Enter the employee number:"; s[i].get1();
cin>>eno; s[i].calculate();
cout<<"Enter the employee name:";25 }
cin>>name; cout<<"\n\t\t\tEmployee Details\n";
cout<<"Enter the designation:"; cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf
cin>>des; \t np \n";
} for (i =0; i < n; i++){
}; s[i].display();
class salary :public emp }
{ return 0;
float bp,hra, da,pf,np; }
public: Output
void get1() Enter the number of employee:2
{ Enter the employee number:1201
cout<<"Enter the basic pay:"; Enter the employee name:Ramkumar
cin>>bp; Enter the designation:Engineer
cout<<"Enter the HouseRent Allowance:"; Enter the basic pay:50000
cin>>hra; Enter the House Rent Allowance:10000
cout<<"Enter the Dearness Allowance :"; Enter the Dearness Allowance :5000
cin>>da; Enter the Provident Fund:1000
cout<<"Enter the Provident Fund:";
cin>>pf; Enter the employee number:1202
} Enter the employee name:Viswanathan
void calculate() Enter the designation:Engineer-Tech
{ Enter the basic pay:40000
np=bp+hra+ da -pf; Enter the House Rent Allowance:9000
} Enter the Dearness Allowance :4500
Enter the Provident Fund:1000

58
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

CS10 -STUDENT DETAILS class Test :public Student


{
protected:
Write a C++ program to create a class called float Mark1,Mark2;
public:
Student with the following details void Readmark (float m1,float m2)
{
Protected member
Mark1=m1;
Rno integer
Mark2=m2;
Public members
}
void Readno(int); to accept roll number and assign to
void Writemark()
Rno
{
void Writeno(); To display Rno.
cout<<"\n\n\tMarks Obtained\n ";
The class Test is derived Publically from the Student
cout<<"\n Mark1 : "<<Mark1;29
class contains the following details
cout<<"\n Mark2 : "<<Mark2;
Protected member
}
Mark1 float
};
Mark2 float
class Sports
Public members
{
void Readmark(float,float); To accept mark1 and mark2
protected:
void Writemark(); To display the marks
int score;// score = Sports mark
Create a class called Sports with the following detail
public:
Protected members
void Readscore (int s)
score integer
{
Public members
score=s;
void Readscore(int); To accept the score
}
void Writescore(); To display the score
void Writescore()
The class Result is derived Publically from Test and
{
Sports class contains the following details
cout<<"\n Sports Score : "<<score;
Private member
}
Total float
};
Public member
class Result :public Test,public Sports
void display() assign the sum of mark1 ,mark2,score in
{
total.
int Total;
invokeWriteno(),Writemark() and Writescore()
public:
Display the total also.
void display()
AIM: To create a class called Student
{
Coding Total = Mark1 + Mark2 + score;
Writeno();
#include<iostream>
Writemark();
using namespace std;
Writescore();
class Student
cout<<"\n\n Total Marks Obtained : "<< Total<<endl;
{
}
protected:
};
int Rno;
int main()30
public:
{
void Readno(int r)
Result stud1;
{
stud1.Readno(1201);
Rno=r;
stud1.Readmark(93.5,95);
}
stud1.Readscore(80);
void Writeno()
cout<<"\n\t\t\t HYBRID INHERITANCE PROGRAM\n";
{
stud1.display();
cout<<"\nRoll no : "<<Rno;
return 0;
}
}
};

59
www.rmkmhsselango.blogspot.com 9677515019
Dept.of C.S. ,RMKMHSS - 601206

60
www.rmkmhsselango.blogspot.com 9677515019
www.nammakalvi.in Dept.of C.S. ,RMKMHSS - 601206

Internal Choice For The Programs

61
www.rmkmhsselango.blogspot.com 9677515019

You might also like