0% found this document useful (0 votes)
128 views31 pages

BSC C++ Unit I

The document discusses various topics related to C++ including tokens, data types, operators, and functions. It provides definitions and examples of: - Tokens in C++ like keywords, identifiers, constants, and operators. Keywords are reserved words and identifiers are user-defined names. Constants can be numeric, character, or string values. - Built-in data types in C++ including integer, character, floating-point, double, and void, along with their sizes and ranges. Derived types include arrays and pointers. - Operators in C++ which are classified into categories like arithmetic, relational, logical, assignment, increment/decrement, conditional, and bitwise operators. New operators introduced
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views31 pages

BSC C++ Unit I

The document discusses various topics related to C++ including tokens, data types, operators, and functions. It provides definitions and examples of: - Tokens in C++ like keywords, identifiers, constants, and operators. Keywords are reserved words and identifiers are user-defined names. Constants can be numeric, character, or string values. - Built-in data types in C++ including integer, character, floating-point, double, and void, along with their sizes and ranges. Derived types include arrays and pointers. - Operators in C++ which are classified into categories like arithmetic, relational, logical, assignment, increment/decrement, conditional, and bitwise operators. New operators introduced
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to C++: Applications, Example Programs, Tokens, Data Types, Operators, Expressions,

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

1. Built-in/Fundamental Data Types


All C++ compilers support 5 fundamental data types, namely integer (int), character
(char), floating point (float), double-precision floating point (double) and void.
2. Derived Data Types
Data types that are derived from fundamental data types are called derived data types.
Derived data types do not create a new data type; instead, they add some functionality to
the basic data types. They are – Arrays, functions, Pointers and reference.
3. User Defined Data Types
User defined data type is used to create new data types. Different user defined data types
are: structure, union, enumeration and class.
Fundamental Data Types
All C++ compilers support 5 fundamental data types, namely integer (int), character (char), floating
point (float), double-precision floating point (double) and void.
The size and range of each data type is given in the table below
Name of data type key word RANGE OF VALUES
1. Integer int -128 to 127

2 Character char -32768 to +32767

3. Floating Point float 3.4 e-38 to 3.4 e+38

4. Double precision floating point double 1.7 e-308 to 1.7 e+308

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

Size and Range of Data Types on 16 bit machine.


type SIZE (Bits) Range

Char or Signed Char 8 -128 to 127

Unsigned Char 8 0 to 255

Int or Signed int 16 -32768 to 32767

Unsigned int 16 0 to 65535

Short int or Signed short int 8 -128 to 127

Unsigned short int 8 0 to 255

Long int or signed long int 32 -2147483648 to 2147483647

Unsigned long int 32 0 to 4294967295

Float 32 3.4 e-38 to 3.4 e+38

Double 64 1.7e-308 to 1.7e+308

Long Double 80 3.4 e-4932 to 3.4 e+4932

# 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

In addition, C++ has introduced some new operators.


<< the insertion operator
>> extraction operator
::     Scope resolution operator
::*    Pointer-to-member declarator
->*  Pointer-to-member operator
.*    Pointer-to-member operator
delete     Memory release operator
endl Line feed operator
new        Memory allocation operator
setw        Field width operator

(1) Arithmetic operators:


All the basic arithmetic operations can be carried out in C. Both unary and binary operations are
available in C++ language. Unary operations operate on a singe operand, therefore the number 5
when operated by unary – will have the value –5.

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.

(3) Logical operators:


has the following logical operators; they compare or evaluate logical and relational expressions.
Operato Meaning
r
&& Logical AND
|| Logical OR
! Logical NOT

Logical AND (&&)


This operator is used to evaluate 2 conditions or expressions with relational operators
simultaneously. If both the expressions to the left and to the right of the logical operator is true then
the whole compound expression is true.
Example:

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

5. Increment and Decrement Operators


The increment and decrement operators are one of the unary operators which are very useful in C+
+language. They are extensively used in for and while loops.
The syntax of the operators is given below
1. ++ variable name
2. Variable name++
3. – –variable name
4. Variable name– –

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.

Explicit Type Casting Operator


 Type casting operators allow us to convert a data of a given type to another. There are two
ways to do this in C++.

(type-name) expression // C notation

type-name (expression) // C++ notation

 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.

#Output and Input Statement in C++

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.

Difference between structure and union

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:

data-type & reference-name = variable-name


 Example:
