Basic Programming Language Overview

Download as pdf or txt
Download as pdf or txt
You are on page 1of 202

Basic Programming Language

Overview
Programming Techniques
• Unstructured Programming

• Procedural Programming

• Modular Programming

• Object-Oriented programming
Unstructured Programming

• Writing small and simple programs consisting only of one


main program.

• Here ''main program'' stands for a sequence of


commands or statements which modify data which is
global throughout the whole program.
Unstructured Programming

• Drawbacks
– This programming technique can only be used in a very small program

– For example, if the same statement sequence is needed at different


locations within the program, the sequence must be copied. If an error
needed to be modified, every copy needs to be modified

– This has lead to the idea to extract these sequences (procedure), name
them and offering a technique to call and return from these procedures
Procedural Programming

• With procedural programming, you are


able to combine sequences of calling
statements into one single place.

• After the sequence is processed, flow of


control proceeds right after the position
where the call was made.
Procedures

• With parameters and sub-procedures (procedures of procedures) ,


programs can now be written more structured and error free

• For example, if a procedure is correct, every time it is used it


produces correct results

• Consequently, in cases of errors you can narrow your search to


those places which are not proven to be correct
Procedure Program View

• Now a program can be viewed as a sequence of procedure calls

• The main program is responsible to pass data to the individual calls,


the data is processed by the procedures and the resulting data is
presented

• Thus, the flow of data can be illustrated as a hierarchical graph, a


tree.
Modular Programming

• Modular programming is subdividing your program into separate


subprograms such as functions and subroutines

• With modular programming, procedures of a common functionality


are grouped together into separate modules

• A program therefore no longer consists of only one single part. It is


now divided into several smaller parts which interact through
procedure calls and which form the whole program
The main program coordinates calls to procedures in separate modules
and hands over appropriate data as parameters.
Object-Orientation

• Thinking in OOP

– It is a kind of thinking methodology

– Everything in the world is an object (Pure OOP)

– Any system is composed of objects

– The evolution and development of a system is caused by the


interactions among the objects inside or outside the system
Everything in the World is an Object

• A flower, a tree, an animal

• A student, a professor

• A machine, an operator, a screen

• A university, a city, a country

• The world, the universe


Any System is Composed of Objects

• A law system

• An engineering system

• A substation automation system

• An educational system

• An economic system

• An Information system
Basic Components of OOP

• Concept/Class (e.g., car)

• Object is an instance of a class (e.g., volvo c30)

• Properties
– Are data attributes (brand, model, color, HK, engine size)

• Methods
– Are functions/capabilities (start, drive, stop, service)
Basic Components of OOP
OOP Based System View
Characteristics of Object Oriented Languages

• Objects

• Classes

• Inheritance

• Reusability

• Polymorphism
Object

• An object is an instance of a class. It can be uniquely identified by


its name and it defines a state which is represented by the values
of its attributes at a particular time.
Class

• A class is the implementation of an abstract data type (ADT). It


defines attributes and methods which implement the data structure
and operations of the ADT, respectively. Instance of classes are
called objects, consequently, classes define properties and behavior
of sets of objects.
Inheritance
• It is a fundamental aspect of human intelligence to seek out, recognize,
and create relationships among concepts. We build hierarchies
matrices, networks, and other interrelationships to explain and
understand the ways in which things interact.

• In C++ inheritance defines an "is a" relationship. The derived class is a


type of its base class. For instance , a "cat " class could be derived
from an" animal" class. A cat is an animal. A cat is a type of animal. A
derived class inherits both the data members and methods of its base
class. It may also define additional members and methods that support
specialized functionally.
Reusability
• Ones a class has been written, created , and debugged, it can be
distributed to other programmers for use in their own programs. This is
called reusability. It is similar to the way a library of functions in a
procedural language can be incorporated into different programs.

• However , in OOP the concept of inheritance provides an important


extension to the idea of reusability. A programmer can take an existing
class and without modifying it, add additional features and capabilities
to it.
Polymorphism
• Generally, the ability to appear in many forms. In object-oriented
programming, polymorphism refers to a programming language's ability
to process objects differently depending on their data type or class.

• More specifically, it is the ability to redefine methods for derived


classes. For example, given a base class shape, polymorphism enables
the programmer to define different area methods for any number of
derived classes, such as circles, rectangles and triangles. No matter
what shape an object is, applying the area method to it will return the
correct results.
C++ and C
• C++ is a superset of C. Almost every correct statement in C is also a
correct statement in C++, although the reverse is not true.

• The most important element added to C to create C++ are concerned


with classes, objects and OOP.
Definitions (1)
• Programming Language
– A set of rules, symbols and special words used to construct a computer program
• Source Program
– A program written in a high-level programming language
• Complier
– A program that translates a program written in a high-level language into
machine code
• Object Program
– A machine language version of source code
• Machine Language
– The language made up of binary coded instructions, that is used directly by the
computer
Definitions (2)
• Assembly Language

– A low-level programming language in which a mnemonic is used to represent


each of the machine language instructions for a particular computer

• High-level Programming Language

– These languages allow programs to be complied on Different Systems (e.g.,


C++, Pascal, FORTRAN, COBOL, Modula-2, and Ada)
High-level programming languages allow programs
to be compiled on different systems
Header & Library Files
Common Escape Sequences

Escape
Character
Sequences
\a Bell (beep)
\b Backspace
\f Form feed
\n New line
\r Return
\t Tab (horizontal)
\v Tab (vertical)
\' Single quote
\" Double quote
\\ Backslash
Basic C++ Variable Types

Keyword Description Bytes of Numerical Range Digits of


Memory Precision
Low High
char Character 1 -128 127 n/a

short Short integer 2 -32,768 32,767 n/a

int Integer 4 -2,147,483,648 2,147,483,647 n/a

long Long integer 4 -2,147,438,648 2,147,438,647 n/a

bool Boolean value 1 true or false n/a

float Floating point number 4 3.4 x 10-38 3.4 x 1038 7

double Double precision 8 1.7 x 10-308 1.7 x 10308 15


floating point number
long Long double precision 10 3.4 x 10-4932 1.1 x 104932 19
double floating point number
Unsigned Data Types

Keyword Numerical Range Bytes of


Memory
Low High
unsigned char 0 255 1

unsigned short 0 65,535 2

unsigned int 0 4,294,967,295 4

unsigned long 0 4,294,967,295 4


BasicProg.cpp
#include<iostream.h> //Preprocessor Directives (Header File)
void main()
{
cout<<"Every age has a language of its own.\n";
}
 The identifier "cout" is actually an object. It is predefined in C++ to correspond to
the standard output stream. A stream is an abstraction that refers to a flow of data.
The standard output stream normally flows to the screen display – although it can be
redirected to other output devices.

 The operator "<<" is called the insertion or put operator. It directs the contents of
the variable on its right to the object on its left.

 "Every age has a language of its own.\n" ……. String Constant

 \n – Escape Sequence (Newline)


Variable
• A location in memory, referenced by an identifier, that contains a data value
that can be changed

• Declaring a variable means specifying both its name and its data type. This
tells the complier to associate a name with a memory location whose
contents are of a specific type (for example, char or string). The
following statement declares myChar to be a variable or type char:

char myChar;
Rules for Writing Variables or Identifiers
 You can use upper and lowercase letters and the digits from 0 to 9

 You can also use underscore (_)

 The first character must be a letter or underscore

 Identifier can be as long as you like but only the 247 characters (in Visual
C++)or 250 characters in(C++ Builder) will be recognized

 The compiler distinguishes between upper and lowercase letters, so Var is


not the same as var or VAR

 You can't use a C++ keyword as a variable name. A keyword is a


predefined word with a special meaning , like int, char, for, while,
do, if, class, etc.
intvars.cpp
#include<iostream.h>
void main()
{
// Declaration of variables
int var1;
int var2;
int abcdefghijklmnopqrstuvwxyz12345678=9;

// Initialization of variables
var1=20;
var2=var1+10;
cout<<"var1+10 is"<<var2<<endl;
cout<<"Long variable value is"<<abcdefghijklmnopqrstuvwxyz12345678;
}
Data Type
 The char Data Type
The built-in type char describes data consisting of one alphanumeric
character - a letter , a digit, or a special symbol
'A‘ 'a' '8' '2' '+' '-' '$' '?' ''

 The string Data Type


Whereas a value of type char is limited to a single character. A string is a

sequence of characters, such as a word, name, or sentence, enclosed in


double quotes. For example

"Problem Solving" "C++" "."


Constants
• All single characters(enclosed in single quotes) and strings (enclosed in double
quotes) are constants

'A' '@' "Please enter your Id no"

• In C++ as in mathematics, a constant is something whose value never changes.

• Constant declaration
const DataType Identifier = LiteralValue;

const string Book_TITLE = "Object Oriented Programming in C++";

const float Max_HOURS = 40.0;

• Literal value any constant value written in a program

• Named constant (symbolic constant) a location in memory, referenced by an


identifier, that contains a data value that cannot be changed
Assignment Statement
 A statement that stores the value of an expression into a variable
Variable= Expression;
 Expression
An arrangement of identifiers, literals, and operators that can be evaluated to
compute a value of a given type

 The semantics (meaning) of the assignment operator (=) is "store"; the value of the
expression is stored into the variable.

 Only one variable can be on the left hand side of an assignment statement. An
assignment statement is not like a math equation (x + y = z + 4); the expression
(what is on the right hand side of the assignment operator) is evaluated, and the
resulting value is stored into the single variable on the left of the assignment
operator.
Assignment Statement (contd…)
 Given the declarations
string firstName;
string middleName;
string lastName;
string title;
char middleInitial;
char letter;
 The following assignment statements are valid:
