You are on page 1of 126

CHAPTER - 5

GENERAL OOP CONCEPTS


1 Mark Questions

1. How are programs written in (i) machine language, (ii) assembly language?
Ans. (i) Machine language: In machine language instructions are written in binary code
(using 0 and 1).
(ii) Assembly language: In assembly language instructions are written using symbolic
names for machine operations (e.g., READ, ADD, STORE etc.) and operands.

2. Why are low level languages considered close to the machine?


Ans. Low level languages are considered close to the machine because it provide a
vehicle for the programmers to specify actions to be executed, so that all important
aspects of a machine are handled simply and efficiently in a way that is reasonably
obvious to the programmer.

3. What is a module? What is modular programming paradigm? What are its


characteristics?
Ans. A set of related procedure with the data they manipulate is called a Module.
Modular programming paradigm combines related procedures in a module and hides
data under modules. The data are dependent on the functions. The arrangement of data
can’t be changed without modifying all the functions that access it.

4. What is an object? What is a class? How is an object different from a class?


Ans. An object is an identifiable entity with some characteristics and behavior. It
represents an entity that can store data and its associated functions.
A class is a group of objects that share common properties and relationship. It
represents a group of similar objects. For example, we can say ‘bird’ is a class but
‘parrot’ is an object.

5. What is object oriented programming paradigm? Name the four basic concepts
of OOP.
Ans. We can define the object oriented programming (OOP) paradigm as following:
Decide which classes and objects are needed; provide a full set of operations for each
class. Following are the basic OOP concepts:
1. Data Abstraction 2. Data Encapsulation 3. Modularity
4. Inheritance 5. Polymorphism

6. What is meant by Abstraction?


Ans. Abstraction is the act of representing essential features without including the
background details. In switch board we only press certain switches according to our
requirement. What is happening inside, how it is happening etc. we need not know. So,
this is abstraction, we know only the essential things to operate on switch board without
knowing the background details of switchboard.

7. What is encapsulation? Why data is considered safe if encapsulated?


Ans. Encapsulation is the way of combining both data and the functions that operate on
the data under a single unit. In encapsulation, data can’t access directly. The only way
to access the data is provided by the functions. The data is hidden, so data is considered

1
safe if encapsulated. For example, cars and owners. All the functions of cars are
encapsulated with the owners; no one else can access it.

8. How are the terms abstraction and encapsulation related?


Ans. Encapsulation is the way of implementing abstraction. Thus, the terms abstraction
and encapsulation are related because while implementing encapsulation, abstraction is
also implemented.

9. What is modularity? What benefits does it offer?


Ans. Modularity is the property of decomposing a system into a set of cohesive and
loosely coupled modules. It offers following benefits:
(i) It reduces its complexity to some degree.
(ii) It creates a number of well-defined, documented boundaries within the program.

10. What is a base class? What is a subclass? What is the relationship between a
base class and subclass?
Ans. A subclass is a class that inherits properties from some other class. A base class is
a class whose properties are inherited by subclass. A subclass has nearly all the
properties of base class but the reverse of it is not true.

11. What do you mean by the transitive nature of inheritance?


Ans. The transitive nature of inheritance states that if a class A inherits properties from
its base class B then all its subclasses will also be inheriting the properties of base class
of A i.e., B.

12. Write a short note on inheritance.


Ans. Inheritance enables us to create new classes that reuse, extend, and modify the
behavior that is defined in other classes. The class whose members are inherited is
called the base class, and the class that inherits those members is called the derived
class. Inheritance is transitive. When we define a class to derive from another class, the
derived class implicitly gains all the members of the base class.

13. What is polymorphism? Give an example illustrating polymorphism.


Ans. Polymorphism is the ability for a message or data to be processed in more than one
form. For example, consider an addition operation. It shows different behavior in
different types of data. For two numbers, it will generate a sum. The numbers may
integers or float. Thus the addition for integer is different from the addition to floats.

14. How the data is hidden and safe if encapsulation is implemented? Explain with
example.
Ans. In encapsulation, data cannot be accessed directly. The only way to access the data
is provided by the functions. To read the item in an object, call a member function in the
object. It will read the item and return the value. The data is hidden, so it is safe from
accidental alteration. The best example of encapsulation is a CLASS because a class
hides class variables/functions from outside the class.

15. Do you think OOP is closer to real world problems? Why? How?
Ans. Yes, OOP is closer to real world problems because object oriented programming
implement inheritance which has capability to express the inheritance relationship.

2
CHAPTER-6
GETTING STARTED WITH C++

1 Mark Questions

1. What is meant by token? Name the tokens available in C++.


Ans. The smallest individual unit in a program is known as a Token. C++ has the
following tokens: 1.Keywords 2.Identifiers 3.Literals 4.Punctuators 5.Operators

2. What are keywords? Can keywords be used as identifiers?


Ans. Keywords are the reserved words having special meaning and purpose. No,
keywords cannot be used as identifiers

3. What is an identifier? What is the identifier forming rule of C++?


Ans. Identifier is a name give by user for a part of the program. The first character must
be a letter; the underscore (_) counts as a letter. Upper and lower-case letters are
different. All characters are significant.

4. Which of the following are valid identifiers and why/why not:


Data_rec, _data, data1, my.file, asm, switch, goto, break,For.
Ans. Following are valid identifiers:
Data_rec, _data, For and data1
Following are invalid identifiers:
my.file contains special character
asm reserved keyword
switch reserved keyword
goto reserved keyword
break reserved keyword

5. What are literals (Constant)? Name the types of integer literals?


Ans. Literals are data items that never change their value during a program run.
Following three types of integer literals are available in C++:1. Decimal Integer
Constants 2. Octal Integer Constants 3. Hexadecimal Integer Constants

6. What is an integer constant? Write integer forming rule of C++.


Ans. Integer constants are whole numbers without any fractional part. Integer forming
rule of C++ is as following:
 An integer constant must have at least one digit and must not contain any
decimal point. It may contain either + or –sign.
 A number with no sign is assumed to be positive. Commas cannot appear in an
integer constant.

7. What kind of program elements are the following?


13, ‘a’, 4.38925, “a”, main()
Ans. 13 = Decimal integer constant
‘a’ = Character constant
4.38925 = Floating constant
“a” = String literals
main() = Function

3
8. What kind of program elements are the following?
14, 011, 0X2A, 17, 014, 0XBC1
Ans. 14 = Decimal integer constant
011 = Octal integer constant
0X2A = Hexadecimal integer constant
17 = Decimal integer constant
014 = Octal integer constant
0XBC1 = Hexadecimal integer constant

9. What is a character constant in C++?


Ans. A character constant is one character enclosed in single quotes, as in ‘a’.

10. How are nongraphic characters represented in C++?


Ans. The nongraphic characters are represented in C++ by using escape sequences. An
escape sequence is represented by a backslash (\) followed by one or more characters.
For example, \n is used for newline or linefeed.

11. Why are characters \, ‘, “ and ? typed using escape sequences?


Ans. The characters \, ‘, “ and ? carry a special meaning and have a special purpose, so,
if these are to be typed as it is, then escape sequences should be used.

12. Which of the following are valid character constants in C++?


‘c’, ‘abc’, “abc”, my, ‘main’s’, ‘ “ ‘, ‘char, ‘\\’
Ans. Following are the valid character constants in C++: ‘c’ ‘\\’ ‘”’

13. What are string-literals in C++? What is the difference between character
constants and string literals in terms of size?
Ans. A string literal is a sequence of characters surrounded by double quotes. The size
of character constant is must be 1 character where as the size of a string literal is the
number of characters plus one for terminator ‘\0’.

14. What is the significance of null (\0) character in a string?


Ans. Each string is by default added with a special character ‘\0’ which makes the end
of a string. ‘\0’ is a single character.
Thus the size of a string is the number of characters plus one for this terminator.

15. What header file must be included with your source file to use cout and cin?
Ans. The header file iostream.h we must include with our source file to use cout and
cin. The standard input device is keyboard, the standard output and error device is
screen/monitor.

16. What are predefined stream objects in C++?


Ans. Following are predefined stream objects in C++:
1. cin – for standard input.
2. cout - for standard output.
3. cerr - for standard error.

4
17. If the file iostream.h is not included in a program, what happens?
Ans. If the file iostream.h is not included in a program, each reference to cin, cout or
cerr will be flagged as a type error by the compiler.

18. Why is function main() special? What would happen if main() is not present in
the program?
Ans. The main() function is the point by where all C++ programs begin their execution
and continues by sequentially executing the statements within main(). A program
terminates normally following execution of the last statement of main(). If main() is not
present in the program, the program does not get execute.

19. What kinds of program errors can you encounter during programming? Why do
these occur?
Ans. Three kinds of program errors can you encounter during programming are:-
1. Syntax Errors: Occurs when rules of a programming language are violated.
2. Semantics Errors: Occurs when program statements are not meaningful.
3. Type Errors: Occurs when data/value of unexpected type is passed or input.

20. Apart from pointing out errors, what is the other role of a compiler?
Ans. Apart from pointing out errors, a compiler translates the corrected program text
into object or assembly instruction text understood by the computer.

21. What is the input operator “>>” and output operator “<<” called?
Ans. The input operator “>>” is called stream extraction operator and output operator
“<<” is called stream insertion operator.

22. What is the difference between run-time error and syntax error? Give one
example of each.
Ans. A run-time error is occurs during the execution of a program. For example, if a
program is trying to open a file which does not exist, it results into an execution error.
Whereas a syntax error occur when rules of a programming language are misused. For
example, int a, b: //then the compiler produces a syntax error as the statement is
terminated by : rather than ;.

2 Mark Questions:

1. Identify the errors in the following code segments:

(i) int main() { cout<<"Enter two numbers";


cin>>num>>auto;
float area=Legth*breadth; }

(ii) #include<isostream.h>
void main()
{ int a,b;
cin<< >>;
if(a>b)MAX=a }

5
Ans. (i) 1. The header file iostream.h has not been included.
2. The variables num, Length & breadth have not been declared before using.
3. auto is a keyword which cannot be used as a variable name.
(ii) 1. There is a spelling mistake in declaration of header file iostream.h
2. The variables MAX has not been declared before using it.
3. The statement cin<< >> has not been written correctly.
4. The statement MAX = a has not been terminated with ;.

2. Can nongraphic characters be used and processed in C++? How? Give examples
to support your answer.
Ans. Yes, in C++ nongraphic characters can be used and processed. Nongraphic
characters are those characters that cannot be typed directly from keyboard e.g.,
backspace, tabs, carriage return etc. these nongraphic characters can be represented by
using escape sequences.
An escape sequence is represented by a backslash (\0 followed by one or more
characters. For eg: ‘\n’ is used for newline or linefeed, ‘\t’ is used for horizontal tab.

3. What are operators? What is their function? Give examples of some unary and
binary operators?
Ans. Operators are tokens that trigger some computation or action when applied to
variables ad other objects in an expression. Following are some unary and binary
operators:
Unary Operators Binary Operators
& Address operator + Addition
* Indirection operator - Subtraction
++ Increment operator % Remainder/Modulus
-- Decrement operator && logical AND

4. Why is it important to include iostream.h in C++ programs?


Ans. The header file iostream.h is included in every C++ program to implement
input/output facilities. Input/output facilities are implemented through a component of
C++ standard library, iostream.h which, is I/O library.
Declarations and functions of cin, cout and cerr are contained within iostream.h. If the
file iostream.h is not included in a program, each reference to cin, cout or cerr will be
flagged as a type error by the compiler.

5. How are files and devices implemented at the lowest level?


Ans. In C++, all devices are treated as files. Thus, the standard input device, the
standard output device and the standard error device are all treated as files. At its
lowest level, a file is interpreted simply as a sequence, or stream of bytes.
At this level, the notion of a data type is absent i.e., data is treated simply as sequence
of bytes without considering its data type.

6. Find out the errors, if any, in the following C++ statements:


(i) cout<<"a=" a; (ii) m=5, n=12; 0=15 (iii) cout<<"x";<<x;
(iv) cin>>y;>>j (v) cin>>"\n">>y; (vi) cout>>\n"abc";
(vii) a=b+c (viii) break=x*y;

6
Ans. (i) The ‘<<’ operator is missing.
(ii) The data type is missing, illegal use of ‘;’ and not terminated by ;.
(iii) Illegal use of semicolon (;).
(iv) Illegal use of ‘;’ and not terminated by ;.
(v) Illegal use of “\n” escape sequence.
(vi) The ‘\n’ should be in double quote.
(vii) Semicolon missing.
(viii) The reserved word ‘break’ should not be used as variable name.

7. Write a program to display the following output using a single cout statement.
Program=20
Documentation=23
Logic=21
Flow chart=18
Ans. #include<iostream.h>
#include<conio.h>
void main()
{clrscr();
cout<<"Program = 20"<<"\n Documentation = 23"<<"\n Logic = 21"
<<"\n Flowchart = 18";
getch();
}

8. Write a program to read values of w, x, y and z and display the values of P,


𝒘+𝒙
where P =
𝒚−𝒛
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int w,x,y,z,P;
cout<<"Enter w : ";
cin>>w;
cout<<"Enter x : ";
cin>>x;
cout<<"Enter y : ";
cin>>y;
cout<<"Enter z : ";
cin>>z;
P=((w+x)/(y-z));
cout<<"P="<<P;
getch();
}

9. Write a C++ program that reads temperature in Celsius and display it in


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

7
{
float f,c;
clrscr();
cout<<"Enter Fahrenheit degree to find temperature in celsius: ";
cin>>f;
c = (f-32)/1.8;
cout<<"\n\n\tCELSIUS DEGREE = "<<c;
getch();
}

10. Write a program that displays on screen


a. the character 'z' b. the name 'Mohan' c. the number 1977
Using (i) single cout statement (ii) multiple cout statements.
Ans. (i) single cout statement:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"a.the character 'z'"<<"\t b.the name 'Mohan'"<<"\t c.the number 1977";
getch();
}
(ii) multiple cout statements:
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
cout<<"a.the character 'z'";
cout<<"\tb.the name 'Mohan'";
cout<<"\tc.the number 1977";
getch();
}

11. Assuming that there are 7.481 gallons in a cubic foot, write a program that
asks the user to enter the number of gallons, and then display the equivalent in
cubic feet.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float gallon,cubic;
cout<<"Enter the number of gallons: ";
cin>>gallon;
cubic=gallon/7.481;
cout<<"\n Cubic feet= "<<cubic;
getch();
}

8
12. Write a program to generate the following using tab and newline:
1992 17421
1993 29210
1994 100523
1995 106802
1996 127000
Use a single cout statement for output. (Hint: Make use of \n and \t.)
Ans. #include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"\t1992\t\t17421\n\t1993\t\t29210\n\t1994\t\t100523\n\t1995\t\t1068
02\n\t1996\t\t127000\n ";
getch();
}

13. Write a program that generate the following output:


5
10
9
Assign value 5 to a variable using =, Multiply it with 2 to generate 10 and subtract
1 to generate 9.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int a=5;
cout<<a;
a=a*2;
cout<<"\n"<<a;
cout<<"\n"<<a-1;
getch();
}

14. Write a C++ program that accepts radius of a circle and prints its area.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float r,area;
cout<<"Enter radius: ";
cin>>r;
area=2*3.14*r;
cout<<"\narea= "<<area;
getch();
}

9
16. Write a C++ program that accept marks in 5 subjects and output average
marks.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
float m1,m2,m3,m4,m5,avg;
cout<<"Enter marks obtained in 5 subjects : ";
cin>>m1>>m2>>m3>>m4>>m5;
avg=(m1+m2+m3+m4+m5)/5;
cout<<"\nAverage= "<<avg;
getch();
}

17. Write a C++ program to accept two integers and print their sum.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
float a,b,sum;
cout<<"Enter a and b ";
cin>>a>>b;
sum=a+b;
cout<<"\nSum= "<<sum;
getch();
}

10
CHAPTER-7
DATA HANDLING
1 Mark Questions:

1. What are the main types of C++ data types? Write data types of each type.
Ans. C++ offers two types of data types:
1. Fundamental data types: These are five fundamental data types: char, int, float,
double and void.
2. Derived data types: These are derived data types: array, function, pointer, reference,
constant, class, structure, union and enumeration.

2. What do you mean by fundamental data types? How many fundamental data
types does C++ provide?
Ans. Fundamental data types are the data types that are not composed of any other
data type. C++ provides these five fundamental data types: char, int, float, double and
void.

3. The data type char is used to represent characters. Then why is it often termed
as an integer type?
Ans. The memory implementation of char data type is in terms of the number code.
Therefore, it is said to be another integer data type.

4. How are the following statements in the same set different?


(i) char pcode = 75; (ii) char pcode = 75; (iii) const int a = 5;
char pcode = 'k' short pcode = 75; const a = 5;
Ans. (i) The first statement stores the ASCII value of character ‘k’, whereas the second
statement stores a character ‘k’.
(ii) The first statement stores the ASCII value of character ‘k’, whereas the second
statement stores numeric value 75.
(iii) No difference. In constant declaration when data type is skipped, by default it is int.

5. Explain the difference among 0, ‘0’, ‘\0’, and “0”.


Ans. 0: is a integer constant.
‘0’: is a character constant.
‘\0’: is a escape sequence for Null.
“0”: is a string constant.

6. What is a reference variable? How is it defined in C++?


Ans. A reference variable provides an alias for a previously defined variable.
It is defined in C++ with following syntax:
type &ref-var = var-name; // int &a=b;
where type is any valid C++ data type, ref-var is the name of reference variable that will
point to variable denoted by var-name.

7. What is wrong with the following statement? const int y;


Ans. A constant must be initialized at the time of declaration. Hear, the constant
variable y is not initialized which is invalid.

11
8. What are the similarities and difference between an array and a structure?
Ans. Similarities:
Both are collection of elements.
Differences:
An array can hold multiple elements of same data type whereas a structure can
hold multiple elements of different data types.
The component element of an array is referenced by the array name and the index
value.
E.g., NAME [3],FILE [7] etc. on the other hand, the component element of a
structure is referenced by the structure name and
the element name e.g., style.main, check.value etc.

9. Find errors, if any in the following C++ statements:


(i) int code = three; // three is an enumerator
(ii) enum (gree, yellow, red);
(iii) const int size;
(iv) size = 10; //size is already defined constant.
Ans.
(i) It is valid only when enumerations are treated as integers.
(ii) Wrong brackets. It should be:
enum {gree, yellow, red};
(iii) A constant variable must be initialized at the time of declaration.
(iii) No, we can’t assign a value to a constant variable.

10. What are derived data types? Name the user defined data types in C++.
Ans. The data types that are composed of fundamental data type are called derived
data types. Following are the user defined data types:
1. Class 2. Structure 3. Union 4. Enumeration

11. What is a variable? In C++, two values are associated with a symbolic variable.
What are these?
Ans. A variable is a named storage location, whose values can be manipulated during
program run. Following are the two values which are associated with a symbolic
variable:
(i) rvalue that gives its contents.
(ii) lvalue that gives its address.

12. Write declaration for


(i) a pointer to a character and an array of 10 integers.
(ii) a reference to a floating-point variable.
(iii) a constant character and a constant integer.
Ans. (i) char *ptr;
int a[10];
(ii) float total;
float &sum = total;
(iii) const char name=’A’;
const int MAX=50;

12
13. What do you mean by dynamic initialization of a variable? Give an example.
Ans. In dynamic initialization a variable can be initialized at run time using expressions
at the place of declaration. For example: float avg = sum/count;

14. What is the impact of access modifier const over a variable?


Ans. The access modifier const modifies the access type of variable, the variable
becomes constant and its value
remains unchanged throughout the program, it can never be changed during program
run.

2 Mark Questions:

1. Write declaration for a class that holds properties of a branch. The class holds
information like branch-number, area, number of employees, head and the
operations associated like branch report printing, branch data modification,
pending works reporting, forecast reporting.
Ans. class Branch
{ int branch_number;
char area[30];
int Num_of_emp;
public:
void Print_Report();
void Modify_Data();
void Pending_Report();
void Forecast_Report();
};

2. Write a declaration for a structure that holds information of a student like roll
no, name, class, marks and grade.
Ans. struct Student
{ int Rollno;
char ame[20];
int class;
float marks;
char grade;
};

3. Explain the function and usage of a union giving an example.


Ans. A union represents a memory location shared by two or more different variables.
The keyword union is used for
declaring and creating a union. For example,
union share
{ int i;
char ch;
};
union share cnvt;

4. “Comments are useful and easy way to enhance readability and


understandability of a program” Elaborate with examples.

13
Ans. Comments are pieces of code that the compiler discards or ignores or simply does
not execute. The purpose of comment is only to allow the programmer to insert some
notes or descriptions to enhance readability of the program. For example,
//A sample program Single line comments
#include<iostream.h> // includes header files
int main()
{ cout<<"Hello There!!";
/* This is a simple program with just one output statement
written for the purpose of explaining comments */ Multiline comment
}

5. Write a program to read a number n and print n2, n3, n4, and n5.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ int n;
clrscr();
cout<<"Enter n: ";
cin>>n;
cout<<n*n<<"\t"<<n*n*n<<"\t"<<n*n*n*n<<"\t"<<n*n*n*n*n;
getch();
}

6. Write a program to find whether a given number is even or odd.


