BSC C++ Unit I
BSC C++ Unit I
Control
Structures, Arrays, Strings, Pointers, Searching and Sorting Arrays.
Functions: Introduction, Prototype, Passing Data by Value, Reference Variables, Using Reference Variables
as
Parameters, Inline Functions, Default Arguments, Overloading Functions, Passing Arrays to Functions.
Object Oriented Programming: Procedural and Object-Oriented Programming, Terminology, Benefits,
OOP
Languages, and OOP Applications.
# C++ tokens
In a C++ source program, the basic element recognized by the compiler is the "token." A token is
character in source-program that the compiler does not break down into component elements. C++
tokens include keywords
keywords
identifiers
constants
strings
operators
Keywords
KEYWORDS implement specific C++ language features.
They are explicitly reserved words and cannot be used as names for the program variables or other
other user defined elements. Example: int, for, ,while, void etc.....
Identifiers
IDENTIFIERS refer to the “names" of variables, functions and arrays. These are user-defined names
and consist of a sequence of letters and digits, with a letter as a first character. Rules for identifiers:
Must consist of only letters, digits or underscore.
Only first 31 characters are significant.
Cannot use a keyword
Must not contain white space.
Constants
A constant is a fixed value that does not change during the execution of a program.
Constants can be any of the basic data types i.e. they can be int, float or char. Constants are
also known as literals in C.
CONSTANTS: (1) NUMERIC CONSTANTS ->INTEGER CONSTANTS
->REAL CONSTANTS
(2) CHARACTER CONSTANTS ->SINGLE CHARACTER CONSTANTS
->STRING CONSTANTS
Integer constants
An integer constant refers to a sequence of digits. There are 3 types of integers, namely,
decimal integer, octal integer and hexadecimal integer.
o Decimal integer constants (base 10) consist of one or more digits, 0 through 9, where 0
cannot be used as the first digit.
o Octal constants (base 8) consist of one or more digits 0 through 7, where the first digit
is 0 (zero).
o Hexadecimal constants (base 16) begin with a 0x or 0X (0 is zero) prefix, followed by a
hexadecimal number represented by a combination of digits 0 through 9, and
characters A through F.
Single character constants
A single character constant contains a single character enclosed within a pair of single quote
marks. Ex: ‘5’, ‘x’.
Character constants have integer values known as ASCII values. For Ex: cout<< “” , ’a’”;
would print the number 97, the ASCII value of letter a.
String constants
A string constant is a sequence of characters enclosed in double quotes. The characters
may be letters, numbers, special characters and blank space.
Ex: “Hello”, “1987”
# Data Types That C++ Supports
Data type is used to determine the type of the value a variable can store. Mainly data types are
classified into 3 categories:-
1. Built-in/Fundamental Data Types
2. Derived Data Types
3. User Defined Data Types
5. Void void -
Integer Type:
Integers are whole numbers with a machine dependent range of values. C++ has 3 classes of integer
storage namely short int, int and long int. All of these data types have signed and unsigned forms.
The qualifier short int requires half the space than normal integer values. The qualifier Unsigned
numbers are always positive and consume all the bits for the magnitude of the number. The qualifier
long and unsigned integers are used to declare a longer range of values.
Floating Point Type:
Floating point number represents a real number with 6 digits precision. Floating point numbers are
denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can
use the double to define the number. The double is same as float but with longer precision. To
extend the precision further we can use long double which consumes 80 bits of memory space.
Void Type:
Two normal uses of void are
to specify the return type of a function when it is not returning any value and
to indicate an empty argument list to a function.
Example:
void funct1(void);
Character Type:
A single character can be defined as a character type of data. Characters are usually stored in 8 bits
of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned
characters have values between 0 and 255, signed characters have values from –128 to 127.
ANSI C++ committee has added two more in built-in/fundamental data types ,
bool
wchar_t
# Operators
C++ operators are classified into a number of categories. They include:
(1) Arithmetic operators
(2) Relational operators
(3) Logical operators
(4) Assignment operators
(5) Increment and decrement operators
(6) Conditional operators
(7) Bitwise operators
(8) Special operators
Operator Meaning
+ Addition or Unary Plus
– Subtraction or Unary Minus
* Multiplication
/ Division
Examples of arithmetic operators are
x+y
x-y
a*b+
Here a, b, c, x, y are known as operands. The modulus operator is a special operator in C language
which evaluates the remainder of the operands after division.
(2) Relational operators:
Operato Meaning
r
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and takes the following form.
exp1 relational operator exp2
Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of
them.
Given below is a list of examples of relational expressions and evaluated values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of C++ language such as if, while and for
statements to decide the course of action of a running program.
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if
both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2
expressions is true.
Example:
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to
true if a is less than either m or n and when a is less than both m and n.
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is false and
evaluates to false if the expression is true. In other words it just reverses the value of the expression.
For example:
! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal
to y
4. Assignment Operators:
The Assignment Operator evaluates an expression on the right of the expression and substitutes it to
the value or variable on the left of the expression.
SYNTAX:
var oper = exp;
Here var is a variable, exp is an expression and oper is a C++ binary arithmetic operator. The
operator oper = is known as shorthand assignment operator
Example:
x=a+b
Here the value of a + b is evaluated and substituted to the variable x.
x + = 1 is same as x = x + 1
The increment operator ++ adds the value 1 to the current value of operand and the decrement
operator – – subtracts the value 1 from the current value of operand. ++variable name and variable
name++ mean the same thing when they form statements independently, they behave differently
when they are used in expression on the right hand side of an assignment statement.
Consider the following
m = 5;
y = ++m; (prefix)
In this case the value of y and m would be 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and
then the result is assigned to the variable on the left. On the other hand, a postfix operator first
assigns the value to the variable on the left and then increments the operand.
6. Conditional or Ternary Operator
The conditional operator consists of 2 symbols the question mark (?) and the colon (:)
The syntax for a ternary operator is as follows:
exp1 ? exp2 : exp3
The ternary operator works as follows:
exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the value
of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the
expression. Note that only one of the expressions is evaluated.
For example:
a = 10;
b = 15;
x = (a > b)? a: b
Here x will be assigned to the value of b. The condition follows that the expression is false
therefore b is assigned to x.
7. Bitwise Operators
A bitwise operator operates on each bit of data. Those operators are used for testing,
complementing or shifting bits to the right on left. Bitwise operators may not be applied to a float or
double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive
<< Shift left
>> Shift right
8. Special Operators
C++supports some special operators such as comma operator, size of operator, pointer operators (&
and *) and member selection operators (. and ->).
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only
one
expression is expected. When the set of expressions has to be evaluated for a value, only the
rightmost
expression is considered.
For example, the following code:
a = (b=3, b+2); would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end,
variable a would contain the value 5 while variable b would contain value 3.
examples :
int i;
float f = 3.14;
i = (int) f;
The previous code converts the float number 3.14 to an integer value (3), the remainder is
lost. Here, the typecasting operator was (int).
Another way to do the same thing in C++ is using the functional notation: preceding the
expression to be converted by the type and enclosing the expression between parentheses:
i = int ( f );
Both ways of type casting are valid in C++.
C++ permits explicit type conversion of variables or expressions using the type cast operator.
sizeof ()
This operator accepts one parameter, which can be either a type or a variable itself and
returns the size in bytes of that type or object:
a = sizeof (char);
This will assign the value 1 to a because char takes 1 byte of memory. The value returned by
sizeof is a constant, so it is always determined before program execution.
An Output statement is used to print the output on computer screen. cout is an output statement.
cout<<”Srinix College of Engineering”; prints Srinix College of Engineering on computer
screen.
cout<<”x”; print x on computer screen.
cout<<x; prints value of x on computer screen.
cout<<”\n”; takes the cursor to a newline.
cout<< endl; takes the cursor to a newline. We can use endl (a manipulator) instead of \n.
<< (two "less than" signs) is called insertion operator.
An Input statement is used to take input from the keyboard. cin is an input statement.
cin>>x; takes the value of x from keyboard.
cin>>x>>y; takes value of x and y from the keyboard.
# Array
Collection of similar data types stored in contiguous memory location is known as array.
Syntax is: Data_type array_name[size];
Example: int a[20]; // a is an array which can hold 20 integers.
char nm[16]; // nm is an array which can hold 16 character.
An array index always starts from 0 and index of last element is n-1, where n is the size of
the array.
In the above example:
a[0] is the first element.
a[1] is the second element………….
And a[19] is the last element of the array a.
# Structure
A structure is a collection of dissimilar data types.
Syntax :
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1, b2, b3 ;
Here b1, b2 and b3 are structure variable of type book. And name, price and pages are called
structure members.
To access a structure member we need dot(.) operator.
b1.name - name of book b1.
b1.price – price of book b1.
b1.pages – price of book b1.
# Union
A union is a collection of dissimilar datatypes.
Syntax:
union book
{
char name ;
float price ;
int pages ;
};
unionbook b1, b2, b3 ;
Here b1, b2 and b3 are union variable of type book. And name, price and pages are called
union members.
To access a union member we need dot(.) operator.
b1.name - name of book b1.
b1.price – price of book b1.
b1.pages – price of book b1.
Structure Union
1) Syntax: 1) Syntax:
struct structure_name union union_name
{ {
//Data types //Data types
} }
2) All the members of the structure can 2) In a union only one member can be used at
be accessed at once. a
3) Structure allocates the memory equal time.
to the total memory required by the 3) Union allocates the memory equal to the
members. maximum memory required by the member
struct example of
{ the union.
int x; union example
float y; {
} int x;
Here memory allocated is size float y;
of(x)+sizeof(y). }
Here memory allocated is sizeof(y), because
size of float is more than size of integer.
# Reference Variables
A reference variable provides an alias (alternative name) for a previously defined variable.
For example, if we make the variable sum a reference to the variable total, then sum and
total can be used interchangeably to represent that variable. A reference variable is created
as follows:
The variable x is an alternative to the array element n[10]. The variable a is initialized to the
newline constant. This creates a reference to the otherwise unknown location where the
new line constant \n is stored.
A major application of reference variables is in passing arguments to functions. Consider the
following:
void f(int & x)
{
x=x+10;
}
int main ( )
{
int m = l0;
f(m) ;
_ _ _
}
When the function call f(m) is executed, the following intialization occurs:
o int & x= m;
Thus x becomes an alias of m after executing the statement
o f(m”;
The Such function calls are known as call by reference. Since the variables x and m are
aliases, when the function increments x, m is also incremented. The value of m becomes 20
after the function is executed.
The call by reference mechanism is useful in object-oriented programming as it permits the
manipulation of objects by reference, and eliminates the copying of object parameters back
and forth. References can be created for built-in data types and also for user defined data
types such as structures and classes.
# Function
A function is a self-contained block of statements that perform a specific task .
A function consists of three parts:
o Function prototype: Function prototype is the declaration of a function.
Syntax is: return_type function_name(type of arguments);
Example: int add(int, int); void display(void);
o Function Calling: A function gets called when the function name is followed by a
semicolon.
Syntax is : function_name(list of arguments);
Example: sum(x,y);
search(mark);
o Function Definition: A function is defined when function name is followed by a pair of
braces in
which one or more statements may be present.
Syntax is:
return_type function_name(list of arguments with their types)
{
//Function Body
}
Call by value and call by reference
In call by value, value of the argument is passed during function calling. In call by reference
address of the argument is passed during function calling.
In call by value of actual arguments do not change. But in call by reference value of actual
argument changes.
Memory can be saved if we call a function by reference(&). When arguments are passed by
reference the formal arguments in the called function become aliases to the actual
arguments .
A program to swap two integers using call by value and call by reference.
Code:
Call by value Call by refernece
#include<iostream.h> #include<iostream.h>
void swap(int, int); void swap(int &, int &);
void main() void main()
{ {
int x=5, y=7; int x=5, y=7;
swap(x, y); swap(x, y);
cout<<x<<y<<endl; cout<<x<<y<<endl;
} }
void swap(int a, int b) void swap(int &a, int &b)
{ {
int t=a; int t=a;
a=b; a=b;
b=t; b=t;
cout<<a<<b; cout<<a<<b;
} }
Output: Output:
57 57
57 75
The pair of square brackets informs the compiler that the arguments array is an
array of numbers. It is not necessary to specify the size of the array here.
main()
{
int largest (float ary[], int n);
int temp[4]={12, 25, 2, 67};
cout<<”\n”<< largest(temp,4);
}
int largest(int ary[], int n)
{
int i;
int max;
max=ary[0];
for(i=1;i<n;i++)
if(max<ary[i])
max=ary[i];
return(max);
}
------------------------------------ ----------------------------------------
# Inline Functions:
C99 has added the keyword inline, which applies to functions.
By preceding a function declaration with inline, the compiler is instructed to expand
in line, rather than called.
A call to a function is replaced by a copy of the function body.
Definition of inline function:
inline int sum(int x, int y)
{
return x+y;
}
-------------------------------------------------------- -------------------
# Default arguments
C++ allows us to call a function without specifying all its arguments.
In such cases function assigns a default value to the parameter which does not have a
matching argument in the function call.
Default values are specified when the function is declared.
Consider the following function prototype:
float amount(int principal, int period, float rate=0.15);
We can call the above function by amount (5000, 7);. Here default value 0.15 will be
assigned to the third argument.
We must add default values from right to left.
int Add(int i, int j=5, int k=10); // legal
int Add(int i=2, int j=5, int k=10); // legal
int Add(int i=5, int j); // illegal
int Add(int i=0, int j, int k=10); // illegal
# Control Structures
Control Structures
One method of achieving the objective of an accurate, error-resistant and maintainable code
is to use one or any combination of the following three control structures:
1. Sequence structure (straight line)
2. Selection structure (branching)
3. Loop structure (iteration or repetition)
All program processing can be coded by using only these three logic structures.
The approach of using one or more of these basic control constructs in programming is
known as structured programming.
Using these three basic constructs, we may represent a function structure either in detail or
in summary form.
Selection /Branching Statements :
C++ provides statements that can alter the flow of a sequence of instructions. These statements are
called control statements.
These statements help to jump from one part of the program to another.
The control transfer may be conditional or unconditional.
Branching Statements are of following categories:
1. If Statement
2. The If else Statement
3. Nested if Statement
4. The else if ladder
5. Switch Statement
6. goto statement
if Statement:
The simplest form of the control statement is the If statement. It is very frequently used in decision
making and alter the flow of program execution.
The If structure has the following syntax
if (condition)
statement;
The statement is any valid C’ language statement and the condition is any valid C’ language
expression, frequently logical operators are used in the condition statement. The condition part
should not end with a semicolon. The command says if the condition is true then performs the
following statement or If the condition is false the computer skips the statement and moves on to
the next instruction in the program.
1. void main ()
2. {
3. int numbers; // declare the variables
4. cout<<"Type a number:”;
5. scanf ( &number”; // read the number from standard input
6. if (number < 0) // check whether the number is a negative no.
7. number = -number; // if it is -ve then convert it into +ve
8. cout<<"The absolute value is \n", number”; //
9. }
The if-else construct:
Another form of the control statement is the if-else statement. It is very frequently used as two
way decision making and alter the flow of program execution to choose one among the two sets of
statements.
The if statement may itself contain another if statement is known as nested if statement.
Syntax:
if (condition1)
{
if(condition2)
statement-1;
else
statement-2;
}
else
statement-3;
The if statement may be nested. One block of code will only be executed if two conditions are true.
Condition 1 is tested first then condition 2 is tested. The second if condition is nested in the first. The
second if condition is tested only when the first condition is true else the program flow will skip to
the corresponding else statement.
Sample Code
if (a > b)
if (a > c)
big = a;
else
big = c;
else
if (b > c)
big = b;
else
big = c;
cout<<”Largest value ”<< big;
When a series of many conditions have to be checked we may use the ladder else if statement which
takes the following general form.
if (condition1)
statement – 1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else if (condition)
statement n;
else
default
statement;
statement-x;
The conditions are evaluated from the top of the ladder to downwards. As soon on the true
condition is found, the statement associated with it is executed and the control is transferred to the
statement – x (skipping the rest of the ladder. When all the condition becomes false, the final else
containing the default statement will be executed.
Sample Code :
When the switch statement is executed the control expression is evaluated first and the value is
compared with the case label values in the given order. If the label matches with the value of the
expression then the control is transferred directly to the group of statements which follow the label.
If none of the statements matches then the statement against the default is executed. The default
statement is optional in switch statement in case if any default statement is not given and if none of
the condition matches then no action takes place in this case the control transfers to the next
statement of the switch statement.
Sample Code
1. char operator
2. ----
3. switch (operator)
4. {
5. case '+':
6. result = num1 + num2;
7. break ;
8. case '-':
9. result = num1 - num2;
10. break ;
11. case '*':
12. result = num1 * num2;
13. break ;
14. case '/':
15. if (num2 != 0)
16. result = num1 / num2;
17. else
18. {
19. cout<<"warning : division by zero \n”;
20. result = 0;
21. }
22. break ;
23. default:
24. cout<<"\n unknown operator”;
25. result = 0;
26. break ;
27. }
28. cout<< result”;
29. }
In the above program the break statement is needed after the case statement to break out of the
loop and prevent the program from executing other cases.
Syntax:
The goto requires a label in order to identify the place where the branch is to be made. A label is a
valid variable name followed by a colon.
The label: can be anywhere in the program either before or after thegoto label; statement.
}
Here the given test condition is evaluated and if the condition is true the body of the loop is
executed. After the execution of the body, the test condition is once again evaluated and if it is true,
the body is executed once again. This process continues as long as the test condition is true once the
condition is false the control is transferred out of the loop. On exit, the program continues with the
statements immediately after the body of the loop. The body of the loop may have one or more
statements. The braces are needed only if the body contain two are more statements
Example:
void main()
{
int i=0; //Declare and initialize the variables
----
while(I < = 10) // While statement with condition
{
cout<<“\t”,I”;
I++; //increment I to the next natural number.
}
}
The Do while statement:
The do while loop is an alternative iterative structure. The do while loop tests at the end of the loop
after executing the body of the loop. Since the body of the loop is executed first and then the loop
condition is checked we can be assured that the body of the loop is executed at least once.
while(test condition”;
Here the statements in the loop are executed, then test condition is evaluated. If the condition
expression is true then the body is executed again and this process continues till the conditional
expression becomes false. When the expression becomes false the loop terminates.
void main()
{
char inchar; // declaration of the character
do // start of the do loop
{
cout<<“Input Y or N”;
scanf(“%c”, &inchar”;
}
while(inchar!=’y’ && inchar != ‘n’”; // end of while loop
}
For Loop:
The for loop header consists of three essential elements ie: initialization, test condition and
increment.
The general form of the for loop is:
for (initialization; test condition; increment)
{
body of the loop
When the control enters for loop the variable used in for loop is initialized with the starting value
such as I=0,count=1. The value which was initialized is then checked with the given test condition.
The test condition is a relational expression, such as I < 5 that checks whether the given condition is
satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will
exit the loop. The body of the loop is entered only if the test condition is satisfied and after the
completion of the execution of the loop the control is transferred back to the increment part of the
loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++
and the new value of the control variable is again tested to check whether it satisfies the loop
condition. If the value of the control variable satisfies then the body of the loop is again executed.
The process goes on till the control variable fails to satisfy the condition.
For loop example program:
void main()
{
------
# Pointers:
Pointers are variables that contain memory addresses and are used to
access the data stored in the memory.
Pointers are used to return the multiple values from a function via
arguments
Each location has a unique address .
ptr = &x;
[&x is used to get the address of x]
Eg :
cout<<*ptr;
cout<< ptr;
cout<<&ptr;
Here , *ptr tells that the variable is a pointer .
Determining the address of a variable can be done with the help of the
operator
‘&’.
Ex: P = & x;
The ‘&’ operator can be used only with a simple variable or an array element.
If x is an array, then expression such as & X [0] and & X [i+3] are valid and
represents the addresses of 0th and (i+3)th elements of X.
To access the value of the variable using the pointer, the operator * usually
known as indirection operator is used.
quantity = 179;
p=&quantity;
n=*p;
Here in n=*p, *p returns the value of the variable quantity, because p contains
the address of quantity. Here * refers to the value at address.
Pointer Expressions:
Pointer variables can be used in expressions. If p1 and p2 are properly declared
and intialised pointer variables, then the following statements are valid.
sum=sum + *p1;
*p2=*p2 + 10;
Eg: p1= p1 + 4;
p2=p2+1;
p3=p3-2;
p1=p1-p2;
Imp: Pointers variables are not used in multiplication and division and two
pointers cannot be added.
POINTERS TO FUNCTIONS :
A function , like a variable , has a type and an address location in the
memory . It is therefore , possible to declare a pointer to a function ,
which can be used as an argument in another function .
A pointer to a function is declared as follows :
type (*fptr) ();
This tells the compiler that fptr is a pointer to a function , which
returns type value . the value parentheses around *fptr are necessary
. remember that a statement like
type *gptr();
Would declare gptr as a function returning a pointer to type
We can make a function pointer to point to a specific function by
simply assigning the name of the function to the pointer . for
example , the statements
double mul (int, int);
double (*p1) ();
p1 = mul;
Declare p1 as a pointer to a function and mul as a function and then
make p1 to point to the function mul. To call the function mul , we
may now use the pointer p1 with the list of parameters. That is ,
(*p1)(x,y) /*function call*/
Is equivalent to
mul(x,y);
POINTERS AND STRUCTURES :
The name of a structure stands for the addresses of the 0 th element .
consider the following declaration :
struct inventory
{
char name[30];
int number ;
float price ;
} product [2] , *ptr ;
Its members can be accesed using the following notation
ptr->name
ptr->number
ptr->price
The symbol ‘->’ is called arrow operator ( also known as “member
selection operator”). ptr -> is simply another way of writing
product[0].
# Search Algorithms
• A search algorithm is a method of locating a specific item of information in a larger collection
of data. Commonly used two algorithms for searching the contents of an array.
The Linear Search
• This is a very simple algorithm.
• It uses a loop to sequentially step through an array, starting with the first element.
• It compares each element with the value being searched for and stops when that value is
found or the end of the array is reached.
Efficiency of the Linear Search
• The advantage is its simplicity.
– It is easy to understand
– Easy to implement
– Does not require the array to be in order
• The disadvantage is its inefficiency
– If there are 20,000 items in the array and the search is in the 19,999 th element, it is
required to search through the entire list.
Linear search method:
cout<<"Enter the number to be search : ";
cin>>num;
for(i=0; i<n; i++)
{
if(arr[i]==num)
{
c=1;
pos=i+1;
break;
}
}
if(c==0)
{
cout<<"Number not found..!!";
}
else
{
cout<<num<<" found at position "<<pos;
}
Binary Search
• The binary search is much more efficient than the linear search.
• It requires the list to be in order.
• The algorithm starts searching with the middle element.
– If the item is less than the middle element, it starts over searching the first half of
the list.
– If the item is greater than the middle element, the search starts over starting with
the middle element in the second half of the list.
– It then continues halving the list until the item is found.
Efficiency of the Binary Search
• Much more efficient than the linear search.
Binary search method :
int BinarySearch(int a[], int start, int end, int item, int iter)
{
int i, mid;
iter++;
// Assigning middle of the array.
mid = start + (end-start+1)/2;
// If value is less than value at start index more than end index then item is
//not in the array.
if(item > a[end] || item < a[start] || mid == end)
{
cout<<"\nNot found";
return -1;
}
// Return the mid index.
else if(item == a[mid])
{
return mid;
}
// Return the start index.
else if(item == a[start])
{
return start;
}
// Return the end index.
else if(item == a[end])
{
return end;
}
// According to the item value choose the partion to proceed further.
else if(item > a[mid])
BinarySearch(a, mid, 19, item, iter);
else
BinarySearch(a, start, mid, item, iter);
}
Sorting Algorithms
• Sorting algorithms are used to arrange random data into some order
The Bubble Sort
• An easy way to arrange data in ascending or descending order.
• Pseudocode:
Do
Set count variable to 0
For count is set to each subscript in Array from 0 to the next-to-last subscript
If array[count] is greater than array[count+1]
swap them
set swap flag to true
end if
End for
While any elements have been swapped.
code:
void sortArray(int array[], int elems)
{
int swap, temp;
do
{
swap = 0;
for (int count = 0; count < (elems - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = 1;
}
}
} while (swap != 0);
}
Function-2 Function-3
Function-1 Local Data Local Data
Local Data
Object Oriented Programming
Emphasis is on data rather than procedure.
Programs are divided into what are known as objects.
Data structures are designed such that objects can be declared
Functions that operate on the data of an object are tied together in the data structure
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through functions.
New data and functions can be easily added whenever necessary.
Employs bottom-up approach in program design
Object A
Data
Function
Object B
communication Data
Function
Object C
Data
Function
Benefits of OOPs
Through inheritance, we can eliminate redundant code extend the use of existing Classes.
We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
The principle of data hiding helps the programmer to build secure program that can not be
invaded by code in other parts of a programs.
It is possible to have multiple instances of an object to co-exist without any interference.
It is possible to map object in the problem domain to those in the program.
It is easy to partition the work in a project based on objects.
The data-centered design approach enables us to capture more detail of a model can
implemental form.
Object-oriented system can be easily upgraded from small to large system.
Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
Software complexity can be easily managed.
OOP Languages
The languages to claim that they are object-oriented they need to support several of the
OOP concepts. Depending upon the features they support, they can be classified into the
following two categories:
1. Object-based programming languages,
2. Object-oriented programming languages.
Languages that support programming with objects are said to the objects-based
programming languages. Major feature that are required for object based programming are:
Data encapsulation
Data hiding and access mechanisms
Automatic initialization and clear-up of objects
Operator overloading
They do not support inheritance and dynamic binding. Ada is a typical object-based programming
language.
Object-oriented programming language incorporates all of object-based programming
features along with two additional features, namely, inheritance and dynamic binding.
Object-oriented programming can therefore be characterized by the following statements:
Object-based features + inheritance + dynamic binding .
Applications of OOP
The promising areas of application of OOP include:
Real-time system
Simulation and modelling
Object-oriented data bases
Hypertext, Hypermedia, and expert text
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAM/CAD systems