Ebook XI-XII CS
Ebook XI-XII CS
Topic Page NO
XI – COMPUTER SCIENCE UNTI – 3
III C++
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 probably compile more
than 99% of C programs without even changing
line ofsource code. a
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.
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
Literals/Constants in C++
Invalid Identifiers
MY Name
1MY
%my
Valid Identifiers
MY_NAME
MY1
_my
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.
Notice that the sentence ends with a semicolon
character (;). This character signifies the end of the
instruction and must be included after every
instruction in any C++ program (one of the most common
errors of students is indeed to forget to include a
semicolon ; at the end of each instruction).
Return; 0;
The return instruction causes the main() function
finish and return the code that the instruction is
followed by, in this case 0. This it is most usual way
to terminate a program that has not found any error
during its execution. As you will see in coming
examples, all C++ programs end with a sentence similar
to this.
Therefore, you may have noticed that not all the lines
of this program did an action. There were lines
containing only comments (those beginning by //), lines
with instructions for the compiler's preprocessor
(those beginning by #), then there were lines that
initiated the declaration of a function (in this case,
the main function) and, finally lines with instructions
(like the call to cout <<), these last ones were all
included within the block delimited by the curly
brackets ({}) of the main function.
The program has been structured in different lines in
order to be more readable, but it is not compulsory to
do so. For example, instead of
#include <iostream.h>
int main ()
{
cout << " Hello World ";
return 0;
}
We can write:
int main () { cout << " Hello World "; return 0; }
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;
}
And the result would have been exactly the same then 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
If you include comments within the source-code of your
programs without using the comment characters
combinations //, /* or */, the compiler will take them
as if they were C++ instructions and, most likely
causing one or several error messages.
Compilation Process of a C++ Program
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)
Variable Declaration in C++:
All variables must be declared before use. A
declaration specifies a type, and contains a list of
one or more variables of that type as follows:
type variable_name;
Here, type must be a valid C++ data type including
char, int, float, double or any user defined object
etc., and variable_name may consist of one or more
identifier names separated by commas. Some valid
declarations are shown
here:
int i, j,k;
char c,
ch;
float f, salary;
double d;
A variable declaration with an initializer is always
a definition. This means that storage is allocated
for the variable and could be declared as follows:
int i = 100;
Variable Initialization in C+
+:
Variables can be initialized (assigned an
initial value) in their declaration. The
initializer consists of an equal sign followed by a
constant expression as follows:
type variable_name = value;
Some examples are:
int a = 3, b = 5; // initializing a and b.
byte c = 22; // initializes c.
double d = 12.3 // initializes d.
char z = 'x'; // the variable z has the value 'x'.
// 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
But following is not a valid statement and would
generate compile-time error:
1 = 2; // Left Hand Side has a Constant
Scope of Variables
A scope is a block of the program. There are three
places where variables can be declared:
Inside a function or a block which is called local
variables,
In the definition of function parameters which is
called formal parameters.
Outside of all functions which is called global
variables.
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;
}
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;
}
When the above code is compiled and executed, it
produces following output:
120
Initializing Local and Global Variables:
When a local variable is defined, it is not initalised
by the system, we have to initalise it. Global
variables are initalised automatically by the system
when we define them as follows:
Data Type Initialser
int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize
variables properly otherwise, sometime program would
produce unexpected result.
Data Types Modifiers
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 largest and smallest value
thatit can store known as the range. An integer
(usually 2bytes long) can store any value ranging from
-32768 to32767.
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.
XI – COMPUTER SCIENCE UNTI –IV C++
Control Flow Statements
When a program runs, the CPU begins execution at
main(), executes some number of statements, and then
terminates at the end of main(). The sequence of
statements that the CPU executes is called the
program’s path. Straight-line programs have sequential
flow — that is, they take the same path (execute the
same statements) every time they are run (even if the
user input changes).
However, often this is not what we desire. For example,
if we ask the user to make a selection, and the user
enters an invalid choice, ideally we’d like to ask the
user to make another choice. This is not possible in a
straight-line program.
C++ provides control flow statements (also called flow
control statements), which allow the user to change the
CPU’s path through the program.
Different C++ flow control Statements
if statement
else if construct
switch statement
break statement
while loop
do while loop
for loop
if-else statement
if ( condition )
{
statement true;
}
else
{
statement false;
}
if-else statement example
#include <iostream.h>
int main()
{ int a = -10;
if ( a > 0 )
{
cout << "a is a positive Integer";
}
else
{
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 )
{
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
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;
cout << "Enter the starting number := ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "Finished !\n";
return 0;
}
Enter the starting number := 8
8, 7, 6, 5, 4, 3, 2, 1, Finished!
When the program starts the user is prompted to insert
a starting number for the countdown. Then the while
loop begins, if the value entered by the user fulfills
the condition n>0 (that n is greater than zero) the
block that follows the condition will be executed and
repeated while the condition (n>0) remains being true.
The whole process of the previous program can be
interpreted according to the following script
(beginning in main):
User assigns a value to n
The while condition is checked (n>0). At this point
there are two possibilities:
*condition is true: This statement will be executed:
cout << n << ", "; --n;
*condition is false:This statement will be executed:
cout << "Finished!\n";return 0;
When creating a while-loop, we must always consider
that it has to end at some point, therefore we must
provide within the block some method to force the
condition to become false at some point, otherwise the
loop will continue looping forever. In this case we
have included --n; that decreases the value of the
variable that is being evaluated in the condition (n)
by one - this will eventually make the condition (n>0)
to become false after a certain number of loop
iterations: to be more specific, when n becomes 0, that
is where our while-loop and our countdown end.
The do-while loop
Its format is:
do
{
statement(s);
}while (condition);
Its functionality is exactly the same as the while
loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of
before, granting at least one execution of statement
even if condition is never fulfilled.
For example, the following example program echoes any
number you enter until you enter 0.
Example of do-while loop
#include <iostream.h>
int main ()
{
long n;
do {
cout << "Enter any number (0 to end): ";
cin >> n;
cout << "You have entered: " << n << "\n";
} while (n != 0);
return 0;
}
Enter number (0 to end): 888
You entered: 888
Enter number (0 to end): 777
You entered: 777
Enter number (0 to end): 0
You entered: 0
The do-while loop is usually used when the condition
that has to determine the end of the loop is determined
within the loop statement itself, like in the previous
case, where the user input within the block is what is
used to determine if the loop has to end.
In fact if you never enter the value 0 in the previous
example you can be prompted for more numbers forever.
The for loop
Its format is:
for (initialization; condition; increase)
{
//statement;
}
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 );
The following program uses a nested for loop to find
the prime numbers from 2 to 50:
#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;
}
List of Some Commonly used inbuilt Functions in C++
Standard input/output functions
stdio.h
gets (), puts ()
Character Functions
ctype.h
isalnum (), isalpha (),isdigit (), islower (),isupper
(), tolower (),toupper ()
String Functions
string.h
strcpy (), strcat (),strlen (), strcmp (),strcmpi (),
strrev (),strlen (), strupr (),strlwr ()
iomanip.h
setw(),
Mathematical Functions
math.h
abs (), pow (), sgrt (),sin (), cos (), abs ()
Other Functions
stdlib.h
randomize (), random (),itoa (), atoi ()
Using Library Functions
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:
Length of string Ambari is 6
[email protected]
<[email protected]>;
#include<string.h>
#include<iostream.h>
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:
pow function returns x raise to the power y where x and
y are variables of double data type.
#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);
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()
{
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>
/* prints 3 random number in the range 0 to 9 */
int main(void)
{
randomize();
cout<<"3 random numbers from 0-9 range:\n";
for(int i=0;i<3;i++)
cout<<random (10)<<endl;
return 0;
}
Declaration:
char*itoa(int value,char *string,int radix);
Description: itoa converts an integer to a string
#include <iostream.h>
#include <stdlib.h>
int main(void)
{
int number = 444;
char string[5];
itoa(number, string, 10);
cout<<"integer = "<<number<<"string ="<<string;
return 0;
}
Output
integer 444 string 444
Declaration: int atoi(const char *s);
Description: Macro that converts string to integer
#include <stdlib.h>
#include <iostream.h>
int main(void)
{
int n;
char *str = "112";
n = atoi(str);
cout<<"string = "<<str<<"integer ="<<n;
return 0;
}
Output
string 112 integer 112
Introduction to User-defined functions
C++ allows programmers to define their own functions.
For example the following is a definition of a function
which return the sum of two numbers.
int SumOfNumbers(int a,int b)
// Returns the sum of a and b
{
int c; //local variable
c = a+b;
return c;
}
This function has two input parameters, a , b and will
returns the sum of these parameters. In the function a
local variable c is used to temporarily hold the
calculated value inside the function.
The general syntax of a function definition:
Return-type function-name( Data_Type parameter )
{
Statements;
}
If the function returns a value then the type of that
value must be specified in return-type. This could be
int, float or char or any other valid data type. If the
function does not return a value then the return-type
must be void.
The function-name follows the same rules of
composition as identifiers.
The parameter-list the formal parameters of the
function along with their data types.
The statements consist of any C++ executable
statements.
Types of user Defined Functions
Functions with no parameters
Functions with parameters and no return value
Functions that return values
Call-by-value
Call-by-reference
Functions with no parameters
Functions with no will not return a value but carry out
some operation. For example consider the following
function with no parameters.
void Display(void)
//void inside the parenthesis is optional
{
cout << "Your Message"<< endl;
}
Note that the return has been given as void, this tells the
compiler that this function does not return any value.
Because the function does not take any
parameters the parameter-list is empty, this is
indicated by the void parameter-list.
Since this function does not return a value it cannot
be used in an expression and is called by treating it
as a statement as follows:
Display();
When a function is called the C++ compiler must insert
appropriate instructions into the object code. To do
this correctly the compiler must know the types of all
parameters and the type of any return value. Thus
before processing the call of a function it must be
defined. This can be done by defining the functions
outside the definition of main function:
#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;
}
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 interchanding 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
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
When declaring an array, we saw that you must specify
the number of items that the array is made of. Here is
an example:
float price[5];
Depending on how you want to deal with your array, you
may sometimes need to increase or decrease its
dimension. To do this, you would need to locate the
declaration of the array and change its dimension. If
the program is long and the array is declared in some
unusual place, this could take some time. The
alternative is to define a constant prior to declaring
the array and use that constant to hold the dimension
of the array. Here is an example:
#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];
Each member of the array can be located using its
index, as we have seen so far. In the same way, you can
request the value of any member of the array using its
index. In the following example, we declare an array of
5 integers and then we request the values of the 2nd
and the 4th members:
#include <iostream.h>
int main()
{
const int count = 5;
int items[count];
cout << "Enter the values of two items\n";
cout << "Item 1: ";
cin >> items[0];
cout << "item 4: ";
cin >> items[3];
cout << "\nYou have Entered following values";
cout << "\nItem 1: " << items[0] ;
cout << "\nItem 4: " << items[3] ;
return 0;
}
Here is an example of running the program:
Enter the values of two items
Item 1: 45
Item 4: 66
You have Entered following values
item 1: 45
item 4: 66
Operations on Arrays
You can add the values of two members of the
array(Number[2]+Number[0]), you can subtract the value
of one of the members from another member(member[1]-
Number[4]). In the same way, you can perform
multiplication, division, or remainder operations on
members of an array.
Sum of all the Elements of an Array
#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
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()
{
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;
}
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;
}
#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;
char temp[100];
for(i=strlen(str),j=0;i!=0;--i,++j){
temp[j]=str[i];
} temp[j]='\0';
strcpy(str,temp);
}
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.
{ 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
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];
}
cout<<endl<<"Maximum element is "<<max;
return 0;
}
Finding Minimum element in MXN Array
// Min Element in a two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M];
int min=9999;
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 Min element
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{ if(min>a1[i][j])
min=a1[i][j];
}
cout<<endl<<"Minimum element is "<<min;
cin>>min;
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.
For example, the following array:
char Ayan[20];
is an array that can store up to 20 elements of type
char. In this array, we can store sequences of
characters up to 20 characters long. But we can also
store shorter sequences. For example, Ayan could store
at some point in a program either the sequence "Hello"
or the sequence "Happy Diwali", since both are shorter
than 20 characters.
Therefore, since the array of characters can store shorter
sequences than its total length, a special character is
used to signal the end of the valid
sequence: the null character, whose literal constant
can be written as '\0' (backslash, zero).
Our array of 20 elements of type char, called Ayan, can
be represented storing the characters sequences "Hello"
and "Happy Diwali" as:
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;
} ;
void StructPass(temp var);
int main(void)
{
temp arg;
arg.a = 123;
arg.b = 321;
StructPass(arg); // Passing structure variable
return 0;
}
void StructPass(temp var)
{
cout<<var.a;
cout<<var.b;
}
Passing structure variable to function using
(call-by-reference)
#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;
cout<<"\n arg.b = "<<arg.b;
return 0;
}
void StructPass(temp *var) // Pointer to structure temp
{
/* The -> (Indirect Member Selector) operator is used
when a structure element has to be accessed through
pointer. */
var->a=888;
var->b=999;
cout<<"\nInside StrutPass ";
cout<<"\nvar->a = "<<var->a;
cout<<"\nvar->b = "<<var->b;
}
Output
Inside StrutPass
var->a =888
var->b =999
Inside Main
arg.a =888
arg.b =999;
The -> Operator
The -> (Indirect Member Selector) operator is used
when a structure element has to be accessed through a
pointer.
Arrays of Structure
#include <iostream.h>
struct student
{ int age;
int roll_no;
char name[20];
};
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;
}
PassArrayStruct(data); // Passing Array of
Structure variables
return 0;}
void PassArrayStruct(student data[])
{ int i;
cout<<endl<<"Accessing Values Inside PassArrayStruct
Function:";
for(i = 0; i<3 ;i++)
{ cout<<data[i].age<<"\t";
cout<<data[i].roll_no<<"\t";
cout<<data[i].name<<endl;
}
}
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;
cout << endl <<"Use of
typedef short
SmallInt" <<tdef;
cout<<endl<<"Use of
typedef unsigned
long Lint" <<LI;
return 0;
}
Output:
Use of typedef short SmallInt 123
Use of typedef unsigned long Lint 321
With typedef short SmallInt and unsigned long Lint can
now be used as a data type to declare variables of type
small integer and unsigned long integer.
Define preprocessor macros .
Syntax:
#define identifier replacement
When the preprocessor encounters this directive, it
replaces any occurrence of identifier in the rest of
the code by replacement. This replacement can be an
expression, a statement or a block. Preprocessor simply
replaces any occurrence of identifier by replacement.
#define SIZE 100
int Number[SIZE];
int Count[SIZE];
After the preprocessor has replaced SIZE, the code
becomes equivalent to:
int Number[100];
int Count[100];
#define can also work with parameters to define
function macros:
#define getmax(a,b) a>b?a:b
{
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 !!!.
XII – COMPUTER SCIENCE UNTI –I C++
Object Oriented Programming
A type of programming in which main concentration is on
DATA rather than on ALGORITHM
Characteristics of Object Oriented Programming
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
{ }
};
};
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;
...
};
Object -It may be defined as identifiable identity with
some characteristics and behavior.
Syntax of creating Object:
Class_name Object_Name;
If we have class named AB then the Object of this class
can be created using above syntax as
AB Obj;
Abstract class
An abstract class is a class that is designed to be
specifically used as a base class. An abstract class
contains at least one pure virtual function.
You declare a pure virtual function by using a pure
Specifier
(= 0) in the declaration of a virtual member function
in the class declaration.
The following is an example of an abstract class:
class AB {
public:
virtual void f() = 0; //Pure virtual
Function
};
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:
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 doesn’t 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
{
a=10;
b=20;
}
void show() //member function
{
int main()
{
};
s=a+b;
cout<<”sum
of numbers
is”<<s<<end
l;
}
sum obj; //object of class
obj.show();
return 0;
}
public, protected and private are three access
specifiers in C++.
{ /*...*/ };
Where derived_class_name is the name of the derived
class and base_class_name is the name of the class on
which it is based. The access specifier may be replaced
by any one of the access specifiers such as
public,protected and private. This access specifier
limits the most accessible level for the members
inherited from the base class: The members with a more
accessible level are inherited with this level instead,
while the members with an equal or more restrictive
access level keep their restrictive level in the
derived class.
// Inheritance Example
#include <iostream.h>
#include<string.h>
class Fruits
{
public:
char taste[20],color[20];
};
class Orange: public Fruits
{
public:
void TasteColor()
{
strcpy(taste,"sweet-sour");
strcpy(color,"orange");
}
void Display()
{
cout<<"Orange Taste = "<<taste<<endl;
cout<<"Orange Colour ="<<color<<endl;
}
};
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:
Orange Taste = sweet-sour
Orange Colour =orange
Apple Taste = sweet
Apple Colour =red
The objects of the classes Orange and Apple each
contain members inherited from Fruits. These are: taste
and color().
Since we wanted taste and color to be accessible from
members of the derived classes Orange and Apple, we
have used public access specifier.
We can summarize the different access types according
to who can access them in the following way:
Access Public
Protected Private
Members of derived
Yes Yes No
classes
Non members
Yes No No
inheritance.
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
{ protecte
d: 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()
{
} Output: m=5
o=6 m*o=30
Multi Level Inheritances:
#include<iostream.h>
class A
{
public :
int a1;
};
class B: public A //class B is publicly derived by
class A
{
public :
int b1;
};
class C: public B // //class C is publicly derived by
class B
{
public :
void Cgetdata()
{
cout<<endl<<"Enter the values of a1 and b1";
cin>>a1>>b1; // a1 and b1 are derived from class A and
class B
}
void Cputdata()
{
cout<<endl<<"You have entered a1 = "<<a1<<"and b1 is
="<<b1;
}
};
int main()
{
C obj;
obj.Cgetdata(); //member function of class C
obj.Cputdata(); //member function of class C
return 0
;
}
Output:
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
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
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.
Failure is indicated by returning a value of -1.
Example
// position of put pointer
#include <fstream.h>
int main ()
{
long pos;
ofstream outfile; outfile.open
("test.txt"); outfile.write ("My Name
is Ayan",15); pos=outfile.tellp();
outfile.seekp (pos-4);
outfile.write ("Sanju",5);
outfile.close();
return 0;
}
In this example, tellp is used to get the position of
the put pointer after the writing operation. The
pointer is then moved back 4 characters to modify the
file at that position, so the final content of the file
shall be:
My name is Sanju
ifstream::tellg()
int tellg ( );
Get position of the get pointer.
Returns the absolute position of the get pointer.
The get pointer determines the next location in the
input sequence to be read by the next input operation.
Return Value
An integral value with the number of characters between
the beginning of the input sequence and the current
position.
Failure is indicated by returning a value of -1.
Example of tellg()
#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);
// get length of file:
length = is.tellg();
is.seekg (0, ios::beg);
// read data:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
return 0;
}
In this example, tellg is used to get the position in
the stream after it has been moved with seekg to the
end of the stream, therefore determining the size of
the file.
#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");
}
This function will modify a record
void modifyrecord(int n)
{
fstream finout;
student obj; int found=0;
finout.open("student.dat",ios::in|ios::out);
while(finout.read((char*)&obj,sizeof(obj)) &&
found==0)
{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 main ()
{
int *intp = NULL; // Pointer initialized with null
intp = new int; // Request memory for the variable
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
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.
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];
Each member of the array can be located using its
index, as we have seen so far. In the same way, you can
request the value of any member of the array using its
index. In the following example, we declare an array of
5 integers and then we request the values of the 2nd
and the 4th members:
#include <iostream.h>
int main()
{
const int count = 5;
int items[count];
cout << "Enter the values of two items\n";
cout << "Item 1: ";
cin >> items[0];
cout << "item 4: ";
cin >> items[3];
cout << "\nYou have Entered following values";
cout << "\nItem 1: " << items[0] ;
cout << "\nItem 4: " << items[3] ;
return 0;
}
Here is an example of running the program:
Enter the values of two items
Item 1: 45
Item 4: 66
You have Entered following values
item 1: 45
item 4: 66
Operations on Arrays
We can add the values of two members of the
array(Number[2]+Number[0]), you can subtract the value of
one of the members from another member(member[1]-
Number[4]). In the same way, you can perform
multiplication, division, or remainder operations on
members of an array.
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.
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};
To locate a member of the array, this time, each must
be identified by its double index. The first member is
indexed at [0][0]. The second is at [0][1]. For a 2x3
array as this one, the 5th member is at [1][1]. You can
use this same approach to display the values of the
members of the array. Here is an example:
#include <iostream.h>
int main()
{ // A 2-Dimensional array
int TwoDArray[2][3] = {1,2,3,4,5,6};
// Display the array
cout << "Elements of the array";
cout<<"\nTwoDArray [0][0]" << ": " << TwoDArray[0][0];
cout<< "\nTwoDArray [0][1]" << ": " << TwoDArray[0][1];
cout<< "\nTwoDArray [0][2]" << ": " << TwoDArray[0][2];
cout<< "\nTwoDArray [1][0]" << ": " << TwoDArray[1][0];
cout<< "\nTwoDArray [1][1]" << ": " << TwoDArray[1][1];
cout<< "\nTwoDArray [1][2]" << ": " << TwoDArray[1][2];
cout << endl;
return 0;
}
Output:
Elements of the array
TwoDArray [0][0]: 1
TwoDArray [0][1]: 2
TwoDArray [0][2]: 3
TwoDArray [1][0]: 4
TwoDArray [1][1]: 5
TwoDArray [1][2]: 6
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:
#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.
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.
//Program for Circular Queue implementation through
Array
#include <iostream.h>
#include<ctype.h>
#include<stdlib.h>
#include<conio.h>
#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;
}
}
XII – COMPUTER SCIENCE UNTI–III MYSQL
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.
Relational Algebra
Algebra is a formal structure consisting of sets and
operations on those sets. Relational algebra is a
formal system for manipulating relations.
Operands of this Algebra are relations.
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.
R1 U R2 (union) is the relation containing all
tuples that appear in R1, R2, or both.
R1 n R2 (intersection) is the relation containing
all tuples that appear in both R1 and R2.
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)
That is, from R1 we create a new relation R2 containing
those tuples from R1 that satisfy the predicate P.
A predicate is a Boolean expression whose operators are
and, or, not and arithmetic comparisons (LT, LE, GT,
GE, EQ, NE), and whose operands are either domain names
or domain constants.
select(students,Class=XII)
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:
The relation r and s must be of the same arity, i.e.
they must have the same number of attributes.
The domains of the ith attribute of r and the ith
attribute of s must be the same for all i.
Example:
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
The Cartesian Product is also an operator which works
on two sets. It is sometimes called the CROSS PRODUCT
or CROSS JOIN. It combines the tuples of one relation
with all the tuples of the other relation.
Example
R X S =
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL is an ANSI (American National Standards
Institute) standard
Note: SQL is not case sensitive. SELECT is the same
as select.
What Can SQL do?
1.SQL can retrieve data from a database/table
2.SQL can insert records in a database/table
3.SQL can update records in a database/table
4.SQL can delete records from a database/table
5.SQL can create new databases/table
6.SQL can create new tables in a database/table
SQL DML and DDL
SQL can be divided into two parts:The Data Manipulation
Language (DML) and the Data Definition Language (DDL).
DML Commands:
SELECT - extracts data from a table
UPDATE - updates data in a table
DELETE - deletes data from a table
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).
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:
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:
Now we want to find the sum of all "OrderPrice"
fields".
We use the following SQL statement:
SELECT SUM(OrderPrice) AS OrderTotal FROM Order
The result-set will look like this:
OrderTotal
5700
OrderAverage
950
Now we want to find the customers that have an
OrderPrice value higher than the average OrderPrice
value. We use the following SQL statement:
SELECT Customer FROM Order
WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Order)
The result-set will look like this:
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;
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
{
(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( )
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
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=5y
=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
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
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]