Ans. #include<iostream.h>
#include<conio.h>
void main()
{ int n;
clrscr();
cout<<"Enter n: ";
cin>>n;
if(n%2==0)
cout<<"The number is even";
else
cout<<"The number is odd";
getch();
}

7. Write a program to convert given inches into its equivalent yards, feet and
inches. (1 yard = 36 inches, 1 foot = 12 inches)
Ans. #include <iostream.h>
#include <conio.h>
void main( )
{
int in, yrd, ft, r;
cout << " Enter distance/length in inches ";
cin >> in;
yrd = in/ 36;
r = in % 36;

14
ft = r / 12;
r = r % 12;
cout << " \n The distance in inches is " << in ;
cout << " \n The yard-feet-inches = " << yrd << " yard" << ft << "feet" << r
<< "inches" ;
getch( );
}

8. Write a program to read two numbers and print their quotient and remainder.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ int n1,n2,qut,rem;
clrscr();
cout<<"Enter n1: ";
cin>>n1;
cout<<"Enter n2: ";
cin>>n2;
qut=n1/n2;
rem=n1%n2;
cout<<"Quotient: "<<qut<<endl<<"Reminder: "<<rem;
getch();
}

9. Write a program to compute simple interest and compound interest.


Ans.
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ float p,r,n,i,a;
clrscr();
cout<<"Enter the principle amount: ";
cin>>p;
cout<<"Enter the rate of intrest: ";
cin>>r;
cout<<"Enter the duration: ";
cin>>n;
i=p*r*n/100;
a=p*pow((1+r/100),n);
cout<<"Simple Intrest: "<<i<<endl<<"Compound Intrest: "<<a;
getch();
}

10. Write a program to: (i) print ASCII code for a given digit. (ii) print ASCII code
for backspace.(Hint: Store escape sequence for backspace in an integer variable).
Ans.
(i) #include<iostream.h>
#include<conio.h>

15
void main()
{ char ch;
int num;
cout<<"Enter digit: ";
cin>>ch;
num=ch;
cout<<"The ASCII code for "<<ch<<"is "<<num<<endl;
}
(ii) #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
char ch='\b';
int num=ch;
cout<<"The ASCII code for backspace is "<<num<<endl;
getch();
}

3 Marks Questions

1. Explain C++ data types with appropriate examples.


Ans. Data types are means to identify the type of data and associated operations of
handling it. C++ offers two types of data types:
i. Fundamental data types: These are the data types that are not composed of any
other data type. Following are the five fundamental data types:
(a) char: Stores character. For example, ‘a’, 65
(b) int: Integers are whole numbers. For example, 5, 39, -1917, 0
(c) float: A number having fractional part is a floating-point number.
For example, 3.14159
(d) double: Same as float data type but occupies twice as much memory as type
float. For example, 5.631
(e) void: Specifies an empty set of values.
ii. Derived data types: These are the data types that are composed of fundamental data
type. Following are the derived data types:
(a) Array: Array is a collection of element that has same name and same data
type. For example, int a[10].
(b) Function: A function is a named part of a program that can be invoked from
other parts of the program as often needed.
For example, float cube (float);.
(c) Pointer: A pointer is a variable that holds a memory address.
For example, char *a;.
(d) Reference: A reference is an alternative name for an object.
For example, int &sum = total;.
(e) Constant: A constant is a data item whose data value can never change during
the program run. For example, const int SIZE = 50;.
(f) Class: A class represents a group of similar objects.
(g) Structure: A structure is a collection of variables of different data types
referenced under one name.

16
(h) Union: A union represents a memory location shared by two or more different
variables.
(i) Enumeration: Enumeration is an alternative method for naming integer
constants.

2. Explain user-defined data types in C++ with appropriate examples.


Ans. The data types which are defined by users are called user-defined data types.
Following are user-defined data types:
i. Class: A class represents a group of similar objects which is achieved by
keyword class. For example,
class Student
{ char name[20];
int rollno;
float mark;
public:
void getdata();
void putdata();
};
ii. Structure: A structure is a collection of variables of different data types
referenced under one name, providing a
convenient means of keeping related information together which is achieved by
keyword struct. For example,
struct department
{
char name[20];
int num_emp;
char h_o_d[20];
float salary;
};
department newemp;
iii. Union: A union represents a memory location shared by two or more different
variables, generally of different
types at different times which are achieved by keyword union. For example,
union first
{ int a;
char c;
};
union first f1;
iv. Enumeration: Enumeration is an alternative method for naming integer
constants which is achieved by keyword
enum. For example, enum status { START = 0, PAUSE, GOO };

3. Write a program to accept three digits (i.e., 0 – 9) and print all possible
combinations from these digits. (For example, if the three digits are 1, 2, and 3
then all possible combinations are 123, 132, 231, 213, 312 and 321).
Ans. #include< iostream.h >
#include< conio.h >
void main( )
{ int a[3];

17
cout<<"Enter three digits :"<
cin>>a[0]>>a[1]>>a[2];
for ( int i = 0; i< 3; i++ )
{ for( int j = 0; j < 3; j++ )
{ for ( int k = 0; k < 3; k++ )
{ if ( i! = j && i! = k && j! = k )
cout << a[ i ] << a[ j ] << a[ k ]<<endl;
}
} }
}

4. An electricity board charges according to following rates:


For the first 100 units – 40 P per unit (P – Paise)
For the next 200 units – 50 P per unit
Beyond 300 unit – 60 P per unit.
All users are charged meter charge also which is Rs. 50/-.
Write a program to read the names of users and numbers of units consumed, and
print out the charges with
names.
Ans. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{ char name[20];
int unit;
float charge;
clrscr();
cout<<"Enter name: ";
gets(name);
cout<<"Enter unit: ";
cin>>unit;
if(unit<=100)
charge=((unit*40)/100)+50;
else if(unit>100 && unit<=300)
charge=((unit*50)/100)+50;
else(unit>300)
charge=((unit*60)/100)+50;
cout<<"Name: "<<name<<endl;
cout<<"Total Charge: "<<"Rs. "<<charge;
cout<<" including meter charge of Rs.50";
getch();
}

18
CHAPTER-8 OPERATORS & EXPRESSIONS IN C++

1 Mark Questions

1. What is the function of operators? What are arithmetic operators?


Ans. Operators represent specific operations. Arithmetic operators carry out arithmetic
for C++. These are unary +, unary -, +, -, *, / and %. For example, 4 + 2, 19 % 6,-a etc.

2. How is ‘unary +’ operator different from ‘+’ operator? How is ‘unary -’ operator
different from ‘-’ operator?
Ans. A ‘unary +’ gives the value of its operand whereas ‘+’ operator gives sum of its
operand’s value. A ‘unary –‘ changes the sign of its operand’s value whereas ‘-‘ operator
subtract the value of second operand from the value of first operand.

3. What are binary operators? Give examples of arithmetic binary operators.


Ans. Operators that act upon two operands are referred to as binary Operators. The +, -,
*, /, % etc are binary arithmetic operators. For example, 4 + 20 results in 24, 3 * 4
evaluates to 12.

4. What does the modulus operator % do? What will be the result of 7.2%2.1
and 8%3?
Ans. The % operator finds the modulus of its first operand relative to the second. The
result of 7.2%2.1 and 8%3 are 0.9 and 2 respectively.

5. What will be the result of a=5/3 if a is (i) float (ii) int?


Ans. (i) 1 (ii) 1

6. Assuming that res starts with the value 25, what will the following code
fragment print out? cout<<res--; cout<<++res;
Ans. 25 25

7. What will be the value of j = --k + 2k (l=k, l++) if k is 20 initially?


Ans. 95

8. What will be the value of P = P * ++J where J is 22 and P = 3 initially?


Ans. P = 69

9. What will be the value of following, if j = 5 initially? (i) (5* ++j)%6 (ii) (5* j++)%6
Ans. (i) 0 (ii) 1

10. A relational operator (a) assigns one operand to another (b) yields a boolean
(logical) result (c) compares two operands (d) logically combines two operands
Ans. (c) compares two operands

11. Write an expression that uses a relational operator to return true if the
variable total is greater than or equal to final.
Ans. if (total >= final) return true;

19
12. Given that i = 4, j = 5, k = 4, what will be the result of following expressions?
(i) i < k (ii) i < j (iii) i <= k (iv) i == j (v) i == k
(vi) j > k (vii) j >= i (viii) j != I (ix) j != k (x) j <= k
Ans. (i) false (ii)true (iii) true (iv) false (v) true
(vi) false (vii) true (viii) true (ix) true (x) false

13. What will be the order of evaluation for following expressions?


(i) i + 5>= j - 6? (ii) s + 10 < p - 2 + 2q (iii) i < j <k >i >= n
Ans. (i) + , - , >= (ii) + , - , + , < (iii) < , < , < , >=

14. What will be the result of the following if ans is 6 initially?


(i) cout<<ans = 8; (ii) cout<<ans == 8;
Ans. (i) ans = 8 is 8 (ii) ans = = 8 is 0

15. What could be the possible error resulting in the wrong behavior of the
following code? int r = -13, l = -12; cout<<"Result=" <<r<fabs(l);
Ans. There is a use of ‘<’ instead of ‘<<’ which is invalid.
Following is correct code: cout<<"Result="<<r<<fabs(l);

16. What is the function of logical operators? Write an expression involving a


logical operator to test if marks are 55 and grade if ‘B’.
Ans. Logical operators connect the relationships among values. Following expression
involve logical operator: if((marks==55)&&(garde=='B'))

17. The && and || operators (a) compare two numeric values (b) combine two
numeric values (c) compares two Boolean values (d) combine two Boolean values
Ans. (b) combine two numeric values

18. What is the order of evaluation in the following expressions:


(i) a>b || b<d? (ii) x==y && y<=m?
Ans. (i) (a>b )|| (b<d) : 1st a>b , 2nd b<c , 3rd ||
(ii) (x==y) && (y<=m) : 1st a==b , 2nd b==c , 3rd &&

19. What is the result of following expression: a>=b && (a+b)>a


(i) a=3, b=0 (ii) a=7, b=7?
Ans. (i) false (ii) true

20. What is the result of following expression if (i) check=3, (ii) check=0,
(iii) check=-3 ? (!check)
Ans. (i) false (ii) true (iii) false

21. Identify the order of evaluation in the following expression:


4 * 5 + 7 * 2 - 8 % 3 + 4 && 4/2 - 1 + 4 || 2 - 4 || 2 - 4 + 6 * 2
Ans. (((4 * 5)+(7 * 2)-(8 % 3)+4) && (4 / 2) - (1 + 4)) || (2 - 4) || (2 - 4(6* * 2))

20
22. Write a statement that uses a conditional operator to set grant to 10 if speed
is more than 68, and to 0 otherwise.
Ans. grant = speed>68 ? 10 : 0

23. What will be the result of following expression age>65 ? 350 : 100
if (i) age = 25 (ii) age = 65 (iii) age = 85:
Ans. (i) 100 (ii) 100 (iii) 350

24. What will be the result of following expression ans – val <500 ? 150 : 50
if (i) ans = 700, val = 300 (ii) ans = 800, val = 700?
Ans. (i) 150 (ii) 150

25. What will be the results of following expression if (i) ans = 700, val = 300 (ii)
ans = 800, val = 700? ans - (val <500 ? 150 : 50)
Ans. (i) 550 (ii) 750

26. Write a statement to print the size of (i) double type on your machine. (ii) a
long variable result.
Ans. (i) cout<<sizeof(double); (ii) long result; cout<<sizeof result;

27. What is the result of following expression?


(i) y = (t = 4, t + 3); (ii) y = ((t = 4, t + 3), (t – 2, t * 3))
Ans. (i) y = 7 (ii) y = 15

28. What is an expression? How many types of expression does C++ support?
Ans. An expression is any valid combination of operators, constants, and variables. C++
supports 3 types of expressions: arithmetic, relational or logical, compound etc.

29. Given the following set of declarations: char ch; int i, j, k; float a, b, c; double
p, q; Which of the following are arithmetic expressions
(i) ch = 40 (ii) i + j - k (iii) j % k (iv) a % b + c - i (v) p + q/b > i
Ans. (i) Not an arithmetic expression (ii) An arithmetic expression
(iii) An arithmetic expression (iv) Not an arithmetic expression
(v) Not an arithmetic expression

30. Using the declaration of previous question identify the logical expression in
the following expressions: (i) (a) (ii) (!a) (iii) a+b%c (iv) a&&!a (v) a||!a
Ans. (ii), (iv) and (v) are logical expressions.

31. Write equivalent C++ expressions for the following expressions

21
Ans.
(i) ut + ((1/2)(f*t*t)) (ii) sqrt (sin(a) + atan(a) – exp(2*x))
(iii) ((fabs(a) + b) >= (fabs(b) + a)
(iv) ((((3*x) + (5*y))/((5*x) + (3*y))) – ((8*x*y)/(2*y*x)))
(v) exp(fabs((2*x*x) – (4*x)))

32. What is type conversion? What is meant by implicit and explicit type
conversion?
Ans. The process of converting one predefined type into another is called Type
conversion. An implicit type conversion is a conversion performed by the compiler
without programmer’s intervention An explicit type conversion is user-defined that
forces an expression to be of specific type.

33.What is the process of type promotion? What is integral promotion?


Ans. In implicit conversion, all operands are converted up to the type of the largest
operand, which is called type promotion. The conversion of integer types (i.e., char,
short, enumerator, int) into int or unsigned int is called integral promotion.

34. What do you mean by type casting? What is type cast operator?
Ans. The explicit conversion of an operand to a specific type is called type casting and it
is done usig type-cast operator () that is used as (type) expression where type is a valid
C++ type to which the conversion is to be done.

35. What will be the resultant type of the following expression if ch represents a
char variable, i is an int variable, fl is a float variable and db is a double variable?
ch - i + db / fl - i * fl + db / i.
Ans. The resultant type of the expression is double as double is the largest data type.

37. Construct logical expression to represent the following conditions:


(i) ch is a lowercase character (The ASCII range for lowercase is 97 – 122)
(ii) a is odd but less than 57.
Ans. (i) ch>=97 && ch<=122 (ii) a%2!=0 && a<57

38. Construct logical expression o represent the following conditions: (i) Either age
is more than 70 or members are more than or equal to 8. (ii) grade is ‘B’ and exper
is more than 3 years.
Ans. (i) age>70 || members>=8 (ii) grade==’B’ && exper>3

39. If a = 50 and b = 4 then determine the result of the following:


(i) a += b (ii) a %= b (iii) a -= b (iv) a /= b
(v) a *= b (vi) cout<<100/9; (vii) float pi = 22/7; cout<<pi;
Ans. (i) 54 (ii) 2 (iii) 46 (iv)12.5 (v) 200 (vi) 11 (vii) 3

22
2 mark Questions:

1. Write a program which will raise any number X to a positive power n. obtain
values of x and n from user.
Ans. #include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ clrscr();
int X,p,res;
cout<<"Enter X: ";
cin>>X;
cout<<"Enter p: ";
cin>>p;
res=pow(X,p);
cout<<"\t"<<res;
getch(); }

2. Write a C++ program to input principle amount and time. If time is more than
10 years, calculate the simple interest with rate 8%. Otherwise calculate it with
rate 12% per annum.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
float i,p,r,n;
cout<<"Enter Price: ";
cin>>p;
cout<<"Enter Duration: ";
cin>>n;
if(n>10)
i=(p*8*n)/100;
else
i=(p*12*n)/100;
cout<<"\n"<<"Simple Interest: "<<i;
getch(); }

3. Write a C++ program to input a number. If the number is even, print its square
otherwise print its cube.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();

23
int n,res;
cout<<"Enter n: ";
cin>>n;
if(n%2==0)
res=n*n;
else
res=n*n*n;
cout<<"\n"<<res;
getch(); }

4. Write a C++ program to input a number. If the number n is odd and positive,
print its square root otherwise print n5.
Ans. #include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ clrscr();
int n,res;
cout<<"Enter n: ";
cin>>n;
if((n%2!=0) && (n>0))
res=sqrt(n);
else
res=n*n*n*n*n;
cout<<"\t"<<res;
getch(); }

5. Write a C++ program to input choice (1 or 2). If choice is 1, print the area of
circle otherwise print the perimeter of circle. User input the radius of circle.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int ch; float r,area,peri;
cout<<"Enter your choice: ";
cin>>ch;
switch(ch)
{ case 1:
cout<<"Enter radius: ";
cin>>r;
area=3.14*r*r;
cout<<"Area of circle: "<<area;
break;

24
case 2:
cout<<"Enter radius: ";
cin>>r; peri=2*3.14*r;
cout<<"perimeter of circle: "<<peri;
break;
default:
cout<<"Wrong choice";
}
getch(); }

6. Write a C++ program to input three integers and print the largest of three.
Ans.
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int a,b,c;
cout<<"Enter a, b, and c: ";
cin>>a>>b>>c;
if((a>b) && (a>c))
cout<<"Largest: "<<a;
else if((b>a) && (b>c))
cout<<"Largest: "<<b;
else
cout<<"Largest: "<<c;
getch(); }

7. Write a C++ program to input a student type (‘A’ or ’B’), if the type is ‘A’
initialize the college account with Rs. 200/- otherwise initialize with Rs. 300/-.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int clg_acc,hos_acc;
char type;
cout<<"Enter Student Type ('A' or 'B'): "; cin>>type;
if(type=='A')
{ clg_acc=200;
cout<<"College account is initialized with Rs."<<clg_acc; }
else
{ hos_acc=300;
cout<<"Hostel account is initialized with Rs."<<hos_acc; }
getch(); }

25
8. Write a program that reads in a character <char> from the keyboard and then
displays one of the following messages:
(i) If <char> is a lower case letter, the message
The upper case character corresponding to <char> is …
(ii) If <char> is a upper case letter, the message
The lower case character corresponding to <char> is ….
(iii) If <char> is not a letter, the message
The <chr> is not a letter
Hint. You will need to refer to a table of ASCII characters. Lowercase letters have
ASCII value range 97-122. Uppercase letters have ASCII value range 65-90.
Ans. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{ clrscr();
char ch;
cout<<"Enter character: ";
cin>>ch;
int code=ch;
if(code>=97 && code<=122)
{ cout<<"The upper case character corresponding to "<<ch<<" is: ";
cout<<(char)(code-32); }
if(code>=65 && code<=90)
{ cout<<"The lower case character corresponding to "<<ch<<" is:";
cout<<(char)(code+32); }
if((code<65 || code>90) && (code<97 || code>122))
{ cout<<"The "<<ch<<" is not a letter"; }
getch(); }

3 Marks Question:
1. Discuss all operators and their types
Ans. Operators are the symbols that represent specific operations.

1. Arithmetic Operators: Carry out arithmetic operations.

(a) Unary Operators: Operators that act on one operand.


(i) Unary +: Gives the value of its operand.
For example, if a = 5 then +a means 5.
(ii) Unary -: Changes the sign of its operand’s value.
For example, if a = -5 then +a means -5.

(b) Binary Operators: Operators that act upon two operands.


(i) Addition Operator (+): Gives sum of its operand’s value.
For example, 4 + 20 results in 24.
26
(ii) Subtraction Operator (-): Subtracts the second operand from its first o
For example, 14 – 3 evaluated to 11.
(iii) Multiplication Operator (*): Gives the product of its operands’ value.
For example, 3 * 4 evaluates to 12.
(iv) Division Operator (/): Divides the first operand by second.
For example, 100/5 evaluates to 20.
(v) Modulus Operator (%): Gives the remainder after dividing first operand
by second. For example, 19 % 6 evaluates to 1.

2. Increment/Decrement Operators (++, --): Add 1 or subtract 1 from operand’s


value. The increment and decrement operators come in two forms:
(i) Postfix version: First uses the value of the operand and then changes it.
For example, a++, b—
(ii) Prefix version: First changes its operand’s value and then uses it.
For example, ++a, --b

3. Relational Operators: Compare the values of their operands. It returns Boolean true
or false value. These are <, >, <=, >=, == and != i.e., less than, greater than, less than or
equal to, greater than or equal to, equal to and not equal to respectively.
For example, 6==5 returns false, 6>5 returns true.

4. Logical Operators: Connect the relationship among values. (i) Logical OR (||):
Evaluates to true if either of its operands evaluate to true. For example, (6<=6) || (5<3)
returns true. (ii) Logical AND (&&): Evaluates to true if both of its operands evaluate to
true. For example, (6<=6) || (5<3) returns false. (iii) Logical NOT(!): Negates the truth
value of its operand. For example, !(6<=6) returns false.

5. Conditional Operator (?:): (Ternary Operator) The general form of conditional


operator is expr1? expr2: expr3. It gives the value of expr2 if expr1 evaluates to true
otherwise it gives the value of the expr3. For example, 6>4? 9: 7 evaluates to 9.

6. Some other Operators:

(a) The sizeof operator: Returns the size of a variable or a data-type.


For example, sizeof (int) returns 2.

(b) The Comma operator: Combines together several expressions which are
evaluated from left-to-right and the value of the
rightmost expression becomes the value of the total
comma-separated expression.
For example, b = (a=3, a+1); first assign a the value 3
and then assigns b the value a+1 i.e., 4.

27
CHAPTER-9 FLOW OF CONTROL
1 Mark Questions

1.What is a null statement and a compound statement? What is the alternate