firstName = "Abraham";
middleName = firstName;
middleName = " ";
lastName = "Lincoln";
title = "President";
middleInitial = ' ';
letter = middleInitial;
Assignment Statement (contd…)

Invalid Assignment Statement Reason

middleInitial = "A."; middleInitial is of type char; "A." is a string

letter = firstName; Letter is of type char; firstName is of type string

"Edison" = lastName; Only a variable can appear to the left of =

lastName = ; The expression to the right of = is missing


String Expressions
 We can't perform arithmetic on strings, the string data type provides a special operation, called
concatenation, that uses the + operator.
For example
string bookTitle;
string pharse1 = "Programming and";
string pharse2 = "Problem Solving";

We could write as: bookTitle = pharse1 + pharse2;


 This statement retrieves the value of phars1 from memory concatenates the value of pharse2
to form a new, temporary string containing the characters "Programming and Problem
Solving". This temporary string is then assigned to (stored into) bookTitle.
 Concatenation works with named string constants, literal strings, and char data as well as with
string variables. The only restriction is that at least on of the operands of the + operator must be
a string variable or named constant (so you cannot use expressions like "Hi" + "there" or
'A' + 'B').
String Expressions (contd..)
 For example
const string WORD1 = "rogramming";
const string WORD3 = "Solving";
const string WORD5 = "C++";

then we write the following assignment statement to store the title of this book into
the variable bookTitle:

bookTitle = 'P' + WORD1 + "and Problem" + WORD3 + "with" + WORD5;

As a result, bookTitle contains the string

"Programming and Problem Solving with C++"


StrProg.cpp
#include<iostream>
#include<string>

using namespace std;

void main()

string bookTitle;

const string WORD1 = "rogramming";

const string WORD3 = "Solving";

const string WORD5 = "C++";

bookTitle ='P'+ WORD1 + "and Problem" + WORD3 + "with" + WORD5;

cout<<"Title of Book is"<<bookTitle<<endl;


}
using namespaces
#include<iostream>
using namespace std;
void main()
{
cout<<"Happy Birthday"<<endl;
}

 It tells the compiler to use the std namespace. Namespaces are a relatively recent
addition to C++. A namespace creates a declarative region in which various program
elements can be placed. Namespaces help in the organization of large programs. The
using statement informs the complier that you want to use the std namespace.
This is the namespace in which the entire Standard C++ library is declared. By using
the std namespace you simplify access to the standard library.
Output Statement
char ch = '2';
string first = "Marie";
string last = "Curie";

Statement What is Printed

cout<<ch; 2
cout<<"ch="<<ch; ch=2
cout<<first + " " + last; Marie Curie
cout<<first <<last; MarieCurie
cout<<first << ' ' <<last; Marie Curie
cout<<"A1 \"Butch\" Jones"; A1 "Butch" Jones;
Numeric Types, Expressions and Output
Overview of C++ Data Types
Arithmetic Operators
+ Unary plus

- Unary minus

+ Addition

- Subtraction

* Multiplication

/ {Floating-point division (floating-point result) / Integer division (no fractional part) }

% Modulus (reminder from integer division)

 Unary operator: An operator that has just one operand

 Binary operator: An operator that has two operands


Expressions Value
3 + 6 9
3.4 – 6.1 -2.7
2 * 3 6
8 / 2 4
7.0 / 2.0 3.5
8 / 8 1
8 / 9 0
8 / 7 1
8 % 8 0
8 % 9 8
8 % 7 1
0 % 7 0
5 % 2.3 Error (both operands must be integers)

7.0 / 0.0, 7 / 0, 7 % 0 Error (Computer cannot divide by zero)


assign.cpp
#include<iostream>
using namespace std;
void main()
{
int ans = 27;
ans+=10;
cout<<ans<<", ";
ans-=7;
cout<<ans<<", ";
ans*=2;
cout<<ans<<", ";
ans/=3;
cout<<ans<<", ";
ans%=3;
cout<<ans<<endl;
}
FreezBoil.cpp
// Freeze Boil Program
// This program computes the midpoint between the freezing and
// boiling points of water

#include<iostream>
using namespace std;
const float FREEZE_PT = 32.0;
const float BOIL_PT = 212.0;
void main()
{
float avgTemp;
cout<<"Water freezes at "<<FREEZE_PT<<endl;
cout<<" and boils at "<<BOIL_PT<<" degress."<<endl;

avgTemp = (FREEZE_PT + BOIL_PT) / 2.0;

cout<<"Halfway between is "<<avgTemp<<" degrees."<<endl;


}
Increment and Decrement Operators
 C/C++ includes two useful operators not generally found in other computer
languages. These are the increment and decrement operators, ++ and --.
The operator ++ adds 1 to its operand, and -- subtracts one. In other
words:
x = x + 1; is the same as ++x;
and
x = x – 1; is the same as --x;

 Both the increment and decrement operators may either precede (prefix) or
follow (postfix) the operand. For example
x = x + 1;
can be written
++x; or x++;
Increment and Decrement Operators (contd..)
 A difference between the prefix and postfix forms when you use these
operators in an expression.
 When an increment or decrement operator precedes its operand, the
increment or decrement operation is performed before obtaining the value
of the operand for use in the expression.
 If the operator follows its operands follows its operand, the value of the
operand is obtained before incrementing or decrementing it. For instance,
x = 10;
y = ++x;
sets y to 11. However, if you write the code as the same as

x = 10;
y = x++;
y is set to 10. Either way, x is set to 11; the difference is in when it
happens
Prefix & Postfix
#include<iostream>
using namespace std;

void main()
{
int count = 10;
cout<<"count = "<<count<<endl;
cout<<"count = "<<++count<<endl; //pre-increment
cout<<"count = "<<count<<endl;
cout<<"count = "<<count++<<endl; //post-increment
cout<<"count = "<<count<<endl;
}
Prefix & Postfix (contd..)
#include<iostream>
using namespace std;

void main()
{
int count = 2;
float avgWeight = 10.5;

double totalWeight = avgWeight * ++count;


// double totalWeight = avgWeight * count++;
cout<<"Total Weight = "<<totalWeight<<endl;
}
Precedence Rules
 Highest level: ++ -- (unary operators)
 Middle level: % / *
 Lowest level: + -

Expression Value
10 / 2 * 3 15
10 % 3 – 4 / 2 -1
5.0 * 2.0 / 4.0 * 2.0 5.0
5.0 * 2.0 / (4.0 * 2.0) 1.25
5.0 + 2.0 / (4.0 * 2.0) 5.25
Input with cin
#include<iostream>
using namespace std;
void main()
{
float rad;
const double PI = 3.14159;
cout<<"Enter radius of circle: ";
cin>>rad;
float area = PI * rad * rad;
cout<<"Area is "<<area<<endl;
}
 The keyword "cin" is an object, predefined in C++ to correspond to the standard
input stream.
 The ">>" is extraction or get from operator. It takes the value from the stream object
on its left and places it in the variable on its right.
Tests Signed and Unsigned Integers
#include<iostream>
using namespace std;

void main()
{
int signedVar = 1500000000;
unsigned int unsignVar = 1500000000;

signedVar = (signedVar * 2) / 3;
unsignVar = (unsignVar * 2) / 3;

cout<<"signedVar = "<<signedVar<<endl;
cout<<"unsignVar = "<<unsignVar<<endl;
}
Type Coercion
 The implicit (automatic) conversion of a value from one data type to another
If you make the declaration
int someInt;
float someFloat;
then someInt can hold only integer values and somefloat can hold only floating
point values. The assignment statement
someFloat = 12;
may seem to store the integer value 12 into someFloat, but this is not true.

 The computer refuses to store anything other than a float value into someFloat.
 The complier inserts extra machine language instructions that first convert 12 into
12.0 and then store 12.0 into someFloat.
 This implicit (automatic) conversion of a value from one data type to another is
known as type coercion.
Type Coercion (contd..)
 The statement
int someInt = 4.8;

also causes type coercion. When a floating-point value is assigned to an int variable,
the fractional part is truncated (cut off). As a result, someInt is assigned the value
4.

Let's examine both these statements:

someFloat = 3 * someInt + 2;
someInt = 15.2 / someFloat – 3.75;
Type Casting
 The explicit conversion of a value from one data type to another; also called type
conversion

 A C++ cast operation consists of a data type name and then, within parentheses, the
expression to be converted

aCharVar = static_cast<char>(anIntVar);
Or
aCharVar = char(anIntVar);
Cast.cpp
#include<iostream>
using namespace std;
void main()
{
int intVar = 1500000000;
intVar = (intVar*10)/10;
cout<<"intVar = "<<intVar<<endl;

intVar = 1500000000;
intVar = (double(intVar)*10)/10;
cout<<"intVar = "<<intVar<<endl;
}
Mixed Type Expression
 An expression that contains operands of different data types; also called mixed mode
expression
 Whenever an integer value and a floating-point value are joined by an operator,
implicit type coercion occurs as follows
1. The integer value is temporary coerced to a floating –point value
2. The operation is performed
3. The result is a floating-point value
 Let's examine how the machine evaluates the expression 4.8 + someInt -3,
where someInt contains the value 2.
 First, the operands of the + operator have mixed types, so the value of someInt is
coerced to 2.0. (This conversion is only temporary; it does not affect the value that
is stored in someInt.) the addition take place, yielding a value of 6.8.
 Next, the subtraction (-) operator joins a floating point value (6.8) and an integer
value (3). The value 3 is coerced to 3.0, the subtraction takes place, and the result
is the floating-point value 3.8.
The setw()Manipulator
 This setw() stands for the set width. The setw() manipulator is used to set the width
of the word to be displayed on screen.
 The general form of setw() is:-
setw(int w)
Where, the integer inside the bracket indicates the total field width.