float total =100;
float &sum = total;
o total is a float type variable that has already been declared; sum is the alternative
name declared to represent the variable total. Both the variables refer to the same
data object in the memory. Now, the statements
cout<< total; and
cout<<sum;
o both print the value 100. The statement total = total + 10; will change the value of
both total and sum to 110. Likewise, the assignemnt sum = 0;
o will change the value of both the variables to zero.
 A reference variable must be initialized at the time of declaration. This establishes the
correspondence between the reference and the data object which it names. It is important
to note that the initialization of a reference variable is completely different from assignment
to it.
 C++ assigns additional meaning to the symbol &. Here, & is not an address operator. The
notation float & means reference to float. Other examples are:
int n[10];
int & x = n[10]; x is alias for n[10]
initialize reference to a
char & a = '\n';
literal

 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

# Passing arrays to functions:


One dimensional array :
To pass a one dimensional array to a called function, it is sufficient to list the name of
the array(without any subscript) and the size of the array as argument.
For example

int ary[10], n; /*array declaration*/


----
----
largest(arry, n); /* function call st. - passing array as actual argument*/
The function calling statement, largest (ary, n) , Will pass the whole array, arry to the
called function. The called function expecting this call must be approximately
defined.
The function header of largest is:

int largest(int ary[], int size) /* function definition. --- array as


formal argument*/

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);
}

Consider a problem of finding the largest value in an array of elements.


When the function call largest( temp,4) is made, the values of all elements of array temp
become the corresponding elements of array, ary in the called function. The largest function
finds the largest value in the array and returns the result to the main.
By passing the array name, we are in fact passing the address of the array to the called
function. The array in the called function now refers to the same array stored in the memory
that is created from the main. Therefore, any changes made in the array in the called function
will be reflected in the original array of the main.
Passing address of parameters to the functions is referred to as pass by address.

------------------------------------ ----------------------------------------
# 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

Selection Sequence Loop

if else switch Do-while while, for

 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 syntax of the If else construct is as follows:-


 If (condition)
  Statement 1;
else
  Statement 2;
If the result of the condition is true, then program statement 1 is executed, otherwise program
statement 2 will be executed. If any case either program statement 1 is executed or program
statement 2 is executed but not both.
Example:
if (num < 0)   // check whether number is less than zero
    cout<<"The number is negative”;  
else  
     cout<<"The number is positive”;
Nested if Statement:

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;   

The else -if Ladder:

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 :

1.   if (marks <= 100 && marks >= 70)


2.            cout<<"\n Distinction";  
3.      else if (marks >= 60)
4.            cout<<"\n First class";
5.      else if (marks >= 50)
6.            cout<<"\n second class";
7.      else if (marks >= 35)
8.            cout<<"\n pass class";
9.      else
10.                cout<<"Fail";

The Switch Statement:

The switch-case statement is a multi-way decision making statement.The switch statement allows a


program to select one set of statements for execution out of a multiple alternative sets. During the
execution of the switch statement only one of the possible sets of statements will be executed the
remaining sets of statements will be skipped.
The value of the expressions in a switch-case statement must have to be an ordinal type i.e. integer,
char, short, long, etc. Double and Float are not allowed.

The general format:


switch( expression )
{
case  case-label-value1: statements1;
[case  case-label-value2:
statements2;]
[case  case-label-value3:
statements3;]
[default : statements4;]
}

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. 

The GOTO statement:


The goto statement is simple statement used to transfer the program control unconditionally from
one statement to another statement. 

Syntax:

Forward Branching       Backward Branching:  


:     
     label;
goto label;      …………
…………      …………
…………      …………
…………      goto        
Label;        label;
………..;  

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.

         main () //start of main


{
      int n, sum = 0, i = 0 ;
     cout<<"Enter a number”;
      scanf ( &n) ;
     loop:
        i++ ;
       sum += i ;
      if (i < n) goto loop ;
      cout<<"\n sum of natural numbers = ", n, sum”;
 }
 
During running of a program a statement
                              if (i < n) goto loop;
the flow of control will jump to the statement immediately following the label loop:
     If the label: is before the statement goto label; a loop will be formed and some statements will be
executed repeatedly. Such a jump is known as a backward jump. On the other hand, if the label is
placed after the goto label; some statements will be skipped and the jump is known as a forward
jump.
A goto  is often used at the end of a program to direct the control to go to the input statement, to
read further data.

Decision Making – Looping:


During looping a set of statements are executed until some conditions for termination of the loop is
encountered. A program loop therefore consists of two segments one known as body of the loop
and other is the control statement. The control statement tests certain conditions and then directs
the repeated execution of the statements contained in the body of the loop.
In general looping process would include the following four steps
1. Setting and initialization of a counter
2. Execution of the statements in the loop
3. Test condition for the execution of the loop to continue or terminate.
4. Incrementing the counter.
 