name for compound statement?
Ans. The simplest statement is a null statement i.e., just a semicolon;. A compound
statement is a sequence of statements enclosed by a pair of braces ( { } ). The alternate
name for compound statement is block.

2. What is the significance of a null statement?


Ans. A null statement is useful in those instances where the syntax of the language
requires the presence of a statement but where the logic of the program does not.

3. What are the three constructs that govern statement flow?


Ans. The three constructs that govern statement flow are sequence, selection or
iteration.

4. What is the significance of a test-condition in a loop?


Ans. The test-condition is a condition whose truth value decides whether the loop-body
will be executed or not. If the test-condition evaluates to true i.e., 1, the loop-body gets
executed, otherwise the loop is terminated.

5. What is a selection statement? Which selection statement does C++ provides?


Ans. The selection statement allows to choose the set-of-instructions for execution
depending upon an expression’s truth value. C++ provides two types of selection
statements: if and switch.

6. Can a conditional operator replace an if statement always?


Ans. No in some situation conditional operator can replace if statement but not always.

7. Correct the following code fragment (Identify the type of error):


if (x=1)
k=100;
else
k=10;
Ans. if (x==1)
k=100;
else
k=10;
This code has logical error.

8. What will be the output of the following code fragment? :


cin>>a;

28
if(a=5)
cout<<"Five";
else
cout<<"Not Five";
if the input given is: (i)7 (ii)5?
Ans. (i) Five (ii) Five

9. What will be the output of the following code fragment?


int year;
cin>>year;
if(year%100==0)
if(year%400==0)
cout<<"LEAP";
else
cout<<"Not centaury year";
if the input given is (i)2000 (ii)1900 (iii) 1971?
Ans. (i) LEAP (ii) Not centaury year (iii) No output

10. What will be the output of the following code fragment?


int year;
cin>>year;
if(year%100==0)
{ if(year%400==0)
cout<<"LEAP";
}
else
cout<<"Not centaury year";
if the input given is (i)2000 (ii)1900 (iii) 1971?
Ans. (i) LEAP (ii) No output (iii) Not centaury year

11. In a nested-if, how does the default matching of dangling-else take place?
Suggest a way to override the default dangling-else matching.
Ans. The default matching of dangling-else arises when in nested if statement, number
of ifs is more than the number of else clauses. One method of over-riding the default
dangling-else matching is to place the last occurring unmatched if in a compound
statement.

12. Write one advantage and one disadvantage of using ?: in place of an if.
Ans. Advantage:
Compare to if, ?: offer more concise, clean and compact code.
Disadvantage:
When ?: operator is used in its nested form, it becomes complex and difficult to
understand.

29
13. What is the significance of a break statement in a switch statement? What is
the effect of absence of break in a switch statement?
Ans. In a switch statement, when a match is found, the statement sequence associated
with that case is executed until the break statement or the end of switch statement is
reached. If a case statement does not include a break statement, then the control
continues right on the next statement until either a break is encountered or end of
switch is reached.

14. Write one limitation and one advantage of a switch statement.


Ans. Limitation:
The switch statement can only test for equality.
Advantage:
The switch statement is more efficient choice in terms of code used in a
situation that support the nature of switch operation.

15. What is “fall-through”? What is the significance of default clause in a switch


statement?
Ans. If a case statement does not include a break statement, then the control continues
right on the next statement until either a break is encountered or end of switch is
reached. This situation is called fall through. The default clause statement gets executed
when no match is found.

16. What are iteration statements? Name the iteration statements provided by
C++.
Ans. The statements that allow a set of instructions to be performed repeatedly are
iteration statements. C++ provides three iteration statements: for, while and do-while.

17. Which elements are needed to control a loop?


Ans. Following elements are needed to control a loop:
1. Initialization Expressions 2. Test Expression
3. Update Expression 4. The Body-of-the-loop

18. What is meant by an entry-controlled loop? Which C++ loops are entry-
controlled?
Ans. The entry-controlled loops impose control at the time of entry into the loop by
testing the test-expression before entering into a loop. The for and while loops are entry-
controlled loops.

19. What is meant by an exit-controlled loop? Which C++ loops are exit-
controlled?
Ans. The exit-controlled loops impose control at the time of exit from the loop by testing
the test-expression before exiting from the loop. The do-while is an exit-controlled loop.

30
20. What is the output of the following code fragment?
for(int i=10;i>0;i=i-3) cout<<i;
Ans. Output: 10741

21. What is the output of the following code fragment?


for(int i=1;i<10;i++)
cout<<i;
Ans. Output: 123456789

22. Why does “Hello” not print even once?


for(i=0;i>10;i++) cout<<”Hello”;
Ans. As value if i is not greater than 10, the test condition is evaluates to false. So the
“Hello” does not print even once.

23. What is the output of the following code?


for(r=0;r<4;r++)
{ for(c=0;c<10;c++)
cout<<"#";
cout<<"\n"; }
Ans. Output: ##########
##########
##########
##########

24. Write a for loop that displays the numbers from 51 to 60.
Ans. for(int i=51;i<60;i++)
{ cout<<i;
cout<<”\n”; }

25. Which expressions are optional in a for loop? Suggest a situation where an
empty loop is useful.
Ans. In a for loop, initialization expression, test expression and update expression are
optional. An empty for loop has its applications in pointer manipulations where you
need to increment or decrement pointer position without doing anything else.

26. An item declared in a for or while loop statement, can be accessed after the
statement is over. True or false?
Ans. False.

27. What is meant by a variable’s scope?


Ans. The program area inside which a variable can be accessed, is called scope.

31
28. What is the difference between a while and do-while loop?
Ans. While loop is entry-check loop. The test-expression is evaluated at the beginning of
the loop.

Syntax: while(test-expression)
{
loop-body
}
Do-while loop is exit-controlled loop. The test-expression is evaluated at the end of the
loop.
Syntax: do
{
statement;
} while(test-expression);

29. Write a while loop that displays numbers 2, 4, 6, 8, ….., 18, 20.
Ans. int i=2;
while(i<=20)
{ if(i%2==0)
{ cout<<i; }
i++;
cout<<"\n";
}

30. Write a do-while loop that displays numbers 2, 4, 6, 8, ….., 18, 20.
Ans. int i=2;
do {
if(i%2==0)
{
cout<<i;
}
i++;
cout<<"\n";
} while(i<=20);

31. Write an equivalent while loop for the following loop:


for(int i=0, sum=0;i<=20;i=i+2)
sum+=i;
Ans. int i=0, sum=0;
while(i<=20)
{ sum+=i; i=i+2; }
32. How many times is the following loop executed?
int s=0,i=0;

32
while(i++<5)
s+=i;
Ans. 5 times.

33. How many times is the following loop executed?


int s=0,i=0;
do
{ s+=i;
} while(i<5);
Ans. Infinite loop

34. Name the jump statements provided by C++. Compare break and continue
statements.
Ans. C++ provides four jump statements: return, goto, break and continue. A break
statement skips the rest of the loop and jumps over to the statement following the loop
whereas, the continue statement skips the rest of the loop statements and causes the
next iteration of the loop.

35. The goto statement causes control to go to


(a) an operator (b) a label (c) a variable (d) a function.
Ans. (b) a label

36. The break statement causes an exit (a) only from the innermost loop (b) only
from the innermost switch (c) from all loops and switches (d) from the innermost
loop or switch.
Ans. (a) only from the innermost loop (or the current loop)

37. The exit() function breaks out of (a) the function it appears in (b) the loop it
appears in (c) the block it appears in (d) the program it appears in.
Ans. (d) the program it appears in.

38. Which header file must be included in the program for using the exit()
function?
Ans. The header file process.h must be included in the program for using the exit()
function.

33
2 Mark Questions

1. What is the problem of dangling-else? When does it arise? What is the default
dangling-else matching and how it can be overridden?
Ans. The nested if-else statement introduces a source of potential ambiguity referred to
as dangling-else problem. This problem arises when in nested if statement, number of
ifs is more than the number of else clauses. One method of over-riding the default
dangling-else matching is to place the last occurring unmatched if in a compound
statement. In nested if statement, a dangling else statement goes with the preceding
unmatched if statement. This is called default dangling-else matching. One method of
over-riding the default dangling-else matching is to place the last occurring unmatched
if in a compound statement.

2. Compare an “if “ and a “?:“ operator.


Ans. 1. Compared to if-else sequence, ?: offer more concise, clean and compact code,
but it is less obvious as compared to if.
2. Another difference is that the conditional operator ?: produces an expression, and
hence a single value can be assigned or incorporated into a larger expression, whereas,
if is more flexible. The if statement can have multiple statements. Multiple assignments
and expressions in its body.
3. When ?: operator is used in its nested form, it becomes complex and difficult to
understand. This form of ?: is generally used to conceal the purpose of code.

3. Given the following code fragment:


if (a==0) cout<<"Zero";
if (a==1) cout<<"One";
if (a==2) cout<<"Two";
if (a==3) cout<<"Three";
Write an alternative code (using if) that saves on number of comparisons.
Ans. if (a==0) cout<<"Zero";
else if (a==1) cout<<"One";
else if (a==2) cout<<"Two";
else if (a==3) cout<<"Three";

4.Discuss when does an if statement prove more advantageous over a switch


statement.
Ans. An if statement prove more advantageous over a switch statement to evaluate a
relational or logical expression i.e., multiple conditions.
The if-else construction lets us use a series of expressions that may involve unrelated
variables and complex expressions.
The if-else statement can handle floating-point tests also apart from handling integer
and character test whereas a switch cannot handle floating-point tests.
The if-else can handle ranges whereas switch cannot.

34
5. Discuss when does a switch statement prove more advantageous over an if
statement.
Ans. The switch statement is more efficient that if in a situation that support the
nature of switch operation.
While using switch, we can optimize our code by putting the most cases first. This way
unnecessary comparisons and thereby wastage of CPU time may be avoided.

6. Rewrite the following code using switch.


if (a==0)
cout<<"Zero";
else if (a==1)
cout<<"One";
else if (a==2)
cout<<"Two";
else if (a==3)
cout<<"Three";
Ans. switch(a)
{ case 0:
cout<<"Zero"; break;
case 1:
cout<<"One"; break;
case 2:
cout<<"Two"; break;
case 3:
cout<<"Three"; break; }

7. What will be the output of the following code fragment when the input is
(a) ‘A’ (b) ‘C’ (c) ‘D’ (d) ‘F’ ?
cin>>ch;
switch(ch)
{case 'A': cout<<” Grade A ";
case 'B': cout<<” Grade B ";
case 'C': cout<<” Grade C "; break;
case 'D': cout<<” Grade D ";
default: cout<<”Grade F"; }
Ans. (a) Grade A Grade B Grade C (b) Grade C (c) Grade D Grade F (d) Grade F

8. Predict the output of following codes:


(a) if(!3)
{ cout<<"Tricky "; }
cout<<" Yes";
b) if(3)
cout<<"Tricky again ";

35
else
cout<<"Am I right? ";
cout<<" No???";
(c) if(0)
cout<<"Third time Tricky";
cout<<"Am I right?";
(d) if(!0)
cout<<"Fourth time again";
cout<<" No???";
(e) if(0)
cout<<"plz! Not again \n";
else
cout<<"Promise, this is the last time ";
cout<<" Thank God!";
Ans. (a) Yes (b) Tricky again No??? (c) Am I right? (d) Fourth time again No???
(e) Promise, this is the last time Thank God!

9. Predict the output of following codes:


(a) int X=3, y=6;
if(X>=3) cout<<"Zip Drive"<<endl;
if((X<=3) && (y>6)) cout<<"Scanner"<<endl;
if((X==3) && (y>=6)) cout<<"TFT LCD Screen"<<endl;
if((X<=3) && (y>6)) cout<<"CD Burner"<<endl;
(b) int x=3, y=6;
if(x>=3) cout<<"Zip Drive"<<endl;
else if((X<=3) && (y>6)) cout<<"Scanner"<<endl;
else if((X==3) && (y>=6)) cout<<"TFT LCD SCreen"<<endl;
else if((X<=3) && (y>6)) cout<<"CD Burner"<<endl;
else cout<<What????";
Ans. (a) Zip Drive TFT LCD Screen (b) Zip Drive

10. Identify the possible error(s) in the following code fragment. Discuss the
reason(s) of error(s) and correct the code:
int f=1,s;
for(int a=40;(a);a--)
f*=a; s=0;
for(int a=1;a<40/a++)
s+=a;
Ans. Error 1. Variable ‘a’ is declared twice which is invalid.
2. There is a ‘/’ instead of semicolon in second for loop which is invalid.
Correct code: int f=1,s;
for(int a=40; (a); a--)
f*=a; s=0;

36
for(a=1;a<40;a++)
s+=a;

11. Identify the possible error(s) in the following code fragment. Discuss the
reason(s) of error(s) and correct the code:
(a) cin>>i>>j;
while(i<j)
cout<<i*j;
i++;
(b) cin>>i>>j;
while(i<j)
{ cout<<i*j;
i++; }
Ans. (a) The while loop should be in curly braces. The correct code is as follows:
cin>>i>>j;
while(i<j)
{ cout<<i*j;
i++; }
(b) This code is correct.

12. What is WRONG with following code fragments?


(a) for (int x=0;x>0;x--)
cout<<x;
(b) int n=7;
do { cout<<"check this !!";
n-=2; } while(n!=2);
(c) int p=8;
do { cout<<"In the loop";
p*=2; } while(p%2==0);
(d) int i=9;
while((i<10) && (i>24))
cout<<"Here I am - in the loop";
i--;
(e) for(int k=2,k<=12,k++)
cout<<k*k*k<<endl;
(f) num=4;
while(num<10)
{ eggs=num*12;
cout<<eggs; }
Ans. (a) x is initialized with 0, and x is decremented so, the test-expression is
evaluated to false every time and statement does not get executed.
(b) Increment/decrement statement is missing so it will create a infinite loop.
(c) Increment/decrement statement is missing so it will create a infinite loop.

37
(d) while loop should be in curly braces.
(e) There should be a ‘;’ instead of ‘,’ in for loop.
(f) Increment/decrement statement is missing so it will create a infinite loop.

13. What output shall be produced by following code fragments?


(a) for(outer=0;outer<2;++outer)
for(inner=0;inner<=3;++inner)
cout<<outer<<inner<<"\t”;
(b) for(outer=0;outer<3;++outer)
for(inner=0;inner<=5;++inner)
cout<<inner<<" ";
cout<<endl;
(c) for(n1=10;n1>5;--n1)
for(n2=1;n2<4;n2++)
cout<<n1<<" "<<n2<<" ";
cout<<endl;
(d) char outer, inner;
for(outer='F'; outer>='A'; --outer)
for(inner='A'; inner<=outer; inner++)
cout<<inner
cout<<”\t”;
Ans.
(a) 00 01 02 03 10 11 12 13

(b) 0 1 2 3 4 5
012345
012345

(c) 10 1 10 2 10 3
919293
818283
717273
616263

(d) ABCDEF ABCDE ABCD ABC AB A

14. Write a C++ code check whether square root of a number is prime or not.
Ans. void main()
{ clrscr();
int n,m,f=0;
cout<<"Enter n: ";
cin>>n; m=sqrt(n);
cout<<"\t"<<m;

38
for(int i=2;i<m/2;i++)
{ if(m%i==0)
{ f=1;
goto lb;
}
}
lb:
if(f==0)
cout<<"Prime";
else
cout<<"Not Prime";
getch();
}

15. Write a C++ code to print first n odd numbers in descending order.
Ans. void main()
{ clrscr();
int n,m,f=0;
cout<<"Enter n: ";
cin>>n;
for(int i=n;i>=0;i--)
{ if(i%2!=0)
{cout<<i<<endl;
}
getch(); }

16. Give the four sides of a rectangle. Write a program to find out whether its area
is greater than its perimeter.
Ans. void main()
{ clrscr();
float l,b,area,peri;
cout<<"Enter length and breadth: ";
cin>>l>>b;
area=l*b;
peri=2*(l+b);
cout<<"Area= "<<area;
cout<<"Perimeter= "<<peri;
if(area>peri)
cout<<"Area is greater than perimeter";
else
cout<<"Area is not greater than perimeter";
getch(); }

39
17. Write a short program to print the following series:
(i) 1 4 7 10 . . . . . . . 40. (ii) 1 -4 7 -10 . . . . . . -40.
Ans. (i) void main()
{ clrscr();
for(int i=1;i<=40;i+=3)
{ cout<<"\t"<<i; }
getch(); }
(ii) void main()
{ clrscr();
for(int i=1;i<=40;i+=3)
{ if(i%2!=0)
cout<<"\t"<<i;
else
cout<<"\t-"<<i;
}
getch(); }

18. Write a short program to find whether the given character is digit or a letter.
Ans. void main()
{ clrscr();
char ch;
cout<<"Enter a character: ";
cin>>ch;
if(ch>=48 && ch<=57)
cout<<"\n"<<"You entered a digit";
else if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
cout<<"\n"<<"You entered a letter";
else
cout<<"\n"<<"You entered a special character";
getch(); }

19. Write a C++ program to convert a lowercase character to uppercase.


(Hint: Subtracting 32 from a lowercase character gives you equivalent uppercase
character e.g., ‘b’ – 32 will give you ‘B’ and ‘w’ – 32 will give you ‘W’).
Ans. void main()
{ clrscr();
char ch,ch2;
cout<<"Enter a lowercase character: ";
cin>>ch;
ch2=ch-32;
cout<<"\t"<<ch2;
getch(); }

40
20. Write a short program to calculate simple interest.
Ans. void main()
{ clrscr();
float p,r,n,i;
cout<<"Enter the principle amount: ";
cin>>p;
cout<<"Enter the rate of intrest: ";
cin>>r;
cout<<"Enter the duration: ";
cin>>n;
i=(p*r*n)/100;
cout<<"Simple interest= "<<i;
getch(); }

21. Write a program to find average of list of numbers entered through keyboard.
Ans. void main()
{ clrscr();
int i,a,n[10],sum=0;
float avg=0;
for(i=0;i<10;i++)
{
cout<<"Enter no."<<i<<": ";
cin>>n[i]; sum+=n[i];
}
cout<<endl<<"Sum="<<sum; avg=sum/10;
cout<<"Average: "<<avg;
getch(); }
22. Write a sample c++ code to (i) Calculate area of a triangle
(ii) Find the radius of a circle whose area is given
(iii) Calculate the volume( 4/3 π r3 ) and area of a sphere ( 4 π r2 ).
Ans. (i) void main()
{ clrscr();
float area,a,b,c,s;
cout<<"Enter three sides of triangle: ";
cin>>a>>b>>c;
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"Area= "<<area;
getch(); }

(ii) void main()


{ clrscr();
cout<<"Enter area:";
41
double A;
cin>>A;
double r = pow(7 * A / 22, 0.5);
cout<<"Radius of circle is:"<<r;
getch(); }

(iii) void main()


{ clrscr();
float r,v,a;
cout<<"Enter radius";
cin>>r;
v=(4/3)*3.14*r*r*r; a=4*3.14*r*r;
cout<<"Volume = "<<v<<endl;
cout<<"Area = "<<a<<endl;
getch(); }

36.Write a short program to find largest number of a list of numbers entered


through keyboard.
Ans. void main()
{ clrscr();
int m,a[10],i;
for(i=0;i<10;i++)
{ cout<<"Enter no."<<i<<": ";
cin>>n[i];
}
m=a[0];
for(i=1;i<10;i++)
{ if(a[i]>m)
m=a[i];
}
cout<<"Largest = "<<m;
getch(); }

37. Write a program using nested loops to produce the following designs:
(a) A
AB
ABC
ABCD
ABCDE
ABCDEF
Ans. (a) void main()
{ clrscr();
char ch='A';

42
int n;
cout<< "\n Enter the height of the triangle :";
cin>> n;
for(int i=1; i< = n ; i++)
{
ch = 'A';
for(int j = 1; j< = i; j++)
{
cout<< ch<< " ";
ch++;
}
cout<< "\n";
}
getch(); }

(b) & & & & & & &


& & & & &
& & &
&
Ans: void main()
{ clrscr();
int n;
clrscr();
cout<<"\n Enter height of a triangle :";
cin>>n;
for(int i = n, sp = 0; i >0 ; i --, sp++)
{
for(int k=0; k<=sp; k++)
cout<<" "<<" ";
for( int j = 1; j < 2*i ; j++)
cout << "&" << " ";
cout<<"\n";
}
getch(); }

(c) &
& &
& &
& &
& &
& & & & & & & & & & &

43
Ans. (c) void main()
{ clrscr();
int n;
cout<<"\n Enter height :";
cin>>n;
for(int r = 1, sp = n-1 ; r<= n ; r++, sp--)
{
for (int k = 0; k<=sp ; k++)
cout<< " " ;
for(int c = 1; c < 2*r ; c++)
{ if(c==1 || c == 2*r - 1 || r == n )
cout << " & "; else cout<< " " ;
}
cout<< endl;
}
getch(); }

38. Write a C++ program using nested loops to produce a rectangle of *’s with 6
rows and 20 *’s per row.
Ans. void main()
{ clrscr();
int i,j;
for(i=1;i<=6;i++)
{
for(j=1;j<=20;j++)
{
cout<<"*";
}
cout<<”\n”;
}
getch();
}

44
3 Mark Questions:

1. Given three numbers A, B, and C, write a program to write their values in an


ascending order. For example, if A=12, B=10 and C=15, your program should print
out: Smallest number = 10 Next highest number = 12 Highest number = 15
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
float a,b,c,small,mid,high;
cout<<"Enter three no. : ";
cin>>a>>b>>c;
small=a;
if(b<small)
small=b;
if(c<small)
small=c;
if(a==small)
{ if(b<c)
{ mid=b;
high=c;
}
else
{ mid=c;
high=b;
}
}
else if(b==small)
{ if(a<c)
{ mid=a;
high=c;
}
else
{ mid=c;
high=a;
}
}
else if(c==small)
{ if(a<b)
{ mid=a;
high=b;
}
else

45
{ mid=b;
high=a;
}
}
cout<<"Smallest number = "<<small<<endl;
cout<<"Next highest number = "<<mid<<endl;
cout<<"Highest number = "<<high<<endl;
getch(); }