#include<iostream>
#include<iomanip> //Manipulator Header File
using namespace std;
void main()
{
long pop1 = 2424785, pop2 = 47, pop3 = 9761;

cout <<setw(8)<<"LOCATION"<<setw(12)<<"POPULATION"<<endl
<<setw(8)<<"Portcity"<<setw(12)<<pop1<<endl
<<setw(8)<<"Hightown"<<setw(12)<<pop2<<endl Output:
LOCATION POPULATION
<<setw(8)<<"Lowville"<<setw(12)<<pop3<<endl;
Portcity 2424785
} Hightown 47
Lowville 9761
The setprecision()Manipulator
 This setprecision() stands for the set precision. The setprecision()
manipulator is used to set the decimal precision to be used by output operations.
 The general form of setprecision() is:-
setprecision(int w)
Where, the integer inside the bracket indicates the total field width.

#include<iostream>
#include<iomanip> //Manipulator Header File
using namespace std;
void main()
{

double Z = 6.8436;
Output:
cout<<"Z = "<<setprecision(4)<<Z<<endl; Z = 6.844

}
Conditions, Logical Expressions and
Selection Control Structures
Flow of Control
 The order in which the computer executes statements in a program.
 Flow of control is normally sequential. That is, when one statement is
finished executing, control passes to the next statement in the program.

Statement A

Statement B

Statement C
Control Structure
 A statement used to alter the normally sequential flow of control.
 We use a selection (or branching) control structure when we want the
computer to choose between alternative actions.

True False
Assertion

Statement A Statement B
Selection Statement (if)
 if
The general form of the if statement is
if (expression)
statement;
else
statement;

 Where a statement may consist of a single statement, a block of


statements, or nothing (in the case of empty statements). The else clause is
optional.
Ifelse.cpp
#include<iostream>
using namespace std;

void main()
{
int x;

cout<<"Enter a number: ";


cin>>x;

if(x > 100)


cout<<"The number "<<x<<" is greater than 100"<<endl;
else
cout<<"The number "<<x<<" is smaller than 100"<<endl;
} Output:
Enter a number: 65
The number 65 is smaller than 100
Nested ifs
 A nested if is an if that is the target of another if or else. Nested ifs are very
common in programming. In a nested if, an else statement always refers to the
nearest if statement that is within the same block as the else and that is not
already associated with an else. For example,
if (i)
{
if (j)
statement 1;
if (k)
statement 2; /* this if*/
else
statement 3; /* is associated with this else*/
}
else
statement 4; /* is associated with if (i)*/

As noted, the final else is not associated with if(j) because it is not in the same

block. Rather, the final else is associated with if(i). Also the inner else is

associated with if(k), which is the nearest if.


The Dangling else

// Incorrect Version // Correct Version


if (average >= 60.0) if (average >= 60.0)
if (average < 70.0) {
cout<<"Passing but marginal"; if (average < 70.0)
else cout<<"Passing but marginal";
cout<<"Failing"; }
else
cout<<"Failing";
The if-else-if Ladder
 A common programming construct is the if-else-if ladder, sometimes called the
if-else-if staircase because of its appearance. Its general form is

if (expression)
statement;
else
if (expression)
statement;
else
if (expression)
statement;
.
.
else
statement;

 The conditions are evaluated from the top downward. As soon as a true condition is
found the statement associated with it, is executed and the rest of the ladder is
bypassed. If none of the condition are true, the final else is executed.
// This Program outputs an appropriate activity for a given temperature
#include<iostream>
using namespace std;
void main()
{
int temperature;
cout<<"Enter the outside temperature: ";
cin>>temperature;
cout<<"\n The recommended activity is ";
if (temperature > 85)
cout<<"Swimming."<<endl;
else
if (temperature > 70)
cout<<"Tennis."<<endl;
else
if (temperature > 32)
cout<<"Golf."<<endl;
else
if (temperature > 0)
cout<<"Skiing."<<endl;
else
cout<<"Dancing."<<endl;
}

Output:
Enter the outside temperature: 37

The recommended activity is Golf.


The ? Alternative
 The ? Is called a ternary operator because it requires three operands. It takes the
general from
Exp1 ? Exp2 : Exp3
Where Exp1, Exp2 and Exp3 are expressions. Notice the use and placement of the
colon.

 The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true,


then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1
is false, then Exp3 is evaluated and its value becomes the value of the expression.
For example, consider

x = 10;
y = x > 9 ? 100 : 200;

In this example, y is assigned the value 100. if x had been less than 9, y would have
received the value 200.
Relational & Logical Operator

Relational Operator Action


= = Equal to
! = Not equal to
> Greater than
< Less than
> = Greater than or equal to
< = Less than or equal to

Logical Operator Action


& & AND
|| OR
! NOT
// demonstrate relational operator (example-1)

#include<iostream>
using namespace std;

void main()
{
int num;

cout<<"Enter a number: ";


cin>>num;

cout<<"num < 10 is "<<(num<10)<<endl;


cout<<"num > 10 is "<<(num>10)<<endl;
cout<<"num == 10 is "<<(num==10)<<endl;
}

Output:
Enter a number: 9
num < 10 is 1
num > 10 is 0
num == 10 is 0
// demonstrate relational operator (example-2)
#include<iostream>
using namespace std;
void main()
{
if ('a' < 109)
{
cout<<"true"<<endl;
cout<<"a = "<<int('a')<<endl;
}
else
cout<<"false"<<endl;
if ('M' > 'S')
{
cout<<"true"<<endl;
cout<<"M = "<<int('M')<<" and S = "<<int('S')<<endl;
}
else
{
cout<<"true"<<endl;
cout<<"M = "<<int('M')<<" and S = "<<int('S')<<endl;
} Output:
} true
a = 97
true
M = 77 and S = 83
Precedence of Operator
Highest Precedence ! Unary + Unary –
* / %
+ –
< <= > >=
== !=
&&
||
Lowest Precedence =
// demonstrate Logical Operator

#include<iostream>
using namespace std;

void main()
{
int x, y, z;
cout<<"\n Enter x: ";
cin>>x;

cout<<"\n Enter y: ";


cin>>y;

z = (x >= 20 && y < 15);

cout<<"\n z = "<<z<<endl;
Output:
Enter x: 18
}
Enter y: 8

z=0
Loops
Iteration Statements
• In C/C++, and all other modern programming languages, iteration
statements (also called loops) allow a set of instructions to be
executed repeatedly until a certain condition is reached.

• This condition may be predefined (as in the for loop), or open-


ended (as in the while and do-while loops).
The for Loop
 for
The general form of the for statement
for (initialization; condition; increment)
statement;
 The for loop allow many variations, but its most common form works like this.
The initialization is an assignment statement that is used to set the loop
control variable.
 The condition is a relational expression that determines when the loop exits.
 The increment defines how the loop control variable changes each time the
loop is repeated. You must separate these three major sections by semicolons.
 The for loop continues to execute as long as the condition is true. Once the
condition becomes false, program execution resumes on the statement following
the for.
//for loop example 1 //for loop example 2
#include<iostream> #include<iostream>
using namespace std; using namespace std;
void main() void main()
{ {
int x; int x, z;
for (x=1; x<=10; for (x=100; x!=65; x-=5)
x++) {
cout<<x<<endl; z = x * x;
} cout<<"Square of "<<x<<" is
Output: "<<z<<endl;
1 }
2
3 } Output:
4 Square of 100 is 10000
5 Square of 95 is 9025
6 Square of 90 is 8100
7 Square of 85 is 7225
8 Square of 80 is 6400
9 Square of 75 is 5625
10 Square of 70 is 4900
The Infinite Loop
 Although you can use any loop statement to create an infinite loop, for is
traditionally used for this purpose. Since none of the three expressions that
form the for loop are required, you can make an endless loop by leaving the
conditional expression empty;

for (; ;)
cout<<"This loop will run forever "<<endl;

 Actually, the for(;;) construct does not guarantee an infinite loop


because a break statement, encountered anywhere inside the body of s
loop, causes immediate termination. Program control then resumes at the
code following the loop.
//The Infinite Loop
#include<iostream>
using namespace std;
void main()
{
char ch ;
for (;;)
{
ch = getchar(); // get a character
if (ch == 'Q')
break; // exit the loop
}
cout<<"You typed an Q"<<endl;
}

Output:
this is about the infinite loop. Q
You typed an Q
// Calculate factorials of a number
#include<iostream>
using namespace std;
void main()
{
unsigned int num;
unsigned long fact = 1;

cout<<"Enter a number: ";


cin>>num;

for (int j=num; j>0; j--)


fact *= j;

cout<<"Factorial is "<<fact<<endl;
}

Output:
Enter a number: 6
Factorial is 720
// Fibonacci Series
#include<iostream>
using namespace std;
void main()
{
int f = 1;

cout<<"Fibonacci Series: "<<endl;


cout<<"----------------"<<endl;

for (int p=0; p<50;)


{
cout<<f<<" ";
int sum = p + f;
p = f;
f = sum;
}
Output:
cout<<endl; Fibonacci Series:
--------------------
} 1 1 2 3 5 8 13 21 34 55
The while Loop

 while

its general form is


while (condition)
statement;
Where statement is either an empty statement, a single statement, or a

block of statements.

 The condition may be any expression and true is any nonzero value.

The loop iterates while the condition is true. When the condition becomes

false, program control passes to the line of code immediately following the

loop.
// Multiple statements in a while loop
// Prints numbers raised to fourth power
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{
int pow = 1, num = 1;

while (pow < 9999)


{
cout<<setw(2)<<num;
cout<<setw(6)<<pow<<endl; Output:
1 1
++num; 2 16
pow = num * num * num * num; 3 81
} 4 256
5 625
cout<<endl; 6 1296
} 7 2401
8 4096
9 6561
// Counts characters and words typed
#include<iostream>
using namespace std;
void main()
{
int chcount = 0;
int wdcount = 1;
int ch;
cout<<"Enter a phrase: \n";
while ( (ch=getchar() ) != '$')
{
if (ch==' ') Output:
Enter a phrase:
wdcount++; its is sunny day $
else
chcount++; Words = 5
} Letters = 13

cout<<"\n Words = "<<wdcount<<"\n Letters = "<<chcount<<endl;


}
The do-while Loop
 do-while