The While Statement:
 
The simplest of all looping structure in C++is the while statement.
 
The general format of the while statement is:
while (test condition)
{
body of the loop;

}
  
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.
 

The syntax of the do while loop is:


do
{
statement;
}

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()
{
------

for (I = 0; I < 5; I++)


{
      -------
       if(num < 0)
         {
           cout<<“You have entered a negative number”;
           continue;       // starts with the beginning of the loop
         }                  // end of if
       sum+=num;
 }                 //end of for loop
  ------
} // end of the program.
 
# The Break Statement:
 
The break statement allows us to exit from inside the loop. A break statement provides an early exit
from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to
be exited immediately.
 
SYNTAX: break;
 
Example program to illustrate the use of break statement.
   char operator
        ----
       switch (operator)
      {
           case '+':
            result = num1 + num2;
            break ;    
       case '-':
            result = num1 - num2;
            break ;
         
          default:
             cout<<"\n unknown operator”;
             result = 0;
              break ;
      }
     cout<< result;
 
 
# Continue statement:
 
During loop operations it may be necessary to skip a part of the body of the loop under certain
conditions and begin the next iteration. The continue statement causes the loop to begin with the
next iteration.
 The format of the continue statement is simply:
 
 
Consider the continue; following program that finds the sum of five positive integers. If a
negative number is entered, the sum is not performed since the remaining
part of the loop is skipped using continue statement.
  
void main()
{
------
 
for (I = 0; I < 5; I++)
{
      -------
       if(num < 0)
         {
           cout<<“You have entered a negative number”;
           continue;       // starts with the beginning of the loop
         }                  // end of if
       sum+=num;
 }                 //end of for loop
  ------
} // end of the program.

# 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 .

Declaring , Accessing and Initialising Pointer Variables


Declaration Syntax:
data_type *ptr_name;
int * ptr; /* * ptr is a pointer variable pointing to an integer values*/
int x ;
x = 10;
“*” indicates that pointer variable ‘ptr’ contains address of variables .
 the address should contain only integer type values .

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 .

 ptr tells the name of memory location and points to a variable .


 &ptr tells us the address of variable .

Determining the address of a variable can be done with the help of the
operator

‘&’.

Ex: P = & x;

Would assign the address of x (the location of quantity) to the variable


p. The ‘&’ operator can be referred as ‘address of’.

The ‘&’ operator can be used only with a simple variable or an array element.

The following are illegal use of an address operator.

(1) int x[10];


&x (pointing at array names).
(2) &(x+y) (pointing at expressions).

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.

Accessing a variable through its pointer

To access the value of the variable using the pointer, the operator * usually
known as indirection operator is used.

Eg: int quantity, *p, n;

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.

y=*p1 * *p2; //same as (*p1) * (*p2)

sum=sum + *p1;

*p2=*p2 + 10;

C allows us to add integers to or subtract integers from pointers, as well as to


subtract one pointer from another if they belong to same datatype.

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 AND ARRAYS :


 An Array name can be assigned to the pointer variable, because it
contains the address of the first element.
 When an array is declared the compiler allocates certain base
address and storage in memory locations .
 The base address is the location of the first element in an array .
 For example : int x[5] = {1,2,3,4,5};
 An array ‘x’ with size of 5 elements is declared and will be stored as
follows .
 Let us assume that the base address of ‘x’ is 1000 then , the
remaining elements will be stored as follows :
x =& x [1] = 1000+1 (no.of bytes required by
the ‘int’ type )
= 1000+ 1(2) = 1002
If we declare ‘p’ as an integer pointer , as
int *p;
p = x is equal to
p = & x [0];  p=& x [0] = 1000
P= & x [1] = 1002
P= & x [2]= 1004
P=& x [3] = 1006
P = & x [4] = 1008

POINTERS AND CHARACTERS :


 Strings can be treated as character arrays .
 The compiler automatically inserts the null character ‘\0’ at the end of
the string .
 Strings can be created using pointer variables .
Eg : char *str = “apple” ;

The pointer ‘str’ points towards the first character . Assignment


operator is used for giving values .
char *string1;
String1 = “apple “;
 The above statement is not a string copy because the variable ‘string1’ is
a pointer not a string .

POINTERS AS FUNCTION ARGUMENTS :

 We can pass the address of a variable as an argument to a function in


the normal fashion.
 When we pass addresses to a function , the parameters receiving the