2. A bank accepts fixed deposits for one year or more and the policy it adopts on
interest is as follows: (i) If a deposit is less than Rs. 2000 and for 2 or more years,
the interest rate is 5% compound annually. (ii) If a deposit is less than Rs. 2000 or
more but less than 6000 and for 2 or more years, the interest rate is 7%
compound annually. (iii) If a deposit is more than Rs. 6000 and is for 1 year or
more, the interest is 8% compound annually. (iv) On all deposit for 5 years or
more, interest is 10 percent compound annually. (v) On all other deposits not
covered by above conditions, the interest is 3 percent compounded annually.
Given the amount deposited and the number of years, write a program to calculate
the money in the customer’s account at the end of the specified time.
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int r,y;
float depo,tot_amt;
cout<<"Enter deposite : ";
cin>>depo;
cout<<"Enter year : ";
cin>>y;
if(depo<2000 && y>=2)
r=5;
else if(depo>=2000 && depo<6000 && y>=2)
r=7;
else if(depo>6000 && y>=1) r=8; else if (y>=5)
r=10;
else
r=3;
tot_amt=depo+((depo*r)/100);
cout<<"Total amount is: "<<tot_amt;
getch(); }

46
3. Write a complete C++ program to do the following:
(i) read an integer X
(ii) from an integer Y by reversing the digits of X and integer S having sum of digits of X
(iii) output Y and S
(For example, if X is equal to 5076, then Y should be equal to 6705 and S should be 18)
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ int X, Y = 0, S = 0;
int r = 0;
cout<< "\n Enter an integer :";
cin >> X;
for(int i = X; i>0 ; i = i /10)
{ r = i % 10; S =S+r; Y = Y*10 + r; }
cout << "\n The reverse of " << X << " is " << Y;
cout<< "\n The Sum of the digits = " << S;
getch(); }

4. Write a program to find the LCM and GCD of two numbers.


Ans. #include<iostream.h>
#include<conio.h>
void main()
{ int x,y,gcd=1;
cout<<"ENTER 1st NO : ";
cin>>x;
cout<<"\n\nEnter 2nd NO. :";
cin>>y;
for(int i=1;i<1000;++i)
{ if((x%i==0)&&(y%i==0))
gcd=i; }
cout<<"\n\n\nGCD :"<<gcd;
cout<<"\n\n\nLCM :"<<(x*y)/gcd;
getch(); }

5. Write a program to print the truth table for XY + Z.


Ans. #include<iostream.h>
#include<conio.h>
void main()
{ cout<< "Truth Table\n";
cout<< "X\t Y\t Z\t \t XY+Z \n\n";
for(int i = 0 ; i<=1 ; i++)
{
for(int j = 0; j<=1; j++)

47
{
for(int k = 0; k<=1; k++)
{ cout<< i<< "\t"<< j << "\t" << k << "\t\t";
if ( (i == 1 && j == 1) || k == 1)
cout<< 0;
else cout<< 1;
}
cout<<"\n";
}
}
getch(); }

6. Write a C++ program to print Fibonacci series (upto 10 terms). [A fibonacci


series is the one in which every term (third term onwards) is sum of previous two
terms. 0 1 1 2 3 5 . . . is a Fibonacci series).
Ans. void main()
{ clrscr();
int f=0,s=1,t;
cout<<f<<" "<<s<<" ";
for(int i=3;i<=10;i++)
{ t=f+s;
cout<<t<<" ";
f=s;
s=t;
}
getch(); }

7. Given a list of integers, write a program to find those which are palindromes.
(For example, the number 4321234 is a palindrome as it reads the same from left to
right and from right to left.)
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ char str[100];
cout << "Enter no.:";
cin >> str;
int x = strlen(str)-1;
for(int i = 0; i <= x; i++)
{ if (str[i] == str[x-i])
{ continue; }
else
{ cout<<"Not a palidrome" << endl;
exit(0); }

48
}
cout << "Yes Entered no. is a palidrome"<< endl;
getch(); }

8. Write a complete C++ program to do the following:


(i) Read an integer X.
(ii) Determine the number of digits n in X.
(iii) Form an integer Y that has the number of digits n at ten’s place and the
most significant digit of X at one’s place.
(iv) Output Y.
(For example, if X is equal to 2134, then Y should be 42 as there are 4 digits
and the most significant number is 2)
Ans. void main()
{ clrscr();
int X, Y = 0, n = 0;
int r = 0;
cout<< "\n Enter an integer :";
cin >> X;
for(int i = X; i>0 ; i = i /10)
{ r = i % 10;
n++;
}
Y = n * 10 + r;
cout << "\n The given number is " << X ;
cout<< "\n The new required number is = " << Y;
getch(); }

9. Write a C++ program print every integer between 1 and n divisible by m. also
report whether the number that is divisible by m is even or odd.
Ans. #include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{ clrscr();
int n, m;
cout<< "\n Enter the value of n :";
cin >> n; \
cout<< "\n Enter the value of m :";
cin >> m;
if(m>n)
{ cout<< "\n The number " << n << " is not divisible by " << m;
exit(1); }
for( int i = n ; i > = m ; i-- )

49
{ if(i % m == 0)
cout << "\n " << i << " is divisible by " << m;
if(i%2 == 0)
cout<< "\n The number " << i << "Even";
else
cout<< "\n The number " << i << "Odd";
}
getch(); }

10. Write C++ program to sum the given sequences:


(a) 𝟐/𝟗 – 𝟓/13 + 𝟖/17 . . . . . . (b) 12 + 32 + 52 + . . . . + n2
Ans. (a) #include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ int i,n,sign=1;
float a=2,b=9;
clrscr();
cout<<"Enter the number of terms in the series: ";
cin>>n;
float sum = a/b;
for(i=1;i<n;i++)
{ a=a+3; b=b+4;
sign= -1*sign;
sum+=sign*(a/b);
}
cout<<"\nThe sum of the series is = "<<sum;
getch(); }
(b) #include<iostream.h>
#include<conio.h>
void main()
{ float n,sum=0;
cout<<"Enter n: ";
cin>>n;
for(int i=1;i<=n;i++)
{ if(i%2==1)
{ sum=sum+(i*i);
cout<<i*i<<"\t";
}
}cout<<endl<<"Sum= "<<sum;
getch(); }

50
11. Write C++ program to sum the sequence 1 + 𝟏/𝟏! + 𝟏/𝟐! + 𝟏/𝟑! + . . . . . . .
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
float n, a, s, sum=0,fact=1;
cout<<"Enter n: ";
cin>>n;
for(int i=1;i<=n;i++)
{ fact=fact*i;
sum+=1/fact;
cout<<"\t"<<fact; }
cout<<endl<<"Sum= "<<1+sum;
getch(); }

12. Write a program to accept the age of n employees and count the number of
persons in the following is group: (i) 26 – 35 (ii) 36 – 45 (iii) 46 - 55
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int a[20], n, m, age;
int c1=0,c2=0,c3=0;
cout<<"Enter how many employees : ";
cin>>n;
for(int i=0;i<n;i++)
{ cout<<"Enter age"<<i+1<<" employe: ";
cin>>a[i];
}
for(i=0; i<n; i++)
{ if(a[i]>=26 && a[i]<=35)
c1++;
else if(a[i]>=36 && a[i]<=45)
c2++;
else if(a[i]>=46 && a[i]<=55)
c3++;
}
cout<<"Number of employees between age 26 - 35 years are: "<<c1<<endl;
cout<<"Number of employees between age 36 - 45 years are: "<<c2<<endl;
cout<<"Number of employees between age 46 - 55 years are: "<<c3<<endl;
getch(); }

51
13. Write a program to find the sum of the following series:
𝒙𝟐 𝒙𝟑 𝒙𝒏
x+ + + ……. +
𝟐 𝟑 𝒏
Ans. #include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ int series=0; int i,n,x; clrscr();
cout<<"ENTER THE VALUE OF N :";
cin>>n;
cout<<"\n ENTER THE VALUE OF X :";
cin>>x;
for(i=1;i<=n+1;i++)
{ series+=(pow(x,i)/i);
cout<<pow(x,i)<<endl;
}
if(n==0)
cout<<"\n Series = 0 ";
else
cout<<"\n Series = "<<series;
getch(); }

2 n
14. Write a program to find sum of the series S = 1 + x + x + . . . . . . + x .
Ans. #include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ int sum=0,x=0,n=0;
clrscr();
cout<<"Enter value for x :";
cin>>x;
cout<<"Enter value for n :";
cin>>n;
for(int i=0;i<=n;i++)
{
sum = sum + pow(x,i);
cout<<pow(x,i);
}
cout<<"Sum is:" << sum;
getch(); }

52
CHAPTER-11
FUNCTIONS
1 Mark Questions

1.A function’s single most important role is to (a) give a name to a block of code
(b) reduce program size (c) accept argument and provide a return value (d) help
organize a program well
Ans. (d) help organize a program well

2.Define a function. What is the name of one-statement description of a function?


Ans. A function is a subprogram that acts on data and often returns a value. The name
of one-statement description of a function is PROTOTYPE.

3. Function prototype is alternatively called. What is the statement specifically


called that invokes a function?
Ans. A function prototype is alternatively called function declaration. The statement that
invokes a function is specifically called function call.

4. What is a function declaration? How is a function declaration different from a


function definition?
Ans. A function declaration tells the program about the type of the value returned by the
function and the number and type of arguments. A function declaration has no body
and no code. A (prototype) declaration introduces a function name to the program. On
the other hand, a definition tells the Program, what is the function doing and how is it
doing so.

5. What are actual and formal parameters of a function?


Ans. The parameter that appear in a function call statement i.e., which are passed are
actual parameters. The parameter that appear in a function definition i.e., which receive
the passed value are formal parameters.

6. Where is a function’s return type specified? What is the return type of a


function that does not return a value? How many values can be returned from a
function?
Ans. A function’s return type is specified first in the function prototype. The return type
of a function that does not return a value is void. Only one value can be returned from a
function.

7. What are global and local prototypes?


Ans. Global prototype: If the function’s prototype appears outside all other functions in
the program file, then it is called global prototype.
Local prototype: If the function’s prototype appears within other functions in the
program file, then it is called local prototype.

53
8. When can a function prototype be omitted?
Ans. When the function definition appears before its calling function.

9. Construct function prototype for descriptions given below:


(i) Rarb() take no argument and has no return value.
(ii) mains() takes a float argument and returns an int.
(iii) san() takes two double arguments and returns a double.
(iv) sum() takes an int array and an it value and returns a long result.
(v) check() takes a string argument and returns an int.
Ans. (i) void Rarb();
(ii) int mains(float);
(iii) double san(double, double);
(iv) long sum(int arr[], int);
(v) int check(char []);

10. What is the condition of using a function in an expression? When a function


returns a value, the entire function call can be assigned to a variable. State True
or False?
Ans. Only the functions returning a value can be used in expressions. True.

11. Identify the errors in the function prototypes given below:


(i) float average (a,b);
(ii) float mult(int x, y);
(iii) void calc(int a[], s=10);
(iv) void arithop (int a[], int b[], int s=10, int j);
(v) float doer (int, int, float=3.14);

Ans. Error Correction


(i) datatype of the argument is missing.
float average(int a, int b);
(ii) datatype of the second argument is missing.
float mult(int x,int y);
(iii) datatype of the second argument is missing.
void calc(int a[],int s=10);
(iv) The argument s cannot have a default value unless argument on its right also
has its default value.
void arithop(int a[], int b[], int s=10, int j=3);
(v) Third argument for which the default value has been provided is not named.
float doer(int, int, float T=3.14);

12. When is a default argument value used inside a function?


Ans. To keep the original copy of the argument value intact.

54
13. What is the use of constant arguments?
Ans. By using constant argument the function cannot modify the values as the values
are constant.

14. Given the function:


int thrice(int x)
{
return a*3;
}
Write a main() function that is necessary to call this function.
Ans. void main()
{ int t;
t=thrice(4);
cout<<t;
getch(); }

15. What is the principle reason for passing argument by value?


Ans. The principle reason for passing argument by value is that the original copy of the
argument value remains intact.

16. What is the principle reason for passing argument by reference? In a function
call, what all data items can be passed by reference?
Ans. The principle reason for passing argument by reference is reflect the changes in
original values. In a function call, the arguments which are pass by reference in function
declaration are passed by reference.

17. How are arrays passed in a function? What are the three ways of receiving an
array in a function?
Ans. In C++, an array can be passed as a pointer to an array by specifying the array's
name without an index. Following are the three ways of receiving an array in a function:
a) Formal parameters as a pointer.
b) Formal parameters as a sized array.
c) Formal parameters as an unsized array.
18. Write the function prototypes for the function definition given below: double
f() { : return 1.0; }
Ans. double f();

19. Write the function declaration for the definition given below:
int &f1()
{ int a,b;
return b; }
Ans. int &f1();

55
20. When can a function appear on the left side of an assignment statement?
Ans. Only the function returning a reference can appear on the left-hand side of an
assignment expression.

21. If the return type of a function is missing, what happens? What is the role of a
return statement in a function?
Ans. If the return type of a function is missing, it is assumed to be returning int values.
The return statement is used for immediate exit from the function or return a value to
the calling code.

22. What are the three types of functions in C++?


Ans. The three types of functions in C++ are: 1. Computational functions.
2. Manipulative Functions. 3. Procedural Functions.

23. Write a declaration for a function called fun() that takes two arguments and
returns a char. The first argument is int and is not to be modified. The second
argument is float with a default value of 3.14.
Ans. char fun(const int a, float b = 3.14);

24. What is meant by scope? What all kinds of scope are supported by C++?
Ans. The program part in which a particular piece of code or a data value can be
accessed is known as its scope. C++ provides four kinds of scope: local, function, file and
class.

25. How is a global prototype different from a local prototype? How is a global
variable different from a local variable?
Ans. A local prototype is placed in the body of another function and the function is
locally available to the function that declares it whereas, a global prototype is placed
outside all the functions and the function is globally available to all the functions. A
local variable is declared inside the function and is locally available within the function,
whereas a global variable is declared outside all the functions and is globally available to
all the functions.

26. Give the following code segment:


float a,b;
int main()
{ char ch;
{ int i=0; : }
}
void f1(char gr)
{ short x,y; : }
Write scopes for all the variables mentioned above.

56
Ans. a,b -> file scope
ch -> function scope (main())
i -> block scope
gr -> function scope of f1()
x,y -> function scope of f1()

27. Write a function that interchanges the value of two integers A and B without
using any extra variable.
Ans. void swap(int x,int y)
{ x=x+y;
y=x-y;
x=x-y;
cout<<"\n The swaped value in x = " << x << " and y = " << y;
}

28. Differentiate between CALL by reference and CALL by value.


Ans. In call by value, the method copies the values of actual parameters, whereas in call
by reference, a reference or the address of the original variable is passed.

29. Write a function which will take a string and returns the world count. Each
word is separated by a single space.
Ans. int word_cnt(char str[50])
{ int c=1;
for(int i=0;str[i]!=’\0’;i++)
{ if( str[i]==’ ’ )
c++; }
return c; }

30. Write a function which will take the height of the person in inches and
displays the height in feet and inches in two separate variables.
Ans. void convert(int inch)
{ int f, i;
f=inch/12;
i=inch%12;
cout<<f<<" feet "<<i<<" inches"; }

31. What is the significance of empty parentheses in a function declaration?


Ans. It shows that the function is not expecting any argument.

57
2 Mark Questions