its general form is
do
{
statement;
} while (condition);

 Unlike for and while loops, which test the loop condition at the top of the
loop, the do-while loop checks its condition at the bottom of the loop.
 This means that a do-while loop always executes at least once.
// Demonstrate do-while loop
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{
long dividend, divisor;
char ch;
do
{
cout<<"\n Enter dividend: "; Output:
cin>>dividend; Enter dividend: 5
Enter divisor: 2
cout<<"\n Enter divisor: ";
cin>>divisor; Quotient is 2
Remainder is 1
if (divisor==0) Do you want to continue (y/n):y
{
Enter dividend: 12
cout<<"\n Illegal division \n"; Enter divisor: 3
continue; Quotient is 4
} Remainder is 0
cout<<"\n Quotient is "<<dividend / divisor; Do you want to continue (y/n):n
cout<<"\n Remainder is "<<dividend % divisor;
cout<<"\n Do you want to continue (y/n):";
cin>>ch;
} while (ch!='n');
}
// Demonstrate Prime Number
#include<iostream>
using namespace std;
void main()
{
unsigned long n, j;

cout<<"Enter a number: ";


cin>>n;

for (j=2; j<n; j++)


if(n%j==0)
{
cout<<"It's not prime, divisible by "<<j<<endl;
exit(0);
}

cout<<"It's prime number \n"; Output 1:


Enter a number: 17
} It's prime number

Output 2:
Enter a number: 12
It's not prime, divisible by 2
switch case
 C/C++ has a built-in multiple branch selection statement, called switch, which
successively tests the value of an expression against a list of constants. When a
match is found, the statements associated with that condition (constant) are
executed. The general form of the switch statement is

switch(expression)
{
case constant1:
statements sequence;
break;
case constant2:
statement sequence;
break;

default:
statement sequence;
}
switch Case (contd..)
 The expression must evaluate to a character or integer value. Floating-point
expressions, for example, are not allowed. The value of expression is tested, in order,
against the values of the constants specified in the case statements.

 When a match is found, the statement sequence associated with that case is
executed until the break statement or the end of the switch statement is reached.
The default statement is executed if no matches are found.

 The default is optional and, if it is not present, no action takes place if all matches
fail.

 The break statement is one of C/C++'s jump statements. You can use it in loops as
well as in the switch statement. When break is encountered in a switch,
program execution "jumps" to the line of code following the switch statement.
// Demonstrate Switch Statement
#include<iostream>
using namespace std;
void main()
{
char grade;
cout<<"\n Enter your grade: ";
cin>>grade;
cout<<"\n";
switch (grade)
{
case 'A':
cout<<"Excellent Work."<<endl; break;
case 'B':
cout<<"Good Work."<<endl; break;
Output 1:
case 'C': Enter your grade: B
cout<<"Average Work."<<endl; break; Good Work.
case 'D':
Output 2:
cout<<"Poor Work."<<endl; break; Enter your grade: a
default: a is not a valid letter grade.
cout<<grade<<" is not a valid letter grade."<<endl;
}
}
Functions
Function
 A function groups a number of program statements into a unit and gives it
a name. This unit can be invoked from other parts of the program.

 The most important reason to use functions is to aid in the conceptual


organization of a program. Dividing a program into functions is one of the
major principles of structured programming.

 Another reason to use functions is to reduce program size. Any sequence of


instructions that appears in a program more than once is a candidate for
being made into a function.

 The function's code is stored in only one place in memory, even though the
function is executed many times in the course of the program.
Flow of Control in Function Calls

Physical versus Logical Order of Functions


Function Components

Component Purpose Example


Declaration Specific function name, argument void func ();
(prototype) types, and return value. Alerts
compiler (and programmer) that
function is coming up later.

Call Causes the function to be executed. func ();

Definition The function itself. Contains the void func ()


lines of code that constitute the {
function //Lines of code
}

Declarator First line of definition void func ()


// Welcome program
#include<iostream>
using namespace std;
void Print2Lines(); // Function prototype
void Print4Lines();
void main()
{
Print2Lines(); // Function Call
cout<<" Welcome Home!"<<endl;
Print4Lines(); // Function Call
}
void Print2Lines() // Function Heading
{
cout<<"***************"<<endl;
cout<<"***************"<<endl;
} Output:
void Print4Lines() // Function Heading ***************
{ ***************
cout<<"***************"<<endl; Welcome Home!
cout<<"***************"<<endl; ***************
cout<<"***************"<<endl; ***************
***************
cout<<"***************"<<endl;
***************
}
// New Welcome program
#include<iostream>
using namespace std;
void PrintLines(int); // Function prototype
void main()
{
PrintLines(2); // Function Call
cout<<" Welcome Home!"<<endl;
PrintLines(4); // Function Call
}
void PrintLines(int numLines) // Function Heading
{
int count; // Loop control variable
count = 1;
while (count <= numLines)
{ Output:
cout<<"***************"<<endl; ***************
***************
count++;
Welcome Home!
} ***************
} ***************
***************
***************
Argument & Parameter
 Argument
A variable or expression listed in a call to function; also called actual
argument or actual parameter.

 Parameter
A variable declared in a function heading; also called formal argument or
formal parameter.
Syntax and Semantics of void Functions

 FunctionCall (to a void function)  FunctionDefinition (for a void function)


FunctionName (ArgumentList); void FunctionName (ParameterList)
{
 ArgumentList statement
.
Expression, Expression …………
.
.
 FunctionPrototyoe (for a void function) }
void FunctionName (ParameterList);

 ParameterList (in a function definition)


 ParameterList (in a function prototype) Datatype & VariableName,
Datetype & VariableName, Datatype & Datatype & VariableName ………
VariableName ………
// Passing Arguments to Function
#include<iostream>
using namespace std;
void repchar(char, int); // Function prototype
void main()
{
repchar('-', 43); // Function Call
cout<<"Data type Range"<<endl;
repchar('=', 23); // Function Call
cout<<"char\t-128 to 127"<<endl
<<"short\t-32,768 to 32,767"<<endl
<<"int\t-2,147,483,648 to 2,147,483,647"<<endl;
repchar('-', 43); // Function Call
}
void repchar(char ch, int n) // Function Heading
{
for(int j=0; j<n; j++) // Function Body
cout<<ch; Output:
cout<<endl; --------------------------------------------------
} Data type Range
=========================
char -128 to 127
short -32,768 to 32,767
int -2,147,483,648 to 2,147,483,647
--------------------------------------------------
// Passing Variables & Returning Values from Functions
// Demonstrates return value, coverts pounds to kg
#include<iostream>
using namespace std;
float lbstokg(float); // Function prototype
void main()
{
float lbs, kgs;
cout<<"Enter your weight in pounds: ";
cin>>lbs;
kgs = lbstokg(lbs); // Function Call
cout<<"\n Your weight in kilograms is "<<kgs<<endl;
}
float lbstokg(float pounds)// Function Heading
{
float kilograms = 0.453592 * pounds;
return kilograms; // Function Body
}
Output:
Enter your weight in pounds: 2.2

Your weight in kilograms is 0.997902


// Eliminates Unnecessary Variables
// Demonstrates return value, coverts pounds to kg
#include<iostream>
using namespace std;
float lbstokg(float); // Function prototype
void main()
{
float lbs;
cout<<"Enter your weight in pounds: ";
cin>>lbs;
cout<<"\n Your weight in kilograms is “<<lbstokg(lbs)<<endl;
}
float lbstokg(float pounds) // Function Heading
{
return 0.453592 * pounds; // Function Body
}

Output:
Enter your weight in pounds: 2.2

Your weight in kilograms is 0.997902


Library Functions
 Certain computations, such as taking square roots or finding the absolute value of a
number, are very common in programs.
 It would be an enormous waste of time if every programmer had to start from
scratch and create functions to perform these tasks. To help make the programmer's
life easier, every C++ system includes a standard library–a large collection of
prewritten functions, data types, and other items that any C++ programmer may
use. Here is a very small sample of some standard library functions:

Header File Function Argument Result Result


Type(s) Type (Value Returned)
<cstdlib> abs(i) int int Absolute value of i
<cmath> cos(x) float float Cosine of x (x is in radians)
<cmath> fabs(x) float float Absolute value of x
<cstdlib> labs(j) long long Absolute value of j
<cmath> pow(x, y) float float x raised to the power y (if x = 0.0, y must be
positive; if x ≤ 0.0, y must be a whole
number)
<cmath> sin(x) float float Sine of x (x is in radians)
<cmath> sqrt(x) float float Square root of x (x ≥ 0.0)
//This program calculates the square root of the number
using standard library function.
#include<iostream>
#include<cmath>
using namespace std;
void main()
{
double x;
char ch;
do
{
cout<<"\n Enter number: ";
cin>>x;
cout<<"Square root of "<<x<<" is "<<sqrt(x)<<endl;
cout<<"Do you want to continue (y/n)? ";
cin>>ch; Output:
} while (ch!='n'); Enter number: 16
} Square root of 16 is 4
Do you want to continue (y/n)? y
Enter number: 50
Square root of 50 is 7.07107
Do you want to continue (y/n)? n
Parameters
 When a function is executed, it uses the arguments given to it in the function call.
How is this done? The answer to this question depends on the nature of the
parameters. C++ supports two kinds of parameters:

 Value Parameter
– A parameter that receives a copy of the value of the corresponding argument.

 Reference Parameter