addresses should be pointers . the process of calling a function using
pointers to pass the address of variables is known as “call by reference” .
 The function which is called by ‘reference’ can change the value of the
variable used in the call .
Consider the following code :
main()
{
int x ;
x=20;
change(&x); /*call by reference or address*/
cout<<“\n”<<x;
}
change(int *p)
{
*p = *p + 10 ;
}
 When the function change() is called , the address of the variable x is
passed into the function change() . Inside change() , the variable p is
declared as a pointer and therefore p is the address of variable x .
 Thus , call by reference provides a mechanism by which the function can
change the stored values in the calling function .
 Note that this mechanism is also known as “call by address” or “pass by
pointers” .
 Rules :
1) The function parameters are declared as pointers .
2) The dereferenced pointers are used in the function body.
3) When the function is called the addresses are passed as actual
arguments .

FUNCTION RETURNING POINTERS :


We can force a function to return a pointer to the calling function .
consider the following code :
int *larger (int * , int *); /*prototype*/
main ( )
{
int a = 10;
int b = 20;
int *p;
p = larger (&a , &b);
cout<< *p; /*function call */
}
int *larger (int *x , int *y)
{
if (*x>*y)
return (x); /*address of a */
else
return (y); /*address of b */
}
 The function larger receives the addresss of the variable a and b ,
decides which one is larger using the pointers x and y and then
returns the address of its location . The returned value is then
assigned to the pointer variable p in the calling function . In this case ,
the address of b is returned and assigned to p and therefore the
output will be the value of b , namely 20 .
 The address returned must be the address of a variable in the calling
function.

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);
}

The Selection Sort


• The bubble sort is inefficient for large arrays because items only move by one element at a
time.
• The selection sort moves items immediately to their final position in the array so it makes
fewer exchanges.
Selection Sort Pseudocode:
For Start is set to each subscript in Array from 0 through the next-to-last subscript
Set Index variable to Start
Set minIndex variable to Start
Set minValue variable to array[Start]
For Index is set to each subscript in Array from Start+1 through the next-to-last subscript
If array[Index] is less than minValue
Set minValue to array[Index]
Set minIndex to Index
End if
Increment Index
End For
Set array[minIndex] to array[Start]
Set array[Start] to minValue
End For
Code:
void selectionSort(int array[], int elems)
{
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (elems - 1); startScan++)
{ minIndex = startScan;
minValue = array[startScan];
for(int index = startScan + 1; index < elems; index++)
{ if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
Inline functions:
• Member functions defined inside the class declaration are called inline functions
• Only very short functions, like the one below, should be inline functions
int getSide()
{ return side; }
Example:
class Square
{
private:
int side;
public:
void setSide(int s) inline functions
{ side = s; }
int getSide()
{ return side; }
};

Procedural and Object-Oriented Programming


Procedural Oriented Programming
 Conventional programming, using high level languages such as COBOL, FORTRAN and C, is
commonly known as procedure-oriented programming (POP).
 In the procedure-oriented approach, the problem is viewed as a sequence of things to be
done such as reading, calculating and printing. A number of functions are written to
accomplish these tasks.
 The primary focus is on functions
 emphasis is on algorithms
 Large programs are divided into smaller ones called functions
 Most of the functions share data
 data move freely around the system from function to function
 functions transform data from one form to another
 Employs top-down approach in program design

Global Data Global Data

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

Basic Concepts of Object-Oriented Programming


Objects
Objects are the basic runtime entities in an object oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to handle.
Class
Object contains data, and code to manipulate that data. The entire set of data and code of an object
can be made a user-defined data type with the help of a class.
Data Encapsulation
The wrapping up of data and functions into a single unit is known as encapsulation.
The data is not accessible to the outside world, only those function which are wrapped in the
can access it.
These functions provide the interface between the object’s data and the program.
This insulation of the data from direct access by the program is called data hiding or
information hiding.
Data Abstraction
Abstraction refers to the act of representing essential features without including the
background details or explanations.
Since classes use the concept of data abstraction, they are known as Abstract Data Types
(ADT).
Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
In OOP, the concept of inheritance provides the idea of reusability. This means we can add
additional features to an existing class without modifying it.
Polymorphism
Polymorphism, a Greek term means ability to take more than one form.
An operation may exhibit different behaviours in different instances. The behaviour depends
upon the type of data used in the operation.
For example consider the operation of addition for two numbers; the operation will generate a
sum. If the operands are string then the operation would produce a third string by
concatenation.
The process of making an operator to exhibit different behaviours in different instances is known
operator overloading.

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

You might also like