1. List the steps you would follow using a function. Answer your question with the
help of an example.
Ans. Before using a function in C++, three things that are required are:
1. Function Declaration to specify the function’s interface to the program.
2. Function Definition to tell the program about what and how a function is doing.
3. Function call to invoke the function.
For example, int sum(int a,int b); //Function Declaration
int sum(int a,int b) //Function Definition
{ return a+b; }
void main()
{ int res;
res=sum(5,2); //Function Call }

2. What is role of void keyword in declaring functions?


Ans. void data type specifies an empty set of values and it is used as the return type for
functions that do not return a value. Thus, a function that does not return a value is
declared as follows:
void function-name (parameter list);
A function that does not require any parameter can be declared as follows: type
function-name(void);

3. Describe the different styles of function prototypes in C++ using appropriate


examples.
Ans. A general form of function prototype is as shown below:
type function-name(parameter list);
In a function prototype, the names of the arguments are optional. Following, are some
examples of function prototypes:
float volume(int a, float b, float c);
float area(float, float);
float power(int m, int n=2);
int sum(const int a, const int b);
int absval(int a);

4. What do you understand by default arguments and constant arguments? Write a


short note on their usefulness.
Ans. C++ allows us to assign default value to a function’s parameter which is useful in
case a matching argument is not passed in the function call statement.
The default values are specified at the time of function declaration.
For example, float interest(float p, int t, float r=0.10);

58
Constant argument means that the function cannot modify these arguments. The
constant arguments are useful when functions are called by reference, the keyword
const is used. For example, int sum(const int a, const int b);
5. How is call-by-value method of function involving different from call-by-
reference method? Give appropriate examples
Ans.
Call by value is used to create a temporary copy of the data which is transferred from
the actual parameter in the final parameter.
The changes done in the function in formal parameter are not reflected back in the
calling environment. It does not use & sign
Call by reference is used to share the same memory location for actual and formal
parameters.
The changes done in the function are reflected back in the calling environment. It
makes the use of the & sign as the reference operator.
Example: void compute (int A, int & B)
{ A++; B++;
cout<<“The function on display gives “;
cout<<“A = “<<A<<“&”<<“B=”<<B<<endl;
}
void main( )
{ int I=50, J=25;
cout<<“Initial of function call “<<endl;
cout<<“I=”<<I<<“&”<<“J=”<<J<<endl;
compute(I,J);
cout<<“After the call of the function”<<endl;
cout<<“I=”<<I<<“&”<<“J=”<<J<<endl;
getch( ); }

6. Write a C++ function that intakes two arguments: a character and an integer
and prints the character given number of times. If, however, the integer is
missing, the function prints the character twice.
Ans. void fun(char a,int n=2)
{ for(int i=0;i<n;i++)
{
cout<<a<<endl;
}
}
void main()
{
fun('A',4);
}

59
7. Comment on passing of arrays as arguments to C++ function. Support your
answer taking an example.
Ans. C++ does not allow passing an entire array as an argument to a function. It is
possible to pass a pointer to an array by specifying the array's name without an index. A
single dimensional array can be passed in functions arguments in three ways: as a
pointer, as a sized array or as an unsized array, and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going
to be received. For example,
double getAverage(int arr[], int size)
{ int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{ sum += arr[i]; }
avg = double(sum) / size;
return avg; }

8. Give the output of the following program:


#include<iostream.h>
void sumfn(int last)
{ auto int sum=0;
static int sum2=0;
for(int i=last; i>0; i--)
sum+=i;
sum2+=sum;
cout<<sum<<" "<<sum2<<endl;
}
void main()
{ for(int i=1;i<11;i++)
sumfn(i); }
Ans. Output: 11
34
6 10
10 20
15 35
21 56
28 84
36 120
45 165
55 220

9. What is the output of the following program?


#include<iostream.h>
#include<string.h>

60
voidchg(char * &nm)
{ strcpy(nm,"kush"); }
voidmain()
{ char name[]="sandeep";
cout<<name<<"\t"<<endl;
chg(name);
cout<<name<<"\t"<<endl; }
Ans. Output: Sandeep
Kush

10. Explain the output of the following program:


#include<iostream.h>
int &max(int &x, int &y)
{ if(x>y)
return(x);
else
return(y);
}
void main()
{ int A=10,B=13;
max(A,B)=-1;
cout<<"A="<<A<<"B="<<B<<endl;
max(B,A)=7;
cout<<"A="<<A++<<"B="<<B--<<endl;
max(A,B)=3;
cout<<"A="<<A<<"B="<<B<<endl; }
Ans. Output: A=10 B=-1
A=7 B=-1
A=3, B=-2

11. Give the output of the following code.


#include<iostream.h>
int m=5;
void main()
{ int m=20;
{ int m=10* ::m;
cout<<"m="<<m<<", ::m="<<::m<<endl; }
cout<<"m="<<m<<", ::m="<<::m<<endl; }
Ans. Output: m=50, ::m=5
m=20, ::m=5

12. Explain the output of the following program, Justify your answer.
#include<iostream.h>

61
#include<string.h>
void Execute(int &X,int Y=200)
{ int TEMP=X+Y;
X+=TEMP;
if(Y!=200)
cout<<TEMP<<X<<Y<<endl;
}
void main()
{ int A=50,B=20;
Execute(B);
cout<<A<<B<<endl;
Execute(A,B);
cout<<A<<B<<endl; }
Ans. 1. On first call of execute() X receives reference of B and as 2nd paramter is
missing so default value of Y i.e. 200 is used. Then sum of X i.e. 20 and Y i.e. 200 is
stored in TEMP, after that value of TEMP i.e. 220 is add to the value of X i.e. 20 so now
the the value of X is 220+20=240. As X holds the reference of B so the value of B also
became 240. And variable A doesn't have any operation with so it is same as it was i.e.
50. So the first output is 50 240.
2. Second out is 290 340 240 because the value of B is changed due to the first
execute method and its current value is 240 so the if condition returns true because B is
passed to Y and if condition Y is not equals to 200 it is 240. Then Temp = X+Y means
50+240=290. A becomes 340 due 290+50. And as there is no calculation with Y it is still
240 because it contains the value of B i.e. 240.
3. Finally cout<<A<<B<<endl; prints the current value of A and B i.e. 340 and 240
as the original values are manipulated by Execute(B); and Execute(A,B);
Output: 50 240
290 340 240
340 240

13. Figure out the errors in the following code fragment:


int Sum(int A[])
int s=0;
{ for(int i=0;i<5;++i)
s+=A[i];
returns; }
void main()
{ int Val[5],R;
for(int i=0;i<5;++i)
cin>>Val[i];
R=Sum(&Val);
cout<<"Sum="<<R; }
Ans. The global variable declaration should be first statement in the program.

62
It should be return instead of returns and it should have some value.
There should be no ‘&’ operator I function call. Following is the correct code:
int s=0;
int Sum(int A[])
{ for(int i=0;i<5;++i)
s+=A[i];
return s; }
void main()
{ int Val[5],R;
for(int i=0;i<5;++i)
cin>>Val[i];
R=Sum(Val);
cout<<"Sum="<<R; }

14. Write a function that takes a double array name and an array size as
arguments and that swaps the first and last value in that array.
Ans. void swap(double Arr[ ],int n)
{ int temp;
temp=Arr[0];
Arr[0]=Arr[n-1];
Arr[n-1]=temp; }
void main()
{ double Arr[100],n;
cout<<"Enter number of elements you want to insert ";
cin>>n;
for(int i=0;i<n;i++)
{ cout<<"Enter element "<<i+1<<":";
cin>>Arr[i]; }
swap(Arr,n);
cout<<"\nArray after swapping"<<endl;
for(i=0;i<n;i++)
cout<<Arr[i]<<" ";
getch(); }

15. Write a function that takes three arguments: a float array, the array size, and a
float value. Have the function set each element of the array to float value?
Ans. void fun(float arr[], int n, float value)
{ for(int i=0;i<n;i++)
{ arr[i]=value; }
}
void main()
{ float arr[20],n,value;
cout<<"Enter how many elements: ";

63
cin>>n; cout<<"Enter value:";
cin>>value;
fun(arr,n,value);
for(int i=0;i<n; i++)
{ cout<<"Element "<<i+1<<": "<<value;
cout<<endl; }
getch(); }

16. Write a function that takes an int argument and doubles it. The function does
not return a value.
Ans. void fun(int a)
{ int b=a*a;
cout<<b; }
void main()
{ int a;
cout<<"Enter a: ";
cin>>a;
fun(a); }

17. Write a function that takes two char arguments and returns 0 if both the
arguments are equal. The function returns -1 if the first argument is smaller than
the second and 1 if the second argument is smaller than the first.
Ans. int fun(char a,char b)
{ if(a==b)
return 0;
else if(a<b)
return -1;
else if(a>b)
return 1; }
void main()
{ char a,b;
int res;
cout<<"Enter first character: ";
cin>>a;
cout<<"Enter second character: ";
cin>>b;
res=fun(a,b);
cout<<res; }

18. Write a function to take an int argument and return 0 if the given number is
prime otherwise return -1.
Ans. int prime(int n)
{ int f=0;

64
for(int i=2;i<n/2;i++)
if(n%i==0)
{ f=1;
goto lb; }
lb:
if(f==0)
return 0;
else
return -1; }
void main()
{ int n,res;
cout<<"Enter n: ";
cin>>n; res=prime(n);
if(res==0)
cout<<"Prime";
else
cout<<"Not prime"; }

19.Write a function to receive an int array, its size and a character ‘+’ or ‘-‘.
By default, the character should be ‘+’. For the character ‘+’, the function returns
the sum of positive numbers stored in the array and for the character ‘-‘, the
function returns the sum of negative numbers stored in the array.
Ans. int funct(int a[], int n, char s = '+')
{ int sum = 0;
for(int i = 0; i< n ; i++ )
{ if(s == '+')
{ if(a[i] > 0 )
sum+=a[i]; }
else if(s== ‘-’)
{ if(a[i]<0)
sum+=a[i]; }
}
return sum; }
void main()
{ int arr[20], dn;
cout<<"\n Enter dimension :"; cin>> dn;
for(int i = 0; i< dn ; i++)
{ cout<<"\n Enter any interger (positive / negetive )";
cin>> arr[i]; }
int s = funct( arr, dn); int s2 = funct(arr, dn, '-');
cout<< "\n The sum of the positive integers : " << s;

65
cout<< "\n The sum of all negative integers : " << s2;
getch(); }
20. Write a function that takes a character argument and prints it number of times
equal to number of times function has been called to the point.
Ans. void fun(char a)
{ cout<<a<<endl; }
void main()
{ int n;
char ch;
cout<<"Enter how many times: ";
cin>>n;
cout<<"Enter character: ";
cin>>ch;
for(int i=1;i<=n;i++)
fun(ch);
getch(); }

21. Write a function that takes two int arguments and returns reference of the odd
number out of the two. If the arguments are odd, then the reference of the smaller
one is returned.
Ans. int &setodd(int &a,int &b)
{ if((a%2!=0) && (b%2!=0))
{ if(a<b)
return a;
else
return b;
}
else if(a%2!=0)
return a;
else
return b;
}
void main()
{ int a,b,res;
cout<<"Enter a and b: ";
cin>>a>>b;
res=setodd(a,b);
cout<<"Odd number is: "<res; }

22. Write a function having this prototype : int replace(char * string, char ch1,
char ch2); Have the function replace every occurrence of ch1 in the string with
ch2, and have the function return the number of replacements it makes.

66
Ans. int replace(char *string, char ch1, char ch2)
{ int l, c=0;
l=strlen(string);
for(int i=0;i<=l;i++)
{ if(string[i]==ch1)
{ string[i]=ch2;
c++; }
}
cout<<"New string: "<<string;
return c; }
void main()
{ char str1[20],ch1,ch2;
cout<<" Enter string1: ";
cin>>str1 ;
cout<<"Enter character u want to change: ";
cin>>ch1;
cout<<"Enter new character: ";
cin>>ch2;
int res=replace(str1,ch1,ch2);
cout<<"Number of replacement: "<<res;
getch(); }

23. Complete the following function power() by filling up the correct


symbols/expressions/variables at places indicated by ________ .
The power() works as given below:
power (0, n) = 0 for each n
power (x, n) = xn if x!=0 and n>0
power (x, 0) = 1 for each x
The function definition is as follows:
long power(int x, int n)
{ long res=1;
if (x= _ _ _ _ )
res=0;
else if (n= _ _ _ _ 0)
res=1;
else if (n= _ _ _ _ _ 0)
for(int i=0;i<n;i++)
res*=x;
else
{ for(int j=0;j>-n;j--)
res*==x;
res=1/res; }
return res; }
67
Ans. long power(int x,int n)
{ long res=1;
if(x==0)
res=0;
else if(n==0)
res=1;
else if(n>0 && x!=0)
for(int i=0;i<n;i++)
res*=x;
else
{ for(int j=0;j>-n;j--)
res*=x;
res=1/res; }
return res; }

24. Write a C++ function to sum n natural numbers starting from a given number.
Ans. int sum(int N)
{ int S = 0;
for(int i = 0; i <= N; i++)
S += i;
return S; }
void main()
{ int n;
cout << "Enter the number: ";
cin >> n;
cout << sum(n) << endl; }

25. Write a C++ function to find least common divisor of two integers.
Ans. void least_div(int a, int b)
{ int i=2,k=-1;
while(k==-1 && i<(a+b))
{ if(a%i==0 && b%i==0)
k=i;
i++;
}
if(k!=-1)
cout<<"Least common divisor: "<<k<<"\n";
else
cout<<"No common divisor\n";
}

68
26. Write a C++ function that compares two string and returns 0 if the two strings
are equal and -1 if the string are unequal.
Ans. int compare(char str1[], char str2[])
{ if ( strcmp (str1,str2) == 0)
return 0;
else
return -1; }
void main()
{ char str1[20]; char str2[20];
int res;
cout<<" first string:\n1: ";
cin>>str1 ;
cout<<" second string:\n 2: ";
cin>>str2;
res=compare(str1,str2);
if(res==0)
cout<<"Equal strings";
else
cout<<"Not equal";
getch(); }

3 Mark Questions

1. Write a complete C++ program that reads a float array having 15 elements. The
program uses a function reverse () to reverse this array. Make suitable assumptions
wherever required.
Ans. #include<iostream.h>
#include<conio.h>
void rev(float a[], int n)
{ float t;
for(int i =0, k = n-1; i< n/2 ; i++, k--)
{ t = a[i];
a[i] = a[k];
a[k] = t; }
}
void main()
{ float arr[15];
cout<< "\n Enter 15 real numbers :";
for(int i = 0; i< 15 ; i++)
cin>> arr[i];
cout<<"\n The original array : \n";

69
for( i = 0; i< 15; i++)
cout<< arr[i] << " ";
cout<<"\n";
rev(arr, 15);
cout<<"\n The reversed array : \n";
for( i = 0; i< 15; i++)
cout<< arr[i] << " ";
getch(); }

2. Write a complete C++ program that invokes a function satis() to find whether
four integers a, b, c, d send to satis() satisfy the equation a3 + b3 + c3 = d3 or not.
The function satis() returns 0 if the above equation is satisfied with given four
numbers otherwise it returns -1.
Ans. #include<iostream.h>
#include<conio.h>
int satis(int a, int b, int c, int d)
{ if( ((a*a*a) + (b*b*b) + (c*c*c)) == d*d*d)
return 0;
else
return -1; }
void main()
{ int x, y, z, w;
cout<< "\n Enter 4 integers : ";
cin>>x>>y>>z>>w;
int s = satis(x, y, z, w);
if(s == 0)
cout<< "\n The equation is satisfied";
else
cout<< "\n The equation is NOT satisfied";
getch(); }

3. Write a complete C++ program that uses a function called carea() to calculate
area of circle. The function carea() receives radius of float type and return are of
double type. The function main() gets a radius value from the user, calls carea(),
and display the result. The function carea() is local to main().
Ans. #include<iostream.h>
#include<conio.h>
double carea(float r)
{ double ar = (double) ( 3.14 * r * r );
return ar; }
void main()
{ float rad;
cout<<" \n Enter Radius :";

70
cin>>rad;
double area = carea(rad);
cout<<"\n The area of the circle of radius " << rad << " unit is ";
cout << area << "sq. unit ";
getch(); }

4. Write a C++ program that uses a function smallo() (that is passed two int
argument by value) to receive reference of the smaller value. Then using this
reference the smaller value is set to 0. Write a main() function also to exercise this
function.
Ans. #include<iostream.h>
#include<conio.h>
int &smallo(int &a, int &b)
{ if(a<b)
return a;
else
return b;
}
void main()
{ int a, b;
cout<< "\n Enter two numbers :";
cin >> a >> b;
cout<< "\n The original values :" << a << " and " << b;
smallo(a, b) = 0;
cout<< "\n The changed values :" << a << " and " << b;
getch(); }

5. Write a C++ program that uses following functions:


(i) sqlarge() that is passed two int argument by reference and then sets the larger
of the two umbers to its square.
(ii) sum() that is passed an int argument by value and that returns the sum of the
individual digits of the passed number.
(iii) main() that exercise above two functions by getting two integers from the user
and by printing the sum of the individual digit of the square of the larger number.
Ans. void sqlarge(int &a, int &b)
{ if(a >b)
a = a*a;
else
b = b*b;
}
int sum(int x)
{ int r, s=0;

71
while(x > 0)
{ r = x % 10;
s = s+r;
x = x / 10;
}
return s; }
void main()
{ int num1, num2,num3;
cout<<" \ n Enter a number :";
cin>>num1;
int tot = sum(num1);
cout<< " \n THE SUM OF DIGITS = " << tot;
cout << "\n Enter two numbers : ";
cin>> num2>>num3;
cout<< "\n The two numbers originally are " <<num2<< " and "<<num3;
sqlarge(num2, num3);
cout<< "\n The two numbers after change are "<<num2 << " and "<<num3 ;
getch(); }

6. Write a C++ program to use the following function:


(i) display() to display a matrix of size m x n.
(ii) times2() to double each number of the matrix of size m x n.
(iii) main() to read a matrix of size m x n and then to display original matrix
and then to display the new matrix formed by doubling its elements.
Ans. #include<iostream.h>
#include<conio.h>
void display(int a[10][10], int m, int n)
{ for(int i = 0; i< m ; i++)
{ for( int j = 0; j< n ; j++)
{
cout << a[i][j] << " ";
}
cout<< endl;
}
}
void times2(int a[10][10], int m, int n)
{ for(int i = 0; i< m ; i++)
{ for( int j = 0; j< n ; j++)
{
a[i][j] = a[i][j] * 2;
}
}
}

72
void main()
{ int mat[10][10], row, col, i, j;
cout<< "\n Enter the total Rows & Columns :";
cin>> row>>col;
cout<< "\n Enter the elements for Matrix:";
for(i = 0; i< row; i++)
{ for(j = 0; j< col; j++)
{
cin>>mat[i][j];
}
}
cout<<"\n The Original Matrix :";
display(mat, row, col);
times2(mat, row, col);
cout<<"\n The New Matrix :";
display(mat, row, col);
getch();
}

7. Write a program uses a function power() to raise a number m to power n. The


function takes int values for m and n returns the result correctly. Use a default
value of 2 for n to make the function calculate squares when this argument is
omitted. Write a main() to get the value of m and n from the user and to display
the calculated result.
Ans. #include<iostream.h>
#include<conio.h>
#include<math.h>
double power(int m, int n = 2)
{
double res = pow(m,n);
return res;
}
void main()
{
int x,y;
double d;
cout<< "\n Enter a number and its power to calculate the result :";
cin>>x>>y;
d = power(x,y);
cout<< "\n The " << x << " to the power " << y <<" is " << d;
getch();
}

73
CHAPTER-12
STRUCTURED DATA TYPE: ARRAY
1 Mark Questions

1. What do you understand by an array? What is the significance of array?


Ans. An array is a collection of variables of the same type that are referenced by a
common name. Arrays are very useful in a case where quite many elements of the same
types to be stored and processed.

2. What is meant by index of an element? How are indices numbered in C++?


Ans. The element’s number is referred to as an index. An array index in C++ starts with
number 0 not 1. That is, array A[4] will be having elements: A[0], A[1], A[2], A[3].

3. Determine the total bytes required to store B[17], a char array.


Ans. As B[17] is a character array, the size of each element is 1 byte. The total bytes
required to store B[17] is: 1 x 17 = 17

4. What is the data type of element of an array called?


Ans. The data type of array elements is known as the base type of the array.

5. How is one-dimensional array represented in memory?


Ans. The elements of an one-dimensional array are stored in contiguous memory
location in their index order.
For example, an array grade of type char with 8 elements declared as char grade [8];
It will have the element grade[0] at the first allocated memory location, grade[1] at the
next contiguous memory location, grade[2] at the next, and so forth.

6. Determine the number of bytes required to store an int array A[23], if the int
size is 4 bytes.
Ans. The size of int is 4 bytes and there are 23 elements in array. So the number of
bytes required to store an int array is: 4 x 23 = 92.

7.An array element is accessed using (a) a first-in-first-out approach (b) the dot
operator (c) an element name (d) an index number
Ans. (d) an index number

8. Write a statement that defines a one-dimensional array called amount of type


double that holds two elements.
Ans. double amount[2];

9. The elements of a twenty-element array are numbered from ______ to ______.


Ans. 0 to 19.

74
10. Write a statement that takes element k of array amount and writes it to
cout<< with the insertion operator.
Ans. cout<<amount[k];

11. Element amount[9] is which element of the array? (a) the eighth (b) the ninth
(c) the tenth (d) impossible to tell.
Ans. (c) the tenth

12. Write a statement that defines a char array to store coins’ types and initializes
it to the values 10-paise, 25-paise, 50-paise, 1-rupee, 2-rupee, 5-rupee, 100-rupee.
Ans. char coins[7][15] = { "10-paise", "25-paise", "50-paise", "1-rupee",
"2-rupee", "5-rupee", "100-rupee" };

13.How does C++ view a string as? Which character marks the end of a string?
Ans. C++ views a string as single-dimensional character array. The null character ’\0’
marks the end of a string.

14. Write a statement that defines a string variable school to hold a string of up to
25 characters.
Ans. char school[26];

15. Write a statement that defines a string constant, called dextrose, that has the
value “C6H1206-H20”.
Ans. char dextrose[20] = { “C6H1206-H20 “ }

16. Declare following arrays: (i) figures of 30 char (ii) check of 100 short
(iii) balance of 26 float (iv) budget of 58 double
Ans. (i) char figures[30]; (ii) short check[100];
(iii) float balance[26]; (iv) double budget[58];

17.Declare an array of 5 ints and initialize it to the first five even numbers.
Ans. int A[5] = { 2, 4, 6, 8, 10 };

18. Write a statement that assign the sum of the first, second and last elements of
the array n question 17 to the variable threesum.
Ans. threesum=(A[0] + A[2] + A[4]);

19. Write a statement that displays the value of the second element in the long
array balance.
Ans. cout<<A[1];

20. Declare an array of char and initialize it to the string “Pizzas”.


Ans. char string[10] = "Pizzas";

75
21. For a multidimensional array: int X[5][24], find the number of bytes required.
Ans. No. of rows = 5, No. of columns = 24, Size of each elements = 2 bytes.
Total bytes = No. of rows x No of columns x size of (base type) = 5 x 24 x 2 =240 bytes.

22. From the above question, find the total number of elements in X.
Ans. Total elements = number-of-rows x number-of-columns = 5 x 24 = 120

23. For a multidimensional array: char B[9][15] find the total No. of elements in B.
Ans. No. of rows = 9, No. of columns = 15, Total Elements = 9 x 15 =135

24. How are the 2-D arrays stored in the memory?


Ans. Two-dimensional arrays are stored in a row-column matrix, where the first index
indicated the row and the second indicates the columns.

25. Given two 2-D arrays, what is the condition to calculate the sum or difference
of the given arrays?
Ans. To calculate the sum or difference of the given 2-D arrays, both arrays should be
identical. For instance, A[n][m] and B[p][q] are the two given matrices, then, in order to
perform sum operation, following condition must be true: n = p and m = q

26. Given two 2-D arrays, what condition must be satisfied to calculate the
difference of the two arrays?
Ans. To calculate the sum of the given 2-D arrays, both arrays should be identical. For
instance, A[n][m] and B[p][q] are the two given matrices, then, in order to perform
difference operation, following condition must be true: n = p and m = q

27. To obtain the product of the two 2-D arrays, what condition must be true?
Ans. Suppose, A[n][m] and B[p][q] are the two given matrices, then, in order to perform
obtain the product, following condition must be true: m= p

28. Given the following 2-D arrays:

A= B=

What will be the sum of the A and B?


Ans. 1 1 1
A + B= 1 1 1
1 1 1

76
29. Given the following 2-D arrays:

X= Y=

Is the product of X and Y possible?


Ans. Yes, the product of X and Y is possible.

30. Given the following array:

A=

Write its diagonal elements.


Ans. Left (Main) diagonal = 1 5 9 Right (Sub) diagonal = 3 5 7

31. What is a vector? Can a 2-D array be called as a vector?


Ans. A vector is a mathematical term that refers to collection of analogous numbers. A
2-D array with one row can be called as a vector.

32. Can any dimension of an array be skipped at its declaration time?


Ans. Only the first dimension can be skipped at its declaration time, the second
dimension must be given.

33. How does C++ calculate the size of unsized array?


Ans. To skip the size of array, we must give list of initializers and C++ calculates the size
of the unsized array by counting them.

34. Define a two dimensional array MAT of (4 x 5) of type integer. Also initialize all
the elements of MAT with the value 0(zero). Construct one statement to assign the
value 100 to cell in row 3 and column 4.
Ans. int MAT[4][5] = { 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0 };
MAT[2][3] = 100;

77
2 Mark Questions:

1. What is an array? What is the need for arrays?


Ans. An array is a collection of variables of the same type that are referenced by a
common name. Arrays are very useful in a case where quite many elements of the same
types to be stored and processed. For example, to store the marks of 50 students we
required 50 variables. But if we use array then we can store all 50 student’s mark in one
array that have 50 elements. Elements of these arrays will be referred to as
arrayname[n], where n is the element number in the array. Writing such a program
would not only be simple but also very easy to code and understand.

2. What are different types of arrays? Give example of each array type.
Ans. There are three different types of arrays as following:
1. One-dimensional array: The array that has only one subscript is known as a one-
dimensional array. For example, int marks[50]; The above statement declare array
marks has 50 elements, mark[0] to mark[49].
2. Two-dimensional array: The array that has two subscripts is known as a two-
dimensional array. For example, int sales[5][12]; Above statement declare an array sales
that has 5 rows and 12 columns.
3. Multi-dimensional array: The array that has more than one dimension is known as
multi-dimensional array. int A[3][3][3]; Above statement declare an A array that have
three dimensions.

3. Write a note on how single-dimension array are represented in memory.


Ans. Suppose an array age of type char with 5 elements declared as int age[5]; Its each
element will have sizeof (int) bytes for its storage. On a system with 2 bytes integer size,
the array age’s element will be having 2 bytes for its storage. If the starting memory
location of array age is 5000, then it will be represented in the memory as shown below:

4. How does the amount of storage (in bytes) depend upon type and size of an
array? Explain with the help of an example.
Ans. The amount of storage required to hold an array is directly related to its type and
size. For a single-dimensional array, the total size (in bytes) can be computed according
to following formula: total bytes = sizeof(type) * size_of_array For example, of we have an
array age of type int that has 5 elements then the amount of storage required is 2*5=10.

5. How are strings manipulated in C++? Support your answer with examples.
Ans. In C++ strings are manipulated as a single-dimensional character array. A string is
defined as a character array that is terminated by a null character ‘\0’. For this reason,

78
the character arrays are declared one character longer than the largest string they can
hold. For instance, to declare an array str that holds a 10-chracter string, we would
write char str[11]; this makes room for the null at the end of the string.

6. What do you understand by two-dimensional arrays? State some situations that


can be easily represented by two-dimensional arrays.
Ans. A two-dimensional array is an array in which each element is itself an array. For
instance, an array A[m][n] is an M by N table with M rows and N columns containing
M x N elements. Situations that can be represented by two-dimensional arrays:
A two-dimensional array can be used to store objects, which is especially convenient
for programming sketches that involve some sort of "grid" or "board."
We might write a program using a two-dimensional array to draw a grayscale image.

7. How are two-dimensional arrays represented in memory?


Ans. Two-dimensional arrays are stored in row-column matrix, where the first index
indicates the row and the second indicates the column. Suppose we have declared an
array pay as follows: float pay[3][4]; it will be having 3 x 4 = 20 elements which will be
represented in memory as shown below:

8. Can you think of a difference between an array of strings and other two-
dimensional arrays? What is it? Support your answer with examples.
Ans. Array of strings
 An array of string is a two-dimensional character array.
 Example: char strings[10][51]; The above can contain 10 strings, each of 51
characters long.
 The first index refers the number of strings and the second index refers to the
maximum length of each string.
 An array of string is terminated with null character ‘\0’.
Two-dimensional array(integer type)
 A two-dimensional array is an array in which each element is itself an array.
 Example: int Arr[2][3]; The above has 2 rows and 3 columns.
 The first index refers the number of rows and the second index refers to the
number of columns in the array.
 Two-dimensional (integer tyoe) array is not terminated with null character.

79
9. Consider a 1-D array ‘A’ containing 100 integers. Develop a program to do the
following: (i) remove all occurrences of a given integer.
(ii) shift the elements of the array to the right so that used space is available at
the left end.
(iii) fill the unused spaces by 0 (zero).
(For example, the array 10 20 15 4 20 2 20 after execution of the program for
given integer 20 should become 0 0 0 10 15 4 2 )
Ans. #include<iostream.h>
#include<conio.h>
void main()
{ int A[100],no,val,found;
clrscr();
cout<<"Enter number of elements you want to insert ";
cin>>no;
for(int i=0;i<no;i++)
{ cout<<"Enter element "<<i+1<<":";
cin>>A[i]; }
cout<<"Enter the number you want to search ";
cin>>val;
for(int j=0; j<no; j++)
{ if(A[j]==val)
A[j]=0;
}
for(int k=0; k<no; k++)
{ cout<<A[k]<<" "; }
int divider = 0;
for (int m = 0; m < no; m++)
{ if (A[m] == 0)
{ int temp = A[m];
A[m] = A[divider];
A[divider] = temp;
divider ++;
}
}
for(k=0; k<no; k++)
{ cout<<A[k]<<" "; }
getch(); }

10. Suppose A, B, C are arrays of integers of sizes m, n, m + n respectively. Give a


program to produce a third array C, containing all the data of array A and B.
Ans. #include<iostream.h>
#include<conio.h>
void main()

80
{ int A[100], B[100], C[200], n, m, k=0, I=0, J=0;
cout<<"\nEnter number of elements you want to insert in first array ";
cin>>n;
cout<<"Enter element in first array\n";
for(int i=0;i<n;i++)
{ cout<<"Enter element "<<i+1<<":";
cin>>A[i]; }
cout<<"\n Enter number of elements you want to insert in second array ";
cin>>m;
cout<<"Enter element in second array\n";
for(i=0;i<m;i++)
{ cout<<"Enter element "<<i+1<<":";
cin>>B[i]; }
for (int T=I;T<n;T++)
C[k++]=A[T];
for (T=J;T<m;T++)
C[k++]=B[T];
cout<<"The Merged Array is:"<<endl;
for(i=0;i<k;i++)
cout<<C[i]<<" ";
getch(); }

11. Write a short program that adds and subtracts two matrices X[3][3] and Y[3][3].
Ans. #include<iostream.h>
#include<conio.h>
void main()
{
int i,j,n,a[3][3],b[3][3],c[3][3];
cout<<"enter value of elements of matrix A"<<"\n";
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{
cin>>a[i][j];
}
}
cout<<"enter values of elements of matrix B"<<"\n";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>b[i][j];
}
}