– A parameter that receives the location (memory address) of the caller's
argument.

void Example (int& param1, int param2, int param3)

By Reference By Value By Value


// Call by Value
#include<iostream>
using namespace std;
int test (int); // Function prototype
void main()
{
int a = 15;
cout<<" a = "<<a<<endl;
cout<<" After Calling function...."<<endl;
cout<<" a = "<<test(a)<<endl;
cout<<" Value in variable 'a' is "<<a<<endl;
}
int test (int n) // Function Heading
{
n++;
return n; Output:
} a = 15
After Calling function....
a = 16
Value in variable 'a' is 15
// Call by Reference
#include<iostream>
using namespace std;

int myfunc (int&); // Function prototype

void main()
{
int i = 21;
cout<<" i = "<<i<<endl;
i /= 3;
cout<<" I am Calling function...."<<endl;
cout<<" i = "<<myfunc(i)<<endl;
cout<<" Now Value in variable 'i' is "<<i<<endl;
}

int myfunc (int& y) // Function Heading


{
Output:
y *= 7; i = 21
return y; I am Calling function....
i = 49
} Now Value in variable 'i' is 49
Function Overloading
 Function Overloading is the process of using the same name for two or
more functions.

 The secret to overloading is that each redefinition of the function must use
either different types of parameters or a different number of parameters.

 It is only through these differences that the complier knows which function
to call in any given situation.
// Function Overloading Prog-1
#include<iostream>
using namespace std;
int myfunc (int i); // these differ in types of parameters
double myfunc (double i);
void main()
{
cout<<myfunc(10)<<endl; // Calls myfunc(int i)
cout<<myfunc(5.4)<<endl; // Calls myfunc(double i)
}
double myfunc (double i) // Function Heading
{
return i;
}
int myfunc (int i) // Function Heading
{
return i; Output:
} 10
5.4
// Function Overloading Prog-2
#include<iostream>
using namespace std;
int myfunc (int i); // these differ in types of parameters
int myfunc (int i, int j);
void main()
{
cout<<myfunc(10)<<endl; // Calls myfunc(int i)
cout<<myfunc(4,5)<<endl; // Calls myfunc(int i, int j)
}
int myfunc (int i, int j) // Function Heading
{
return i * j;
}
int myfunc (int i) // Function Heading
{
return i; Output:
} 10
20
Function Overloading (contd..)
 As mentioned, the key point about function Overloading is that the
functions must differ in regard to the types and/or number of parameters.
Two functions differing only in their return types cannot be overloaded.

 For example, this is an invalid attempt to overload myfunc():

int myfunc (int i);


float myfunc (int i);
// Error: differing return types are insufficient when
overloading
// Orders two arguments passed by reference
#include<iostream>
using namespace std;
void order (int&, int&); // prototype
void main()
{
int n1 = 99, n2 = 11; // this pair not ordered
int n3 = 22, n4 = 88; // this pair ordered
order (n1, n2); // order each pair of numbers
order (n3, n4);
cout<<" n1 = "<<n1<<endl; // printout all numbers
cout<<" n2 = "<<n2<<endl;
cout<<" n3 = "<<n3<<endl;
cout<<" n4 = "<<n4<<endl;
}
void order (int& numb1, int& numb2) // order two numbers
{
if (numb1 > numb2)
{
int temp = numb1; // swap them Output:
numb1 = numb2; n1 = 11
numb2 = temp;
n2 = 99
}
}
n3 = 22
n4 = 88
Scope, Lifetime and More on Functions
Scope
 The region of program code where it is legal to reference (use) an identifier.

 Local Scope
The scope of an identifier declared inside the a block extends from the
point of declaration to the end of that block.
Also, the scope of a function parameter (formal parameter) extends from
the point of declaration to the end of the block that is the body of the
function.

 Global Scope
The scope of an identifier declared outside all functions and classes extends
from the point of declaration to the end of the entire file containing the
program code.
Name Precedence
 The precedence that a local identifier in a function has over a global
identifier with the same name in any references that the function makes to
that identifier; also called name hiding.

int gamma; // Global variable


void main ()
{
gamma = 3;
.
.
}
void SomeFunc ()
{
gamma = 5;
}
// Demonstrate local and global declarations
#include<iostream>
using namespace std;
void SomeFunc (double); // Function Prototype
const int a = 17; // A global constant
int b; // A global variable
int c; // Another global variable
void main()
{
b = 4; // Assignment to global b
c = 6; // Assignment to global c
SomeFunc (42.8); // Function Call
}
void SomeFunc (double c) // Prevent access to global c
{
double b; // Prevent access to global b
b = 2.3; // Assignment to local b
cout<<" a = "<<a<<endl; // Output global a (17)
cout<<" b = "<<b<<endl; // Output local b (2.3)
cout<<" c = "<<c<<endl; // Output local c (42.8) Output:
} a = 17
b = 2.3
c = 42.8
Scope Rules
 The rules that determine where in the program an identifier may be accessed,
given the point where that identifier is declared.
1. A function name has global scope. Function definitions cannot be nested
within function definitions.
2. The scope of a function parameter is identical to the scope of a local
variable declared in the outermost block of the function body.
3. The scope of a global variable or constant extends from its declaration to
the end of the file, except as noted in Rule 5.
4. The scope of a local variable or constant extends from its declaration to
the end of the block in which it is declared. This scope includes any
nested blocks, except as noted in Rule 5.
5. The scope of an identifier does not include any nested blocks that contain
a locally declared identifier with the same name (local identifiers have
name precedence).
// Scope_Rules Program
#include<iostream>
using namespace std;
void Block1(int, char&); // Function Prototypes
void Block2();
int a1; // A global variable
char a2; // Another global variable
void main()
{ ………
………
}
void Block1(int a1, char& b2)// Prevent access to global a1
{ // Has same scope as c1,d2
int c1; // A variable local to Block1
int d2; // Another variable local to Block1
…………
}
void Block2()
{
int a1; // Prevents access to global a1
int b2; // Local to Block2; no conflict with b2 in Block1
while (…)
{ // Block3
int c1; // Local to Block3; no conflict with c1 in Block1
int b2; // Prevents non-local access to b2 in Block2; no conflict with b2 in Block1

}
}
Scope Diagram for Scope_Rules Program

int a1;
char a2;
int main ( )
{

}
void block1 ( int a1,
{ char& b2 )
int c1;
int d2;
}
void block2 ( )
{
int a1;
int b2;
while (…)
{ //Block3
int c1;
int b2;
}
}
Lifetime of a Variable
 Lifetime
– The period of time during program execution when an identifier has
memory allocated to it.

 Automatic Variable
– A variable for which memory is allocated and de-allocated when control
enters and exits the block in which it is declared.

 Static Variable
– A variable for which memory remains allocated throughout the
execution of the entire program.
// Demonstrates static variables
#include<iostream>
using namespace std;
float getavg (float); // Function Prototypes
void main()
{
float data=1, avg;
while (data != 0)
{
cout<<"\n Enter a number: ";
cin>>data; Output:
avg = getavg (data); Enter a number: 10
cout<<" New average is "<<avg<<endl; New average is 10
} Enter a number: 8
} New average is 9
// finds averages of old plus new data
Enter a number: 0
float getavg (float newdata) New average is 6
{
static float total = 0; // static variables are initialized
static int count = 0; // only once per program
count++; // increment count
total += newdata; // add new data to total
return total / count; // return the new average
}
Arrays
Arrays
 An array is a consecutive group of memory locations.

 Each group is called an element of the array.

 The contents of each element are of the same type.

– Could be an array of int, double, char, ……

 We can refer to individual elements by giving the position number


(index) of the element in the array.
Memory and Arrays
Arrays (contd..)
 As a data structure, an array differs from a struct or class in
two fundamental ways:

1. An array is a homogenous data structure (all components are


of the same data type), whereas structs and classes are
heterogeneous types (their components may be of different
types).

2. A component of an array by its position in the structure,


whereas a component of a struct or class is accessed by
an identifier (the member name).
One-dimensional Array
 A structured collection of components, all of the same type, that is given a
single name.
 Each component (array element) is accessed by an index that indicates the
component's position within the collection.
 Here is a syntax template describing the simplest form of a one-dimensional
array declaration:

DataType ArrayName [ConstIntExpression];


// Input 1000 integer values and print them in reverse order
#include<iostream>
using namespace std;
void main()
{
int value0;
int value1;
int value2;
.
.
int value9999;

cin>>value0;
cin>>value1;
cin>>value2;
.
.
cin>>value9999;

cout<<value9999<<endl;
cout<<value9998<<endl;
cout<<value9997<<endl;
.
.
cout<<value0<<endl;
}
/* Input 1000 integer values and print them in reverse order
using arrays */
#include<iostream>
using namespace std;

void main()
{
int value[1000];
int number;

for (number=0; number<1000; number++)


cin>>value[number];

for (number=999; number>=0; number--)


cout<<value[number]<<endl;
}
Accessing Individual Components
 The syntax template for accessing an array component is

ArrayName [IndexExpression];

 The index expression may be as simple as a constant or a variable name or


as complex as a combination of variables, operators, and function calls.
Whatever the form of the expression, it must result in an integer value.
/* Averaging Array Elements */
#include<iostream>
using namespace std;
const int SIZE = 6; // number of array elements
void main()
{
float sales[SIZE]; // array of 6 variables
cout<<"\nEnter widget sales for days"<<endl;
for (int j=0; j<SIZE; j++) // put figures in array
cin>>sales[j];
float total = 0;
for (j=0; j<SIZE; j++) // read figures from array
total += sales[j]; // find total
float average = total / SIZE; // find average
cout<<"\nAverage = "<<average<<endl;
} Output:
Enter widget sales for days
8
5
6
4
5
6
Average = 5.66667
Array Initialization – 1 Dimension

