Professional Documents
Culture Documents
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.
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
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.
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.
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
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
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’.
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.
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:
(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
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();
}
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();
}
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();
}
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.
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.
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
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;
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;
};
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();
}
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();
}
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
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.
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;
}
} }
}
18
CHAPTER-8 OPERATORS & EXPRESSIONS IN C++
1 Mark Questions
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.
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.
6. Assuming that res starts with the value 25, what will the following code
fragment print out? cout<<res--; cout<<++res;
Ans. 25 25
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
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);
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
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
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;
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.
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.
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.
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
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.
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.
(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
28
if(a=5)
cout<<"Five";
else
cout<<"Not Five";
if the input given is: (i)7 (ii)5?
Ans. (i) Five (ii) Five
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.
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.
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
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.
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);
32
while(i++<5)
s+=i;
Ans. 5 times.
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.
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.
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.
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
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!
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.
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.
(b) 0 1 2 3 4 5
012345
012345
(c) 10 1 10 2 10 3
919293
818283
717273
616263
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(); }
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(); }
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(); }
(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:
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(); }
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(); }
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(); }
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(); }
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
53
8. When can a function prototype be omitted?
Ans. When the function definition appears before its calling function.
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.
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.
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.
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;
}
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"; }
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 }
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; }
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
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
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(); }
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(); }
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(); }
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();
}
73
CHAPTER-12
STRUCTURED DATA TYPE: ARRAY
1 Mark Questions
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
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];
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
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
A= B=
76
29. Given the following 2-D arrays:
X= Y=
A=
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:
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.
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.
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(); }
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( );
}
83
3 Mark Questions
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(); }
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 ( ); }
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
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; }
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.
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;
}
}
}
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;
}
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.
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
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.
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.
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
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.
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.
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.
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
i) Binary to Octal:
iii)
Binary to Decimal:
122
2. Decimal Number Conversion
i) Decimal to Binary:
123
3. Octal Number Conversion
i) Octal to Binary:
iii) Octal to
HexaDecimal:
124
4. Hexadecimal Number Conversion
i) Heaxdecimal to Binary:
iii) Hexadecimal to
Octal:
125
126