Академический Документы
Профессиональный Документы
Культура Документы
in
Notes on:
XI-XII Computer Science
C++ and Database/Mysql
Review Version
(Last reviewed on 09-06-2015)
New Modifications are
4 Spelling's Correction
5 More MYSQL's examples
Page 01 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Index
Topic Page NO
XI COMPUTER SCIENCE UNIT 3
III C++
Page 02 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 03 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Introduction to C++
C++ is a general purpose programming language invented
in the early 1980s by Bjarne Stroustrup at Bell Labs.
In fact C++ was originally called C with Classes and is
so compatible with C that it will probably compile more
than 99% of C programs without changing a line of
source code.
How do I get started with C++?
First you need a C++ compiler. There are many
commercial and free ones available. All compilers
listed below are completely free and include an IDE for
you to edit, compile and debug your program.
Page 04 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
C++ keywords
Chart of reserved keywords in C++. Since they are used
by the language, these keywords are not available for
re-definition.
Identifiers
The name of a variable (or other item you might define
in a program) is called an identifier. A C++ identifier
must start with either a letter or the underscore
symbol, and all the rest of the characters must be
letters, digits, or the underscore symbol. Some of the
valid and Invalid identifiers of c++ are
Page 05 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Literals/Constants in C++
Invalid Identifiers
MY Name
1MY
%my
Valid Identifiers
MY_NAME
MY1
_my
Literals are the most obvious kind of constants. They
are used to express particular values within the source
code of a program. when we wrote:
a = 5;
There are only two valid Boolean values: true and false.
These can be expressed in C++ as values of type bool by
using the Boolean literals true and false.
Page 06 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
int main ()
This line corresponds to the beginning of the main
function declaration. The main function is the point
where all C++ programs begin their execution. It is
independent of whether it is at the beginning, at the
end or in the middle of the code - its content is
always the first to be executed when a program starts.
In addition, for that same reason, it is essential that
all C++ programs have a main function.
main is followed by a pair of parenthesis () because it
is a function. In C++ all functions are followed by a
pair of parenthesis () that, optionally, can include
arguments within them. The content of the main function
immediately follows its formal declaration and it is
enclosed between curly brackets ({}), as in our
example.
cout << "Hello World";
This instruction does the most important thing in this
program. cout is the standard output stream in C++
(usually the screen), and the full sentence inserts a
sequence of characters (in this case "Hello World")
into this output stream (the screen). cout is declared
in the iostream.h header file, so in order to be able
to use it that file must be included.
Page 08 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 09 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
in just one line and this would have had exactly the
same meaning.
In C++ the separation between instructions is specified
with an ending semicolon (;) after each one. The
division of code in different lines serves only to make
it more legible and schematic for humans that may read
it.
Here is a program with some more instructions:
// my second program in C++
#include <iostream.h>
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output : Hello World! I'm a C++ program
In this case we used the cout << method twice in two
different instructions. Once again, the separation in
different lines of the code has just been done to give
greater readability to the program, since main could
have been perfectly defined thus:
int main () { cout << " Hello World! "; cout << " I'm
to C++ program "; return 0; }
We were also free to divide the code into more lines if
we considered it convenient:
#include <iostream.h>
int main ()
{ cout <<"Hello World!";
cout<< "I'm a C++ program";
return 0;
}
Page 10 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
And the result would have been exactly the same than in
the previous examples.
Preprocessor directives (those that begin by #) are out
of this rule since they are not true instructions. They
are lines read and discarded by the preprocessor and do
not produce any code. These must be specified in their
own line and do not require the include a semicolon (;)
at the end.
Comments.
Comments are pieces of source code discarded from the
code by the compiler. They do nothing. Their purpose is
only to allow the programmer to insert notes or
descriptions embedded within the source code.
C++ supports two ways to insert comments:
// line comment
/* block comment */
The first of them, the line comment, discards
everything from where the pair of slash signs (//) is
found up to the end of that same line. The second one,
the block comment, discards everything between the /*
characters and the next appearance of the */
characters, with the possibility of including several
lines.
We are going to add comments to our second program:
/* my second program in C++ with more comments */
#include <iostream.h>
int main ()
{
cout << "Hello World! "; // says Hello World!
cout << "I'm a C++ program"; // says I'm a C++ program
return 0;
}
Output :Hello World! I'm a C++ program
Page 11 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 12 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Variable in C++
Variables are memory locations to store data of a
program. Whenever we want to accept a data (as input to
your program) or store some temporary data, we would
likely to store that data into a temporary memory
location (or variable).Variable must first be declared
before it can be used.
Once a variable is declared, we are telling the
compiler the name of the variable, the initial value of
the variable (optional) and the type of data our
variable can hold.
The name of the variable must be a valid identifier.
The following image show that internal structure of a
typical C++ variable inside the RAM(Random Access
Memory)
Page 13 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 14 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
// Initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 12.0/2.0;
cout << f << endl ;
return 0;
}
Output:
30
6.0000
Lvalues and Rvalues
Variables are lvalues and may appear on the left-hand
side of an assignment. Numeric literals are rvalues and
may not be assigned and can not appear on the left-hand
side. Following is a valid statement:
int a = 2; // Here a is a Variable
Page 15 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Local Variables:
Variables that are declared inside a function or block
are local variables. They can be used only by
statements that are inside that function or block of
code. Local variables are not known to functions
outside their own. Following is the example using local
variables:
#include <iostream.h>
int main ()
{
// Local variable :
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Page 16 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Global Variables:
Global variables are defined outside of all the
functions, usually on top of the program. The global
variables will hold their value throughout the lifetime
of your program.
A global variable can be accessed by any function. That
is, a global variable is available for use throughout
your entire program after its declaration. Following is
the example using global and local variables:
#include <iostream.h>
// Global variable
int t;
int main ()
{
// Local variables
int a, b;
// Initialization
a = 10;
b = 20;
t = a + b;
cout << t;
return 0;
}
A program can have same name for local and global
variables but value of local variable inside a function
will take preference. For example:
#include <iostream.h>
// Global variable:
int t = 20;
int main ()
{
// Local variable with same name as Global variable
int t = 120;
cout << t;
return 0;
}
Page 17 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
1.signed
2.unsigned
3.short
4.long
Int, char, float, double data types can be preceded
with these modifiers to alter the meaning of the base
type to fit various situations properly. Every data
type has a limit of the larges and smallest value that
it can store known as the range. An integer (usually 2
bytes long) can store any value ranging from -32768 to
32767.
Data Type modifiers usually alter the upper and lower
limit of a data type. Unsigned modifier makes a
variable only to store positive values. For Example- if
a data type has a range from a to a then unsigned
variable of that type has a range from 0 to 2a.
Preceding any data type with signed is optional because
every data type is signed by default. Short integers
are 2 bytes long and long integers are 4 bytes long.
Page 18 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 19 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 20 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
int main()
{
int a = -10;
if ( a > 0 )
{
{
cout << "a is a negative or zero";
}
return 0;
}
else-if construct
(else-if ladder)
if ( condition-1 )
{
statement; // condition-1 is true
}
else if ( condition-2 )
{
statement; // condition-2 is true
}
else if ( condition-3 )
Page 21 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
statement; // condition-3 is true
}
else
{
// default case:
statement; // all above conditions were false
}
else-if ladder example
#include <iostream.h>
int main()
{
int a = -10;
if ( a > 0 )
{
cout << "a is a positive integer";
}
else if ( a < 0 )
{
cout << "a is negative";
}
else
{
cout << "a is zero";
}
return 0;
}
Switch statement
The switch statement provides a alternative to the if
when dealing with a multi-way branch. Suppose we have
some integer value called test and want to do different
operations depending on whether it has the value 1, 5
or any other value, then the switch statement could be
employed:-
switch ( test expression ) {
case 1 :
Page 22 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 23 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
switch ( ans )
{
case 'y':
cout<<"Your Ans is True";
break;
case 'n':
cout<<"Your Ans is False";
break;
default:
cout << "Wrong Input\n";
return 0;
}
Output :if user press 'y' than
it will display "Your Ans is true"
Page 24 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
switch(a) {
case 10:
cout << "This is part of outer switch" << endl;
switch(b) {
case 20:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
Output:
This is part of outer switch
This is part of inner switch
Exact value of a is : 10
Exact value of b is : 20
Page 25 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Loops in C++
Loops have a purpose to repeat a statement a certain
number of times or while a condition is fulfilled.
Loops in C++ are mainly of three types :-
'while' loop
'do while' loop
'for' loop
The while loop
while (expression)
{ statement(s) };
and its functionality is simply to repeat statement
while the condition set in expression is true.For
example, we are going to make a program to countdown
using a while-loop:
// custom countdown using while
#include <iostream.h>
int main ()
{
int n;
Page 26 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 27 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 28 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 29 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 30 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Syntax:
The syntax for a nested for loop statement in C++ is as
follows:
for ( initialisation; condition; increment )
{
for ( initialisation; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C++ is
as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C+
+ is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
Page 31 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
int main ()
{
int i, j;
for(i=2; i<50; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j))
break; //if not prime
if(j > (i/j))
cout << i << " is prime\n";
}
return 0;
}
Page 32 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Mathematical Functions
math.h
abs (), pow (), sgrt (),sin (), cos (), abs ()
Other Functions
stdlib.h
randomize (), random (),itoa (), atoi ()
Using Library Functions
Page 33 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
o 1 2 3 4 5 6 7 8 9
Return Value
The function returns nonzero if c is alphanumeric
otherwise this will return zero which will be
equivalent to false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( isalnum( '#' ) )
{
cout<< "Character # is not alphanumeric\n" ;
}
if( isalnum( 'A' ) )
{
cout<< "Character A is alphanumeric\n" ;
}
return 0;
}
It will produce following result:
Character A is alphanumeric
int isalpha(int c);
Description:
The function returns nonzero if c is any of:
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Return Value
The function returns nonzero if c is just alpha
otherwise this will return zero which will be
equivalent to false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( isalpha( '1' ) )
Page 34 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
cout<< "Character 1 is not alpha\n" ;
}
if( isalpha( 'A' ) )
{
cout<< "Character A is alpha\n";
}
return 0;
}
It will produce following result:
Character A is alpha
int isdigit(int c);
Description:
The function returns nonzero if c is any of:
0 1 2 3 4 5 6 7 8 9
Return Value
The function returns nonzero if c is a digit otherwise
this will return zero which will be equivalent to
false.
Example
#include <iostream.h>
#include<ctype.h>
int main() {
if( isdigit( '1' ) )
{
cout<< "Character 1 is a digit\n" ;
}
if( isdigit( 'A' ) )
{
cout<< "Character A is digit\n" ;
}
return 0;
}
It will produce following result:
Character 1 is a digit
int islower(int c);
Description:
Page 35 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 36 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Example
#include <iostream.h>
#include<ctype.h>
int main() {
cout<< "Upper case of t is \n"<<toupper('t');
return 0;
}
It will produce following result:
Upper case of t is T
Page 37 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 38 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <string.h>
#include <iostream.h>
int main()
{
char src[20];
char dest[20];
strcpy(src, "Ayan");
strcpy(dest, "Sharma");
cout<<"Concatenated String = \n"<<strcat(src,dest);
return 0;
}
It will produce following result:
Concatenated String = AyanSharma
int strlen(char *src );
Description:
The strlen function calculates the length, in bytes, of
src. This calculation does not include the null
terminating character.
Example
#include <string.h>
#include <iostream.h>
int main()
{
char src[20];
strcpy(src, "Ambari");
cout<<"Length of string :"<<src<< " is "<<strlen(src );
return 0;
}
It will proiduce following result:
Page 39 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 40 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 41 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
int main(void)
{
char *s = "AYAN";
cout<<"After strrev(): "<<strrev(s);
return 0;
}
Output
NAYA
C++ Library Functions Header File :math.h
Declaration :- abs(int n);
Description:
abs is not a function but is a macro and is used for
calculating absolute value of a number.
#include <iostream.h>
#include <math.h>
int main()
{
int n, result;
cout<<"Enter an integer to calculate it's absolute
value\n";
cin>>n;
result = abs(n);
cout<<"Absolute value of "<<n<< "is "<<result;
return 0;
}
Output
Enter an integer to calculate it's absolute value -5
Absolute value of -5 is 5
Declaration :- double pow(double, double);
Description:
Page 42 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
#include <math.h>
int main()
{
int m,n, result;
cout<<"Enter two integers to calculate power\n";
cin>>m>>n;
result = pow(m,n);
cout<<"Result is "<<result;
return 0;
}
Output
Enter two integers to calculate power 3 4
Result is 81
Declaration :- double sqrt(double);
Description:
sqrt function returns square root of a number.
#include <iostream.h>
#include <math.h>
int main()
{
double n, result;
cout<<"Enter an integer to calculate it's square
root \n";
cin>>n;
result = sqrt(n);
Page 43 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cout<<"Result is "<<result;
return 0;
}
Output
Enter an integer to calculate it's square root 9
Result is 3
Declaration: double sin(double);
Description:
Sin function returns sine of an angle(in radian).
#include <iostream.h>
#include <math.h>
int main()
{
double result, x = 0.5;
result = sin(x);
cout<<"sin(x ) of 0.5 is "<<result;
return 0;
}
Output
sin(x) of 0.5 is 0.479426
Declaration: double cos(double);
Description:
Cos function returns cosine of an angle(in radian).
1 radian = 57.2958(approximately).
#include <iostream.h>
#include <math.h>
int main()
Page 44 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
double result, x = 0.5;
result = cos(x);
cout<<"cos(x) of 0.5 is "<<result;
return 0;
}
Output
cos(x) of 0.5 is 0.877583
C++ Library Functions Header File :stdlib.h
Declaration: int random(int n);
Description:
random return a random number between 0 to (n-1)
#include <stdlib.h>
#include <iostream.h>
#include <time.h>
/* prints a random number in the range 0 to 9 */
int main(void)
{
randomize();
cout<<"Random number from 0-9 range:\n"<<random(10);
return 0;
}
Declaration: void randomize(void);
Description:
randomize initializes random number generator
#include <stdlib.h>
#include <iostream.h>
#include <time.h>
Page 45 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 46 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
n = atoi(str);
cout<<"string = "<<str<<"integer ="<<n;
return 0;
}
Output
string 112 integer 112
Page 47 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 48 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 49 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
void Display(void) // Function Definition
{
cout <<"Hello World";
}
void main()
{
cout << "Inside main function";
Display(); // call to Display Function
}
Function Prototype
A function prototype supplies information about the
return type of a function and the types of its
parameter. The function prototype is merely a copy of
the function definition with body. Thus the function
prototype for the function Display is:
void Display(void);
Example of Function Prototype:
#include <iostream.h>
void Display(void); // function prototype
int main()
{
cout << "Inside Main Function";
Display();
return 0;
}
Page 50 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 51 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
cout << endl<<" a = "<<a <<endl <<" b = "<<b;
}
Functions that return values
One of the most useful forms of function is one that
returns a value . In this case the return type given in
the function prototype is that of the value to be
returned.
Page 52 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
SUM=CalSum(a,b);
//Here the value return by CalSum will be assigned to
SUM
cout<<endl<<"The Sum of a and b is = "<<SUM;
return 0;
}
int CalSum(int a ,int b)
{
int c; //local variable
c = a+b;
return c; // return statement
Page 53 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
Output
Inside Main- Enter Two Values
2 3
The Sum of a and b is = 5
Default Arguments
C++ allows a function to assign default values to
parameters. The default value is assigned when no
argument corresponding to that parameter is specified
in the call to that function. For Example :
int calSum(int a = 10, int b = 20)
{
return a+b;
}
In the above code segment, if the CalSum() function is
invoked without arguments, then the default values of
10 and 20 are assigned to a and b respectively. If
values are passed to the function, then corresponding
values are assigned to a and b.
Example of Default Arguments
//This program illustrates the use of default arguments
#include<iostream.h>
void CalSum(int a = 10, int b = 20)
{
cout<<"Sum is "<<a+b<<endl;
}
void main()
{
int a = 2, b = 4;
CalSum(); // Without Arguments Call will use Default
Arguments
CalSum(a,b); // With Arguments Call will not use
Default Arguments
Page 54 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
Output:
Sum is 30
Sum is 6
Use of One default arguments
//This program illustrates the use of ONE default
arguments
#include<iostream.h>
void CalSum(int a , int b = 20)
{
cout<<"Sum is "<<a+b<<endl;
}
void main()
{
int a = 2, b = 4;
CalSum(a); // With one Argument Call will use ONE
Default Argument
CalSum(a,b); // With Arguments Call will not use
Default Arguments
}
Output:
Sum is 22
Sum is 6
Some points to remember when using default arguments:
Default arguments must be the last argument(s)(Right to
Left). Therefore, the following code is illegal:
int CalSum(int a=20 ,int b,int c); // Wrong
int CalSum(int a ,int b=20 , int c); // Wrong
int CalSum(int a =10 ,int b=20 , int c); // Wrong
Right method to specify Default Arguments is
int CalSum(int a ,int b=10 , int c=20); // Right
int CalSum(int a =5 ,int b=10 , int c=20); // Right
Page 55 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 56 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 57 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
*m=20
*n=10;
After interchanging the values
a=20
b=10
Page 58 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Array
Page 59 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 60 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
int main()
{
double weight[] = {20.2,24.5,34.7};
cout << "2nd member = " << weight[1] << endl;
cout << "3rd member = " << weight[2] << endl;
return 0;
}
This would produce:
2nd member = 24.5
3rd member = 34.7
The Size of an Array
Page 61 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 62 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 63 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int sum=0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Sum
for(i=0;i<N;i++)
sum=sum+a1[i];
cout<<endl<<"Sum of all The elements is "<<sum;
return 0;
}
Product of all the Elements of an Array
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int pro=1;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Product
Page 64 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
for(i=0;i<N;i++)
pro=pro*a1[i];
cout<<endl<<"Product of all The elements is "<<pro;
return 0;
}
Average of all the Elements of an Array
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int sum=0;float avg=0.0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Average
for(i=0;i<N;i++)
sum=sum+a1[i];
avg=(float)sum/N;
cout<<endl<<"Average of all The elements is "<<avg;
return 0;
}
Maximum Element of an Array
#include <iostream.h>
#define N 3
int main()
Page 65 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
int a1[N];
int max=0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Max element
for(i=0;i<N;i++)
if(max<a1[i])
max=a1[i];
cout<<endl<<"Max elements is "<<max;
cin>>i;
return 0;
}
Minimum Element of an Array
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int min=9999;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
cin>>a1[i];
// Now we will find Min element
for(i=0;i<N;i++)
if(min>a1[i])
min=a1[i];;
cout<<endl<<"Max elements is "<<min;
return 0;
}
Page 66 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Linear Search
Another type of operation regularly performed on an
array consists of looking for a value held by one of
its members. For example, you can try to know if one of
the members holds a particular value you are looking
for. Here is an example:
#include <iostream.h>
int main()
{
// Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find;
int i, m = 8;
cout << "Enter a number to search: ";
cin >> find;
for (i = 0;i<m; ++i)
if(numbers[i]==find)
cout << find << "Found" << endl;
// Find whether the number typed is a member of the
array
if (i == m)
cout << find << " Not Found"<< endl;
return 0;
}
Page 67 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include<iostream.h>
#include<string.h>
void Reverse(char str[]);
int main(){
char str[100];
cout<<"Enter a string to reverse: ";
gets(str);
Reverse(str);
cout<<"String after reversing: ";
puts(str);
return 0;
}
void Reverse(char str[]){
int i,j;
Page 68 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
char temp[100];
for(i=strlen(str),j=0;i!=0;--i,++j){
temp[j]=str[i];
}
temp[j]='\0';
strcpy(str,temp);
}
Page 69 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Two-Dimensional Arrays
A 2-dimensional array is an array of arrays. In other
words, it is an array where each member of the array is
also an array.
Page 71 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
C++ also allows you to include each row in its own pair
of curly brackets. You must separate each row from the
next with a comma. Here is an example:
int items[2][3] = {
{ 1,2,3},{4,5,6}
};
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M],s;
int i,j;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
// Now we will find sum of diagonal elements
Page 72 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
if(i==j)
s=s+ a1[i][j];
}
cout<<endl<<"Sum of diagonal elements of a1 and a2
is "<<s;
return 0;
}
Finding Maximum element in MXN Array
// Max Element in a two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M];
int max=0;
int i,j;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
// Now we will find Max element
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
if(max<a1[i][j])
max=a1[i][j];
}
Page 73 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 74 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 75 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 76 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 77 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 78 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 79 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
return 0;
}
Enter Roll No: 11
Enter Name : Sample
Roll No = 11
Name = Sample
Passing structure variable to a function
(call by-value)
#include <iostream.h>
struct temp
{
int a, b;
} ;
Page 80 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
struct temp
{
int a, b;
} ;
void StructPass(temp *var);
int main(void)
{
temp arg;
// Here the name of ".(dot)" is Direct Member
Selector Operator
arg.a = 123;
arg.b = 321;
StructPass(&arg); // Passing structure variable
address
cout<<"\nInside Main ";
cout<<"\n arg.a = "<<arg.a;
Page 81 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 82 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
};
int main()
{
student data[3];// Array of 3 Structure variables
int i = 0;
cout<<endl<<"Enter age,roll no and name of three
students:";
for(i = 0; i<3 ;i++)
{
cin>>data[i].age;
cin>>data[i].roll_no;
cin>>data[i].name;
}
cout<<endl<<"Your have Entered:";
for(i = 0; i<3 ;i++)
{
cout<<data[i].age<<"\t";
cout<<data[i].roll_no<<"\t";
cout<<data[i].name<<endl;
}
return 0;
}
Passing Array of Structure to a Function
#include <iostream.h>
struct student
{
int age;
int roll_no;
char name[20];
};
int main()
{
void PassArrayStruct(student data[]);
student data[3];// Array of 3 Structure variables
int i = 0;
cout<<endl<<"Enter age,roll no and name of three
students:";
for(i = 0; i<3 ;i++)
{
cin>>data[i].age;
cin>>data[i].roll_no;
cin>>data[i].name;
}
Page 83 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
}
typedef keyword in C++
In C++, we can declare a variable using one of the
built-in data types. In the same way, we can declare an
array or a pointer. If we want to use the same data
type for many declarations of variables, we can
customize its name. The typedef keyword allows us to
create an alias for a data type. The syntax to use
typedef is:
typedef DataType AliasName;
The typedef keyword is required. The typedef keyword
can be followed by any C++ built-in data type, like
int, char, double etc. On the right side of the data
type, type the name(alias) that will be used to
represent the data type. Here is the example:
#include <iostream.h>
typedef short SmallInt;
typedef unsigned long Lint;
int main()
{ SmallInt tdef = 123;
Lint LI = 321;
Page 84 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 85 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
int x=5, y;
y= getmax(x,2);
cout << y << endl;
cout << getmax(7,x) << endl;
return 0;
}
Output
7
Because preprocessor replacements happen before any C++
syntax check, macro definitions can be a tricky feature
so be careful !!!.
Page 86 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 87 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
protected:
int n // n is only accessible within the class and
// to the subclass of Kangra
public:
int p; //p is accessible inside and outside the class
Kangra() // constructor
{ }
};
Page 88 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
};
Page 89 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
int a ,b;
void show ()
{
cout<<a<<b;
}
};
class B: private A //Use of Inheritance
{
int c;
void dispdata ()
{
cout<<c;
}
};
Concept of Class and Object in C++
Class -A class is a blue print for creating objects.
Definition:
A class is a group of objects which show a common
property.
OR
A class is a collection of objects of similar type.Once
a class is defined, any number of objects can be
created which belong to that class.For example Define
a class to print the values of two numbers.
Class HelloWorld
{
int one;
int two;
public:
Page 90 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
void setdata()
{
cout<<enter two numbers;
cin>>one>>two;
}
void putdata()
{
cout<<one<<endl<<two;
}
};
int main()
{
HelloWrold obj;
Obj.setdata();
Obj.putdata();
return 0;
}
Classes are generally declared using the keyword class,
with the following format:
class class_name
{
access_specifier_1:
member;
access_specifier_2:
member;
...
};
Page 91 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
};
Concrete class It is a derived class that implement
all the missing functionality of a abstract class.
The following is an example of an concrete class:
Page 92 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
/* do stuff of f() */
}
};
Page 93 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Member Functions
};
Data members are data type properties that describe the
characteristics of a class. There may be zero or more
data members of any type in a class.
Member functions are the set of operations that may be
applied to the objects of that class. It is the
interface between the class members and object. It is
always single it doesnt make any copy. There may be
zero or more member functions in a class.
Program Access Level that control access to members
from within the program. These access levels are
private, protected or public. Depending upon the access
level of a class member , access to it is allowed or
denied.
Class name that serves as a type specifier for the
class using which object of this class type can be
created.
For Example
#include<iostream.h>
#include<conio.h>
class sum // class
{
int a,b,s; //data members
public:
sum() // constructor
{
Page 94 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
a=10;
b=20;
}
void show() //member function
{
s=a+b;
cout<<sum of numbers is<<s<<endl;
}
};
int main()
{
sum obj; //object of class
obj.show();
return 0;
}
public, protected and private are three access
specifiers in C++.
Page 95 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
public:
Data Members/Member Functions
};
The class body contains the declaration of members
(data and functions). There are generally three types
of member in a class: private, protected and public
which are grouped under three sections namely private:
protected: and public:.
The private member can be accessed only from within the
class and public members can be accessed from outside
the class also. If no access specifier (public,
protected or private) is specified then by default,
members are private.
Private variables can only be accessed by the class
Class A
{
private:
int x;
public:
void SetX(int n) { x = n; } //this is ok
};
int main()
{
A aobj;
aobj.x = 0; //error because x is private and not
accessible outside the class
}
Protected is similar to private but can also be
accessed by inherited classes
class A
{
protected:
int x;
public:
void SetX(int n) { x = n; } // this is ok
};
class B : public A
{
Page 96 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
public:
void ShowX() { cout << x << "\n"; }
// this is ok as x is protected member
};
Public member can be accessed from outside the class
Class A
{
public:
int x
void SetX(int n) { x = n; } // <<< this is ok
};
int main()
{
A aobj;
aobj.x = 0;
// Ok because x is public accessible outside the class
}
Page 97 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 98 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Page 99 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
return a+b;
}
};
int main(void)
{
Kangra obj;
cout<<obj.add();
return 0;
}
Example 2: Explicit constructor function to initialize
data members to values passed as arguments
#include<iostream.h>
class Kangra
{
private:
int a;
int b;
public:
Kangra(int i, int j)//Explicit Constructor with
arguments
{
a=i;
b=j;
}
int add(void)
{
return a+b;
}
};
int main()
{
myclass obj(10,20); //This Can be written as Kangra obj
obj=Kangra(10,20);
cout<<obj.add();
}
Default/Implicit constructor: - These constructors are
inserted automatically by the Compiler into class
declarations that do not have any implicit constructor.
Example:
class Ayan
{
Ayan() { } //Default/Implicit Constructor
};
Copy Constructor
A copy constructor is a special constructor that
creates a new object from an existing object. If we do
not define a copy constructor, the compiler will
generate one for us that performs a shallow copy
(copies only a pointer so that the two pointers refer
to the same object) of the existing object's member
variables. So, if our object allocates any resources,
we most likely need a copy constructor so that we can
perform a deep copy (copies what a pointer points to so
that the two pointers now refer to distinct objects).
// Shallow Copy Example
char *ch = new char('Z');
char *cp = ch; // copy the pointer ch
*ch = 'X'; // change the value of the char pointed to
by *ch
// Deep Copy Example
int *p = new int(99);
int *q = new int(*p);
// Allocate a new int before copying the value pointed
to by p
*p = 100; // change the value of the int pointed to by
p
Example of Default Copy Constructor that compiler
provides and its problem:
#include <iostream.h>
#include<string.h>
class Kangra
{
int *temp;
public:
Kangra(int i)
{
cout << " Constructor";
temp=new int();
*temp = i;
}
~Kangra()
{
cout << "Destructor";
delete temp;
}
};
int main()
{
Kangra kg(150); // First Object Created Invoke our
Constructor
Kangra kg1(kg); // Here is the Problem;
/* When Second Object will be Created It will
not Invoke our Constructor. It will invoke Default Copy
Constructor */
cout << "Main";
return 0;
}
Let's look at the output:
Constructor
Main
Destructor
Destructor
Null Pointer Assignment
Destructor does delete. The problem is it is trying to
delete a pointer we haven't allocated. When default
copy constructor is called (Kangra kg1(kg)), it does
not allocate anything.
Constructor
Copy Constructor
Main
Destructor
Destructor
This should be our choice.
Summary
The copy constructor gets called in the following
cases:
An object is passed to a method by value or returned by
value.
An object is initialized using the syntax, MyClass a =
b.
An object is thrown or caught in an exception.
Constructor with Default Argument:
#include <iostream.h>
#include<string.h>
class Kangra
{
int temp;
public:
Kangra(int i=10) //Constructor with Default Argument 10
{
cout << " Inside Constructor with Default Argument";
temp=i;
cout<<"Temp = "<<temp;
}
};
int main()
{
Kangra kg; // Object Created without argument. This
Inheritance in C++
A key feature of C++ is inheritance. Inheritance allows
to create classes which are derived from other classes,
so that they automatically include some of its
"parent's" members, plus its own. For example, If we
declare a class FRUIT which describes all the common
attribute of fruits such as their taste , colour etc.
From this FRUIT class we cab drive two other classes
Apple and Orange.
{ /*...*/ };
}
};
class Apple: public Fruits
{
public:
void TasteColor()
{
strcpy(taste,"sweet");
strcpy(color,"red");
void Display()
{
cout<<"Apple's Taste = "<<taste<<endl;
cout<<"Apple's Colour ="<<color<<endl;
}
};
int main ()
{
Orange org;
Apple app;
org.TasteColor();
app.TasteColor();
org.Display();
app.Display();
return 0;
}
Output:
Members of derived
Yes Yes No
classes
Non members
Yes No No
Examples
Single Inheritance
When a class is inherited from one base class,this type
of Inheritance is called Single Inheritance Example
// Inheritance Example
#include <iostream.h>
#include<string.h>
class Fruits
{
public:
char taste[20],color[20];
};
class Orange: public Fruits // Single Inheritance
{
public:
void TasteColor()
{
strcpy(taste,"sweet-sour");
strcpy(color,"orange");
}
void Display()
{
cout<<"Orange Taste = "<<taste<<endl;
cout<<"Orange Colour ="<<color<<endl;
}
};
int main ()
{
Orange org;
org.TasteColor();
org.Display();
return 0;
}
Output:
Orange's Taste = sweet-sour
Oange's Colour =orange
Multiple Inheritances:
A C++ class can inherit members from more than one
class and here is the syntax:
class derived-class: access base_A, access base_B....
Where access is one of public, protected, or private
and would be given for every base class and they will
be separated by comma as shown above. Let us try the
following example:
#include<iostream.h>
#include<conio.h>
class A
{
protected:
int m;
};
class B
{
protected:
int o;
};
class C: public A, public B //Use of Multiple
Inheritance
{
public:
void set_m_o()
{
m=5; // m is Inherited from class A
o=6; // o is Inherited from class B
}
void display() // Not Inherited from any class
{
cout<<"m="<<m<<endl;
cout<<"o="<<o<<endl;
cout<<"m*o="<<m*o<<endl;
}
};
int main()
{
A aobj;
B bonj;
C cobj;
cobj.set_m_o();
cobj.display();
return 0;
}
Output:
m=5
o=6
m*o=30
;
}
Output:
A()
{
cout << "A's no parameter constructor\n";
}
A(int a)
{
File
while(!fin.eof())
{
fin>>words;
count++;
}
cout<<"Number of words in file is "<<count;
fin.close();
getch();
return 0;
}
Program to count number of lines
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char line[80]; int count=0;
while(!fin.eof())
{
fin.getline(line,80);
count++;
}
cout<<"Number of lines in file is "<<count;
fin.close();
getch();
return 0;
}
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
count++;
}
cout<<"Number of vowels in file are "<<count;
fin.close();
getch();
return 0;
}
Program to count number of digits
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);
if(isdigit(ch))
count++;
}
cout<<"Number of digits in file are "<<count;
fin.close();
getch();
return 0;
}
Program to count number of line starting with alphabet
A.
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("input.txt");
char line[80]; int count=0;
while(!fin.eof())
{
fin.getline(line,80);
if(line[0]=='A')
count++;
}
cout<<"Number of lines starting with A are
"<<count;
fin.close();
getch();
return 0;
}
Program to copy contents of one file to another file.
#include<fstream.h>
int main()
{
ifstream fin;
fin.open("source.txt");
ofstream fout;
fout.open("destination.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();
fout.close();
return 0;
}
Binary File Handling Functions
ifstream::read
ofstream::write
Parameters
t
Pointer to a block data with the content to be written.
n
Integer value of type streamsize representing the size
in characters of the block of data to write.
Return Value
Parameters
pos
The new position in the stream buffer. This parameter
is an integral value.
off
Integral value representing the offset to be applied
relative to an absolute position specified in the dir
parameter.
dir
Seeking direction. It is an object of type ios::seekdir
that specifies an absolute position from where the
offset parameter off is applied. It can take any of the
following member constant values:
Return Value
The function returns *this.
Example
outfile.write ("Sanju",5);
outfile.close();
return 0;
}
In this example, seekp is used to move the put pointer
back to a position 4 characters before the end of the
first output operation. The final content of the file
shall be:
My Name is Sanju
ifstream::seekg()
Parameters
pos
The new position in the stream buffer. This parameter
is an integral value of type streampos.
off
Integral value representing the offset to be applied
relative to an absolute position specified in the dir
parameter.
dir
Seeking direction. It is an object of type ios::seekdir
that specifies an absolute position from where the
offset parameter off is applied. It can take any of the
following member constant values:
ios::beg beginning of the stream buffer
ios::cur current position in the stream buffer
ios::end end of the stream buffer
Return Value
The function returns *this.
Example
#include <fstream.h>
int main () {
int length;
char buffer[100];
ifstream is;
is.open ("test.txt", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// read data as a block:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
return 0;
}
ofstream ::tellp ( );
int tellp ( );
Get position of put pointer
Returns the absolute position of the put pointer.
The put pointer determines the location in the output
sequence where the next output operation is going to
take place.
Return Value
An integral value of type int with the number of
characters between the beginning of the output sequence
and the current position.
#include <iostream.h>
#include <fstream.h>
int main () {
int length;
char buffer[50];
ifstream is;
is.open ("test.txt", ios::binary );
is.seekg (0, ios::end);
#include<iostream.h>
#include<string.h>
class student
{
int rollno;
char name[20];
public:
void getdata()
{
cout<<"\nEnter The Roll no. ";
cin>>rollno;
cout<<"\n\nEnter The Name of The Student ";
gets(name);
}
void showdata()
{
cout<<"\nRoll no. : "<<rollno;
cout<<"\nStudent Name : ";
puts(name);
}
int returnrollno()
{
return rollno;
}
};
This function will write on Binary File
void write_data()
{
student obj;
ofstream fout;
fout.open("student.dat",ios::binary|ios::app);
obj.getdata();
fout.write((char*)&obj,sizeof(obj));
fout.close();
}
void deleterecord(int n)
{
student obj;
ifstream fin;
fp1.open("student.dat",ios::binary);
ofstream fout;
fout.open("Temp.dat",ios::out|ios::binary);
while(fin.read((char*)&obj,sizeof(obj)))
{
if(obj.returnrollno()!=n)
fout.write((char*)&obj,sizeof(obj));
}
fin.close();
fout.close();
remove("student.dat");
rename("Temp.dat","student.dat");
}
if(obj.returnrollno()==n)
{
obj.showdata();
cout<<"\nEnter The New data of student";
obj.getdata();
int pos=-1*sizeof(obj);
finout.seekp(pos,ios::cur);
finout.write((char*)&obj,sizeof(obj));
found=1;
}
}
finout.close();
}
Pointer
A pointer is a variable which contains the address in
memory of another variable. We can have a pointer to
any variable type.
The & operator gives the address of the variable
pointed by the pointer. The indirection or dereference
operator * gives the contents of the variable pointed
to by a pointer.
To declare a pointer to a variable do:
Data-type *pointer_variable_name;
NOTE: We must associate a pointer to a particular type:
You can't assign the address of a short int to a long
int, for instance.
Consider the effect of the following code:
int x = 1, y = 2;
int *ip;
ip = &x;
y = *ip;
x = ip;
*ip = 3;
Assume that the variable x resides at memory location
100, y at 200 and ip at 1000.
int x;
ip = &x;
*ip = 100; // Now the value of x is 100
We can do integer arithmetic on a pointer:
int *ip;
int i=10;
ip= &i;
*ip = *ip + 5;
++*ip;
(*ip)++;
// The value of i and *ip would be 17
The reason we associate a pointer to a data type is so
that it knows how many bytes the data is stored in.
When we increment a pointer we increase the pointer by
one block memory.
So for a character pointer ++ch_ptr adds 1 byte to the
address.For an integer pointer ++ip_ptr adds 2 bytes to
the address. For a float pointer ++flp_ptr adds 4 bytes
to the address.
Consider a float variable (fl) and a pointer to a float
(flp)
int main ()
{
int *intp = NULL; // Pointer initialized with null
intp = new int; // Request memory for the variable
}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=10
b=20
Note: No change to the values of a and b inside the
calling function .Because when we pass values to the
function only the copies of those values get passed not
the original data value .Any change made inside the
called function to these data value is not reflected to
the calling function. That is why we call it call by
value.
swap(a, b) WON'T WORK.
Pointers provide the solution: Pass the address of the
variables to the functions and access address of
function.
Thus our function call in our program would look like
this:
swap(&a, &b)
// Call by Reference Example
#include<iostream.h>
int main()
{
void swap(int *m,int *m);
int a=10 ,b=20;
swap(&a,&b); // Call by reference
cout<<"After interchanging the values ";
cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int *m ,int *n)
{
int a;
a=*m;
*m=*n;
*n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" *m = "<<m<<endl<<" *n= "<<n;
}
output:
Inside swap function the values are
*m=20
*n=10;
After interchanging the values
a=20
b=10
}
void swap(int &m ,int &n)// use of reference variable
{
int a;
a=m;
m=n;
n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" m = "<<m<<endl<<" n= "<<n;
}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=20
b=10
Pointers and Arrays
Pointers and arrays are very closely linked.
Consider the following:
int a[10], x;
int *pa;
pa = &a[0]; /* pa pointer to address of a[0] */
x = *pa;
/* x = contents of pa (a[0] in this case) */
pa = &a[0]
and
a[i] can be written as *(a + i).
We also express pointer addressing like this:
pa[i] = *(pa + i).
However pointers and arrays are different:
A pointer is a variable. We can do
pa = a;
pa++ ;
An Array is not a variable.
a = pa and a++ ARE ILLEGAL.
We can now understand how arrays are passed to
functions. When an array is passed to a function what
is actually passed is its initial elements location in
memory.
So:
int a[]={1,2};
void arpass(int a[]);
arpass(a) ;
/* Passing array in a function. Here only name of the
array is required, it is same as arpass(&a[0]); */
Example of passing array in a function
#include <iostream.h>
int main ()
{
int a[]={1,2}; // Declare simple int arry
void arpass(int a[]); // Function declaration for
accepting array as an argument
return 0;
}
void arpass(int a[]) // Function Definition
{
for(int i=0;i<2;i++)
cout<<a[i];
}
Pointer to an One Dimensional Array
#include <iostream.h>
int main ()
{
int i,a[5];
int *p;
p=a; // same as p = &a[0]
cout<<endl<<"Enter 5 Numbers ";
for(i=0;i<5;i++)
cin>>p[i]; // same as a[i]
//Other form of the above statement is cin>>*(p+i);
for(i=0;i<5;i++)
cout<<p[i]<<endl; // same as a[i]
// Other form of the above statement is cout<<*(p+i);
return 0;
}
Function Returning a Pointer
If a function return type is a Pointer of any data type
then we say that this function will return Pointer.
cin>>a;
p=func(a); // P will point to the pointer
returned by *func()
cout<<" *p = "<<*p;
return 0;
}
int *func(int a)
{
int *t;
t =&a;
return t; // This statement will return a
Pointer
}
Arrays of Pointers
{
cout << "Value of arrp[" << t << "] = ";
cout << *arrp[i] << endl;
}
return 0;
}
When the above code is compiled and executed, it
produces following result:
Value of arrp[0] = 10
Value of arrp[1] = 20
Array
int main()
{
double weight[] = {20.2,24.5,34.7};
cout << "2nd member = " << weight[1] << endl;
cout << "3rd member = " << weight[2] << endl;
return 0;
}
This would produce:
2nd member = 24.5
3rd member = 34.7
The Size of an Array
#include <iostream.h>
int main()
{
const int SIZE = 5;
int weight[SIZE] = {20,30,40,50,60};
cout << "weight 1: " << weight[0] << endl;
cout << "weight 2: " << weight[1] << endl;
cout << "weight 3: " << weight[2] << endl;
cout << "weight 4: " << weight[3] << endl;
cout << "weight 5: " << weight[4] << endl;
return 0;
}
We knew the dimensions of the arrays we have used so
far, because we could count the number of members of
the array. Imagine you declare a large array, possibly
made of 50 or 100 members, you wouldn't start counting
the number of members. C++ provides the sizeof operator
that can be used to get the dimension of an array. The
syntax you would use is:
sizeof(NameofArray)
If we declare an array as follows:
int number[] = {1,2,3,4,5};
Instead of counting the number of members of this array
we can use the sizeof operator as follows:
int NumberOfElements = sizeof(Number)/sizeof(int);
Accessing Array Members
int items[5];
int main()
{
int array[100], position, c, n;
cout<<"Enter number of elements in array\n";
cin>>n;
cin>>a1[i];
cout<<"Enter Elements of Second Array:";
for(i=0;i<N;i++)
cin>>a2[i];
// Now we will Concatenate These two Arrays
for(i=0;i<N;i++)
a3[i]=a1[i];
k=i;
for(i=0;i<N;i++)
a3[k++]=a2[i];
cout<<"After Concatenation The third Array Contain:";
for(i=0;i<N+N;i++)
cout<<a3[i]<<endl;
return 0;
}
Merging of Two sorted Arrays
#include <iostream.h>
cout<<"Sorted array:\n";
for (c = 0; c < m + n; c++)
cout<<sorted[c];
return 0;
}
void merge(int a[], int m, int b[], int n, int
sorted[])
{
int i, j, k;
j = k = 0;
for (i = 0; i < m + n;)
{
if (j < m && k < n)
{
if (a[j] < b[k])
{
sorted[i] = a[j];
j++;
}
else
{
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m)
{
for (; i < m + n;)
{
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;)
{
sorted[i] = a[j];
j++;
i++;
}
}
}
}
Linear Search
Another type of operation regularly performed on an
array consists of looking for a value held by one of
its members. For example, you can try to know if one of
the members holds a particular value you are looking
for. Here is an example:
#include <iostream.h>
int main()
{
// Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find;
int i, m = 8;
cout << "Enter a number to search: ";
cin >> find;
for (i = 0;i < m; ++i)
if(numbers[i]== find)
cout << find << " Found" << endl;
//Find whether the number typed is a member of the
array
if (i == m)
cout << find << " Not Found" << endl;
return 0;
}
This would produce:
Enter a number to search: 44
44 Found
Binary Search
Another type of search in an Array is Binary search.
Binary search can work only on sorted array.
#include <iostream.h>
int main()
{ // Declare the members of the array
int numbers[] = {12, 17, 23, 45, 50, 71, 80, 93};
int find;
int mid,low=0,high=7;
cout << "Enter a number to search: ";
cin >> find;
while(low<=high)
{
mid= (low+high)/2;
if( find==numbers[mid])
{
cout<<"Element Found";
break;
}
else if( find >numbers[mid])
low=mid+1;
else
high=mid-1;
}
if(low>high)
cout<<"Element not Found";
return 0;
}
This would produce:
Enter a number to search: 23
Element Found
Bubble Sort
The basic idea of Bubble sort is to compare two
adjoining values and exchanged then if are not in
proper order.
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
cout << "After Sorting The Array elements are ";
for(i=0;i<7;i++)
cout<<number[i]<<endl;
return 0;
}
This would produce:
10,20,25,36,43,52,75,89.
Selection Sort
The algorithm works as follows:
#include<iostream.h>
#define n 10
int main()
{
int a[n];
int i,j,k,temp;
int iMin;
cout<<"Enter Array Elements "<<endl;
for(k=0;k<n;k++)
cin>>a[k];
for (j = 0; j < n-1; j++)
{ /* find the min element in the unsorted a[j .. n-
1]
assume the min is the first element */
iMin = j;
// test against elements after j to find the
smallest
for ( i = j+1; i < n; i++)
{
// if this element is less, then it is the new
minimum
if (a[i] < a[iMin])
iMin = i;
}
// iMin is the index of the minimum element. Swap it
with the current position
if ( iMin != j )
{ temp=a[j];
a[j]=a[iMin];
a[iMin]=temp;
}
}
cout<<"After Selection Sort Array Elements are
"<<endl;
for(k=0;k<n;k++)
cout<<a[k]<<endl;
return 0;
}
Insertion Sort
Insertion sort is a simple sorting algorithm: a
comparison sort in which the sorted array (or list) is
built one entry at a time.
How it works:
In insertion sort,elements are entered into the array
1-by-1.
When the first element is entered, it is placed at the
1st position in the array.
When a new element is entered, it is compared to our
already entered element and is decided whether to place
before or after it in the array.
Now when the third element is entered is entered, it is
compared with the greater element of the 2 already
existing elements. If smaller, then it is swapped. If
not, then the array can be considered sorted.
If swapped, then is compared with the smaller element
of the 2 already existing elements and swapped again
with it if it is even smaller.
Example:
5 7 0 3 4 2 6 1 (0)
5 7 0 3 4 2 6 1 (0)
0 5 7 3 4 2 6 1 (2)
0 3 5 7 4 2 6 1 (2)
0 3 4 5 7 2 6 1 (2)
0 2 3 4 5 7 6 1 (4)
0 2 3 4 5 6 7 1 (1)
0 1 2 3 4 5 6 7 (6)
#include<iostream.h>
int main()
{
double arr[8],temp;
cout<<"Insertion sort Demonstration."<<endl<<endl;
for (int i=0;i<8;i++)
{
cout<<"Enter element number "<<i+1<<": ";
cin>>arr[i];
//Runs until the new number has been placed in its
correct place
#include <iostream.h>
int main()
{
void Display(char items[]);
const int NumberOfItems = 5;
char items[NumberOfItems] = {'A','B','C','D','E'};
Display(items); //The compiler only needs the name of
the array to process it
return 0;
}
Data_Type NameOfArray[ROWS][COLUMNS];
int TwoDArray[5][5];
This declarations creates 5 rows and each row contains
5 elements.
You can initialize an array the same way you would
proceed the a one-dimensional array: simply provide a
list of values in the curly brackets.
A multidimensional array is represented as an algebraic
matrix as MxN. This means that the array is made of M
rows and N columns. Total number of elements of a
multidimensional array can be calculated by multiply
the number of rows by the number of columns. Therefore
a 2x3 array contains 2*3=6 elements.
Based on this, when initializing a 2-dimensional array,
make sure you provide a number of values that is less
than or equal to the total number of elements.
Here is an example:
double age[2][3] = {12,14,16,17,18,19};
=200+4[4*11+2]
=200+4[44+2]
=200+4[46]
=200+184
=384
Column-major order as
Address(Arr[12][3] )= 200+4[25(3-1)+(12-1)]
=200+4[25*2+11]
=200+4[50+11]
=200+4[61]
=200+244
=444
Processing a 2-Dimensional Array
To process a 2D array, we should know how many columns
the array contains. We can use two for loops to process
the array. Here is an example:
#include <iostream.h>
int main()
{
// A 2-Dimensional array
int items[2][3] = {
{ 1,2,3},
{ 4,5,6}
};
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M],a2[N][M],s[N][M],d[N][M];
int sum=0,i,j;
cout<<"Enter Elelemts of First Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
cout<<"Enter Elelemts of Second Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a2[i][j];
// Mow we will find sum and difference
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
s[i][j] =a1[i][j]+a2[i][j];
d[i][j] =a1[i][j]-a2[i][j];
}
cout<<"Sum of a1 and a2 is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<s[i][j];
cout<<endl;
}
cout<<"Difference of a1 and a2 is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<d[i][j];
cout<<endl;
}
return 0;
}
Interchanging ROWS and COLUMN of a N X M Arrays
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M],a2[N][M];
int i,j;
cout<<"Enter Elements Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
// Mow we will Interchange row and columns
elements
for(i=0;i<N;i++)
for(j=0;j<M;j++)
a2[j][i] =a1[i][j];
cout<<"Original Array is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<a1[i][j];
cout<<endl;
}
cout<<"After interchanging row and columns ";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<a2[i][j];
cout<<endl;
}
return 0;
}
2D Array and String
Because strings are in fact sequences of characters, we
can represent them also as plain arrays of char
elements.
Stack
Stack is one of the important data structures that
every computer programmer should be aware of. It
follows the simple LIFO (Last In First Out) principle.
Implementation of stack can be done in many ways. One
of the simplest way is using Arrays. Here an array is
initialized to a maximum value first, lets call it
capacity. As and when we push elements onto the array,
its size will get increased. As and when we pop
elements from the array, its size will get decreased
push(num);
cout<<"Enter the data to stack.";// Use to check stack
full condition
cin>>num;
push(num);
cout<<"Enter the data to stack.";
cin>>num;
push(num);
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop(); // use to check stack empty condition
return 0;
}
void push(int y)
{
if(top==MAXSIZE)
{
cout<<endl<<"STACK FULL";
return;
}
else
{
top++;
stack[top]=y;
}
}
int pop()
{
int a;
top--;
if(top<0)
{
cout<<endl<<"STACK EMPTY";
return 0;
}
else
{
a=stack[top];
}
return a;
}
}
//THIS FUNCTION INSERT NODE IN THE TOP OF THE STACK
void push(int y)
{
struct node *x;
x=(node *)malloc(sizeof(struct node));
x->data = y;
x->link = top;
top = x;
}
//THIS FUNCTION REMOVES TOP NODE FROM THE STACK AND
RETURNS ITS VALUE
void pop()
{
int a;
if(top==NULL)
{
cout<<"STACK EMPTY...";
return ;
}
else
{
a=top->data;
cout<<endl<<"The value at the top of stack is "<<a;
top=top->link;
}
}
//THIS FUNCTION DISPLAY ELEMENTS OF STACK
void display()
{
int i =0;
struct node * temp;
temp = top;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->link;
}
}
Queue
void deleteQ();
void insertQ()
{
int value;
cout<<endl<<"Enter the element to be inserted in
queue\n";
cin>>value;
if(rear < MAX-1)
{
rear= rear +1;
queue[rear] = value;
}
else
{
cout<<"The queue is full \n";
exit(1);
}
}
void deleteQ()
{ int value;
if(front == rear)
{
cout<<"The queue is empty \n";
exit(1);
}
front = front + 1;
value = queue[front];
cout<<endl<<"The value deleted is "<<value;
}
int main()
{
int n;
front=rear=-1;
do
{
do
{
insertQ();
cout<<"Enter 1 to continue and 0 for exit\n";
cin>>n;
}while(n == 1);
cout<<endl<<"Enter 1 to delete an element and 0 for
exit" ;
cin>>n;
while( n == 1)
{
deleteQ();
cout<<endl<<"Enter 1 to delete an element and 0 for
exit";
cin>>n;
}
cout<<endl<<"Enter 1 to continue and 0 for exit\n";
cin>>n;
} while(n == 1);
return 0;
}
// Linked Implementation of Queue data Structure
#include<iostream.h>
#include<stdlib.h>
break;
case 3:
display();
break;
case 4:
break;
default:
cout<<"Invalid choice\n";
break;
}
}while(n!=4);
return 0;
}
void insertQ()
{
int item;
n *temp;
cout<<"Enter the item\n";
cin>>item;
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=NULL;
if(rear==NULL)
{
front=temp;
rear=temp;
}
else
{
rear->link=temp;
rear=temp;
}
}
void deleteQ()
{
int item;
if(front==NULL)
cout<<"Queue is empty\n";
else
{
item=front->data;
cout<<"The element deleted = \n"<<item;
}
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
front=front->link;
}
void display()
{
n *ptr;
if(front==NULL)
cout<<"Queue is empty\n";
else
{
ptr=front;
cout<<"The elements of the queue are :";
while(ptr!=NULL)
{
cout<<ptr->data<<endl;
ptr=ptr->link;
}
}
}
Circular Queue
In circular queue, the insertion of a new element is
performed at the very first location of the queue if
the last location of the queue is full, in which the
first element comes just after the last element.
Advantages :
It overcomes the problem of unutilized space in leaner
queues, when it is implemented as arrays.
Insertion :
Rear = (rear+1)%Maxsize
Algorithm Steps:
Step 1:
create and set the variables front,rear,MAXSIZE,cq[]
step 2:
Read the circular queue operation type.
step 3:
If operation type is Insertion below steps are
executed.
Assign rear=rear%MAXSIZE.
if front equal to (rear+1)%MAXSIZE then display queue
is overflow.
if front equal to -1 then assign front=rear=0.
Otherwise assign rear=(rear+1)%MAXSIZE and read queue
data
Assign cq[rear] as data.(i.e. cq[rear]=data).
step 4:
If operation type is Deletion below steps are executed.
Check front=-1 then display queue is underflow.
Set temp as cq[front] (i.e. temp=ca[front]).
Check front equal to rear if it is true then assign
front=rear=-1(Move the front to beginning)
Assign front=(front+1)%MAXSIZE.
#define MAXSIZE 5
int cq[MAXSIZE];
int front,rear;
int main()
{
void add(int);
void del();
int will=1,i,num;
front = -1;
rear = -1;
//clrscr();
cout<<"\nProgram for Circular Queue through array";
while(1)
{
cout<<"\n\nMENU\n1.INSERTION\n2.DELETION\n3.EXIT";
cout<<"\n\nENTER YOUR CHOICE : ";
cin>>will;
switch(will)
{
case 1:
cout<<"\n\nENTER THE QUEUE ELEMENT : ";
cin>>num;
add(num);
break;
case 2:
del();
break;
case 3:
exit(0);
default:
cout<<"\n\nInvalid Choice . ";
}
} //end of outer while
return 0;
} //end of main
void add(int item)
{
//rear++;
//rear= (rear%MAXSIZE);
if(front ==(rear+1)%MAXSIZE)
{
cout<<"\n\nCIRCULAR QUEUE IS OVERFLOW";
}
else
{
if(front==-1)
front=rear=0;
else
rear=(rear+1)%MAXSIZE;
cq[rear]=item;
cout<<"\n\nRear = "<<rear<<" Front = "<<front;
}
}
void del()
{
int a;
if(front == -1)
{
cout<<"\nCIRCULAR QUEUE IS UNDERFLOW";
}
else
{
a=cq[front];
if(front==rear)
front=rear=-1;
else
front = (front+1)%MAXSIZE;
cout<<"\n\nDELETED ELEMENT FROM QUEUE IS : "<<a;
cout<<"\n\nRear = "<<rear<<" Front = "<<rear;
}
}
Database
Databases are designed to offer an organized mechanism
for storing, managing and retrieving information. They
do so through the use of tables. In simple terms we can
say that in a Database the data is stored in Rows and
Columns.
Example Table
Relational Algebra
Algebra is a formal structure consisting of sets and
operations on those sets. Relational algebra is a
formal system for manipulating relations.
1. Operands of this Algebra are relations.
2. Operations of this Algebra include the usual set
operations and special operations defined for
relations such as :
selection
projection
join
Set Operations on Relations
For the set operations on relations, both operands must
have the same schema, and the result has that same
schema.
1. R1 U R2 (union) is the relation containing all
tuples that appear in R1, R2, or both.
2. R1 n R2 (intersection) is the relation containing
all tuples that appear in both R1 and R2.
3. R1 - R2 (set difference) is the relation containing
all tuples of R1 that do not appear in R2.
Selection
Selects tuples from a relation whose attributes meet
the selection criteria, which is normally expressed as
a predicate.
R2 = select(R1,P)
Projection
Chooses a subset of the columns in a relation, and
discards the rest.
R2 = project(R1,D1,D2,...Dn)
That is, from the tuples in R1 we create a new relation
R2 containing only the domains D1,D2,..Dn.
project(Students,Name,Address)
Union
R UNION S
Includes all tuples that are in either R or S.
Duplicate tuples are removed.
For a union operation r U s to be valid, two conditions
must hold:
Join
Combines attributes of two relations into one.
R3 = join(R1,D1,R2,D2)
Given a domain from each relation, join considers all
possible pairs of tuples from the two relations, and if
their values for the chosen domains are equal, it adds
a tuple to the result containing all the attributes of
both tuples (discarding the duplicate domain D2).
Natural join: If the two relations being joined have
exactly one attribute (domain) name in common, then we
assume that the single attribute in common is the one
being compared to see if a new tuple will be inserted
in the result.
OUTER JOIN
Notice that much of the data is lost when applying a
join to two relations. In some cases this lost data
might hold useful information. An outer join retains
the information that would have been lost from the
tables, replacing missing data with nulls. There are
three forms of the outer join, depending on which data
is to be kept.
LEFT OUTER JOIN - keep data from the left-hand table
RIGHT OUTER JOIN - keep data from the right-hand table
FULL OUTER JOIN - keep data from both tables
Cartesian Product
R X S =
What is SQL?
1. SQL stands for Structured Query Language
2. SQL lets you access and manipulate databases
3. SQL is an ANSI (American National Standards
Institute) standard
Note: SQL is not case sensitive. SELECT is the same
as select.
DML Commands:
1. SELECT - extracts data from a table
2. UPDATE - updates data in a table
3. DELETE - deletes data from a table
4. INSERT INTO - inserts new data into a table
DDL Commands:
1. CREATE DATABASE - creates a new database
2. CREATE TABLE - creates a new table
3. ALTER TABLE - modifies a table
4. DROP TABLE - delete a table
5. CREATE INDEX - creates an index
6. DROP INDEX - deletes an index
Data Types
Max Size:
Data type Description
Magnitude
Number having
DECIMAL(p,s) 1E-130 ..
precision p and scale s.
10E125
A date in YYYY-MM-DD
DATE format
DML Commands:
Quotes Around Text Fields
SQL uses single quotes around text values (most
database systems will also accept double quotes).
However, numeric values should not be enclosed in
quotes.
For text values:
This is correct:
Operator Description
= Equal
OR Operator Example
Now we want to select only those students with the name
equal to "Nishant" OR City equal to "Sagoor":
We use the following SELECT statement:
SELECT * FROM Student WHERE Name='Nishant' OR
City='Sagoor'
The result will look like this:
ORDER BY Example
The "Student" table:
The IN Operator
The IN operator allows you to specify multiple values
in a WHERE clause.
SQL IN Syntax
SELECT coumn_name(s)FROM table_name WHERE column_name
IN (value1,value2,...)
IN Operator Example
The "Order" table:
SQL Functions
SQL has many built-in functions for performing
calculations on data.
SQL Aggregate Functions
SQL aggregate functions return a single value,
calculated from values in a column.
Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
The SUM() Function
The SUM() function returns the total sum of a numeric
column.
SQL SUM() Syntax
SELECT SUM(column_name) FROM table_name
SQL SUM() Example
We have the following "Order" table:
OrderTotal
5700
OrderAverage
950
Customer
Ayan
Anya
Aneesh
CustomerAyan
NumberOfOrders
NumberOfCustomers
LargestOrderPrice
2000
SmallestOrderPrice
100
CLASS-XII
COMPUTER SCIENCE
(Subject Code 083)
SAMPLE PAPER 2014 - 15
Section A (C++)
b. Write the related library function name based upon the given information in
C++.
(i) Get single character using keyboard. This function is available in stdio.h file.
(ii) To check whether given character is alpha numeric character or not. This
c. Rewrite the following C++ program after removing all the syntactical errors (if
any), underlining each correction. : [2]
include<iostream.h>
#define PI=3.14
void main( )
{ float r;a;
cout<<enter any radius;
cin>>r;
a=PI*pow(r,2);
cout<<Area=<<a
}
d. Write the output from the following C++ program code: [2]
#include<iostream.h>
#include<ctype.h>
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
class Class
{
int Cno,total;
char section;
public:
Class(int no=1)
{
Cno=no;
section='A';
total=30;
}
void addmission(int c=20)
{
section++;
total+=c;
}
void ClassShow()
{
cout<<Cno<<":"<<section<<":"<<total<<endl;
}
};
void main()
{
Class C1(5),C2;
C1.addmission(25);
C1.ClassShow();
C2.addmission();
C1.addmission(30);
C2.ClassShow();
C1.ClassShow();
}
f. Study the following C++ program and select the possible output(s) from it :
Find the maximum and minimum value of L. [2]
#include<stdlib.h>
#include<iostream.h>
#include<string.h>
void main()
{
randomize();
char P[]="C++PROGRAM";
long L;
for(int I=0;P[I]!='R';I++)
{
L=random (sizeof(L)) +5;
cout<<P[L]<<"-";
}
}
}
i) R-P-O-R-
ii) P-O-R-+-
iii) O-R-A-G-
iv) A-G-R-M-
b. Answer the questions (i) and (ii) after going through the following C++ class:
[2]
class Stream
{
int StreamCode ; char Streamname[20];float fees;
public:
Stream( ) //Function 1
{
Private Members :
Customer_no integer
Customer_name char (20)
Qty integer
Price, TotalPrice, Discount, Netprice float
Member Functions:
Public members:
* A constructer to assign initial values of Customer_no as
111,Customer_name as Leena, Quantity as 0 and Price, Discount and
Netprice as 0.
*Input( ) to read data members(Customer_no, Customer_name, Quantity
and Price) call Caldiscount().
* Caldiscount ( ) To calculate Discount according to TotalPrice and
NetPrice
TotalPrice = Price*Qty
TotalPrice >=50000 Discount 25% of TotalPrice
TotalPrice >=25000 and TotalPrice <50000 - Discount 15% of TotalPrice
TotalPrice <250000 - Discount 10% of TotalPrice
Netprice= TotalPrice-Discount
*Show( ) to display Customer details.
d. Answer the questions (i) to (iv) based on the following code: [4]
class AC
{
char Model[10];
char Date_of_purchase[10];
char Company[20];
public( );
AC( );
void entercardetail( );
void showcardetail( );
};
class Accessories : protected AC
{
protected:
char Stabilizer[30];
char AC_cover[20];
public:
float Price;
Accessories( );
void enteraccessoriesdetails( );
void showaccessoriesdetails( );
};
class Dealer : public Accessories
{
int No_of_dealers;
char dealers_name[20];
int No_of_products;
public:
Dealer( );
void enterdetails( );
void showdetails( );
};
(i) How many bytes will be required by an object of class Dealer and class
Accessories?
(ii) Which type of inheritance is illustrated in the above c++ code? Write the base
class and derived class name of class Accessories.
(ii) Write names of all the members which are accessible from the objects of
class Dealer.
(iv) Write names of all the members accessible from member functions of class
Dealer.
Q3a) An array T[-1..35][-2..15] is stored in the memory along the row with each
element occupying 4 bytes. Find out the base address and address of element
T[20][5], if an element T[2][2] is stored at the memory location 3000. Find the
total number of elements stored in T and number of bytes allocated to T
[3]
d. Write a function in C++ to print the sum of all the non-negative elements
present on both the diagonal of a two dimensional array passed as the argument
to the function. [2]
e. Evaluate the following postfix expression. Show the status of stack after
execution of each operation separately:
Q4. a. Write the command to place the file pointer at the 10th and 4th record
starting position using seekp() or seekg() command. File object is file and record
name is STUDENT. [1]
b. Write a function in C++ to count and display the no of three letter words in
the file VOWEL.TXT. [2]
Example:
If the file contains:
A boy is playing there. I love to eat pizza. A plane is in the sky.
Then the output should be: 4
c. Given the binary file CAR.Dat, containing records of the following class CAR
type: [3]
class CAR
{
int C_No;
char C_Name[20];
float Milage;
public:
void enter( )
{
cin>> C_No ; gets(C_Name) ; cin >> Milage;
}
void display( )
{
cout<< C_No ; cout<<C_Name ; cout<< Milage;
}
int RETURN_Milage( )
{
return Milage;
}
};
Write a function in C++, that would read contents from the file CAR.DAT and
display the details of car with mileage between 100 to 150.
Section B (Python)
c) Rewrite the following python code after removing all syntax error(s). Underline
the corrections done. [2]
def main():
r = raw-input(enter any radius : )
a = pi * math.pow(r,2)
print Area = + a
f) What are the possible outcome(s) expected from the following python code?
Also specify maximum and minimum value, which we can have. [2]
def main():
p = 'MY PROGRAM'
i=0
while p[i] != 'R':
l = random.randint(0,3) + 5
print p[l],'-',
i += 1
i) R - P - O - R -
ii) P - O - R - Y -
iii) O -R - A - G -
iv) A- G - R - M -
Q2. a) How data encapsulation and data abstraction are implemented in python,
explain with example. [2]
b) What will following python code produce, justify your answer [2]
x=5
y=0
print A
try :
print B
a=x/y
print C
except ZerorDivisionError:
print F
except :
print D
Instance attributes:
d) What are the different ways of overriding function call in derived class of
python ? Illustrate with example. [2]
Q3. a) What will be the status of following list after third pass of bubble sort and
third pass of selection sort used for arranging elements in ascending order?
40, 67, -23, 11, 27, 38, -1 [3]
b) Write a python function to search for a value in the given list using binary
search method. Function should receive the list and value to be searched as
argument and return 1 if the value is found 0 otherwise. [2]
d) Write a python function using yield statement to generate prime numbers till
the value provided as parameter to it. [3]
e) Evaluate the following postfix expression. Show the status of stack after
execution of each operation separately:
2,13, + , 5, -,6,3,/,5,*,< [2]
b) Given a pickled file - log.dat, containing list of strings. Write a python function
that reads the file and looks for a line of the form
Xerror: 0.2395
whenever such line is encountered, extract the floating point value and compute
the total of these error values. When you reach end of file print total number of
such error lines and average of error value. [3]
Section C
Q5. a. Define degree and cardinality. Based upon given table write degree and
cardinality. [2]
PATIENTS
b. Write SQL commands for the queries (i) to (iv) and output for (v) & (viii) based
COMPANY
CID NAME CITY PRODUCTNAME
CUSTOMER
CUSTID NAME PRICE QTY CID
(i) To display those company name which are having prize less than 30000.
(ii) To display the name of the companies in reverse alphabetical order.
(iii) To increase the prize by 1000 for those customer whose name starts with S
(iv) To add one more column totalprice with decimal(10,2) to the table customer
(v) SELECT COUNT(*) ,CITY FROM COMPANY GROUP BY CITY;
(vi) SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER WHERE QTY>10 ;
(vii) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE %r%;
(viii) SELECT PRODUCTNAME,CITY, PRICE FROM COMPANY,CUSTOMER
WHERE COMPANY.CID=CUSTOMER.CID AND PRODUCTNAME=MOBILE;
b) Write the equivalent boolean expression for the following logic circuit [2]
c) Write Product Of Sum expression of the function F (a,b,c,d) from the given
truth table [1]
a b c d F
0 0 0 0 0
0 0 0 1 0
0 0 1 0 1
0 0 1 1 1
0 1 0 0 0
0 1 0 1 1
0 1 1 0 1
0 1 1 1 0
1 0 0 0 0
1 0 0 1 0
1 0 1 0 1
1 0 1 1 1
1 1 0 0 0
1 1 0 1 0
1 1 1 0 0
1 1 1 1 1
d) Obtain the minimal SOP form for the following boolean expression using K-
Map.
F(w,x,y,z) = (0,2,3,5,7,8,10,11,13,15) [3]
SENIOR
JUNIOR
ADMIN
HOSTEL
c. Identify the Domain name and URL from the following. [1]
http://www.income.in/home.aboutus.hml
d. What is Web Hosting? [1]
e. What is the difference between packet & message switching? [1]
f. Define firewall. [1]
g. Which protocol is used to creating a connection with a remote machine? [1]