int number [5] = {3, 7, 12, 24, 45}; int number [5] = {3, 7};

3 7 12 24 45 3 7 0 0 0

The rest
are filled
with 0s

a) Basic Initialization c) Partial Initialization

int number [ ] = {3, 7, 12, 24, 45}; int number [1000] = {0};

3 7 12 24 45 0 0 …. 0 0

All filled
with 0s

b) Initialization without size d) Initialization to all zeros


Out-of-Bounds Array Indexes
 Given the declaration

float alpha [100];

the valid range of index is 0 through 99. What happen if we execute the
statement

alpha [i] = 62.4;

 When i is less than 0 or when i is greater than 99? The result is that a
memory location outside the array is accessed.
 C++ does not check for invalid (out-of-bounds) array indexes either at
compile time or at runtime.
Aggregate Array Operations

Aggregate Operation Arrays


I/O No

Assignment No

Arithmetic No

Comparison No

Argument Passage Reference only

Return from a function No


Aggregate Array Operations (contd..)

 If x and y declared as:


int x[50];
int y[50];

 There is no aggregate assignment y to x:


x = y; // Not valid

 To copy array y into array x, you must do it yourself, element by element:


for (index=0; index<50; index++)
x[index] = y[index];
 Similarly, there is no aggregate comparison of arrays:
if (x==y) // Not valid
Aggregate Array Operations (contd..)
 You can not perform aggregate I/O of arrays:
cout<< x; // Not valid
or aggregate arithmetic on arrays:
x = x + y; // Not valid
 It is not possible to return an entire array as the value of a value-returning
function:
return x; // Not valid
 The only thing you can do to an array as a whole is to pass it as an
argument to a function:
DoSomething (x);
 Passing an array as an argument gives the function access to the entire
array.
2-D Array Example

table[0][0] table[0][1] table[0][2] table[0][3]


int table [5][4]; table[0]

table[1][0] table[1][1] table[1][2] table[1][3]


table[1]

table[2][0] table[2][1] table[2][2] table[2][3]


table[2]

table[3][0] table[3][1] table[3][2] table[3][3]


table[3]

table[4][0] table[4][1] table[4][2] table[4][3]


table[4]
// Multidimensional Arrays
#include<iostream>
#include<iomanip>
using namespace std;
const int DISTRICTS = 3; // array dimension
const int MONTHS = 2;
void main()
{ int d, m;
float sales [DISTRICTS][MONTHS]; // 2-dimensional array definition
cout<<endl;

for (d=0; d<DISTRICTS; d++) // get array values


for (m=0; m<MONTHS; m++)
{
cout<<"Enter sales for district "<<d+1;
cout<<" month "<<m+1<<": ";
cin>>sales[d][m]; // put numbers in array
}
Output:
cout<<"\n\n";
cout<<"\t\tMonth\n"; Enter sales for district 1 month 1: 1234
cout<<"\t1\t2"; Enter sales for district 1 month 2: 5678
Enter sales for district 2 month 1: 9876
for (d=0; d<DISTRICTS; d++) Enter sales for district 2 month 2: 5432
{ Enter sales for district 3 month 1: 7890
cout<<"\n District "<<d+1; Enter sales for district 3 month 2: 1357
for (m=0; m<MONTHS; m++) // read values from array
cout<<setw(8)<<sales[d][m]; Month
} 1 2
cout<<endl; District 1 1234 5678
} District 2 9876 5432
District 3 7890 1357
// Initializing Multidimensional Arrays
#include<iostream>
#include<iomanip>
using namespace std;
const int DISTRICTS = 4; // array dimension
const int MONTHS = 3;
void main()
{
int d, m;
double sales [DISTRICTS][MONTHS] // initialize array elements
= { {1432.7, 234.50, 654.01},
{322.00, 13838.32, 17589.88},
{9328.34, 934.00, 4492.30},
{12838.29, 2332.63, 32.93} };
cout<<"\n\n"; Output:
cout<<"\t\t\tMonth\n"; Month
1 2 3
cout<<"\t1\t2\t3";
District 1 1432.7 234.5 654.01
for (d=0; d<DISTRICTS; d++) District 2 322 13838.3 17589.9
{ District 3 9328.34 934 4492.3
District 4 12838.3 2332.63 32.93
cout<<"\n District "<<(d+1);
for (m=0; m<MONTHS; m++) // access array element
cout<<setw(10)<<sales[d][m];
}
cout<<endl;
}
Passing Array Elements
 Individual elements can be passed to a function like ordinary values.

#include <iostream.h> 3 base[0]


void print_square (int);
void main () 7 base[1]
{
int i; 2 base[2]
int base[5]={3, 7, 2, 4, 5};
for (i=0; i<5; i++) 4 base[3]
print_square (base[i]);
} 5 base[4]

base
void print_square (int x)
{
cout<<" "<<x*x;
x
return;
}
Passing Array as Parameters

 Arrays can be passed to functions in their entirety.


 All that is required is the address of the first element and
dimensions of the array.
 The remainder of the array will be passed by reference
automatically.
 Using “[ ]” in the formal parameter specification indicates that
the variable is an array.
Example: Multiple an array by 2
 Individual elements can be passed to a function like ordinary values.
Before After
#include <iostream.h> 3 base[0] 6
void multiply (int x[]);
void main () 7 base[1] 14
{
int base[5]={3, 7, 2, 4, 5}; 2 base[2] 4
multiply (base);
4 base[3] 8
} //main

void multiply (int x[]) 5 base[4] 10


{
int i; x base base

for (i=0; i<5; i++) Any reference to


x[i]*=2; x means a
reference to
return; i base[]
} //multiply
Background Information (C, C++ & Arrays as Arguments)
Structures
Structures
 Structures form a very large building block with which to collect like data
into one collective unit.
 They are versatile data structure in which to clump data together in
convenient little packages.
 Examples:
 Groceries are organized into bags
 Employees into departments
 Words into sentences
 A structure is a collection of simple variables. The variables in a structure
can be of different types: Some can be int, some can be float, and so
on. (This is unlike the arrays in which all the variables must be the same
type).
 The data items in a structure are called the members of the structure.
Structure Declaration
struct TypeName
{
MemeberList
};

MemberList
DataType MemberName;
DataType MemberName;
.
.
.
Specifying the Structure
 The structure specifier tells how the structure is organized. It specifies what
members the structure will have. Here it is:

struct part

int modelno;

int partno;

float cost;

};
Defining a Structure Variable
 The first statement in main()
part part1;
defines a variable, called part1,of type
structure part.

 This definition reserves space in memory


for part1. How much space? Enough to
hold all the members of part1—namely
modelno, partno and cost.

 In this case there will be 4 bytes for each


of the two ints, and 4 bytes for the
float.
Accessing Structure Members
 Once a structure variable has been defined, its
members can be accessed using something
called the dot operator.

 Here's how the first member is given a value:

part1.modelno = 6244;
// Uses parts inventory to demonstrate structures
#include<iostream>
using namespace std;

struct part // Specify a structure


{
int modelno; // Structure members
int partno;
float cost;
};

void main()
{
part part1; // Define a structure variable
part1.modelno = 7896; // Accessing structure members
part1.partno = 456;
part1.cost = 321.56f;

cout <<"\n Model Number: "<<part1.modelno;


cout <<"\n Part Number: "<<part1.partno; Output:
cout <<"\n Cost: $"<<part1.cost; Model Number: 7896
Part Number: 456
cout<<endl;
Cost: $321.56
}
Combining Specifier and Definition
#include<iostream>
using namespace std;
Struct
{ int modelno; // Structure members
int partno;
float cost;
}part1; // Definition goes here

void main()
{
part1.modelno = 7896; // Accessing structure members
part1.partno = 456;
part1.cost = 321.56f;

cout <<"\n Model Number: "<<part1.modelno;


cout <<"\n Part Number: "<<part1.partno; Output:
cout <<"\n Cost: $"<<part1.cost; Model Number: 7896
Part Number: 456
cout<<endl; Cost: $321.56
}
// Initialization of structure variables
#include<iostream>
using namespace std;
struct part //specify a structure
{ int modelno; //ID number of widget
int partno; //ID number of widget part
float cost; //cost of part
};
void main()
{
part part1 = {6244, 373, 217.55}; //initialize variable
part part2; //define variable
//display first variable
cout <<"\n Model Number: "<<part1.modelno;
cout <<"\n Part Number: "<<part1.partno;
cout <<"\n Cost: $"<<part1.cost<<endl;

part2 = part1; //assign first variable to second Output:


Model Number: 6244
//display second variable Part Number: 373
cout <<"\n Model Number: "<<part2.modelno; Cost: $217.55
cout <<"\n Part Number: "<<part2.partno;
Model Number: 6244
cout <<"\n Cost: $"<<part2.cost<<endl; Part Number: 373
} Cost: $217.55
Aggregate Operations on struct
 In addition to accessing individual components of a struct variable, we
can in some cases use aggregate operations.
 An aggregate operation is one that manipulates the struct as an entire
unit.
 Aggregate operation: An operation on a data structure as a whole, as
opposed to an operation on an individual component of the data structure.

Aggregate Operation Allowed on struct?


I/O No
Assignment Yes
Arithmetic No
Comparison No
Argument passage Yes, by value or by reference
Return as a function's return value Yes
Aggregate Operations on struct (contd..)

 According to the table, one struct variable can be assigned to another. However,
both variables must be declared to be of the same type.
 For example, given the declarations
StudentRec student;
StudentRec anotherStudent;
 The statement
anotherStudent = student;
copies the entire contents of the struct variable student to the variable
anotherStudent, member by member.
 On the other hand, aggregate arithmetic operations and comparisons are not allowed