81
cout<<"addition of matrix A and B is"<<"\n";
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{ c[i][j]=a[i][j]+b[i][j];
cout<<c[i][j]<<"\t";
}
cout<<"\n";
}
cout<<"Subtraction of matrix A and B is"<<"\n";
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{ c[i][j]=a[i][j]-b[i][j];
cout<<c[i][j]<<"\t";
}
cout<<"\n";
}
getch(); }

15. Let A(n x n) that are not diagonal array. Write a program to find the sum of all
the elements which lie on either diagonal. For example, for the matrix shown
below, your program should output 68 = (1+6+11+16+4+7+10+13):

Ans. #include<iostream.h>
#include<conio.h>
void main()
{ int i,j,n,m,a[10][10];
int sum=0;
cout<<"Enter m:";
cin>>m;
cout<<"Enter n:";
cin>>n;
cout<<"enter value of elements of matrix A"<<"\n";
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
{ cin>>a[i][j]; }
}
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
{ if(i==j||i+j==m-1)
sum+= a[i][j]; }
}
cout<<"\t"<<sum;
getch(); }

82
16. Write a program to count number of spaces in a string.
Ans. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main( )
{ char str[50];
int c=0;
cout<<"Enter string: ";
gets(str);
for(int i=0;i<strlen(str);i++)
{ if(str[i]==' ')
c++; }
cout<<"\n The no. of spaces are: "<<c;
getch( );
}

17. Write a program to count number of occurrences of a given character in a


string.
Ans. #include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{ char str[50],ch; int c=0;
cout<<"Enter string: ";
cin>>str;
cout<<"Enter character: ";
cin>>ch;
for(int i=0;i<strlen(str);i++)
{ if(str[i]==ch)
c++; }
cout<<"the no. of occurences is: "<<c;
getch( );
}

83
3 Mark Questions

1. From a two-dimensional array A[4][4], write a program to prepare a 1D array


B[16] that will have all the elements of A if they are stored in row-major form.
For example, for the following array

The resultant array should be 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16


Ans. #include<iostream.h>
#include<conio.h>
void main( )
{ int B[16];
int A[4][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
cout<<"\n The Original matrix : \n\n";
for(int i = 0; i < 4 ; i++)
{ for(int j = 0; j < 4 ; j++)
cout<< A[i][j]<<"\t";
cout<< "\n";
}
int n=0;
for(int p = 0; p < 4 ; p++)
{ for(int q = 0; q < 4 ; q++)
{ B[n] = A[p][q];
n++;
}
}
cout<<"\n \n";
for(int k=0; k<16; k++)
cout<< B[k] << " ";
getch( ); }

2. Write a program to count the number of words in a string as well as the number
of characters other than a space.
Ans. #include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{ char sen[50];
int word_count = 0, chr = 0, space = 0;
cout<< "\n Enter A String :";
gets(sen);

84
for(int i = 0; sen[i] != '\0' ; i++)
{ if (sen[i] == ' ')
space++;
}
chr = strlen(sen) - space;
word_count = space + 1;
cout<< "\n The Total no. of words = " << word_count;
cout << "\n The total characters without spaces = " << chr;
getch(); }

3. Write a program to print the upper and lower triangle of a matrix.


Ans. #include<iostream.h>
#include<conio.h>
# define n 10
void main( )
{ int mat[n][n];
int d;
cout<< "\n Enter dimension of square matrix:";
cin >> d;
for(int i = 0; i < d ; i++)
{ for( int j = 0; j < d ; j++)
{
cin >> mat[i][j];
}
}
cout<<"\n The Original matrix : \n\n";
for( i = 0; i < d ; i++)
{ for( j = 0; j < d ; j++)
cout<< mat[i][j]<<"\t";
cout<< "\n";
}
cout<<"\n The Upper half of the matrix : \n\n";
for( i = 0; i < d ; i++)
{ for( j = 0; j < d ; j++)
{ if(i < j)
cout << mat [i][j] << " " ;
else
cout << " " << " ";
}
cout << "\n ";
}

85
cout<<"\n The Lower half of the matrix : \n\n";
for( i = 0; i < d ; i++)
{ for( j = 0; j < d ; j++)
{ if(i > j)
cout << mat [i][j] << " " ;
else
cout << " " << " ";
}
cout << "\n ";
}
getch ( ); }

4. Write a program to find the sum of squares of elements on the diagonal of a


