Unit 1
Unit 1
Introduction
The main pitfall with standard C has been identified as the lack of facilities for data
abstraction. With the emergence of more abstract and modular languages like Modula-2 and
Ada and Object-oriented languages like Small-Talk, BJARNE STROUSRUP at Bells Lab
was motivated to develop C++ by upgrading C with appropriate mechanisms to create object
like abstract data structures. The introduction of the class mechanism in C++ mainly
provides the base for implementing abstract data types to suit object-oriented programming.
The C++ language is thus considered as the superset of the standard C.
Applications of C++
C++ is a versatile language for handling very large programs; it is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real life applications systems.
• Since C++ allow us to create hierarchy related objects, we can build special object-oriented
libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
• It is expected that C++ will replace C as a general-purpose language in the near future.
Our first C++ program is a “Hello World!” program that prints the text “Hello World!” as
the output on the screen.
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello World!";
return0;
}
1 #include <iostream>
2 using namespace std
3 ;
1
4 int main() { }
5 cout<< “Hello World!”;
6 return 0;
This statement includes the header file into the application so that we are able to use the
operations included in them.
What is iostream?
What is #include?
The #include includesiostream file into the program. This ensures that now we are
able to use the operations, iostream operations (like: taking input from user,
displaying output on the screen), in the program.
The statement tells that we are “using” the “namespace” “std” in our program.
We use the namespace std to make it easier to reference operations included in that
namespace.
If we hadn’t used the namespace, we’d have to write std::cout instead of cout. This tells the
compiler that every cout is actually std::cout.
What’s a namespace?
It’s a region where our code resides. It limits or expands the scope of our code to one or
more files.
Like two persons can have the same name, variables and functions in C++ can have same
names as well. The use of namespace is to avoid the confusion of which variables/functions
we are referencing to.
What is std?
It is the main function of the program. The code inside { } is called the body and is executed
first when we run our C++ program.
2
This statement prints “Hello World!” onto the output screen.
The cout is an object of standard output stream. It outputs/prints the data after << , i.e.
Hello World!into a stream (in this case, the output screen).
What is a stream?
Stream is basically a sequence of objects, usually bytes. It can describe files, input/output
terminal, sockets, etc.
What is <<?
<< is the insertion operator used to write formatted data into the stream.
This is called a “return” statement. It isn’t mandatory to return anything from the main()
function but is rather a convention. If not return, the compiler returns a status
automatically.
It denotes Exit status of the application that basically tells system “The program worked
fine.”
TOKENS:
Tokens are the basic lexical building blocks of source code. In other words, tokens
are one or more symbols understood by the compiler that help it interpret the
program code.
Characters are combined into tokens according to the rules of the programming
language.
The compiler checks the tokens so that they can be formed into legal strings
according to the syntax of the language.
1. Identifiers:
It is a sequence of characters invented by the programmer to identify or name a
specific object, and the name is formed by a sequence of letters, digits, and
underscores.
2. Keywords:
3
These are explicitly reserved words that have a strict meaning as individual tokens to
the compiler. They cannot be redefined or used in other contexts. Use of variable
names with the same name as any of the keywords will cause a compiler error.
3. Operators:
These are tokens used to indicate an action to be taken (usually arithmetic
operations, logical operations, bit operations, and assignment operations). Operators
can be simple operators (a single character token) or compound operators (two or
more character tokens).
4. Separators:
These are tokens used to separate other tokens. Two common kinds of separators
are indicators of an end of an instruction and separators used for grouping.
5. Constants:
It is an entity that does not change.
Identifiers:
Identifier or name is a sequence of characters created by the programmer to identify
or name a specific object.
In C++, variables, arrays, functions, and labels are named. Describing them may
help to learn something about the character of the language since they are elements
that C++ permits the programmer to define and manipulate.
4
job_number,
and tool_4.
Special characters :
All characters other than listed as alphabets, numerals and underscore, are special
characters.
Keywords
Keywords are also identifiers but cannot be user defined since they are reserved
words.
Keywords in C++
Variables:
As you probably know, a variable is a named location in memory that is used to hold
a value that may be modified by the program. All variables must be declared before
they can be used. The general form of a declaration is
typevariable_list;
Here, type must be a valid data type plus any modifiers, and variable_listmay consist
of one or more identifier names separated by commas. Here are some declarations:
inti, j, l;
shortintsi;
unsignedintui;
doublebalance, profit, loss;
Remember, in C/C++ the name of a variable has nothing to do with its type.
5
Where Variables Are Declared:
Variables are declared in three basic places: inside functions, in the definition of
function parameters, and outside of all functions. These are local variables,
formal parameters, and global variables.
Q) Explain about constants, variables in c++( for variables take above content
briefly)
Constants
Constants refer to fixed values that the program may not alter. Constants can be of
any of the basic data types. The way each constant is represented depends upon its
type. Constants are also called literals. Character constants are enclosed between
single quotes.
For example 'a' and '%' are both character constants.
Floating-point constants require the decimal point followed by the number's fractional
component. For example, 11.123 is a floating-point constant.
C/C++ also allows you to use scientific notation for floating-point numbers.
String Constants
6
C/C++ supports one other type of constant: the string.
A string is a set of characters enclosed in double quotes.
For example, "this is a test" is a string.
Code Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote
\0 Null
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
\N Octal constant (where N is an octal constant)
\xN Hexadecimal constant (where N is a hexadecimal constant)
Data Types
What is a data type?
When we wish to store data in a C++ program, such as a whole number or a
character, we have to tell the compiler which type of data we want to store. The data
type will have characteristics such as the range of values that can be stored and the
operations that can be performed on variables of that type.
Q). Write about data types in c++. (in this case, cover total topic briefly)
Data types in C++ can be classified under various categories as shown in Fig.
7
Basic Data Types (Built-in Data Types) or Primary data types:
The Six Basic Data Types:
There are six atomic data types in C++: character, integer, floating-point, double
floating-point, boolean, and novalue (char, int, float, double, bool, and void,
respectively).
8
bool data type :
bool data type can store two value only 0 or 1. 0 for false& 1 for true. Any nonzero value is
also considered as true value. If we declare bool variable az = 1212313; it storesaz = 1 or az
= true; It shows 0 when it is false or value is 0.
Functions:
Functions are the building blocks of C and C++ and the place where all program
activity occurs.
A function is a group of statements that is executed when it is called from some point
of the program. The following is its format:
where:
• type is the data type specifier of the data returned by the function.
• name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data type
specifier followed by an identifier, like any regular variable declaration (for example:
int x) and which acts within the function as a regular local variable. They allow to
pass arguments to the function when it is called. The different parameters are
separated by commas.
• statements is the function's body. It is a block of statements surrounded by
braces { }.
9
Pointers:
A pointeris a variable that holds a memory address. This address is the location of
another object (typically another variable) in memory.
For example, if one variable contains the address of another variable, the first
variable is said to point to the second.
Reference variables
The '&'operator is used to reference an object. When using this operator on an
object, you are provided with a pointer to that object. This new pointer can be used
as a parameter or be assigned to a variable.
programming.
10
OPERATORS IN C++
An operator is a symbol that tells the compiler to perform specific mathematical or
logicalmanipulations.
C++ is rich in built-in operators and provides the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators:
There are following arithmetic operators supported by C++ language:
Relational Operators:
There are following relational operators supported by C++ language
11
Assume variable A holds 10 and variable B holds 20, then:
> Checks if the value of left operand isgreater thanA >B is not true.
the value of right operand, ifyes then condition
becomes true.
>= Checks if the value of left operand isgreater than A >= B is not true.
or equal to the value of rightoperand, if yes then
condition becomestrue.
Logical Operators:
There are following logical operators supported by C++ language
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation.
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
12
A|B =0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table.
Assumevariable A holds 60 and variable B holds 13, then:
Operator Description Example
& Binary AND Operator copies a bit A & B will give 12 which is 0000 1100
to theresult if it exists in both operands.
^ Binary XOR Operator copies the bit ABwill give 49 which is 0011 0001
if it isset in one operand but not both.
~ Binary Ones Complement Operator is A will give -61 which is 1100 0011 in
unary and has the effect of 'flipping' bits. 2's complement form due to a signed
binary number.
<< Binary Left Shift Operator. A << 2 will give 240 which is 1111 0000
The leftoperands value is moved left
by thenumber of bits specified by
the rightoperand.
>> Binary Right Shift Operator. The left A>> 2 will give 15 which is 0000 1111
operands value is moved right by the
number of bits specified by the right
operand.
Assignment Operators:
There are following assignment operators supported by C++ language:
Operator Description
sizeof sizeof operator returns the size of a variable. For example,
sizeofa,where a is integer, will return 4.
Here, operators with the highest precedence appear at the top of the table, those
with the lowestappear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
EXPRESSIONS IN C++
"Expression in C++ is a form when we combine operands (variables and constant)
and C++ OPERATORS."
1 Constant Expressions:
Constant Expressions consist of only constant values, Examples:
15
20+15/2.0
‘X’
2. Arithmetic Expressions:
"An expression in which arithmetic operators are used is called arithmetic
expression".
For example an arithmetic expression is look just like that a+b=5
for example:
a=5 , b=5
a*b=25 ,
a/b=1 ,
a+b=10 ,
a-b=0
15
a=10.0 , b=5.0
a*b=50.0
a/b=2.0
a+b=15.0
a-b=5.0
For example:
a=10 , b=5.0
a*b=50.0,
a/b=2.0,
a+b=15.0,
a-b=5.0
3. Relational expressions
"A relational operator with constants and variables makes relational expression or An
expressions in which relational operators are use is called relational expression."
4Logical Expression
"A Logical operator with constants and variables makes logical expression or An
expressions in which logical operators are use is called logical expression."
Examples using logical operators
(i< 10) && (j > 0)
((x + y) <= 15) || (i == 5)
!((i >= 10) || (j <= 0))
(i< 10) && 0
return 0;
}
The header file iostream must be included to make use of the input/output (cin/cout)
operators.
#include<iostream>
using namespace std;
int main()
{
cout<< "Hello World!";
return 0;
}
Note:the double quotes around Hello World (because it is a constant string of
characters.)
#include<iostream>
using namespace std;
int main()
{
char MY_CHAR;
cout<< "Press a character and press return: ";
cin>> MY_CHAR;
cout<< MY_CHAR;
return 0;
}
17
Control Structures(Decision Making):
Q) What are various control structures in C++ (or) write about control flow
statements.
There are three types of control structures:
1) Sequence Structure (straight line)
2) Selection Structure (branching)
3) Loop structure (iteration or repetition)
The following figure shows how these structures are implemented using one-entry,
one-exit concept.
18
Loop structure (iteration or repetition) (or) Loop control statements
1) forLoop
2) whileLoop
3) do-while Loop
Jumping statements:
1) gotoStatement
2) breakStatement
3) continueStatement
Syntax:
if (Condition or test expression)
Statement;
Rest of the program;
OR
if (Condition or test expression)
{
Statements;
}
Rest of the program
19
if((m-n)= =0)
cout<<“\n two numbers are equal”;
return 0;
}
Example 2:
#include <iostream>
using namespace std;
int main ()
{
int a = 10; / / local variable definition
if( a < 20 ) // check the boolean condition using if statement
{
cout<<"a is less than 20\n"; // if condition is true then print the following
}
cout<<"value of a is ”<<a;
return 0;
}
Syntax:
if ( Test Expression or Condition )
{
/*true block (or) if block */
Statements;
}
else
{
/* false block (or) else block */
Statements;
}
20
Output:
Run 1:
Enter a number: 24
The given number is EVEN
Run 2:
/* that means one more time we run the program */
Enter a number: 17
The given number is ODD
Syntax:
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement -4;
}
} /* end of outer if-else */
- If Test Condition-1 is true then enter into outer if block, and it checks Test
Condition-2 if it is true then Statement-1 executed if it is false then else block
executed i.e Statement-2.
- If Test Condition -1 is false then it skips the outer if block and it goes to else
block and Test Condition-3 checks if it is true then Statement-3 executed, else
Statement-4 executed.
Example: Program to select and print the largest of the three float numbers using
nested “if-else” statements.
# include<iostream>
using namespace std;
int main( )
{
21
float a,b,c;
cout<<“Enter Three Values:”;
cin>>a>>b>>c;
Output:
Run 1:
Enter three values: 9.12 5.34 3.87
Largest Value is: 9.12
Run 2:
Enter three values: 45.781 78.34 145.86
Largest Value is: 145.86
Syntax:
if (Test Condition -1)
Statement -1;
else if ( Test Condition -2)
Statement -2;
else if ( Test Condition -3)
Statement -3;
:
:
:
: else if ( Test Condition –n)
Statement –n;
else
default statement;
22
- The above construction is known as else if ladders.
- The conditions are evaluated from top to bottom.
- As soon as a true condition is found, the statement associated with it is
executed and the control is transferred to the Rest of the Program
Statement–X (skipping rest of the ladder).
- When all the "n conditions become false, then the final else containing the
default statement will be executed.
Write a program to read three numbers and find the largest one by using “else-if”
ladder.
# include<iostream>
using namespace std;
int main( )
{
int a, b, c;
cout<<“Enter 1st number: \n”;
cin>>a;
cout<<“Enter 2nd number: \n”;
cin>>b;
cout<<“Enter 3rd number: \n”;
cin>>c;
Output:
Enter 1st number: 52
Enter 2nd number: 74
Enter 3rd number: 90
Highest Numbers is: 90
23
(5) The “switch-case” Statement:
- The switch statement causes a particular group of statements to be chosen
from several available groups.
- The selection is based upon the current value of an expression which is
included within the switch statement.
- The switch statement is a multi-way branch statement.
- In a program if there is a possibility to make a choice from a number of
options, this structured selected is useful.
- The switch statement requires only one argument of intorchar data type,
which is checked with number of case options.
- The switch statement evaluates expression and then looks for its value
among the case constants.
- If the value matches with case constant, then that particular case statement is
executed. If no one case constant not matched then default is executed.
- Here switch, case and default are reserved words or keywords.
- Every case statement terminates with colon “:”.
- In switch each case block should end with break statement, i.e.
Syntax:
switch(variable or expression)
{
case Constantvalue-1: Block -1;
(or)
Statement-1;
break;
case Constantvalue-2: Block -2;
(or)
Statement-2;
break;
________
________
24
case Constantvalue-n: Block -n;
(or)
Statement-n;
break;
Flow Chart:
# include<iostream>
using namespace std;
int main( )
{
int a, b, c, ch;
cout<<“\t = = = = = = = = = = = = = =”;
cout<<“\n\t MENU”;
cout<<“\n\t= = = = = = = = = = =”;
25
cout<<“\n \t [3] MULTIPLICATION” ;
cout<<“\n \t [4] DIVISION” ;
cout<<“\n \t [5] REMAINDER” ;
cout<<“\n \t [6] LARGER OUT OF TWO” ;
cout<<“\n \t [7] EXIT” ;
cout<<“\n \t = = = = = = = = = =”;
if(ch< = 6 &&ch>=1)
{
cout<<(“ENTER TWO NUMBERS:”);
cin>>a>>b;
}
switch(ch)
{
case 1:
c = a+b ;
cout<<“ \n Addition: “<< c;
break;
case 2:
c=a-b;
cout<<“\n Subtraction:”<< c;
break;
case 3:
c = a* b ;
cout<<“\n Multiplication: “<< c;
break;
case 4:
c = a / b;
cout<<“\n Division: << c;
break;
case 5:
c = a % b;
cout<<“ \n Remainder: << c;
break;
case 6:
if (a > b)
cout<<“\n \t <<a <<”is larger than << b;
else if (b > a)
cout<<“ \n \t <<b<<” is larger than <<a;
else
cout<<“\n \t <<a<<”and “<<b<<”are same”;
break;
case 7:
cout<< “ \ n Terminated by choice”;
exit();
break;
default:
cout<<“ \ n invalid choice”;
}
26
return 0;
}
Output:
=========
MENU
=========
[1] ADDITION
[2] SUBTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[6] LARGER OUT OF TWO
[7] EXIT
===============
Enter your choice: 6
Enter two numbers: 8 9
9 is larger than 8
Expression_1?Expression_2 : Expression_3
Where,
Expression_1 is Condition
Expression_2 is statement followed if Condition is True
Expression_3 is statement followed if Condition is False
Explanation of syntax:
1. Expression_1 is a condition so it will return the result either True or False.
2. If result of expression_1 is True that is NON-ZERO, then Expression_2 is
Executed.
3. If result of expression_1 is False that is ZERO, then Expression_3 is
Executed.
Let us take the simple example of finding greater number from two given numbers
using Conditional Operator.
#include<iostream>
using namespace std;
int main()
{
int num1=10;
int num2=20;
27
return 0;
}
Output:
num2 is greater than num1
During running of a program, when a statement like “goto begin;” is met, the
flow of control will jump to the statement immediately following the label
“begin:” this happens unconditionally.
“goto‟ breaks the normal sequential execution of the program.
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‟.
If the “label:” is placed after the “goto label;” some statements will be skipped
and the jump is known as a “forward jump”.
* Write a program to detect the entered number as to whether it is even or odd. Use
goto statement.
# include<iostream>
using namespace std;
int main( )
{
int x;
cout<<“Enter a Number:”;
cin>>x;
if(x % 2 = = 0)
goto even;
else
goto odd;
28
even:
cout<<x<<” is Even Number”;
return;
odd:
cout<<x<<” is Odd Number”);
return 0;
}
Output:
Enter a Number : 5
5 is Odd Number.
Loop: A loop is defined as a block of statements which are repeatedly executed for
certain number of times.
Syntax:
for(initialize expression; test condition; updation )
{
Statement-1;
Statement-2;
}
(i) The initialization sets a loop to an initial value. This statement is executed only
once.
(ii) The test condition is a relational expression that determines the number of
iterations desired or it determines when to exit from the loop.
- The forloop continues to execute as long as conditional test is satisfied.
- When the condition becomes false the control of the program exits from the
body of for loop and executes next statements after the body of the loop.
- The body of the loop may contain either a single statement or multiple
statements
29
#include <iostream>
using namespace std;
int main ()
{
Output:
value of i : 0
value of i : 1
value of i : 2
value of i : 3
value of i : 4
value of i : 5
value of i : 6
value of i : 7
value of i : 8
value of i : 9
30
Syntax:
Initialization Expression;
while( Test Condition)
{
Body of the loop
Updation Expression
}
o The whileis an entry – controlled loop statement.
o The test condition is evaluated and if the condition is true, then the
body of the loop is executed.
o The execution process is repeated until the test condition becomes
false and the control is transferred out of the loop.
o On exit, the program continues with the statement immediately after
the body of the loop.
o The body of the loop may have one or more statements.
o The braces are needed only if the body contains two or more
statements.
Its a good practice to use braces even if the body has only one statement.
#include <iostream>
using namespace std;
int main ()
{
intnum = 5; // Local variable declaration
while(num< 10 ) // while loop execution
{
cout<< "Number : " <<num<<endl;
num++;
}
return 0;
}
Output:
Number : 5
Number : 6
Number : 7
Number : 8
Number : 9
Syntax:
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while ( Test Condition);
#include <iostream>
using namespace std;
int main ()
{
int i = 0; // Local variable declaration:
do // do loop execution
{
cout<< "value of i : " << i <<endl;
i++;
}while( i < 10 );
return 0;
}
Output:
value of i : 0
value of i : 1
value of i : 2
value of i : 3
value of i : 4
value of i : 5
value of i : 6
value of i : 7
value of i : 8
value of i : 9
32
Difference between do..while and while loop :
do-while while
Syntax:
break;
Example:
switch (choice = = toupper(getchar( ))
{
case ‘R : cout<<“Red”;
break;
case ‘W : cout<<”White”;
break;
case ‘B : cout<<”Blue”;
break;
default: cout<<”Error”;
}
Notice that each group of statements ends with a break statement, (in order)
to transfer control out of the switch statement.
The last group does not require a break statement; since control will
automatically be transferred out of the switch statement after the last group
has been executed.
# include<iostream>
using namespace std;
int main( )
{
int i = 1;
cout<<” \n \t \t Table of Even numbers from 1 to 20”;
cout<<“ \n \t \t = = = = = = = = = = = = = = = = = = = \n”;
for ( ; ; ) /*=> Infinite loop (No Arguments).*/
{
if( i = = 21)
break;
else
if( i % 2 = = 0)
{
cout<<”\t”<< i;
i++ ;
continue;
}
else
{
i++ ;
continue;
}
}
return 0;
}
Output:
Table of Even numbers from 1 to 20
2 4 6 8 10 12 14 16 18
Arrays:
34
Q) Define Array
An array is a collection of variables of the same type that are referred to througha
common name.
A specific element in an array is accessed by an index. InC++, all arrays consist of
contiguous memory locations. The lowest addresscorresponds to the first element
and the highest address to the last element.
Arrays may have from one to several dimensions. The most common array is
thenull-terminated string, which is simply an array of characters terminated by a null.
(or)
An array consists of a set of objects (called its elements), all of which are ofthe
same type and are arranged contiguously in memory.
In general, only the arrayitself has a symbolic name, not its elements. Each element
is identified by an indexwhich denotes the position of the element in the array. The
number of elements inan array is called its dimension. The dimension of an array is
fixed andpredetermined; it cannot be changed during program execution.
Arrays are suitable for representing composite data which consist of manysimilar,
individual items.
An array variable is defined by specifying its dimension and the type of its elements.
int heights[10];
The individual elements of the array are accessed by indexing the array. The
firstarray element always has the index 0. Therefore, heights[0] and
heights[9]denote, respectively, the first and last element of heights. Each of
heightselements can be treated as an integer variable. So, for example, to set the
thirdelement to 177, we may write:
heights[2] = 177;
Processing of an array usually involves a loop which goes through the arrayelement
by element. Example illustrates this using a function which takes anarray of integers
and returns the average of its elements.
35
double Average (intnums[size])
{
double average = 0;
for (register i = 0; i< size; ++i)
average += nums[i];
return average/size;
}
Like other variables, an array may have an initializer. Braces are used tospecify a list
of comma-separated initial values for array elements. For example,
initializes the three elements of nums to 5, 10, and 15, respectively. When the
number of values in the initializer is less than the number of elements, the remaining
elements are initialized to zero:
An array may have more than one dimension (i.e., two, three, or higher). The
organization of the array in memory is still the same (a contiguous sequence of
elements), but the programmer’s perceived organization of the elements is different.
For example, suppose we wish to represent the average seasonal temperature for
three major Australian capital cities (see Example Table).
Example Table:
int seasonTemp[3][4];
As before, elements are accessed by indexing the array. A separate index isneeded
for each dimension. For example, Sydney’s average summer temperature(first row,
second column) is given by
36
seasonTemp[0][1].
int seasonTemp[3][4] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
Because this is mapped to a one-dimensional array of 12 elements in memory, it is
equivalent to:
int seasonTemp[3][4] = {
26, 34, 22, 17, 24, 32, 19, 13, 28, 38, 25, 20
};
The nested initializer is preferred because as well as being more informative, it is
more versatile.
For example, it makes it possible to initialize only the first element of each row and
have the rest default to zero:
We can also omit the first dimension (but not subsequent dimensions) and let it be
derived from the initializer:
int seasonTemp[][4] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
Processing a multidimensional array is similar to a one-dimensional array, butuses
nested loops instead of a single loop. Example, illustrates this by showing afunction
for finding the highest temperature in seasonTemp.
int seasonTemp[rows][columns] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
37
the same logic in the program form:
#include<iostream>
using namespace std;
int HighestTemp (int temp[][4], int rows, int columns)
{
int highest = 0;
for (inti = 0; i< rows; ++i)
for (int j = 0; j < columns; ++j)
if (temp[i][j] > highest)
highest = temp[i][j];
return highest;
}
int main()
{
const int rows = 3;
const int columns = 4;
int seasonTemp[rows][columns] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
HighestTemp (seasonTemp, rows, columns);
return 0;
}
38
cout<<"\nMatrix A:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<A[i][j]<<" ";
cout<<"\n";
}
cout<<"\nEnter Matrix B row wise:";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>B[i][j];
}
cout<<"\n\nMatrix B:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<B[i][j]<<" ";
cout<<"\n";
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
c[i][j]=A[i][j]+B[i][j];
}
if(n==p)
{
cout<<"\nEnter first matrix:\n";
for(i=0;i<m;++i)
for(j=0;j<n;++j)
cin>>a[i][j];
39
cout<<"\nEnter second matrix:\n";
for(i=0;i<p;++i)
for(j=0;j<q;++j)
cin>>b[i][j];
/* reading mat */
for (i = 0; i< 3; i++)
{
for (j = 0; j < 3; j++)
{
cin>> mat[i][j];
}
}
40
for (j = 0; j < 3; j++)
{
cout<<trans_mat[i][j] << "\t";
}
cout<<endl;
}
return 0;
}
Strings:
Null-Terminated Strings
By far the most common use of the one-dimensional array is as a character string.
C++ supports two types of strings. The first is the null-terminated string, which is a
null-terminated character array. (A null is zero.)
Thus a null-terminated string contains the characters that comprise the string
followed by a null.
When declaring a character array that will hold a null-terminated string, you need to
declare it to be one character longer than the largest string that it is to hold. For
example, to declare an array strthat can hold a 10-character string, you would write
charstr[11];
This makes room for the null at the end of the string.
When you use a quoted string constant in your program, you are also creating anull-
terminated string. A string constant is a list of characters enclosed in double
quotes.For example,
"hello there"
You do not need to add the null to the end of string constants manually—the
compilerdoes this for you automatically.
#include <iostream>
using namespace std;
int main()
{
char MyName[20];
cout<< "Please enter your name" <<endl;
cin.getline(MyName,20);
cout<< "your name is " <<MyName<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
char str[3][20] = {
"I",
"like",
41
"C++" };
for(int i=0;i<3; i++)
{
cout<<str[i];
cout<<endl;
}
return 0;
}
Q) State and explain any five built-in functions which are used for string
manipulation in a program.
Name Function
strcpy(s1, s2) Copies s2 into s1.
strcat(s1, s2) Concatenates s2 onto the end of s1.
strlen(s1) Returns the length of s1.
strcmp(s1, s2) Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;greater
than 0 if s1>s2.
strchr(s1, ch) Returns a pointer to the first occurrence of chin s1.
strstr(s1, s2) Returns a pointer to the first occurrence of s2 in s1.
These functions use the standard header file string.h. The following program
illustrates the use of these stringfunctions:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i, n;
char person[10][LEN];
cout<<"How many persons ? ";
cin>>n;
for(i=0; i<n; i++)
{
cout<<"Enter person"<<i+1<<" name: ";
cin>> person[i];
}
42
cout<<person[i]<<" ";
cout.width(2);
cout<<strlen(person[i])<<" ";
cout.width(LEN);
cout<<strlwr(person[i]);
cout.width(LEN);
cout<<strupr(person[i])<<endl;
}
cout<<"----------------------------------------------\n";
return 0;
}
POINTERS
Pointer operator
A pointer operator can be represented by a combination of *(asterisk) with a variable.
For eg.
int *ptr;
float *fp;
data_type *pointer_variable;
Address operator
An address operator can be represented by a combination of & (ambersand) with a
pointer variable.
For eg.
k = &ptr;
Pointer Expressions
Pointer assignment : A pointer is a variable data type and hence the general rule to
assign its value to the pointer is same as that of any other variable data type.
Eg.
int x,y;
int *ptr1, *ptr2;
ptr1 = &x;
The memory address of variable x is assigned to the pointer variable ptr1.
y = *ptr1;
The contents of the pointer variable ptr1 is assigned to the variable y, not the
memory address.
ptr1 = &x;
ptr2 = ptr1;
43
The address of the ptr1 is assigned to the pointer variable ptr2. The contents of both
prt1 and ptr2 will be the same as these two pointer variables hold the same address.
A program to assign a character variable to the pointer and to display the contents of
the pointer.
#include <iostream>
using namespace std;
int main()
{
char x,y;
char *pt;
x = ‘k’; // assign character
pt = &x;
y = *pt;
cout<< “Value of x = “ << x <<endl;
cout<< “Pointer value = “ << y <<endl;
}
Functions:
Functions allow to structure programs in segments of code to perform individual
tasks.
In C++, a function is a group of statements that is given a name, and which can be
called from some point of the program. The most common syntax to define a function
is:
Where:
- type is the type of the value returned by the function.
- function-name is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type followed by
an identifier, with each parameter being separated from the next by a comma. Each
parameter looks very much like a regular variable declaration (for example: int x),
and in fact acts within the function as a regular variable which is local to the function.
The purpose of parameters is to allow passing arguments to the function from the
location where it is called from.
- statements is the function's body. It is a block of statements surrounded by braces
{ } that specify what the function actually does.
44
int main ()
{
int z;
z = addition (5,3);
cout<<"The result is "<< z;
return 0;
}
Output:
The result is 8
In the example above, main begins by declaring the variable z of type int, and right
after that, it performs the first function call: it calls addition. The call to a function
follows a structure very similar to its declaration. In the example above, the call
to addition can be compared to its definition just a few lines earlier:
At the point at which the function is called from within main, the control is passed to
function addition: here, execution of main is stopped, and will only resume once
the addition function ends. At the moment of the function call, the value of both
arguments (5 and 3) are copied to the local variables inta and int b within the
function.
Then, inside addition, another local variable is declared (int r), and by means of the
expression r=a+b, the result of aplus b is assigned to r; which, for this case,
where a is 5 and b is 3, means that 8 is assigned to r.
Ends function addition, and returns the control back to the point where the function
was called; in this case: to function main. At this precise moment, the program
resumes its course on main returning exactly at the same point at which it was
interrupted by the call to addition. But additionally, because addition has a return
type, the call is evaluated as having a value, and this value is the value specified in
the return statement that ended addition: in this particular case, the value of the local
variable r, which at the moment of the return statement had a value of 8.
Therefore, the call to addition is an expression with the value returned by the
45
function, and in this case, that value, 8, is assigned to z. It is as if the entire function
call (addition(5,3)) was replaced by the value it returns (i.e., 8).
In this case, function addition is passed 5 and 3, which are copies of the values
of x and y, respectively. These values (5 and 3) are used to initialize the variables
set as parameters in the function's definition, but any modification of these variables
within the function has no effect on the values of the variables x and y outside it,
because x and y were themselves not passed to the function on the call, but only
copies of their values at that moment.
In certain cases, though, it may be useful to access an external variable from within
a function. To do that, arguments can be passed by reference, instead of by value.
For example, the function duplicate in this code duplicates the value of its three
arguments, causing the variables used as arguments to actually be modified by the
call:
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout<< "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
Output:
x=2, y=6, z=14
46
To gain access to its arguments, the function declares its parameters as references.
In C++, references are indicated with an ampersand (&) following the parameter
type, as in the parameters taken by duplicate in the example above.
When a variable is passed by reference, what is passed is no longer a copy, but the
variable itself, the variable identified by the function parameter, becomes somehow
associated with the argument passed to the function, and any modification on their
corresponding local variables within the function are reflected in the variables passed
as arguments in the call.
In fact, a, b, and c become aliases of the arguments passed on the function call (x, y,
and z) and any change on a within the function is actually modifying
variable x outside the function. Any change on b modifies y, and any change
on cmodifies z. That is why when, in the example, function duplicate modifies the
values of variables a, b, and c, the values of x, y, and z are affected.
The variables would not be passed by reference, but by value, creating instead
copies of their values. In this case, the output of the program would have been the
values of x, y, and z without being modified (i.e., 1, 3, and 7).
Inline functions:
Calling a function generally causes a certain overhead (stacking arguments, jumps,
etc...), and thus for very short functions, it may be more efficient to simply insert the
code of the function where it is called, instead of performing the process of formally
calling a function.
Preceding a function declaration with the inline specifier informs the compiler
that inline expansion is preferred over the usual function call mechanism for a
specific function. This does not change at all the behavior of a function, but is just
used to suggest the compiler that the code generated by the function body shall be
inserted at each point the function is called, instead of being invoked with a regular
function call.
47
#include <iostream>
using namespace std;
This informs the compiler that when add() is called, the program prefers the function
to be expanded inline, instead of performing a regular call. inline is only specified in
the function declaration, not when it is called.
Note that most compilers already optimize code to generate inline functions when
they see an opportunity to improve efficiency, even if not explicitly marked with
the inline specifier. Therefore, this specifier merely indicates the compiler that inline
is preferred for this function, although the compiler is free to not inline it, and
optimize otherwise.
int main ()
{
cout<< divide (12) << '\n';
cout<< divide (20,4) << '\n';
return 0;
}
Output:
6
5
48
In this example, there are two calls to function divide(). In the first one:
divide (12)
The call only passes one argument to the function, even though the function has two
parameters. In this case, the function assumes the second parameter to be 2 (notice
the function definition, which declares its second parameter as int b=2). Therefore,
the result is 6.
divide (20,4)
The call passes two arguments to the function. Therefore, the default value for b (int
b=2) is ignored, and b takes the value passed as argument, that is 4, yielding a result
of 5.
int x;
The same applies to functions. Functions cannot be called before they are declared.
That is why, in all the previous examples of functions, the functions were always
defined before the main function, which is the function from where the other
functions were called. If main were defined before the other functions, this would
break the rule that functions shall be declared before being used, and thus would not
compile.
The parameter list does not need to include the parameter names, but only their
types. Parameter names can nevertheless be specified, but they are optional, and do
not need to necessarily match those in the function definition. For example, a
function called protofunction with two int parameters can be declared with either of
these statements:
Anyway, including a name for each parameter always improves legibility of the
declaration.
int main()
{
int i;
do {
cout<< "Please, enter number (0 to exit): ";
cin>> i;
odd (i);
} while (i!=0);
return 0;
}
This example is indeed not an example of efficiency. You can probably write yourself
a version of this program with half the lines of code. Anyway, this example illustrates
how functions can be declared before its definition:
Declare the prototype of the functions. They already contain all what is necessary to
call them, their name, the types of their argument, and their return type (void in this
case). With these prototype declarations in place, they can be called before they are
50
entirely defined, allowing for example, to place the function from where they are
called (main) before the actual definition of these functions.
But declaring functions before being defined is not only useful to reorganize the
order of functions within the code. In some cases, such as in this particular case, at
least one of the declarations is required, because odd and even are mutually called;
there is a call to even in odd and a call to odd in even. And, therefore, there is no
way to structure the code so that odd is defined before even, and even before odd.
5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ could be:
// factorial calculator
#include <iostream>
using namespace std;
int main ()
{
long number = 9;
cout<< number << "! = " << factorial (number);
return 0;
}
Output:
9! = 362880
Notice how in function factorial we included a call to itself, but only if the argument
passed was greater than 1, since, otherwise, the function would perform an infinite
recursive loop, in which once it arrived to 0, it would continue multiplying by all the
negative numbers (probably provoking a stack overflow at some point during
runtime).
Overloaded functions:
In C++, two different functions can have the same name if their parameters are
different; either because they have a different number of parameters, or because any
of their parameters are of a different type. For example:
51
// overloading functions
#include <iostream>
using namespace std;
int main ()
{
int x=5,y=2;
double n=5.0,m=2.0;
cout<< operate (x,y) << '\n';
cout<< operate (n,m) << '\n';
return 0;
}
Output:
10
2.5
In this example, there are two functions called operate, but one of them has two
parameters of type int, while the other has them of type double. The compiler knows
which one to call in each case by examining the types passed as arguments when
the function is called. If it is called with two int arguments, it calls to the function that
has two int parameters, and if it is called with two doubles, it calls the one with
two doubles.
In this example, both functions have quite different behaviors, the int version
multiplies its arguments, while the double version divides them. This is generally not
a good idea. Two functions with the same name are generally expected to have -at
least- a similar behavior, but this example demonstrates that is entirely possible for
them not to. Two overloaded functions (i.e., two functions with the same name) have
entirely different definitions; they are, for all purposes, different functions, that only
happen to have the same name.
Note that a function cannot be overloaded only by its return type. At least one of its
parameters must have a different type.
52
void display(int marks[5]);
int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
Output:
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
display(marks);
Also notice the difference while passing array as an argument rather than a variable.
The argument marks in the above code represents the memory address of first
element of array marks[5].
And the formal argument intm[5] in function declaration converts to int* m;. This
pointer points to the same address pointed by the array marks.That's the reason,
although the function is manipulated in the user-defined function with different array
name m[5], the original array marks is manipulated.
53
void display(int n[3][2]);
int main()
{
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
display(num);
return 0;
}
Procedure-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. A typical program structure
for procedural programming is shown in Pig. 1.4. The technique of
hierarchical decomposition has been used to specify the tasks to be completed for
solving a problem.
54
Procedure-oriented programming basically consists of writing a list of instructions (or
actions) for the computer to follow, and organizing these instructions into groups
known as functions. We normally use a flowchart to organize these actions and
represent the flow of control from one action to another.
many important data items are placed as global so that In a multi-function program,
they may be accessed by all the functions. Each function may have its own local
data. Figure 1.5 shows the relationship of data and functions in a procedure-oriented
program.
Another serious drawback with the procedural approach is that it does not model real
world problems very well. This is because functions are action-oriented and do not
really correspond to the elements of the problem.
55
Some characteristics exhibited by procedure-oriented programming are:
OOP treats data as a critical element in the program development and does not
allow it to flow freely around the system. It ties data more closely to the functions that
operate on it, and protects it from accidental modification from outside functions.
OOP allows decomposition of a problem into a number of entities called objects and
then builds data and functions around these objects. The organization of data and
functions in object-oriented programs is shown in Fig. 1.6.
The data of an object can be accessed only by the functions associated with that
object. However, functions of one object can access the functions of other objects.
56
Object-oriented programming is the most recent concept among programming
paradigms and still means different things to different people.
In the most general sense, a program can be organized in one of two ways: around
its code (what is happening) or around its data (who is being affected).
Object-oriented programs work the other way around. They are organized around
data, with the key principle being "data controlling access to code." In an object-
oriented language, you define the data and the routines(functions) that are permitted
to act on that data. Thus, a data type defines precisely what sort of operations can
be applied to that data.
Q) State the features of object oriented program (or) Write about the basic
concepts of object oriented programming in detail.
Before starting to learn C++ it is essential that one must have a basic knowledge of
the concepts of Object Oriented Programming.
1. Objects
2. Classes
3. Data Abstraction and Data Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing.
57
1. Objects
Objects are the basic run-time 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.
They may also represent user-defined data such as vectors, time problem is
analysed in terms of objects and the nature of communication between them.
Program objects should be chosen such that they match closely with the real-world
objects. Objects take up space in the memory and have an associated address like a
record in Pascal, or a structure in C.
Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class. There can be
more than one instance of an object. Each instance of an object can hold its own
relevant data.
58
An Object is a collection of data members and associated member functions also
known as methods.
2. Classes
We just mentioned that objects contain 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. In fact, objects are variables of the type class. Once a class has been defined, we
can create any number of objects belonging to that class. Each object is associated with the
data of type class with which they are created.
A class is thus a collection of objects of similar type. For example, mango, apple and orange
are members of the class fruit.
Classes are user-defined data types and behave like the built-in types of a programming
language.
The syntax used to create an object is no different than the syntax used to create an integer
object in C. If fruit has been defined as a class, then the statement
fruit mango;
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class 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.
Abstraction refers to the act of representing essential features without including the
background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes such
as size, weight and cost, and functions to operate on these attributes.
59
They encapsulate all the essential properties of the objects that are to be created. The
attributes are sometimes called data members because they hold information. The
functions that operate on these data are sometimes called methods or member functions.
Since the classes use the concept of data abstraction, they are known as Abstract Data
Types (ADD).
Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects
of another class.
It supports the concept of hierarchical classification. For example, the bird 'robin' is a part
of the class flying bird' which is again a part of the class bird'.
The principle behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated in Fig. 1.8.
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one. The new class will
have the combined features of both the classes.
The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the
class in such a way that it does not introduce any undesirable side-effects into the rest of the
classes.
Polymorphism :
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than one form. An operation may exhibit different behaviours in different
instances. The behaviour depends upon the types 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 strings, 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 as operator overloading.
Figure 1.9 illustrates that a single function name can be used to handle different number and
different types of arguments.
60
This is something similar to a particular word having several different meanings depending
on the context- Using a single function name to perform different types of tasks is known
as function overloading.
Polymorphism plays an important role in allowing objects having different internal structures
to share the same external interface. This means that a general class of operations
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding (also known as late binding) means that the code associated with a
given procedure call is not known until the time of the call at run-time. It is associated with
polymorphism and inheritance.
A function call associated with a polymorphic reference depends on the dynamic type of that
reference.
Consider the procedure "draw" in Pig. 1.9. By inheritance, every object will have this
procedure- Its algorithm is, however, unique to each object and so the draw procedure will
be redefined in each class that defines the object.
At run-time, the code matching the object under current reference will be called.
Message Passing
An object-oriented program consists of a set of objects that communicate with each other.
Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another.
The concept of message passing makes it easier to talk about building systems that directly
model or simulate their real-world counterparts.
61
A message for an object is a request for execution of a procedure, and therefore will invoke
a function (procedure) in the receiving object that generates the desired result. Message
passing involves specifying the name of the object, the name of the function (message) and
the information to be sent.
Objects have a life cycle. They can be created and destroyed.Communication with an object
is feasible as long as it is alive.
Benefits of OOP
The main advantages are
It is easy to model a real system as real objects are represented by programming
objects in OOP. The objects are processed by their member data and functions. It is
easy to analyze the user requirements.
With the help of inheritance, we can reuse the existing class to derive a new class
such that the redundant code is eliminated and the use of existing class is extended.
This saves time and cost of program.
In OOP, data can be made private to a class such that only member functions of the
class can access the data. This principle of data hiding helps the programmer to build
a secure program that can not be invaded by code in other part of the program.
With the help of polymorphism, the same function or same operator can be used for
different purposes. This helps to manage software complexity easily.
Large problems can be reduced to smaller and more manageable problems. It is
easy to partition the work in a project based on objects.
It is possible to have multiple instances of an object to co-exist without any
interference i.e. each object has its own separate member data and function
62