(primarily because they wouldn't make sense):
student = student * anotherStudent; // Not allowed
if (student < anotherStudent) // Not allowed
 Furthermore, aggregate I/O is not permitted:
cin>>student; // Not allowed
 We must input or output a struct variable one member at a time:
cin>> student.firstName;
cin >> student.lastName;
// demonstrates nested structures
#include<iostream>
using namespace std;
struct Distance //English distance
{ int feet;
float inches;
};
struct Room //rectangular area
{ Distance length; //length of rectangle
Distance width; //width of rectangle
};
void main()
{
Room dining; //define a room
dining.length.feet = 13; //assign values to room
dining.length.inches = 6.5;
dining.width.feet = 10; Output:
dining.width.inches = 0.0; Dining room area is 135.417 square feet
//convert length & width
float l = dining.length.feet + dining.length.inches/12;
float w = dining.width.feet + dining.width.inches/12;
//find area and display it
cout<<"\n Dining room area is "<<l * w<<" square feet\n";
}
// Demonstrates passing structure as argument
#include<iostream>
using namespace std;
struct Distance //English distance
{ int feet;
float inches;
};
void engldisp (Distance); // Function Prototype
void main()
{ Distance ucs1, ucs2; // Define two lengths
//get length ucs1 from user
cout<<"\n Enter feet: "; cin>>ucs1.feet;
cout<<" Enter inches: "; cin>>ucs1.inches;
//get length ucs2 from user
Output:
cout<<"\n Enter feet: "; cin>>ucs2.feet;
Enter feet: 10
cout<<" Enter inches: "; cin>>ucs2.inches; Enter inches: 6.75
cout<<"\n ucs1 = ";
engldisp(ucs1); // Display length 1 Enter feet: 13
cout<<"\n ucs2 = "; Enter inches: 0.0
engldisp(ucs2); // Display length 2 ucs1 = 10'-6.75"
}
ucs2 = 13'-0"
// Display structure of type Distance in feet and inches
void engldisp (Distance ucs) // Parameter ucs of type Distance
{
cout<<ucs.feet<<"\'-"<<ucs.inches<<"\""<<endl;
}
// Demonstrates returning a structure
#include<iostream>
using namespace std;
struct Distance //English distance
{ int feet;
float inches;
};

Distance addengl (Distance, Distance); // Function Prototype


void engldisp (Distance);
void main()
{ Distance d1, d2, d3; // Define three lengths
//get length d1 from user
cout<<"\n Enter feet: "; cin>>d1.feet;
cout<<" Enter inches: "; cin>>d1.inches;
//get length d2 from user
cout<<"\n Enter feet: "; cin>>d2.feet;
cout<<" Enter inches: "; cin>>d2.inches;
cout<<endl;
d3 = addengl (d1, d2); // d3 is sum of d1 and d2
engldisp(d1); cout<<" + "; // Display all lengths
engldisp(d2); cout<<" = ";
engldisp(d3); cout<<" \n";
}
// Demonstrates returning a structure (contd..)
// Adds two structures of type Distance, return sum
Distance addengl(Distance dd1, Distance dd2)
{ Distance dd3; // define a new
structure for sum
dd3.inches = dd1.inches + dd2.inches; // add inches
dd3.feet = 0;
if (dd3.inches >= 12.0)
{
dd3.inches - = 12.0; // decrease inches by 12.0
dd3.feet++; // increase feet by 1
}

dd3.feet += dd1.feet + dd2.feet; // add the feet


return dd3; // return structure
}
// Display structure of type Distance in feet and inches
void engldisp (Distance ucs)
{
cout<<ucs.feet<<"\'-"<<ucs.inches<<"\""<<endl;
} Output:
Enter feet: 13
Enter inches: 6.75
Enter feet: 10
Enter inches: 8.5
13'-6.75" + 10'-8.5" = 24'-3.25"
Unions & Enumeration
Unions
• A union is a memory location that is shared by two or more
different variables, generally of different types, at different
times. Declaring is similar to declare a structure.
• Its general form is:
union union-type-name
{
type member-name;
type member-name;
type member-name;
.
.
.
}union-variable;
Specifying the Union
union u_type
{
int i;
char ch;
};
u_type cnvt;

• In cnvt, both integer i and character ch shared the same memory


location. Of course, i occupies 4 bytes and ch uses only 1.

• When a union variables is declared, the complier automatically


allocates enough storage to hold the largest member of the union.
Union
Example:
union
{
int i;
double d;
} u;

• The members of a union are accessed in the same way as members


of a structure:

u.i = 15; or u.d = 8.89;

• Since u.i and u.d have the same memory address, changing the
value of one alters the value of the other.
Union
• Unions have the same properties as structures.

• Unions can be initialized (the initializer specifies the value of the first
member).

• Unions can be assigned, passed to functions, and returned by


functions.

• Uses of unions:
– To save space.

– To view a data item in two or more different ways.

– To build heterogeneous data structures.


Union
• Unions have the same properties as structures:

• Unions can be initialized (the initializer specifies the value of the first
member).

• Unions can be assigned, passed to functions, and returned by


functions.

• Uses of unions:
– To save space.

– To view a data item in two or more different ways.

– To build heterogeneous data structures.


Enumeration
• An enumeration is a collection of named integer constants.

• Syntax of enum specifier:


enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

• Difference between enum type & int type

• enum type:
– A small number of values are individually named and are referred to by name.
Enumeration are treated internally as Integers.

• int type:
– A large number of values are not named and are referred to by value.
// Demonstrates enum type

#include<iostream>
using namespace std;
// Specify enum type
enum days_of_week {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

void main()
{
days_of_week day1, day2;// define variables of type days_of_week

day1 = Mon; // give values to variables


day2 = Thu;

int diff = day2 - day1; // can do integer arithmetic


cout<<" Days between = "<<diff<<endl;

if (day1 < day2) // can do comparison


cout<<" day1 comes before day2\n"; Output:
} Days between = 3
day1 comes before day2
Other Example
enum months {Jan, Feb, Mar, Apr, May, Jun,
Jul, Aug, Sep, Oct, Nov, Dec};

enum Switch {off, on};

enum meridian {am, pm};

enum directions {north, south, east, west};

enum rank {Two, Three, Four, Five, Six, Seven, Eight,


Nine, Ten, Jack, Queen, King, Ace};
Strings
Strings
• 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. This is the only type of string defined by C, and it is still the
most widely used. Sometimes null-terminated strings are called
C-strings.

– C++ also defines a string class, called string, which provides an


object-oriented approach to string handling.
Null-Terminated Strings
• 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 str that can hold a 10-character


string, you would write

char str[11];

This makes room for the null at the end of the string.

str[0]= 'H';

str[1]= 'i';

str[2]= '\0';
String Variables
// Demonstrate String Variables
#include<iostream>
using namespace std;
const int MAX = 80;// Max characters in string
void main()
{
char str[MAX]; // String variable str
cout<<"\n Enter a string: ";
cin>>str; //put string in str
//display string from str
cout<<"You entered :"<<str<<endl;
}
Avoiding Buffer Overflow
// Avoids Buffer Overflow
#include <iostream>
#include <iomanip>
using namespace std;
const int MAX = 20; // Max characters in string
void main()
{
char str[MAX]; //string variable str
cout<<"\nEnter a string: ";
cin>>setw(MAX)>>str; //put string in str, no more than MAX chars
cout<<"You entered: "<<str<<endl;
Output:
}
Enter a string:
11223344556677889900
You entered:
1122334455667788990
String Constants
// Initialized string

#include <iostream>
using namespace std;

void main()
{
char str[] = "Listen to many, speak to a few. ";
cout<<str<<endl;
}
Output:
Listen to many, speak to a few.
Reading Embedded Blanks
// Reads string with embedded blanks
#include <iostream>
using namespace std;

const int MAX = 80; //max characters in string

void main()
{
char str[MAX]; //string variable str
cout<<"\nEnter a string: ";
cin.get(str, MAX); //put string in str
cout<<"You entered: "<<str<<endl;
}

To read text containing blanks we use another function, cin.get(). This syntax
means a member function get() of the stream class of which cin is an object.
Reading Multiple Lines
// Reads multiple lines, terminates on '$' character
#include <iostream>
using namespace std;

const int MAX = 2000; //max characters in string


char str[MAX]; //string variable str

void main()
{
cout<<"\nEnter a string:\n";
cin.get(str, MAX, '$'); //terminate with $
cout<<"You entered:\n"<<str<<endl;
}
Copying a String the Hard Way
// Copies a string using a for loop
#include <iostream>
#include <cstring> //for strlen()
using namespace std;
const int MAX = 80; //size of str2 buffer
void main()
{ //initialized string
char str1[] = "Oh, Captain, my Captain! our fearful trip is done";
char str2[MAX]; //empty string

for(int j=0; j<strlen(str1); j++) //copy strlen characters


str2[j] = str1[j]; // from str1 to str2

str2[j] = '\0'; //insert NULL at end


cout<<str2<<endl; //display str2
}
Output:
Oh, Captain, my Captain! our fearful trip is done
Copying a String the Easy Way
// Copies a string using strcpy() function
#include <iostream>
#include <cstring> //for strcpy()
using namespace std;
const int MAX = 80; //size of str2 buffer
void main()
{
char str1[] = "Tiger, tiger, burning bright\n"
"In the forests of the night";

char str2[MAX]; //empty string

strcpy(str2, str1); //copy str1 to str2

cout << str2 << endl; //display str2


} Output:
Tiger, tiger, burning bright
In the forests of the night
Arrays of Strings
// Array of strings
#include <iostream>
using namespace std;
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string

void main()
{ //array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday" };
Output:
for(int j=0; j<DAYS; j++) //display every string
Sunday
Monday
cout<<star[j]<<endl; Tuesday
} Wednesday
Thursday
Friday
Saturday
Arrays of Strings
// Array of strings
#include <iostream>
using namespace std;
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string

void main()
{ //array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday" };
Output:
for(int j=0; j<DAYS; j++) //display every string
Sunday
Monday
cout<<star[j]<<endl; Tuesday
} Wednesday
Thursday
Friday
Saturday
Defining String Objects
// Defining and assigning string objects
#include <iostream>
#include <string>
using namespace std;
void main()
{
string s1("Man"); //initialize
Output:
string s2 = "Beast"; //initialize
s3 = Man
string s3;
s3 = Neither Man nor Beast
s3 = s1; //assign Beast nor Man
cout<<"s3 = "<<s3<<endl;
s3 = "Neither " + s1 + " nor "; //concatenate

s3 += s2; //concatenate
cout<<"s3 = "<<s3<<endl;

s1.swap(s2); //swap s1 and s2


cout<<s1<<" nor "<<s2<<endl;
}
Modifying String Objects
// Changing parts of string objects
#include <iostream>
#include <string>
using namespace std;
void main()
{
string s1("Yes, Pascal is better");
string s2 = "++";

s1.erase(0, 5); //remove "Yes, "


s1.insert(0, s2); //insert "++" at beginning
s1.replace(0, 6, "C"); //replace 'c' with 'C'
s1.append(" language !"); //append " language"

cout<<"s1: "<<s1<<endl;
cout<<"s1 is "<<s1.size()<<" characters"<<endl;
} Output:
s1: Cal is better language !
s1 is 24 characters
Classes & Objects
Class
• A class is an expanded concept of a data structure: instead of holding only data,
it can hold both data and functions.
• An object is an instantiation of a class. In terms of variables, a class would be
the type, and an object would be the variables.
• Classes are generally declared using the keyword class, with the following
format:
class class-name
{
private data and functions
access-specifier:
data and functions
access-specifier:
data and functions
// ………
access-specifier:
data and functions
} object-list;
Class (contd..)
• The object-list is optional, it declares objects of the class. Here
access-specifier is one of these three C++ keywords:
– public
– Private
– protected

• These specifier modify the access rights that the members following
them acquire:
– Private members of a class are accessible only from within other members of the
same class or from their friends.

– Protected members are accessible from members of their same class and from
their friends, but also from members of their derived classes.

– Finally, public members are accessible from anywhere where the object is visible.
Specifying the Class
• By default, all members of a class declared with the class keyword have
private access for all its members. Therefore, any member that is declared
before one other class specifier automatically has private access. For
example:
class CRectangle
{
int x, y;
public:
void set_values (int,int);
int area ();
} rect;

• Declares a class (i.e., a type) called CRectangle and an object (i.e., a


variable) of this class called rect. This class contains four members: two
data members of type int (member x and member y) with private access
(because private is the default access level) and two member functions with
public access: set_values() and area(), of which for now we have only
included their declaration, not their definition.
Example of Class CRectangle
// classes example
#include <iostream>
using namespace std;
class CRectangle
{
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b)
{
x = a;
y = b;
}
void main ()
{
CRectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
}
Example of Class CRectangle
• The most important new thing in this code is the operator of scope (::, two colons)
included in the definition of set_values(). It is used to define a member of a class from
outside the class definition itself.
• You may notice that the definition of the member function area() has been included
directly within the definition of the CRectangle class given its extreme simplicity,
whereas set_values() has only its prototype declared within the class, but its definition
is outside it. In this outside definition, we must use the operator of scope (::) to specify
that we are defining a function that is a member of the class CRectangle and not a
regular global function.
• The scope operator (::) specifies the class to which the member being declared belongs,
granting exactly the same scope properties as if this function definition was directly
included within the class definition. For example, in the function set_values() of the
previous code, we have been able to use the variables x and y, which are private members
of class CRectangle, which means they are only accessible from other members of their
class.
• The only difference between defining a class member function completely within its class
or to include only the prototype and later its definition, is that in the first case the function
will automatically be considered an inline member function by the compiler, while in the
second it will be a normal (not-inline) class member function, which in fact supposes no
difference in behavior.
// one class, two objects

#include <iostream>
using namespace std;
class CRectangle
{
int x, y;
public:
void set_values(int,int);
int area() { return (x*y); }
};
void CRectangle::set_values (int a, int b)
{
x = a;
y = b;
}
void main ()
{
CRectangle rect, rectb;
rect.set_values(3,4);
rectb.set_values(5,6);
cout<<"rect area: "<<rect.area()<<endl; Output:
cout<<"rectb area: "<<rectb.area()<<endl; rect area: 12
} rectb area: 30
One Class, Two Objects
• In this concrete case, the class (type of the objects) to which we are talking
about is CRectangle, of which there are two instances or
objects: rect and rectb. Each one of them has its own member variables and
member functions.

• Notice that the call to rect.area() does not give the same result as the call
to rectb.area(). This is because each object of class CRectangle has its
own variables x and y, as they, in some way, have also their own function
members set_value() and area() that each uses its object's own variables
to operate.

• That is the basic concept of object-oriented programming: Data and functions


are both members of the object. We no longer use sets of global variables that
we pass from one function to another as parameters, but instead we handle
objects that have their own data and functions embedded as members. Notice
that we have not had to give any parameters in any of the calls
to rect.area or rectb.area. Those member functions directly used the data
members of their respective objects rect and rectb.
Constructors
• Objects generally need to initialize variables or assign dynamic memory during
their process of creation to become operative and to avoid returning unexpected
values during their execution.

• For example, what would happen if in the previous example we called the
member function area() before having called function set_values()?
Probably we would have gotten an undetermined result since the
members x and y would have never been assigned a value.

• In order to avoid that, a class can include a special function called constructor,
which is automatically called whenever a new object of this class is created. This
constructor function must have the same name as the class, and cannot have
any return type; not even void.
// class constructor
#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public:
CRectangle (int, int);
int area () {return (width * height); }
};
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}
void main ()
{
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout<<"rect area: "<<rect.area()<<endl; Output:
cout<<"rectb area: "<<rectb.area()<<endl; rect area: 12
} rectb area: 30
Constructors (contd..)
• As you can see, the result of this example is identical to the previous one. But
now we have removed the member function set_values(), and have included
instead a constructor that performs a similar action: it initializes the values
of width and height with the parameters that are passed to it.