square matrix n x n.
Ans. #include<iostream.h>
#include<conio.h>
# define n 10
void main( )
{ int mat[n][n], d;
long sum=0;
cout<< "\n Enter dimension of square matrix:";
cin >> d;
for(int i = 0; i < d ; i++)
{ for( int j = 0; j < d ; j++)
{
cin >> mat[i][j];
}
}
for( i = 0; i < d ; i++)
{ for( j = 0; j < d ; j++)
cout<< mat[i][j]<<"\t";
cout<< "\n";
for( i = 0; i < d ; i++)
{ for( j = 0; j < d ; j++)
{ if(i==j ||(i+j==d-1))
sum += mat[i][j] * mat [i][j];
}
}
cout<<”\n Sum of the squares of elements on the diagonal is: ”<<sum
getch ( ); }

86
5. Write a program that reads an array of strings and counts the number of strings
of each length that occurs, as well as the total number of strings. The program
should then print the mean (average) entirely of (uppercase and lowercase) letters
and is terminated by ’~’.
Ans. #include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{ char str[255] ;
cout<< "\n Enter a String (~ to terminate ): ";
cin.getline(str, 255, '~');
int no_f_strings = 0;
for(int i = 0; str[i] != '\0' ; i++)
if(str[i] == '\n')
no_f_strings ++;
int tot_strings = 0;
for( i = 0 ; str[i] != '\0' ; i++)
{ if( str[i] == ' ' || str [i] == '\n' || str[i] == '.')
{ tot_strings++;
while(str[i] == ' ')
i++;
}
if(str[i] == '\0')
i--;
}
tot_strings++;
cout<< "\n The number of strings of each length : " << no_f_strings;
cout<<"\n The total number of strings (words) : " << tot_strings;
int len = strlen(str);
int ucas=0, lcas = 0, fullst = 0;
for( i=0; str[i] != '\0' ; i++)
{ if(str[i]>='A' && str[i]<='Z')
ucas++;
if(str[i]>='a' && str[i]<='z')
lcas++; if(str[i]=='.')
fullst++;
}
float avg_ucas =(float) (ucas/len);
float avg_lcas = (float) (lcas/len);
cout<< "\n The Mean of lowercase letters = " << avg_lcas;
cout<< "\n The Mean of uppercase letters = " << avg_ucas;
cout<< "\n The total number of terminating fullstop= " << fullst;
getch();

87
CHAPTER-13
STRUCTURES
2 Mark Questions

1. Discuss the similarity and differences of a structure as compared to an array


and a class.
Ans. Similarities: Array and Structure
Both structures and arrays are used to hold more than 1 elements under
single name.
Difference: Array and Structure
Arrays bring together a group of items of the same data type
Structures bring together a group of related data items of any data type.
Similarities: Class and Structure
Both Class and Structures can have methods, variables and objects.
Both can have constructor.
Both are user defined types.
Difference between Class and Structure
Declared with the keyword “class”
Declared with the keyword “struct”
By default, all members are “private” in a class
By default, all members are “public” in a structure

2. Define a structure to store information about a fish. The structure should


include the kind, the weight in grams, and the length in inches. Declares variables
of this structure type and discuss various methods of initializing them.
Ans. struct Fish_Info
{ char kind[50];
int gram;
int length;
};
Fish_Info fish;
First method of initializing
The structure elements of a structure can be initialized separately, using separate
assignment statement.
fish.kind=”abc”;
fish.gram=300;
fish.length=5;
Second method of initializing
The structure element of a structure can be initialized jointly, using the notation
Fish_Info fish = { “abc”, 300, 5);

3. Write definition for a structure EMPREC that stores information about an


employee such as empno, name, address, salary, and joining_date. The address

88
member of EMPREC stores the information houseno, area, and city. The
joining_date member of EMPREC stores information day, month, and year.
Ans. struct date
{ int day;
int month;
int year;
};
struct addr
{ int houseno;
char area[31];
char city[31];
};
struct EMPREC
{ int empno;
char name[41];
addr address;
float salary;
date joining_date;
};

4. What is structure? Declare a structure in C++ with name, roll number and total
marks as components.
Ans. A structure is a collection of variables having different data types.
The declaration as:
struct student
{ char name[20];
int roll_no,marks;
};

5. Rewrite the following program after removing the syntactical error(s), if any.
Underline each correction.
#include<iostream.h>
int main( )
{ struct STUDENT
{ char stu_name[20];
char stu_sex;
int stu_age=17;
}student;
gets(stu_name);
gets(stu_sex);
return 0;
}

89
Ans. #include<iostream.h>
#include<stdio.h>
int main( )
{ struct STUDENT
{ char stu_name[20]; char stu_sex;
int stu_age; //Initialization inside a structure is not allowed.
}student;
gets(student.stu_name);
cin>>student.stu_sex; //A single char cannot be read in gets
return 0; }

6. What are Nested Structures? Give an example.


Ans. Nested structures are structures as member of another structure.
#include< iostream.h>
struct course
{ int couno;
int coufees;
};
struct student
{ int studno;
course sc;
course sc1;
} s1;
void main( )
{ s1.studno=100; s1.sc.couno=123; s1.sc.coufees=5000;
s1.sc1.couno=200; s1.sc1.coufees=5000;
int x = s1.sc.coufees + s1.sc1.coufees;
cout<< “\n Student Number: ”<< s1.studno<< ”\n Total Fees: Rs.”<< x;
}
7. Rewrite the corrected code for the following program. Underline each correction
(if any).
#include<iostream.h>
structure Swimmingclub
{ int mem number;
char memname[20];
char memtype[]=”LIG”;
};
int main( )
{ Swimmingclub per1,per2;
cin>>”Member Number: “;
cin>>memnumber.per1;
cout<<”Member Name: “;
cin>>per1.membername;

90
per1.memtype = “HIG”;
per2=per1;
cin>>”Member Number;“ <<per2.memnumber;
cin<<”Member Name” <<per2.memname; 3
cin<<”Member Number:”<<per2.memtype;
return 0;
}
Ans. #include<iostream.h>
#include<string.h>
struct Swimmingclub
{ int memnumber;
char memname[20];
char memtype[4];
};
int main( )
{ Swimmingclub per1,per2;
cout<<”Member Number: “;
cin>>per1.memnumber;
cout<<”Member Name: “;
cin>>per1.memname;
strcpy(per1.memtype, “HIG”);
per2=per1;
cout<<”Member Number;“ <<per2.memnumber;
cout<<”Member Name” <<per2.memname;
cout<<”Member Number:”<<per2.memtype;
return 0; }
8. Identify and discuss the error(s) in the following code fragment:
#include<iostream.h>
struct s1
{ int a; float b; char c;
} st1,st2, st3;
int main()
{ struct s2
{ int x;
float y;
char z;
} ss1,ss2,ss3;
ss2=ss1;
:
ss3.z=st1.c;
:
}
void func1()

91
{ ss2.x=st1.a;
ss3.y=st2.b;
ss1.z=st3.c; 4
:
ss1=ss3;
}
Suggest way(s) to rectify the errors.
Ans. #include<iostream.h>
struct s1
{ int a;
float b;
char c;
}st1, st2, st3;
int main()
{ struct s2
{ int x;
float y;
char z;
}ss1, ss2, ss3;
ss2=ss1;
:
ss3.z=st1.c;
:
}
void func1() //main() Variable used inside the func1 is not accessible
{ ss2.x=st1.a;
ss3.y=st2.b;
ss1.z=st3.c;
:
ss1=ss3;
}

10. Give appropriate declaration to store 10 records where each record store the
following information:
Authorno, Authorname and book_list containing information of 5 books.
The book-list stores the following information:
bookno, bookname, subject, price, edition, and publication.
The publication stores the following information:
proprietor-name, publishing company’s name, address, and phonenum.
Ans. struct publication
{ char proprietor_name[50];
char company_name[50];
char address[50];

92
int phone_no;
};
struct book_list
{ int bookno;
char bookname[50];
char subject[20];
float price;
char edition[10];
publication public[20];
};
struct book_info
{ int authorno;
char author_name[50];
book_list book[5];
};

12.Write a function that accepts a date type structure and returns a date 50 days
after it.
Ans. struct date { int dd; int mm; int yy; };
date modify(date d1,int add=50)
{ int d= d1.dd+50; d1.dd=d%30;
int m = d1.mm+(d/30);
d1.mm=m%12;
d1.yy += (m/12);
if(d1.dd= =0)
{ d1.dd=12;
--d1.mm; }
if(d1.mm< =0)
{ d1.mm=30;
--d1.yy; }
return (d1); }

13. Predict the output of the following code (Assuming that required header files
have been included):
struct Time
{ int hour, minutes, seconds; };
void updatetime(Time new_time)
{ ++new_time.seconds;
if(new_time.seconds==60)
{ new_time.seconds=0;
++new_time.minutes;
}
if(new_time.minutes==60)

93
{ new_time.minutes=0;
++new_time.hour;
}
if(new_time.hour==24)
new_time.hour=0;
}
int main()
{ Time cur_time;
cout<<"Enter the time(hh:mm:ss:):\n";
cin>>cur_time.hour>>cur_time.minutes>>cur_time.seconds;
updatetime(cur_time);
cout<<"New time is";
cout<<cur_time.hour<<":"<<cur_time.minutes<<":"<<cur_time.seconds;
return 0;
}
Ans.

14. Find the output of the following program:


#include<iostream.h>
struct Package
{ int Length,Breadth,Height; };
void Occupies(Package M)
{ cout<<M.Length<<”x” <<M.Breadth<<”x” cout<<M.Height<<endl;
}
void main( )
{ Package P1={100,150,50},P2,P3;
++P1.Length;
Occupies(P1);
P3=P1;
++P3.Breadth;
P3.Breadth++;
Occupies(P3);
P2=P3;
P2.Breadth+=50;
P2.Height--;
Occupies(P2);
}

Ans.

94
15. Give the output of the following program:
#include<iostream.h>
struct Pixel
{ int C,R; };
void Display(Pixel P)
{ cout<<”col”<<P.C<<”Row”<<P.R<<endl ; }
void main( )
{ Pixel X={40,50},Y,Z;
Z=X;
X.C+=10;
Y=Z;
Y.C+=10;
Y.R+=20;
Z.C-=15;
Display(X);
Display(Y);
Display(Z);
}
Ans.

95
3 Mark Questions

1. Write a code fragment to declare and read in values (from user) for an array ARR
of size 10 whose elements consists of name, category, Marks in 5 subjects and
registration number. The category can be one of Gen, SC, ST, and OBC. The
registration number is a combination of areacode, region code, school code,
current year (yy) and a serial number.
Ans. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct rege_num
{
int areacode, region_code, school_code, current_year, serial_number;
};
struct info
{ char name[50];
char category[10];
int marks[5];
rege_num regno;
};
info arr[10];
void main()
{
int i,j;
clrscr();
for(i=0;i<10;i++)
{
cout<<"Enter name =";
gets(arr[i].name);
cout<<"Enter one of gen,sc,st or obc category =";
gets(arr[i].category);
for(j=0;j<5;j++)
{
cout<<"enter marks"<<j+1<<" = ";
cin>>arr[i].marks[j];
}
cout<<"enter areacode =";
cin>>arr[i].regno.areacode;
cout<<"enter region code =";
cin>>arr[i].regno.region_code;
cout<<"enter school code =";
cin>>arr[i].regno.school_code;

96
cout<<"enter current year =";
cin>>arr[i].regno.current_year;
cout<<"enter serial number =";
cin>>arr[i].regno.serial_number;
}
cout<<"******************* Student info ******************"<<endl;
for(i=0;i<10;i++)
{ cout<<"Name :"<<arr[i].name<<endl;
cout<<"category :"<<arr[i].category<<endl;
for(j=0;j<5;j++)
{
cout<<"marks"<<j+1<<" = "<<arr[i].marks[j]<<endl;
}
cout<<"Registration Number :"<<arr[i].regno.areacode
<<arr[i].regno.region_code<<arr[i].regno.school_code
<<arr[i].regno.current_year<<arr[i].regno.serial_number<<endl;
}
getch();
}

2. Write a code fragment to store 10 records where each record store the following
information:
Authorno, Authorname and book_list containing information of 5 books.
The book-list stores the following information:
bookno, bookname, subject, price, edition, and publication.
The publication stores the following information:
proprietor-name, publishing company’s name, address, and phonenum
Ans. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct publication
{ char proprietor_name[50];
char company_name[50];
char address[50];
int phone_no;
};
struct book_list
{ int bookno;
char bookname[50];
char subject[20];
float price;
char edition[10];
publication pub;

97
};
struct book_info
{
int authorno;
char author_name[50];
book_list bookl[5];
};
book_info book[2];
void main()
{ int i, j;
for(i=0;i<2;i++)
{
cout<<"enter author no =";
cin>>book[i].authorno;
cout<<"enter author name =";
gets(book[i].author_name);
for(j=0;j<2;j++)
{ cout<<"enter book no =";
cin>>book[i].bookl[j].bookno;
cout<<"enter book name =";
gets(book[i].bookl[j].bookname);
cout<<"enter subject =";
gets(book[i].bookl[j].subject);
cout<<"enter price =";
cin>>book[i].bookl[j].price;
cout<<"enter edition =";
gets(book[i].bookl[j].edition);
cout<<"enter proprietor name =";
gets(book[i].bookl[j].pub.proprietor_name);
cout<<"enter publiching company's name =";
gets(book[i].bookl[j].pub.company_name);
cout<<"enter address =";
gets(book[i].bookl[j].pub.address);
cout<<"enter phone number =";
cin>>book[i].bookl[j].pub.phone_no;
}
}
cout<<"*************** BOOK INFORMATION *****************"<<endl;
for(i=0;i<2;i++)
{ cout<<" author no ="<<book[i].authorno<<endl;
cout<<"author name ="<<book[i].author_name<<endl;
cout<<" BOOK LIST"<<endl;

98
for(j=0;j<2;j++)
{ cout<<"book no ="<<book[i].bookl[j].bookno<<endl;
cout<<"book name ="<<book[i].bookl[j].bookname<<endl;
cout<<"subject ="<<book[i].bookl[j].subject<<endl;
cout<<"price ="<<book[i].bookl[j].price<<endl;
cout<<"edition ="<<book[i].bookl[j].edition<endl;
cout<<"PUBLICATION"<<endl;
cout<<"proprietor name =";
cout<<book[i].bookl[j].pub.proprietor_name<<endl;
cout<<"publiching company's name =";
cout<<book[i].bookl[j].pub.company_name;
cout<<"\n address ="<<book[i].bookl[j].pub.address<<endl;
cout<<"phone number ="<<book[i].bookl[j].pub.phone_no<<endl;
}
}
}

3. Declare a structure to represent a complex number (a number having a real and


imaginary part). Write C++ function to add, subtract, multiply and divide two
complex numbers.
Ans. #include<conio.h>
#include<iostream.h>
struct complexNo
{ float real, img; };
typedef complexNo cm;
void main()
{ cm n1,n2,res;
cout<<"\nEnter 2 complex nos:";
cout<<"\n\n Enter 1st No.:";
cout<<"\n Real = ? ";
cin>>n1.real;
cout<<"\n Imaginary = ? ";
cin>>n1.img;
cout<<"\n Enter 2st No.:";
cout<<"\n Real = ? ";
cin>>n2.real;
cout<<"\n Imaginary = ? ";
cin>>n2.img;
res.real = n1.real +n2.real;
res.img = n1.img + n2.img;
cout<<"\n Sum of " << n1.real << " + i " << n1.img << " & "
<< n2.real << " +i " << n2.img << "is "<< res.real << " + i " <<res.img;
res.real = n1.real -n2.real;

99
res.img = n1.img - n2.img;
cout<<"\n Diff. of " << n1.real << " + i " << n1.img << " & "
<< n2.real << " +"<< res.img;
res.real = n1.real *n2.real;
res.img = n1.img *n2.img;
cout<<"\n Product of " << n1.real << " + i " << n1.img << " & "
<< n2.real << " +i " << n2.img << "is "<< res.real << " + i "<< res.img;
res.real = n1.real / n2.real;
res.img = n1.img / n2.img;
cout<<"\n Result od dividing of " << n1.real << " + i " << n1.img << "by "
<< n2.real << " +i " << n2.img << "is "<< res.real << " + i "<< res.img;
}

4. Write a program to record score of a cricket match. One array stores


information of batting team such as batsman’s name, runs scored, indication if
out, mode by which out along with total runs, overs played, total overs and extras.
The other array stores information about bowling team such as bowler's name,
overs bowled, maiden overs, runs given, and wicked taken. The program reads in
the above information and depending upon the user's choice, it displays either the
batting team's information or the bowling team's information.
Ans. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct batting
{ char batsman[20];
int run;
char out;
int tot_run, overs, total_over, extra;
};
struct bowling
{ char bowler[20];
int overs, maiden_overs, runs, wicket;
};
void main()
{ batting bat_team[12];
bowling bo_team[12];
cout<<"\n Enter records of batting team :\n\n";
for(int i =0; i < 12 ; i++)
{ cout<<"\n Enter bat's man name :";
gets(bat_team[i].batsman);
cout<<"\n Enter run scored :";
cin>>bat_team[i].run;
cout<<"\n Type 0 NOT-OUT , Type 1 if OUT :";

100
cin>>bat_team[i].out;
cout<<"\n Enter total run :";
cin>>bat_team[i].tot_run;
cout<<"\n Enter no. of overs played :";
cin>>bat_team[i].overs;
cout<<"\n Enter total over:";
cin>>bat_team[i].total_over;
cout<<"\n Extra ?";
cin>>bat_team[i].extra;
}
cout<<"\n Enter records of bowling team :\n\n";
for( i = 0; i < 12 ; i++)
{ cout<<"\n Enter bowler's name :";
gets(bo_team[i].bowler);
cout<<"\n Enter overs bowled :";
cin>>bo_team[i].overs;
cout<<"\n Enter maiden overs :";
cin>>bo_team[i].maiden_overs;
cout<<"\n Enter runs :";
cin>>bo_team[i].runs;
cout<<"\n Enter wicked taken:";
cin>>bo_team[i].wicket;
}
char ch;
int n;
do
{
cout<<"\n Enter 1 to view batting team information:";
cout<<"\n Enter 2 to view bowling team information:";
cout<<"\n Enter your choice :";
cin>>n;
switch(n)
{
case 1:
cout<<"\n ************* BATTING TEAM *************\n";
cout<<"\n Name \t RUN-Scored Out Total-run Overs-played
cout<<Total-Overs Extra ";
for( i = 0; i < 12 ; i++)
{ cout<<"\n"<< bat_team[i].batsman <<"\t"<< bat_team[i].run<<" ";
if(bat_team[i].out)
cout<<"OUT";
else
cout<<"NOT-OUT";

101
cout<< " " << bat_team[i].tot_run<< " " << bat_team[i].overs << " "
<< bat_team[i].total_over<< " "<< bat_team[i].extra;
}
break;
case 2:
cout<< "\n ************* BOWLING TEAM *************\n";
cout<< "\n Name \t Overs_bowled Maiden-Overs Runs-Given Wicket-Taken ";
for( i = 0; i < 12 ; i++)
{ cout<< "\n"<< bo_team[i].bowler<< "\t"<< bo_team[i].overs<< " ";
cout<< " "<< bo_team[i].maiden_overs<< " "<< bo_team[i].runs<< " "
<< bo_team[i].wicket<<" ";
}
break;
default:
cout<< "\n Wrong choice.";
}
cout<<"\n Do you continue (y/n)";
cin>>ch;
}while((ch=='y')||(ch=='Y'));
getch();
}

5. Create a structure called volume that uses 3 variables (length, width, height) of
type distance (feet and inches) to model the volume of a room. Read the three
dimensions of the room and calculate the volume it represents, and print out the
result. The volume should be in cu. feet form, i.e., you will have to convert each
dimension in to feet and fractions of foot. For instance, the length 12 feet 6
inches will be 12.5 feet.
Ans. #include<iostream.h>
#include<conio.h>
struct vol
{ int l_in_feet, b_in_feet, h_in_feet;
int l_in_inch, b_in_inch, h_in_inch;
};
void main()
{ vol room;
char ch[10];
cout << "\n Enter length in feet and inches(XfeetXinch/X F. X I.) :";
cin>>room.l_in_feet>>ch>>room.l_in_inch>>ch;
cout << "\n Enter breadth in feet and inches (XfeetXinch..):";
cin >>room.b_in_feet >> ch >>room.b_in_inch >> ch;
cout << "\n Enter height in feet and inches(XfeetXinch…) :";
cin >>room.h_in_feet >> ch >>room.h_in_inch >> ch;

102
float len, br, height;
len =room.l_in_feet + (float)(room.l_in_inch/12);
br = room.b_in_feet + (float)(room.b_in_inch/12);
height = room.h_in_feet + (float)(room.h_in_inch/12);
double volm = (double)len * br*height;
cout<< "\n The Length of the Room = " << len << "feet";
cout<< "\n The Breadth of the Room = "<< br << "feet";
cout<< "\n The Volume of the Room =" << height << "feet";
cout<< "\n The Volume of the Room =" << volm << "c.feet";
}
6. Details of 50 clients of an investment company are stored in an array of
structures. Details include customer name, code, date of starting, number of years,
interest rate, and total amount. Write a program to calculate compound interest
for these clients.
Ans. #include<math.h>
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
struct client_info
{ char name[50];
int code;
double d_o_s, year, rate, amount;
};
client_info client[50];
void main()
{ int i,j;
double compound,x;
for(i=0;i<50;i++)
{ cout<<"enter customer name = ";
gets(client[i].name);
cout<<"enter code = ";
cin>>client[i].code;
cout<<"enter date of starting = ";
cin>>client[i].d_o_s;
cout<<"enter number of years = ";
cin>>client[i].year;
cout<<"enter intrest rate = ";
cin>>client[i].rate;
cout<<"enter total amount =";
cin>>client[i].amount;
x= client[i].amount*pow(( 1.0+client[i].rate/100.0), client[i].year);
compound=x-client[i].amount;
}

103
for(i=0;i<50;i++)
{ cout<<" customer name = "<<client[i].name<<endl;
cout<<"code = "<<client[i].code<<endl;
cout<<"date of starting = "<<client[i].d_o_s<<endl;
cout<<"number of years = "<<client[i].year<<endl;
cout<<"intrest rate = "<<client[i].rate<<endl;
cout<<"total amount ="<<client[i].amount<<endl;
cout<<"compound intrest ="<<compound<<endl;
}
}
7. An array stores details of 25 students (roll no, name, marks in three subjects).
Write a program to create such an array and print out a list of students who have
failed in more than one subject. Assume 40% as pass marks.
Ans. #include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct stud
{ int roll;
char nm[50];
float m1, m2, m3;
};
typedef stud S;
void main()
{
S student[25];
for(int i =0 ; i < 25 ; i++)
{ cout << "\n Enter Roll no : ";
cin >> student[i].roll;
cout << "\n Enter Name : ";
gets(student[i].nm);
cout << "\n Enter marks of three subjects :";
cin >> student[i].m1 >> student[i].m2 >> student[i].m3 ;
}
cout<< "\n STUDENTS FAILED IN MORE THAN 1 SUBJECT \n ";
for(i =0 ; i < 25 ; i++)
{ if(( student[i].m1< 40 && student[i].m2 < 40) || (student[i].m2 < 40 &&
student[i].m3 < 40) || ( student[i].m1 < 40 && student[i].m3 < 40))
cout << student[i].roll << "\t" << student[i].nm << "\n";
}
}
8. A linear array if size 50 stores following information’s: name of the country,
country's capital and per capita income of the country.
Write a complete program in C++ to do the following :

104
(a) To read a country's name and display capital and per-ca pita income.
(b) To read name of the capital city and displays country's name and displays
country's name and per capital income.
Ans. #include<iostream.h>
#include<conio.h>
#include <string.h>
#include <stdio.h>
struct country
{ char country[30], capital[30];
float income;
};
void main()
{ country c[3];
for( int i=0; i<3 ; i++)
{ cout << "\n Country's name : ";
cin.ignore();
cin.getline(c[i].country, 30);
cout << "\n Country's capital :";
cin.getline(c[i].capital,30);
cout << "\n Per capita income :";
cin >> c[i].income;
}
char cap[30];
cin.ignore();
cout << "\n Enter Capital name : ";
cin.getline(cap, 30);
for(int k=0; k<3 ; k++)
{ if(strcmp(c[k].capital,cap)==0)
cout<<"\n"<<c[k].country<<"\t"<<c[k].capital<<"\t"<<c[k].income <<"\n;
}
char con[30];
cout << "\n Enter Country name : ";
cin.getline(con,30);
for(int m=0; m<3 ; m++)
{ if(strcmp(c[m].country,con)==0)
cout << c[m].capital << "\t" << c[m].income << "\n" ;

}
}

105
COMPUTER FUNDAMENTALS
(COMPUTER OVERVIEW, SOFTWARES AND MICROPROCESSOR)

What is Computer?
Computer is an advanced electronic device that takes raw data as input from the user
and processes these data under the control of set of instructions (called program) and
gives the result (output) and saves output for the future use. It can process both
numerical and non-numerical (arithmetic and logical) calculations.
It works the principle of I-P-O Cycle
A computer has four functions:
a. accepts data Input
b. processes data Processing
c. produces output Output
d. stores results Storage
Input (Data): Input is the raw information or facts entered into a computer from the
input devices. It is the collection of letters, numbers, images etc.
Process: Process is the operation of data as per given instruction. It is totally internal
process of the computer system.
Output: Output is the processed data given by computer after data processing. Output
is also called Result or information. We can save these results in the storage devices for
the future use.

COMPUTER SYSTEM
The components of the Computer System are:-
1. Hardware
2. Software
3. Firmware
4. Liveware
COMPUTER SYSTEM = HARDWARE + SOFTWARE+ USER
Hardware = Internal Devices + Peripheral Devices. All physical parts of the computer (or
everything that we can touch) are known as Hardware.
Eg: Keyboard, Mouse,
Software = Programs. Software gives "intelligence" to the computer.
USER = Person, who operates computer.
Software: Software is a set of instructions or a program that enables a hardware to run.
Without the use of software hardware cannot work.
Eg. Windows 8, Photoshop, MS Office etc.
Firmware Instructions written/embedded on a hardware are known as firmware e.g.,
BIOS instruction on ROM chip are called Firmware.
Liveware: Persons or the users, using Computers in day to day activity are known as
liveware.

106
GENERATIONS OF COMPUTER:
First Generation (1940-56):
The first generation computers used Vacuum tubes & Machine language was used for
giving the instructions. These computers were large in size & their programming was
difficult task. The electricity consumption was very high. Some computers of this
generation are ENIAC, EDVAC, EDSAC& UNIVAC-1.
Second Generation(1956-63): In 2nd generation computers, Vacuum tubes were
replaced by Transistors. They required only 1/10 of power required by Vacuum tubes.
This generation computers generated less heat & were
reliable. The first operating system developed in this generation.
The Third Generation(1964-71): The 3rd generation computers replaced transistors
with Integrated circuit known as chip. From
Small scale integrated circuits which had 10 transistors per chip, technology developed
to MSI circuits with 100 transistors per chip. These computers were smaller, faster &
more reliable. High level languages invented in this generation.
The fourth Generation(1972- present): LSI & VLSI were used in this generation. As a
result microprocessors came into existence. The computers using this technology known
to be Micro Computers. High capacity hard disk were invented. There is great
development in data communication.
The Fifth Generation (Present & Beyond): Fifth generation computing devices, based
on artificial intelligence, are still in development, though there are some applications,
such as voice recognition, that are being used today. The use of parallel processing and
superconductors is helping to make artificial intelligence a reality. Quantum
computation and molecular and nanotechnology will radically change the face of
computers in years to come.

ARCHITECTURE OF COMPUTER
Input Devices: Those devices which help to enter data into computer system. Eg.
Keyboard, Mouse, Touch screen, Bar Code Reader, Scanner, MICR, etc.
Output Devices: Those devices which help to display the processed information. Eg.
Monitor, Printer, Plotter, Projector, etc.
CENTRAL PROCESSING UNIT (CPU)
The main component to make a computer operate is the computer chip or
microprocessor. This is referred to as the Central Processing Unit (CPU). It is also
known as Brain of computer. It performs arithmetic and logic operations. The CPU
(Central Processing Unit) is the device that interprets and executes instructions.

MEMORY: It facilitates the remembrance power to computer system. It refers to the


physical devices used to store programs (sequences of instructions) or data (e.g. program
state information) on a temporary or permanent basis for use in a computer or other
digital electronic device. Memory can be of two types:-
1. Primary Memory
2. Secondary Memory

107
The term primary memory is used for the information in physical systems which are fast
(i.e. RAM), as a distinction from secondary memory, which are physical devices for
program and data storage which are slow to access but offer higher memory capacity.
Primary memory stored on secondary memory is called virtual memory.
Primary Memory can be categorized as:-
1. Volatile Memory (RAM)
2. Non-Volatile Memory (ROM)

Volatile memory (RAM) Volatile memory is computer memory that requires power to
maintain the stored information. RAM stands for Random Access Memory. The data is
primarily stored on RAM. This is also known as Read-Write memory as both the
operation can take place on it. It is volatile in nature
because as soon as the power is off its contents are also removed. It can be of two
types:-
1. Static RAM or SRAM.
2. Dynamic RAM or DRAM
SRAM retains its contents as long as the power is connected and is easy to interface to
but uses six transistors per bit.
Dynamic RAM is more complicated to interface to and control and needs regular refresh
cycles to prevent its contents being lost. However, DRAM uses only one transistor and a
capacitor per bit, allowing it to reach much higher densities and, with more bits on a
memory chip, be much cheaper per bit. SRAM is not worthwhile for desktop system
memory, where DRAM dominates, but is used for their cache memories..

Non Volatile Memory (ROM): Non-volatile memory is computer memory that can retain
the stored information even when not powered. ROM stands for Read Only Memory. As
the name suggests we can perform only read operation on ROM. It is permanent in
nature. In ROM booting instructions for computer in the form of firmware are stored.
Other examples of non-volatile memory are flash memory and PROM/EPROM/EEPROM
memory.

Cache Memory:
Cache memory is an intermediate between RAM and processor. It is very fast. Cache
memory is random access memory (RAM) that a computer microprocessor can access
more quickly than it can access regular RAM. As the microprocessor processes data, it
looks first in the cache memory and if it finds the data there (from a previous reading of
data), it does not have to do the more time consuming reading of data from larger
memory.

Secondary Memory:
A. Hard Disk (Local Disk)
B. Optical Disks: CD-R, CD-RW, DVD-R, DVD-RW
C. Floppy Disks

108
D Memory Cards
E. External Hard Disk
F. Blu Ray Disk
Blu-Ray Disk: Blu-ray (not Blue-ray) also known as Blu-ray Disc (BD), is the name of a
new optical disc format. The format offers more than five times the storage capacity of
traditional DVDs and can hold up to 25GB on a single-layer disc and 50GB on a dual-
layer disc. While current optical disc technologies such as DVD, DVD±R, DVD±RW, and
DVD-RAM rely on a red laser to read and write data, the new format uses a blue-violet
laser instead, hence the name Blu-ray.
Units of Memory:
The smallest unit is bit, which mean either 0 or 1.
1 bit = 0 or 1
1 Byte = 8 bit
1 Nibble = 4 bit
1 Kilo Byte = 1024 Byte= 210 Byte
1 Mega Byte = 1024 KB= 210 KB
1 Gega Byte = 1024 MB= 210 MB
1 Tera Byte = 1024 GB= 210 GB
1 Peta Byte =1024 TB= 210 TB
1 Exa Byte =1024 PB= 210 PB
1 Zetta Byte = 1024 EB= 210 EB
1 Yotta Byte = 1024 ZB= 210 ZB

TYPES OF COMPUTER (ON THE BASIS OF WORKING PRINCIPLE)


a) Analog Computer: An analog computer is a form of computer that uses continuous
physical phenomena such as electrical, mechanical, or hydraulic quantities to model the
problem being solved.Eg: Thermometer, Speedometer, Petrol pump indicator,
Multimeter.
b) Digital Computer: A computer that performs calculations and logical operations with
quantities represented as digits, usually in the binary number system.
c) Hybrid Computer (Analog + Digital): A combination of computers those are capable
of inputting and outputting in both digital and analog signals. A hybrid computer
system setup offers a cost effective method of performing complex simulations. The
instruments used in medical science lies in this category.

TYPES OF COMPUTER (ON THE BASIS OF SIZE)


a) Super Computer: The fastest type of computer. Supercomputers are very expensive
and are employed for specialized applications that require immense amounts of
mathematical calculations. For example, weather forecasting requires a supercomputer.
Other uses of supercomputers include animated graphics, fluid dynamic calculations,
nuclear energy research, and petroleum exploration. PARAM, Pace & Flosolver are the
supercomputer made in India.

109
b) Mainframe Computer: A very large and expensive computer capable of supporting
hundreds, or even thousands, of users simultaneously. In the hierarchy that starts with
a simple microprocessor (in watches, for example) at the bottom and moves to
supercomputers at the top, mainframes are just below supercomputers. In some ways,
mainframes are more powerful than supercomputers because they support more
simultaneous programs. But supercomputers can execute a single program faster than a
mainframe.
c) Mini Computer A midsized computer. In size and power, minicomputers lie between
workstations and mainframes. In the past decade, the distinction between large
minicomputers and small mainframes has blurred, however, as has the distinction
between small minicomputers and workstations. But in general, a minicomputer is a
multiprocessing system capable of supporting from 4 to about 200 users
simultaneously. Generally, servers are comes in this
category.
d) Micro Computer
i. Desktop Computer: a personal or micro-mini computer sufficient to fit on a desk.
ii. Laptop Computer: a portable computer complete with an integrated screen and
keyboard. It is generally smaller in size than a desktop computer and larger than a
notebook computer.
iii. Palmtop Computer/Digital Diary /Notebook /PDAs: a hand-sized computer.
Palmtops have no keyboard but the screen serves both as an input and output device.
e) Workstations: A terminal or desktop computer in a network. In this context,
workstation is just a generic term for a user's machine (client machine) in contrast to a
"server" or "mainframe."

SOFTWARE
As specified earlier Software, simply are the computer programs. The instructions given
to the computer in the form of a program is called Software. Software is the set of
programs, which are used for different purposes. All the programs used in computer to
perform specific task is called Software.

Types of software
1. System software:
a) Operating System Software: DOS, Windows XP, Windows Vista, Unix/Linux,
MAC/OS X etc.
b) Utility Software: Windows Explorer (File/Folder Management), Compression
Tool, Anti-Virus Utilities, Disk Defragmentation, Disk Clean, BackUp, WinZip,
WinRAR etc…
c) Language Processors: Compiler, Interpreter and Assembler
2. Application software:
a) General Application Software: Ms. Office 2003, Ms. Office 2007, Macromedia
(Dreamweaver, Flash, Freehand), Adobe (PageMaker, PhotoShop)

110
b) Tailored or Customized Software: School Management system, Inventory
Management System, Payroll system, financial system etc.

Operating system
Operating system is an interface between hardware and user which is responsible
for the management and coordination of activities and the sharing of the resources of a
computer. It hosts the several applications that run on a computer and handles the
operations of computer hardware.
Functions of operating System:
• Processor Management
• Memory Management
• File Management
• Device Management
Types of Operating System:
• Real-time Operating System: It is a multitasking operating system that aims at
executing real-time applications. Example of Use: e.g. control of nuclear power plants,
oil refining,chemical processing and traffic control systems, air
• Single User Systems: Provides a platform for only one user at a time. They are
popularly associated with Desk Top operating system which run on standalone systems
where no user accounts are required. Example: DOS.
• Multi User Systems: Provides regulated access for a number of users by maintaining
a database of known users. Refers to computer systems that support two or more
simultaneous users. Another term for multi-user is time sharing. Ex: All mainframes are
multi-user systems. Example: Unix
• Multi-tasking and Single-tasking Operating Systems: When a single program is
allowed to run at a time, the system is grouped under the single-tasking system
category, while in case the operating system allows for execution of multiple tasks at a
time, it is classified as a multi-tasking operating system.
• Distributed Operating System: An operating system that manages a group of
independent computers and makes them appear to be a single computer is known as a
distributed operating system. Distributed computations are carried out on more than
one machine. When computers in a group work in cooperation, they make a distributed
system.

Commonly used operating system


UNIX: Pronounced uoo-niks, a popular multi-user, multitasking operating system
developed at Bell Labs in the early 1970s. UNIX was one of the first operating systems to
be written in a highlevel programming language, namely C. This meant that it could be
installed on virtually any computer for which a C compiler existed.
LINUX: Pronounced lee-nucks or lih-nucks. A freely-distributable open source operating
system that runs on a number of hardware platforms. The Linux kernel was developed
mainly by Linus Torvalds and it is based on Unix. Because it's free, and because it runs

111
on many platforms, including PCs and Macintoshes, Linux has become an extremely
popular alternative to proprietary
operating systems.
Windows: Microsoft Windows is a series of graphical interface operating systems
developed, marketed, and sold by Microsoft. Microsoft introduced an operating
environment named Windows on November 20, 1985 as an add-on to MS-DOS in
response to the growing interest in graphical user interfaces (GUIs). Microsoft Windows
came to dominate the world's personal computer market with over 90% market share,
overtaking Mac OS, which had been introduced in 1984.The most recent client version
of Windows is Windows 7; the most recent server version is Windows Server 2008 R2;
the most recent mobile version is Windows Phone 7.5.
SOLARIS: Solaris is a Unix operating system originally developed by Sun Microsystems.
It superseded their earlier SunOS in 1993. Oracle Solaris, as it is now known, has been
owned by Oracle Corporation since Oracle's acquisition of Sun in January 2010.
BOSS: BOSS (Bharat Operating System Solutions) GNU/Linux distribution developed by
C-DAC (Centre for Development of Advanced Computing) derived from Debian for
enhancing the use of Free/ Open Source Software throughout India. This release aims
more at the security part and comes with an easy to use application to harden your
Desktop.

Mobile OS: A mobile operating system, also called a mobile OS, is an operating system
that is specifically designed to run on mobile devices such as mobile phones,
smartphones, PDAs, tablet computers and other handheld devices. The mobile operating
system is the software platform on top of which other programs, called application
programs, can run on mobile devices.
• Android: Android is a Linux-based mobile phone operating system developed by
Google. Android is unique because Google is actively developing the platform but giving
it away for free to hardware manufacturers and phone carriers who want to use Android
on their devices.
• Symbian: Symbian is a mobile operating system (OS) targeted at mobile phones
that offers a high-level of integration with communication and personal information
management (PIM) functionality. Symbian OS combines middleware with wireless
communications through an integrated mailbox and the integration of Java and PIM
functionality (agenda and contacts). The Symbian OS is open for third-party
development by independent software vendors, enterprise IT departments, network
operators and Symbian OS licensees.

LANGUAGE PROCESSORS: Since a computer hardware is capable of understanding


only machine level instructions, So it is necessary to convert the HLL into Machine Level
Language.
There are three Language processors:

112
A. Compiler: It is translator which converts the HLL language into machine language in
one go. A Source program in High Level Language get converted into Object Program in
Machine Level Language.
B. Interpreter: It is a translator which converts and executes the HLL language code
line by line. It takes one statement of HLL and converts it into machine code which is
immediately executed. It eliminates the need of separate compilation/run. However, It is
slow in processing as compare to compiler.
C. Assembler: It translates the assembly language into machine code.

MICROPROCESSOR:
A microprocessor is a semiconductor chip, which is manufactured using the Large Scale
Integration (LSI) or Very Large Scale Integration (VLSI), which comprises Arithmetic
Logic Unit, Control unit and Central Processing Unit (CPU) fabricated on a single chip.

Terminologies:
Registers: A register is a very small amount of very fast memory that is built into the
CPU (central processing unit) in order to speed up its operations by providing quick
access to commonly used values. All data must be represented in a register before it can
be processed. For example, if two numbers are to be multiplied, both numbers must be
in registers, and the result is also placed in a register.

Bus: A collection of wires through which data is transmitted from one part of a computer
to another. You can think of a bus as a highway on which data travels within a
computer. When used in reference to personal computers, the term bus usually refers to
internal bus. This is a bus that connects all the internal computer components to the
CPU and main memory. All buses consist of two parts -- an address bus and a data bus.
The data bus transfers actual data whereas the address bus transfers information about
where the data should go. The control bus is used by the CPU to direct and monitor the
actions of the other functional areas of the computer. It is used to transmit a variety of
individual signals (read, write, interrupt, acknowledge, and so forth) necessary to control
and coordinate the operations of the computer. The size of a bus, known as its width, is
important because it determines how much data can be transmitted at one time. For
example, a 16-bit bus can transmit 16 bits of data, whereas a 32-bit bus can transmit
32 bits

113
Clock speed: Also called clock rate, the speed at which a microprocessor executes
instructions. Every computer contains an internal clock that regulates the rate at which
instructions are executed and synchronizes all the various computer components. The
CPU requires a fixed number of clock ticks (or clock cycles) to execute each instruction.
The faster the clock, the more instructions the CPU can execute per second. Clock
speeds are expressed in megahertz (MHz) or gigahertz ((GHz). 16 bit Microprocessor: It
indicates the width of the registers.

16-bit microprocessor can process data and memory addresses that are represented by
16 bits. Eg. 8086 processor
32 bit Microprocessor: It indicates the width of the registers. A 32-bit microprocessor
can process data and memory addresses that are represented by 32 bits. Eg. Intel 80386
processor, Intel 80486
64 bit Microprocessor: It indicates the width of the registers; a special high-speed
storage area within the CPU. A 32-bit microprocessor can process data and memory
addresses that are represented by 32 bits. e.g. Pentium dual core, Core 2 duo. 128 bit
Microprocessor: It indicates the width of the registers. A 28-bit microprocessor can
process data and memory addresses that are epresented by 128 bits.E.g. Intel core i7

Difference between RISC & CISC architecture


RISC (Reduced Instruction Set Computing):
1. RISC system has reduced number of instructions.
2. Performs only basic functions.
3. All HLL support is done in software.
4. All operations are register to register.
CISC (Complex Instruction Set Computing):
1. A large and varied instruction set.
2. Performs basic as well as complex functions.
3. All HLL support is done in Hardware.
4. Memory to memory addressing mode
EPIC (Explicitly Parallel Instruction Computing): It is a 64-bit Microprocessor
instruction set, jointly defined and designed by Hewlett Packard and Intel, that provides
up to 128 general and floating point unit registers and uses speculative loading,
predication, and explicit parallelism to accomplish its computing tasks. By comparison,
current 32- bit CISC and RISC microprocessor architectures depend on 32-bit registers,
branch prediction, memory latency, and implicit parallelism, which are considered a less
efficient approach in micro architecture design.

PORTS: A port is an interface between the motherboard and an external device.


Different types of port are available on motherboard as serial port, parallel port, PS/2
port, USB port, SCSI port etc.

114
Serial port(COM Port): A serial port transmit data one bit at a time. Typically on older
PCs, a modem, mouse, or keyboard would be connected via serial ports. Serial cables
are cheaper to make than parallel cables and easier to shield from interference. It is also
called communication port.
Parallel Port (LPT ports): It supports parallel communication i.e. it can send several
bits simultaneously. It provides much higher data transfer speed in comparison with
serial port. It is also called Line Printer Port.
USB (Universal Serial Bus): It is a newer type of serial connection that is much faster
than the old serial ports. USB is also much smarter and more versatile since it allows
the "daisy chaining" of up to 127 USB peripherals connected to one port. It provides plug
& play communication.
PS/2 Port : PS/2 ports are special ports for connecting the keyboard and mouse to
some PC systems. This type of port was invented by IBM
FireWire Port : The IEEE 1394 interface, developed in late 1980s and early 1990s by
Apple as FireWire, is a serial bus interface standard for high-speed communications and
isochronous realtime data transfer. The 1394 interface is comparable with USB and
often those two technologies are considered together, though USB has more market
share.
Infrared Port: An IR port is a port which sends and receives infrared signals from other
devices. It is a wireless type port with a limited range of 5-10ft.
Bluetooth: Bluetooth uses short-range radio frequencies to transmit information from
fixed and mobile devices. These devices must be within the range of 32 feet, or 10
meters for Bluetooth to effectively work. A Bluetooth port enables connections for
Bluetooth-enabled devices for synchronizing. Typically there are two types of ports:
incoming and outgoing. The incoming port enables the device to receive connections
from Bluetooth devices while the outgoing port makes connections to Bluetooth devices.

INTERNAL STORAGE ENCODING OF CHARACTERS:


ASCII (American standards code for information interchange): ASCII code is most
widely used alphanumeric code used in computers. It is a 8- bit code, and so it has
28 =256 possible code groups. It represents all of the standard keyboard characters as
well as control functions such as Return & Linefeed functions.
ISCII (Indian standards code for information interchange): To use the Indian
language on computers, ISCII codes are used. It is an 8-bit code capable of coding 256
characters. ISCII code retains all ASCII characters and offers coding for Indian scripts
also.
Unicode: It is a universal coding standard which provides a unique number for every
character, no matter what the platform, no matter what the program, no matter what
the language. Unicode is a 16-bit code capable of representing more than 65000
characters. The coding for ASCII characters remain the same in Unicode. It can
represent almost all the languages of the world.

115
PROGRAMMING METHODOLOGY

STYLISTIC GUIDELINES:
Writing good program is a skill. This can be developed by using the following
guidelines .
1. Meaningful Names for identifiers: A programmer should give the meaningful names
to each section of the program so that it can help him to identify the variable used for
specific purpose. This helps him to execute the right elements during the complex run of
a program.
2. Ensure clarity of expression: Expression carry out the specified action. Thus they
must be clearly understood by the users. There should not be any compromise with the
clarity of expression.
3. Use of comments and indentations: Comments generally are used as the internal
documentation of a program .if comments are used in the program they will guide the
program while debugging and checking. While indentation is the proper way of writing to
avoid the confusion regarding the flow of program. These highlights nesting of groups of
control statements.
4. Insert blank lines and blank spaces: Blank lines should be used to separate long,
logically related blocks of code. Specifically Normally in programming the standard for
the use of spaces is to follow normal English rules. This means that: Most basic symbols
in C++ (e.g., “=”, “+”, etc.) should have at least one space before and one space after
them.
5. Statements: Each statement should appear on a separate line. The opening brace
following a control statement such as if or while should appear on the line after the if or
while, lined up with the left of the control statement, and the closing brace should
appear on its own line, lined up with the left of the control statement. The opening and
closing braces for a function should be lined up in the same way. The statements within
a {_____} pair are indented relative to the braces.

Characteristics of a Good Program:


Following are the characteristics of a good program.
1. Effective and efficient: The program produces correct results and is faster, taking
into account the memory constraints.
2. User friendly: The program should be user friendly. The user should not be confused
during the program execution . The user should get correct direction and alerts when he
is going through the program.
3. Self documenting code: A good program must have self documenting code. This
code will help the programmer to identify the part of the source code and clarify their
meaning in the program.
4. Reliable: The good program should be able to cope up from any unexpected
situations like wrong data or no data.
5. Portable: The program should be able to run on any platform, this property eases the
use of program in different situations.
6. Robustness: Robustness is the ability of the program to bounce back an error and to
continue operating within its environment

116
PROBLEM SOLVING METHODOLOGY AND TECHNIQUES:
To develop an efficient and effective programs we should adopt a proper problem
solving methodology and use appropriate techniques. Following are some of the methods
and techniques to develop a good program.
1. Understand the problem well: for a good program one should understand the
problem well . one should know what exactly is expected from the problem. Knowing the
problem well is the half way done.
2. Analyze the program. : Analyzing the problem involves identifying the program
specification and defining each program’s minimum number of inputs required for
output and processing components.
3. Design : In this phase of design a Model is developed which look alike a program .
This phase gives the face to the program. Outputs are designed in this phase.
4. Code program :This step is the actual implementation of the program. In this
program algorithm is translated into programming language. in this it is essential to
decide which technique or logical will be more appropriate for coding.
5. Test and Debug program.: Once the solution algorithm is coded the next step is to
test and debug the program. Testing is the process of finding errors in a program and
debugging is of correcting the errors. The developed program is put to test in different
conditions and verified at different level for its proper and efficient working.
6. Implementation & Documentation: After successful execution of the program it is
implemented. Documentation refers to written descriptions specification, design code
and comments, internal and external to program which makes more readable and
understandable.
Uses of documentation:
1. This becomes an useful interface between a technical personnel and non
technical personnel.
2. This is very useful for upkeep and maintenance.
3. Documentation makes ease for any technical emergencies.
4. Very useful in operating for learners and trainers.

ALGORITHM :-Algorithm is a step-by-step process of solving a well-defined


computational problem. An algorithm is an effective method expressed as a finite list of
well-defined instructions forcalculating a function, starting from an initial state and
initial input. Thus, a step-by-step procedure to solve the problem is called algorithm.
Example: Let us take one simple day-to-day example by writing algorithm for making
“Maggi Noodles‟ as a food.
Step 1: Start
Step 2: Take pan with water
Step 3: Put pan on the burner
Step 4: Switch on the gas/burner
Step 5: Put maggi and masala
Step 6: Give two minutes to boil
Step 7: Take off the pan
Step 8: Take out the magi with the help of fork/spoon
Step 9: Put the maggi on the plate and serve it
Step 10: Stop.
Further, the way of execution of the program shall be categorized into three ways:

117
(i) sequence statements; (ii) selection statements; and (iii) iteration or looping
statements. This is also called as “control structure‟.
Selective Statements: In this program, some portion of the program is executed based
upon the conditional test. If the conditional test is true, compiler will execute some part
of the program, otherwise it will execute the other part of the program.
Example :Write an algorithm to check whether a person is eligible to vote?
(Age more than or equal to 18 years makes one eligible to vote).
Step 1: Start
Step 2: Take age and store it in age
Step 3: Check age value, if age >= 18 then go to step 4 else step 5
Step 4: Print “Eligible to vote” and go to step 6
Step 5: Print “Not eligible to vote”
Step 6: Stop
Iterative statements: In some programs, certain set of statements are executed again
and again based upon conditional test. i.e. executed more than one time. This type of
execution is called “looping or iteration‟.
Example: Write an algorithm to print all natural numbers up to “n‟.
Step 1: Start
Step 2: Take any number and store it in n.
Step 3: Store 1 in I
Step 4: Check I value, if I<=n then go to step 5 else go to step 8
Step 5: Print I
Step 6: Increment I value by 1
Step 5: Go to step 4
Step 8: Stop

FLOWCHART : We can also show steps of an algorithm in graphical form by using some
symbols.
This is called
flowcharting.
Thus, Flowchart is
a pictorial
view of algorithm.

118
1. Draw a flowchart to find the simple interest. (Sequence)

2. Draw a
flowchart to
find bigger
number
among two
numbers
(selective)

119
3. Draw a flowchart to find a factorial of any number.

120
TYPE OF ERRORS: There are three types of errors generally occur during compilation
and running a program. They are
(i) Syntax error; (ii) Logical error; and (iii) Runtime error.
Syntax error: Every programming language has its own rules and regulations (syntax).
If we overcome the particular language rules and regulations, the syntax error will
appear (i.e. an error of language resulting from code that does not conform to the syntax
of the programming language). It can be recognized during compilation time.

Example:
int a = 0;
while (a < 10)
{
a=a+1
cout<<a;
}
In the above statement, the fourth line is not correct. Since the statement does not end
with ;. This will flash a syntax error.
Logical error: Programmer makes errors while writing program that is called logical
error. It is an error in a program's source code that results in incorrect or unexpected
result. It is a type of runtime error that may simply produce the wrong output or may
cause a program to crash while running. The logical error might only be noticed during
runtime, because it is often hidden in the source code and are typically harder to find
and debug.
int a = 100;
while (a < 10)
{
a = a + 1;
cout<< a;
}
In the above example, the while loop will not execute even a single time, because the
initial value of a is 100.
Runtime error: A runtime error is an error that causes abnormal termination of
program during run time. In general, the dividend is not a constant but might be a
number typed by you at runtime. In this case, division by zero is illogical. Computers
check for a "division by zero" error during program execution, so that you can get a
"division by zero" error message at runtime, which will stop your program abnormally.

121
DATA REPRESENTATION

1. Binary Number Conversion

i) Binary to Octal:

Binary: 000 001 010 011 100 101 110 111


Octal: 0 1 2 3 4 5 6 7

Binary: (11100101)2 = 11 100 101


011 100 101 Pad the most significant digits with
zeros if necessary to complete a group
of three.

Then, look up each group in the above table:


Binary =011 100 101
Octal = 3 4 5 = (345)8

ii) Binary to Hexadecimal:

Binary: 0000 0001 0010 0011 0100 0101 0110 0111


Hexadecimal: 0 1 2 3 4 5 6 7
Binary: 1000 1001 1010 1011 1100 1101 1110 1111
Hexadecimal: 8 9 A B C D E F

Binary = 1110 0101


Hexadecimal = E 5 = (E5)16

iii)
Binary to Decimal:

122
2. Decimal Number Conversion

i) Decimal to Binary:

ii) Decimal to Octal:

iii) Decimal to Hexadecimal:

123
3. Octal Number Conversion

i) Octal to Binary:

ii) Octal to Decimal:

iii) Octal to
HexaDecimal:

124
4. Hexadecimal Number Conversion

i) Heaxdecimal to Binary:

ii) Hexadecimal to Decimal:

iii) Hexadecimal to
Octal:

125
126

You might also like