• Notice how these arguments are passed to the constructor at the moment at
which the objects of this class are created:

CRectangle rect (3,4);


CRectangle rectb (5,6);

• Constructors cannot be called explicitly as if they were regular member


functions. They are only executed when a new object of that class is created.

• You can also see how neither the constructor prototype declaration (within the
class) nor the latter constructor definition include a return value; not even void.
Destructor
• The destructor fulfills the opposite functionality. It is automatically called when
an object is destroyed.

• The destructor must have the same name as the class, but preceded with a tilde
sign (~) and it must also return no value.

• The use of destructors is especially suitable when an object assigns dynamic


memory during its lifetime and at the moment of being destroyed we want to
release the memory that the object was allocated.
Destructor (contd..)
class Foo
{
private:
int data;
Public:
Foo(){data ==0;}
~Foo (){} // destructor (same name with tilde)
};
Overloaded Constructors
• Like any other function, a constructor can also be overloaded with more than
one function that have the same name but different types or number of
parameters. Remember that for overloaded functions the compiler will call
the one whose parameters match the arguments used in the function call. In
the case of constructors, which are automatically called when an object is
created, the one executed is the one that matches the arguments passed on
the object declaration:
• Important: Notice how if we declare a new object and we want to use its
default constructor (the one without parameters), we do not include
parentheses ():
CRectangle rectb; // right
CRectangle rectb(); // wrong!
// overloading class constructors
#include <iostream>
using namespace std;
class Crectangle
{
int width, height;
public:
CRectangle();
CRectangle(int,int);
int area(){return (width*height);}
};
CRectangle::CRectangle()
{
width = 5;
height = 5;
}
CRectangle::CRectangle(int a, int b)
{
width = a;
height = b;
}
void main()
{
CRectangle rect(3,4);
CRectangle rectb; Output:
cout<<"rect area: "<<rect.area()<<endl; rect area: 12
cout<<"rectb area: "<<rectb.area()<<endl; rectb area: 25
}
Default Constructor
• If you do not declare any constructors in a class definition, the compiler
assumes the class to have a default constructor with no arguments.
Therefore, after declaring a class like this one:
class CExample
{
public:
int a, b, c;
void multiply (int n, int m) { a=n; b=m; c=a*b; }
};
• The compiler assumes that CExample has a default constructor, so you can
declare objects of this class by simply declaring them without any arguments:
CExample ex;
• But as soon as you declare your own constructor for a class, the compiler no
longer provides an implicit default constructor. So you have to declare all
objects of that class according to the constructor prototypes you defined for
the class:
Default Constructor
• If you do not declare any constructors in a class definition, the compiler
assumes the class to have a default constructor with no arguments.
Therefore, after declaring a class like this one:
class CExample
{
public:
int a, b, c;
void multiply (int n, int m) { a=n; b=m; c=a*b; }
};
• The compiler assumes that CExample has a default constructor, so you can
declare objects of this class by simply declaring them without any arguments:
CExample ex;
• But as soon as you declare your own constructor for a class, the compiler no
longer provides an implicit default constructor. So you have to declare all
objects of that class according to the constructor prototypes you defined for
the class:
Default Constructor
class Cexample
{
public:
int a, b, c;
CExample(int n, int m){a=n; b=m;};
void multiply(){c=a*b;};
};
• Here we have declared a constructor that takes two parameters of type int.
Therefore the following object declaration would be correct:
CExample ex (2,3);
But,
CExample ex;
• Would not be correct, since we have declared the class to have an explicit
constructor, thus replacing the default constructor.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy