You are on page 1of 87

There are several kinds of major programming paradigms:

1. Imperative
2. Logical
3. Functional
4. Object-Oriented

It can be shown that anything solvable using one of these paradigms can be solved using
the others; however, certain types of problems lend themselves more naturally to
specific paradigms.

Imperative

 Introduction:
Computations are performed through a guided sequence of steps, in which these
variables are referred to or changed. The order of the steps is crucial, because a
given step will have different consequences depending on the current values of
variables when the step is executed.
 Advantages

o efficient;
o close to the machine;
o popular;
o familiar.
 Disadvantages
o The semantics of a program can be complex to understand or prove,
because of referential transparency does not hold(due to side effects)
o Side effects also make debugging harder;
o Abstration is more limitted than with some paradigms;
o Order is crucial, which doesn't always suit itself to problems.

Logical

o Introduction:
The Logical Paradigm takes a declarative approach to problem-solving.
Various logical assertions about a situation are made, establishing all
known facts. Then queries are made. The role of the computer becomes
maintaining data and logical deduction.
o Logical Paradigm Programming:
A logical program is divided into three sections:
1. a series of definitions/declarations that define the problem domain
2. statements of relevant facts
3. statement of goals in the form of a query
Any deducible solution to a query is returned. The definitions and
declarations are constructed entirely from relations. i.e. X is a member of
Y or X is in the internal between a and b etc.

o Advantages:
The advantages of logic oriented programming are bifold:
1. The system solves the problem, so the programming steps
themselves are kept to a minimum;
2. Proving the validity of a given program is simple.

Sample Code of Logical Paradigm.

Functional

o Introduction
The Functional Programming paradigm views all subprograms as
functions in the mathematical sense-informally, they take in arguments
and return a single solution. The solution returned is based entirely on the
input, and the time at which a function is called has no relevance. The
computational model is therefore one of function application and
reduction.
o Languages
Functional languages are created based on the functional paradigm. Such
languages permit functional solutions to problems by permitting a
programmer to treat functions as first-class objects(they can be treated as
data, assumed to have the value of what they return; therefore, they can
be passed to other functions as arguments or returned from functions).
o Advantages
The following are desirable properties of a functional language:
1. The high level of abstraction, especially when functions are used,
supresses many of the details of programming and thus removes
the possibility of commiting many classes of errors;
2. The lack of dependence on assignment operations, allowing
programs to be evaluated in many different orders. This
evaluation order independence makes function-oriented languages
good candidates for programming massively parallel computers;
3. The absence of assignment operations makes the function-oriented
programs much more amenable to mathematical proof and
analysis than are imperative programs, because functional
programs possess referential transparency.
o Disadvantages
1. Perhaps less efficiencey
2. Problems involving many variables or a lot of sequential activity
are sometimes easier to handle imperatively or with object-
oriented programming.

Sample Code of Functional Paradigm.

Object-Oriented

o Introduction
Object Oriented Programming (OOP) is a paradigm in which real-world
objects are each viewed as seperate entities having their own state which
is modified only by built in procedures, called methods.

Because objects operate independently, they are encapsulated into


modules which contain both local environments and methods.
Communication with an object is done by message passing.

Objects are organized into classes, from which they inherit methods and
equivalent variables. The object-oriented paradigm provides key benefits
of reusable code and code extensibility.
o Features & Benefits
A new class (called a derived class or subclass) may be derived from
another class (called a base class or superclass) by a mechanism called
inheritance. The derived class inherits all the features of the base class: its
structure and behavior(response to messages). In addition, the derived
class may contain additional state (instance variables), and may exhibit
additional behavior (new methods to resond to new messages).
Significantly, the derived class can also overridebehavior corresponding to
some of the methods of the base class: there would be a different method
to respond to the same message. Also, the inheritance mechanism is
allowed even without access to the source code of the base class.

The ability to use inheritance is the single most distinguishing feature of


the OOP paradigm. Inheritance gives OOP its chief benefit over other
programming paradigms - relatively easy code reuse and extension
without the need to change existing source code.

The mechanism of modeling a program as a collection of objects of


various classes, and furthermore describing many classes as extensions or
modifications of other classes, provides a high degree of modularity.

Ideally, the state of an object is manipulated and accessed only by that


object's methods. (Most O-O languages allow direct manipulation of the
state, but such access is stylistically discouraged). In this way, a class'
interface (how objects of that class are accessed) is separate from the
class' implementation (the actual code of the class' methods).
Thusencapsulation and information hiding are inherent benefits of OOP.
Sample Code of Object-Oriented Programming Paradigm.

NEED FOR OOP PARADIGM:


To build today's complex software it is just not enough to put together a
sequence of programming statements and sets of procedures and
modules; we need to incorporate sound construction techniques and
program structures that are easy to comprehend, implement and
modify.
Since the invention of the computer, many programming approaches
have been tried.
These include techniques such as modular programming, top-down
programming, bottom-up programming and structured programming. The
primary motivation in each has been the concern to handle the
increasing complexity of programs that are reliable and
maintainable. These techniques have become popular among
programmers over the last two decades.
With the advent of languages such as c, structured
programmningbecame very popular and was the main technique of the
1980s. Structured programming was a powerful tool that enabled
programmers to write moderately complex programs fairly easily.
However, as the programs grew larger, even the structured approach
failed to show the desired results in terms of bug-free, easy-to-maintain,
and reliable program.
Object-Oriented programming(OOP) is an approach to program
organization and development that attempts to eliminate some of the
pitfalls of conventional programming methods by incorporating the
best of structured programming features with several powerful new
concepts. ltis a new way of organizing and developing program and has
nothing to do with any particular language. However, not all languages are
suitable to implement the OOP concepts easily.

Structure of a C++ Program:


Let us begin with a simple example of a c++program that prints a string on the screen.

PRINTING A STRING
#include <iostream>// include header file
Using namespace std;

Int main()
{
Cout<<”C++ is better than C\n”; //C++ statement
Return 0;
} //End of example
Program Features:
Like C, the C++ program is a collection of functions. The above example
contains only onefunction, main(). As usual, execution begins at main().
Every C++ program must have amain(). C++ is a free-form language.
With a few exceptions, the compiler ignores carriagereturns and white
spaces. Like C, the C++ statements terminate with semicolons.
Comments:
C++ introduces a new comment symbol // (double slash). Comments
start with a doubleslash symbol and terminate at the end of the line. A
comment may start anywhere in theline, and whatever follows till the
end of the line is ignored. Note that there is no closing symbol.
The double slash comment is basically a single line comment. Multiline
comments can bewritten as follows:
// This is an example of
// C++ program to illustrate
// Some of its features
The C commentsymbols /*, */ arc still valid and are more suitable for
multiline comments.
The following comment is allowed:
/* This is an example of
C++ program to illustrate
Some of its features
*/
Output Operator:
The only statement in example program is an output statement. The
statement
cout<<“c++ is better than C”;
causes the string in quotation marks to be displayed on the screen. This
statementintroduces two new C++ features, cout and<<. The identifier
cout (pronounced as 'C out') isa predefined object that represents the
standard output stream in C++. Here, the standardoutput stream
represents the screen. It is also possible to redirect the output to other
outputdevices.

The operator<< is called the insertion or put to operator. It inserts (or


sends) the contentsof the variable on its right to the object on its left
(Fig. 1).
The object couthas a simple interface. If string represents a string
variable, then thefollowing statement will display its contents:
cout<< string;
You may recall that the operator<< is the bit-wise left-shift operator
and it can still beused for this purpose. This is an example of how one
operator can be used for differentpurposes depending on the context.
This concept is known as operator overloading, animportant aspect of
polymorphism.
Figure 1: Output Using Insertion Operator

The iostream File:


We have used the following #include directive in the program:
#include <iostream>
This directive causes the preprocessor to add the contents of the
iostream file to theprogram. lt contains declarations for the identifier
cout and the operator <<. Some oldversions of C++ use a header file
called iootream.h. This is one of the changes introduced byANSI C++.
Tables 2.1 and 2.2 provide lists ofC++ standard library header files
that may be neededin C++ programs. The header files with .h extension
are "old style" files which should beused with old compilers. Table 2.l
also gives the version of these files that should be usedwith the ANSI
standard compilers.
Namespace:
Namespace is a new concept introduced by the ANSI C++ standards
committee. This definesa scope for the identifiers that are used in a
program. For using the identifiers defined inthe namespace scope we
must include the using directive, like
using namespace std;
Here, std is the namespace where ANSI C++ standard class libraries are
defined. AllANSI C++ programs must include this directive. This will
bring all the identifiers defined in std to the current global scope. using
and namespace are the new keywords of C++.

Return type of main( ):


ln C++, main() returns an integer type value to the operating system.
Therefore, everymain() in C++ should end with a return(O) statement;
otherwise a warning or an errormight occur. Since main() returns an
integer type value, return type for main() is explicitly specified as int.
Note that the default return type for all functions in C++ is int. The
following main without type and return will run with a warning:
main ()
{
_____
_____
}

DATA TYPES:
Data types in C++ can be classified under various categories as shown
in Fig. 3.1.
Figur 3.1: Hierarchy of C++ data types

Both C and C++ compilers support all the built-in (also known as basic
or fundamental)data types. With the exception of void, the basic data
types may have several modifierspreceding them to serve the needs of
various situations. The modifiers signed, unsigned,long, and short may
be applied to character and integer basic data types. However,
themodifier long may also be applied to double. Data type
representation is machine specific inC++. Table 3.2 lists all
combinations of the basic data types and modifiers along with theirsize
and range for a 16-bit word machine.
ANSI C++ committee has added two more data types, bool andwchar_t.
User-Defined Data Types:
Structures and Classes:
We have used user-defined data types such as struct and union in C.
While these data types are legal in C++, some more features have been
added to make them suitable for object-oriented programming. C++
also permits us to define another user-defined data type known as
class which can be used, just like any other basic data type, to declare
variables. The class variables are known as objects, which are the
central focus of object-oriented programming.
Enumerated Data Type:
An enumerated data type is another user-defined type which provides
a way for attaching names to numbers, thereby increasing
comprehensibility of the codo. The enum keyword (from C)
automatically enumerates a list of words by assigning them values
0,1,.2. and so on. This facility provides an alternative means for
creating symbolic constants. The syntax of an enum statement is
similar to that of the struct statement. Examples:
enumshape{circle, square, triangle);
enum colour {red, blue, Green, yellow);
enum position {off , on };
The enumerated data types differ slightly in C++ when compared with
those in ANSI C. ln C++, the tag names shape, colour, and position
become new type names. By using these tag names, we can declare
new variables. Examples:
shape ellipse; // ellipse is of type shape
colour background; // background is of type colour
ANSI C defines the types of enums to be ints. In C++, each enumerated
data type retains its own separate type. This means that C++ does not
permit an int value to be automatically converted to an enum value.
Examples:
colour background = blue; // allowed
colour background = 7; // Error in C++
colour background = (colour ) 7; // OK
By default, the enumerators are assigned integer values starting with 0
for the first enumerator, 1 for the second, and so on . We can
overridethe default by explicitly assigninginteger values to the
enumerators. For example,
enumcolour{red, blue=4, green=81};
enumcolour{red=5, blue, green};
are valid definitions. In the first case, red is 0 by default. In the second
case, blue is 6 andgreen is 7. Note that the subsequent initialized
enumerators are larger by one than theirpredecessors.

Derived Data Types:


Arrays:
The application of arrays in C++ is similar to that in C. The only
exception is the way characterarrays are initialized. When initializing a
character array in ANSI C, the compiler will allow us to declare the
array size as the exact length of the string constant. For instance,
char string[3] =”xyz";
is valid in ANSI C. It assumes that the programmer intends to leave out
the null character \0in the definition. But in C++, the size should be one
larger than the number of characters inthe string.
char string[4] = "xyz"; // O.K. for C++
Functions:
Functions have undergone major changes in C++. While some of these
changes are simple, others require a new way of thinking when
organizing our programs. Many of thesemodifications and
improvements were driven by the requirements of the object-Oriented
concepts of C++. Some of these were introduced to make the C++
program more reliable and readable.
Pointers:
Pointers are declared and initialized as in C. Examples:
int *ip; // int pointer
ip =&x; // address of x assigned to ip
* ip = 10; // 10 assigned to x through indirection
C++ adds the concept of constant pointer and pointer to a constant.
char *const ptr1=”GOOD”; // constant pointer
We cannot modify the address that ptr1 is initialized to.
int const* ptr2 =&m; // pointer to a constant
ptr2 is declared as pointer to a constant. It can point to any variable of
correct type, but thecontents of what it points to cannot be changed.
Pointers are extensively used in C++ for memory management and
achieving polymorphism.

Declaration of Variables:
We know that, in C, all variables must be declared before they are used
in executable statements. This is true with C++ as well. However, there
is a significant difference between C and C++ with regard to the place
of their declaration in the program. C requires all the variables to be
defined at the beginning of a scope. When we read a C program, we
usually come across a group of variable declarations at the beginning of
each scope level. Their actual use appears elsewhere in the scope,
sometimes far away from the place of declaration. Before using a
variable. we should go back to the beginning of the program to see
whether it has been declared and, if so, of what type.
C++ allows the declaration of a variable anywhere in the scope. This
means thata variablecan be declared right at the place of its first use.
This makes the program much easier towrite and reduces the errors
that may be caused by having to scan back and forth. It alsomakes the
program easier to understand because the variables are declared in the
context oftheir use.
The example below illustrates this point.
int main()
{
float x; // declaration
float sum = 0;
for(int i=l; i<5; i++) // declaration
{
cin>> x;
sum = sum +x;
}
float average; // declaration
average = sum/(i-1):
cout<< average;
return 0;
}
The only disadvantage of this style of declaration is that we cannot see
all the variables used in a scope at a glance.

Expressions:
An expression is a combination of operators, constants and variables
arranged as per therules of the language. It may also include function
calls which return values. An expression may consist of one or more
operands, and zero or more operators to produce a value.
Expressions may be of the following seven types:
• Constant expressions
• Integral expressions
• Float expressions
• Pointer expressions
• Relational expressions
• Logical expressions
• Bitwise expressions
An expression may also use combinations of the above expressions. Such
expressions areknown as compound expressions.
Constant Expressions:
Constant Expressions consist of only constant va1ues. Examples:
15
20 + 5 / 2.0
‘x’
Integral Expressions:
Integral Expressions are those which produce integer results after
implementing all theautomatic and explicit type conversions. Examples:
m
m*n-5
m * 'x'
5 + int(2.0)
where m and n are integer variables.

Float Expressions:
Float Expressions are those which, after all conversions, produce floating-
point results.
Examples:
x+y
x * y I 10
5 + float(10)
10.75
where x and y are floating-point variables.
Pointer Expressions:
Pointer Expressions produce address values. Examples:
&m
ptr
ptr + 1
“xyz"
where m is a variable and ptr is a pointer.
Relational Expressions:
Relational Expressions yield results of type bool which takes a value true
or false. Examples:
X <= y
a+b == c+d
m+-n > 100
When arithmetic expressions are used on either side of a relational
operator, they will be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.

Logical Expressions:
Logical Expressions combine two or more relationa1 expressions and
produces bool type results. Examples:
a>b && x ==10
x==10 || y==5

Bitwise Expressions:
Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits. Examples:
x << 3 II Shift three bit position to left
y » 1 II Shift one bit position to right
Shift operators are often used for multiplication and division by powers
of two.
Operators:
C/C++ is rich in built-in operators. In fact, it places more significance on
operators thando most other computer languages. There are four main
classes of operators: arithmetic,relational, logical, and bitwise.
Arithmetic Operators:
Table 2-4 lists C/C++'s arithmetic operators. The operators +, −, *, and / work
as they do in most other computer languages. You can apply them to almost
any built-in data type. When you apply / to an integer or character, any
remainder will be truncated.
For example, 5/2 will equal 2 in integer division. The modulus operator % also
works in C/C++ as it does in other languages, yielding the remainder of an
integer division. However, you cannot use it on floating-point types. The
following code fragment illustrates %:
int x, y;
x = 5;
y = 2;
printf("%d ", x/y); /* will display 2 */
printf("%d ", x%y); /* will display 1, the remainder of
the integer division */
x = 1;
y = 2;
printf("%d %d", x/y, x%y); /* will display 0 1 */
The last line prints a 0 and a 1 because 1/2 in integer division is 0 with a
remainder of 1.The unary minus multiplies its operand by –1. That is, any
number preceded bya minus sign switches its sign.
Arithmetic Operators
Increment and Decrement:
C/C++ includes two useful operators not found in some other computer
languages. These are the increment and decrement operators, ++ and − −. The
operator ++ adds 1 to its operand, and − − subtracts 1. 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++;
There is, however, 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 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
x = 10;
y = x++;
y is set to 10. Either way, x is set to 11; the difference is in when it happens.
Here is the precedence of the arithmetic operators:
highest ++ – –
– (unary minus)
*/%
Lowest +–
Operators on the same level of precedence are evaluated by the compiler from
left toright. Of course, you can use parentheses to alter the order of
evaluation. C/C++ treatsparentheses in the same way as virtually all other
computer languages. Parenthesesforce an operation, or set of operations, to
have a higher level of precedence.
Relational and Logical Operators:
In the term relational operator, relational refers to the relationships that
values canhavewith one another. In the term logical operator, logical refers to
the ways these relationshipscan be connected.
The idea of true and false underlies the concepts of relational and logical
operators.In C, true is any value other than zero. False is zero. Expressions that
use relational orlogical operators return 0 for false and 1 for true.
Table 2-5 shows the relational and logical operators. The truth table for the
logicaloperators is shown here using 1's and 0's.
p q p && q p || q !p
000 0 1
010 1 1
1 11 1 0
100 1 0

Both the relational and logical operators are lower in precedence than
thearithmetic operators. That is, an expression like 10 > 1+12 is evaluated as if
it werewritten 10 > (1+12). Of course, the result is false.
You can combine several operations together into one expression, as shown
here:
10>5 && !(10<9) || 3<=4
In this case, the result is true.
Although neither C nor C++ contain an exclusive OR (XOR) logical operator,
youcan easily create a function that performs this task using the other logical
operators.The outcome of an XOR operation is true if and only if one operand
(but not both) istrue. The following program contains the function xor( ), which
returns the outcome ofan exclusive OR operation performed on its two
arguments:
#include <stdio.h>
int xor(int a, int b);
int main(void)
{
printf("%d", xor(1, 0));
printf("%d", xor(1, 1));
printf("%d", xor(0, 1));
printf("%d", xor(0, 0));
return 0;
}
/* Perform a logical XOR operation using thetwo arguments. */
int xor(int a, int b)
{
return (a || b) && !(a && b);
}
The following table shows the relative precedence of the relational and logical
operators:
Highest !
>>= <<=
== !=
&&
Lowest ||
Bitwise Operators:
Unlike many other languages, C/C++ supports a full complement of bitwise
operators.Since C was designed to take the place of assembly language for
most programmingtasks, it needed to be able to support many operations that
can be done in assembler,including operations on bits. Bitwise operation refers
to testing, setting, or shifting theactual bits in a byte or word, which
correspond to the char and int data types andvariants. You cannot use bitwise
operations on float, double, long double, void,bool, or other, more complex
types. Table 2-6 lists the operators that apply to bitwiseoperations. These
operations are applied to the individual bits of the operands.

The followingprogram illustrates the shift operators:


/* A bit shift example. */
#include <stdio.h>
int main(void)
{
unsigned int i;
int j;
i = 1;
/* left shifts */
for(j=0; j<4; j++) {
i = i<< 1; /* left shift i by 1, whichis same as a multiply by 2 */
printf("Left shift %d: %d\n", j, i);
}
/* right shifts */
for(j=0; j<4; j++)
{
i = i>> 1; /* right shift i by 1, whichis same as a division by 2 */
printf("Right shift %d: %d\n", j, i);
}
return 0;
}
C++ has a rich set of operators. All C operators are valid in C++ also. In addition, C++
introduces some new operators. We have already seen two such operators, namely, the
insertion operator <<,and the extraction operator>>. Other new operators are:
:: Scope resolution operator
::* Pointer-to-member declarator
->* Pointer-to-member operator
.* Pointer-to-member operator
Delete Memory release operator
Endl line feed operator
New Memory allocation operator
Setw field width operator

In addition, C++ also allows us to provide new definitions to some of


the built-in operators.That is, we can give several meanings to an
operator, depending upon the types of argumentsused. This process is
known as operator overloading.
Scope Resolution Operator:
Like C. C++ is also a block-structured language. Blocks and scopescan be
used in constructingprograms. We know that the same variable name
can be used to have different meanings indifferent blocks. The scope of
the variable extends from the point of its declaration till the endofthe
block containing the declaration. A variable declared inside a block is
said to be local tothat block. Consider the following segment of a
program:
-----
-----
{
Int x=10;
---
----
}
---
---
{
Int x=1;
---
---
}
The two declarations of x refer to two different memory locations
containing differentvalues. Statements in the second block cannot refer
to the variable x declared in the firstblock, and vice versa. Blocks in C++
are often nested. For example, the following style iscommon:
Block2 is contained in block1. Note that a declaration in an inner block
hides a declarationof the same variable in an outer block and,
therefore, each declaration ofx causes it to refer toa different data
object. Within the inner block, the variable x will refer to the data
objectdeclared therein.
ln C, the global version of u variable cannot be accessed from within
the inner block. C++resolves this problem by introducing a new
operator :: called the scope resolution operater. Thiscan be used to
uncover a hidden variable. It takes the following form:
:: variable-name
This operator allows access to the global version of a variable. For
example, ::countmeans the global version of the variable count (and
not the local variable count declared inthat block). Program 3.1
illustrates this feature.
#include<iostream>
Using namespace std;
Int m=10; //Global m
Int main()
{
Int m=20; //m redeclared, local to main
{
Int k=m;
Int m=30; //m declared again local to inner block
Cout<<”We are in inner block”;
Cout<<”k=”<<k<<”\n”;
Cout<<”m=”<<m<<”\n”;
Cout<<”::m=”<<::m<<”\n”;
}
Cout<<”We are in outer block\n”;
Cout<<”m=”<<m<<”\n”;
Cout<<”::m=”<<::m<<”\n”;
Return 0;
}
The output of Program 3.1 would be:
We are in inner block
k = 20
m =30
: :m=10
We are in outer block
m = 20
: :m= 10

NOTE:It is to be noted ::m will always refer to the global m. In the


inner block, ::m refers to thevalue 10 and not 20.
Operator Precedence:
Table 2-8 lists the precedence of all operators defined by C. Note that all operators,except the

unary operators and ?, associate from left to right. The unary operators(*, &, -) and ? associate

from right to left.

Evaluation of Expressions:
In C/C++ language expression evaluation is mainly depends on
priority and associativity.
Priority:
This represents the evaluation of expression starts from
"what"operator.
Associativity:
It represents which operator should be evaluated first if
anexpression is containing more than one operator with same
priority.
Neither C nor C++ specifies the order in which the subexpressions of
an expression areevaluated. This leaves the compiler free to
rearrange an expression to produce moreoptimal code. However, it
also means that your code should never rely upon the orderin which
subexpressions are evaluated. For example, the expression
x = f1() + f2();
does not ensure that f1( )will be called before f2( ).

Type Conversion:
When an operator’s operands are of different data types, C++ will
automatically convert them to the same data type. This can affect the result of
mathematical expressions.

If a floating-point value is assigned to an int variable, what value will the


variable receive?

If an int is multiplied by a float, what data type will the result be?

What if a double is divided by an unsigned int?

Is there any way of predicting what will happen in these instances?

Yes. C++ follows a set of rules when performing mathematical operations on


variables of different data types.
Data Type Ranking:

Long double

Double

Float

Unsigned long

Long

Unsigned int

Int

--------------------------------------------------------------

One exception to the ranking in above table is when an int and a long are the
same size. In that case, an unsigned int outranks long because it can hold a
higher value.

When C++ is working with an operator, it strives to convert the operands to


the same type. This automatic conversion is known as type coercion. When a
value is converted to a higher data type, it is said to be promoted. To demote a
value means to convert it to a lower data type. Following are the rules that
govern the evaluation of mathematical expressions:

Rule 1: chars, shorts, and unsigned shorts are automatically promoted to int.

Notice that char, short, and unsigned short do not appear in above table.
That’s because anytime they are used in a mathematical expression, they are
automatically promoted to an int. The only exception to this rule is when an
unsigned short hold a value larger than can be held by an int. This can happen
on systems where shorts are the same size as ints. In this case, the unsigned
short is promoted to unsigned int.

Rule 2: When an operator works with two values of different data types, the
lower-ranking value is promoted to the type of the higher-ranking value.

In the following example, assume that years is an int and interestRate is a float:

Years * interestRate

Before the multiplication takes place, years will be promoted to a float.


Rule 3: When a final value of an expression is assigned to a variable, it will be
converted to the data type of that variable.

This means that if the variable receivingthe value is of a lower data type than
the value it is receiving , the value will be demoted to the type of the variable.
If the variable’s data type does not have enough storage space to hold the
value, part of the value will be lost, and the variable could recive an accurate
result. If the variable receiving the value is an integer and the value being
assigned to it is a floating-point number, the value will be truncated before
being assigned to the variable. This means everything after the decimal-point
will be “chopped off”:

Int x=3.75; //3.75 will be truncated to integer 3

// x will be assigned a 3

If the variable receiving the value has a higher data type than the value being
assigned to it, there is no problem.

Warning: Remember, when both operands of division are integers, the


fractional part will be truncated, or thrown away.

ARRAYS:
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.
In C/C++, all arrays consist of contiguous memory locations. The
lowestaddress corresponds 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.
The general form for declaring a single-dimension array is

type var_name[size];

Like other variables, arrays must be explicitly declared so that the compiler
may allocate space for them in memory. Here, type declares the base type of
the array, which is the type of each element in the array, and size defines how
many elements the array will hold. For example, to declare a 100-element
array called balance of type double, use this statement:

double balance[100];

An element is accessed by indexing the array name. This is done by placing


theindex of the element within square brackets after the name of the array.
For example,

balance[3] = 12.23;

assigns element number 3 in balance the value 12.23.

#include <stdio.h>

int main(void)

int x[100]; /* this declares a 100-integer array */

int t;

/* load x with values 0 through 99 */

for(t=0; t<100; ++t) x[t] = t;

/* display contents of x */

for(t=0; t<100; ++t) printf("%d ", x[t]);

return 0;

The amount of storage required to hold an array is directly related to its type
andsize. For a single-dimension array, the total size in bytes is computed as
shown here:

total bytes = sizeof(base type) x size of array

C/C++ has no bounds checking on arrays. You could overwrite either end of an
array and write into some other variable's data or even into the program's
code. As the programmer, it is your job to provide bounds checking where
needed. For example, this code will compile without error, but is incorrect
because the for loop will cause the array count to be overrun.

int count[10], i;

/* this causes count to be overrun */

for(i=0; i<100; i++) count[i] = i;

Generating a Pointer to an Array:

You can generate a pointer to the first element of an array by simply specifying
thearray name, without any index. For example, given

int sample[10];

you can generate a pointer to the first element by using the name sample.
Thus, thefollowing program fragment assigns p the address of the first element
of sample:

int *p;

int sample[10];

p = sample;

You can also specify the address of the first element of an array using the
&operator.For example, sample and &sample[0] both produce the same
results. However, inprofessionally written C/C++ code, you will almost never
see &sample[0].

Passing Single-Dimension Arrays to Functions:

In C/C++, you cannot pass an entire array as an argument to a function. You


can,however, pass to the function a pointer to an array by specifying the
array's namewithout an index. For example, the following program fragment
passes the addressof ito func1( ):

int main(void)

int i[10];

func1(i);
.

If a function receives a single-dimension array, you may declare its


formal parameterin one of three ways: as a pointer, as a sized array,
or as an unsized array. For example,to receive i, a function called
func1( ) can be declared as
void func1(int *x) /* pointer */
{
.
.
.
}
or
void func1(int x[10]) /* sized array */
{
.
.
.
}
or finally as
void func1(int x[]) /* unsized array */
{
.
.
.
}
All three declaration methods produce similar results because each
tells thecompiler that an integer pointer is going to be received. The
first declaration actuallyuses a pointer. The second employs the
standard array declaration. In the final version,a modified version of
an array declaration simply specifies that an array of type int ofsome
length is to be received. As you can see, the length of the array
doesn't matter asfar as the function is concerned because C/C++
performs no bounds checking.

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 anull-terminated character array. (A null is
zero.) Thus a null-terminated string containsthe characters that
comprise the string followed by a null. This is the only type of
stringdefined by C, and it is still the most widely used. Sometimes null-
terminated stringsare called C-strings. C++ also defines a string class,
called string, which provides anobject-oriented approach to string
handling. It is described later in this book. Here,null-terminated strings
are examined.
When declaring a character array that will hold a null-terminated
string, you needto declare it to be one character longer than the largest
string that it is to hold. Forexample, 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.
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.
C/C++ supports a wide range of functions that manipulate null-
terminated strings.
The most common are
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 ifs1<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. (C++ programs
can also use theC++-style header <cstring>.) The following program
illustrates the use of these stringfunctions:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[80], s2[80];
gets(s1);
gets(s2);
printf("lengths: %d %d\n", strlen(s1), strlen(s2));
if(!strcmp(s1, s2)) printf("The strings are equal\n");
strcat(s1, s2);
printf("%s\n", s1);
strcpy(s1, "This is a test.\n");
printf(s1);
if(strchr("hello", 'e')) printf("e is in hello\n");
if(strstr("hi there", "hi")) printf("found hi");
return 0;
}
If you run this program and enter the strings "hello" and "hello", the
output is
lengths: 5 5
The strings are equal
hellohello
This is a test.
e is in hello
found hi
Two-Dimensional Arrays:
C/C++ supports multidimensional arrays. The simplest form of the
multidimensionalarray is the two-dimensional array. A two-
dimensional array is, essentially, an array ofone-dimensional arrays. To
declare a two-dimensional integer array d of size 10,20, youwould
write
int d[10][20];
To access point 1,2 of array d, you would use
d[1][2]
The following example loads a two-dimensional array with the
numbers 1 through 12and prints them row by row.
#include <stdio.h>
int main(void)
{
int t, i, num[3][4];
for(t=0; t<3; ++t)
for(i=0; i<4; ++i)
num[t][i] = (t*4)+i+1;
/* now print them out */
for(t=0; t<3; ++t) {
for(i=0; i<4; ++i)
printf("%3d ", num[t][i]);
printf("\n");
}
return 0;
}
Arrays of Strings:
To create an array of null-terminated strings, use a two-dimensional
character array.The size of the left index determines the number of
strings and the size of the rightindex specifies the maximum length of
each string. The following code declares an arrayof 30 strings, each
with a maximum length of 79 characters, plus the null terminator.
char str_array[30][80];
It is easy to access an individual string: You simply specify only the left
index.For example, the following statement calls gets( )with the third
string in str_array.
gets(str_array[2]);
The preceding statement is functionally equivalent to
gets(&str_array[2][0]);
but the first of the two forms is much more common in professionally
writtenC/C++ code.
/* A very simple text editor. */
#include <stdio.h>
#define MAX 100
#define LEN 80
char text[MAX][LEN];
int main(void)
{
register int t, i, j;
printf("Enter an empty line to quit.\n");
for(t=0; t<MAX; t++)
{
printf("%d: ", t);
gets(text[t]);
if(!*text[t]) break; /* quit on blank line */
}
for(i=0; i<t; i++)
{
for(j=0; text[i][j]; j++)
putchar(text[i][j]);
putchar('\n');
}
return 0;
}

POINTERS:
Pointers are used for the following purposes:
1. pointers provide the meansby which functions can modify their
calling arguments.
2. pointers supportdynamic allocation.
3. pointers can improve the efficiency of certain routines.
Pointers are one of the strongest but also one of the most dangerous
features inC/C++. For example, uninitialized pointers (or pointers
containing invalid values)can cause your system to crash. Perhaps
worse, it is easy to use pointers incorrectly,causing bugs that are very
difficult to find.
Definition:A pointer is a variable that holds a memory address. This
address is the location ofanother object (typically another variable)
in memory. For example, if one variablecontains the address of
another variable, the first variable is said to point to the second.
Pointer Variables
If a variable is going to hold a pointer, it must be declared as such.
Apointer declarationconsists of a base type, an *, and the variable
name. The general form for declaring apointer variable is
type *name;
where type is the base type of the pointer and may be any valid type.
The name ofthe pointer variable is specified by name.The base type
of the pointer defines what type of variables the pointer can point
to.Technically, any type of pointer can point anywhere in memory.
However, all pointerarithmetic is done relative to its base type, so it
is important to declare the pointer correctly.
The Pointer Operators:
There are two special pointeroperators: * and &. The &is a unary
operator that returns the memory address ofits operand.
(Remember, a unary operator only requires one operand.) For
example,
m = &count;
places into m the memory address of the variable count. This
address is the computer'sinternal location of the variable. It has
nothing to do with the value of count. You canthink of &as returning
"the address of." Therefore, the preceding assignment
statementmeans "m receives the address of count."
To understand the above assignment better, assume that the
variable count usesmemory location 2000 to store its value. Also
assume that count has a value of 100.Then, after the preceding
assignment, m will have the value 2000.
The second pointer operator, *, is the complement of &. It is a unary
operator thatreturns the value located at the address that follows.
For example, if m contains thememory address of the variablecount,
q = *m;
places the value of count into q. Thus, q will have the value 100
because 100 is storedat location 2000, which is the memory address
that was stored in m. You can think of* as "at address." In this case,
the preceding statement means "q receives the value ataddress m."
Both &and * have a higher precedence than all other arithmetic
operators exceptthe unary minus, with which they are equal.
You must make sure that your pointer variables always point to the
correct type ofdata. For example, when you declare a pointer to be
of type int, the compiler assumesthat any address that it holds points
to an integer variable—whether it actually doesor not. Because you
can assign any address you want to a pointer variable, thefollowing
program compiles without error, but does not produce the desired
result:
#include <stdio.h>
int main(void)
{
double x = 100.1, y;
int *p;
/* The next statement causes p (which is an
integer pointer) to point to a double. */
p = (int *)&x;
/* The next statement does not operate as
expected. */
y = *p;
printf("%f", y); /* won't output 100.1 */
return 0;
}
NOTE:In C++, it is illegal to convert one type of pointer into another
without the use of anexplicit type cast. In C, casts should be used for
most pointer conversions.

POINTERS AND ARRAYS:


There is a close relationship between pointers and arrays. Consider
this program fragment:
char str[80], *p1;
p1 = str;
Here, p1 has been set to the address of the first array element in str.
To access the fifth element in str, you could write
str[4]
or
*(p1+4)
Both statements will return the fifth element. Remember, arrays
start at 0. To accessthe fifth element, you must use 4 to index str.
You also add 4 to the pointer p1 toaccess the fifth element because
p1 currently points to the first element of str. (Recallthat an array
name without an index returns the starting address of the array,
whichis the address of the first element.)
The preceding example can be generalized. In essence, C/C++
provides two methodsof accessing array elements: pointer
arithmetic and array indexing. Although thestandard array-indexing
notation is sometimes easier to understand, pointer arithmeticcan
be faster. Since speed is often a consideration in programming, C/C+
+ programmerscommonly use pointers to access array elements.
These two versions of putstr( )—one with array indexing and one
with pointers—illustrate how you can use pointers in place of array
indexing. The putstr( )functionwrites a string to the standard output
device one character at a time.
/* Index s as an array. */
void putstr(char *s)
{
register int t;
for(t=0; s[t]; ++t)
putchar(s[t]);
}
/* Access s as a pointer. */
void putstr(char *s)
{
while(*s) putchar(*s++);
}
Most professional C/C++ programmers would find the second version
easier toread and understand. In fact, the pointer version is the way
routines of this sortare commonly written in C/C++.
Arrays of Pointers:
Pointers may be arrayed like any other data type. The declaration for
an int pointerarray of size 10 is
int *x[10];
To assign the address of an integer variable called var to the third
element of thepointer array, write
x[2] = &var;
To find the value of var, write
*x[2]
If you want to pass an array of pointers into a function, you can use
the samemethod that you use to pass other arrays—simply call the
function with the arrayname without any indexes. For example, a
function that can receive array x lookslike this:
void display_array(int *q[])
{
int t;
for(t=0; t<10; t++)
printf("%d ", *q[t]);
}
Remember, q is not a pointer to integers, but rather a pointer to an
array of pointers tointegers. Therefore you need to declare the
parameter q as an array of integer pointers,as just shown. You
cannot declare q simply as an integer pointer because that is
notwhat it is.
Pointer arrays are often used to hold pointers to strings. You can
create a functionthat outputs an error message given its code
number, as shown here:
void syntax_error(int num)
{
static char *err[] = {
"Cannot Open File\n",
"Read Error\n",
"Write Error\n",
"Media Failure\n"
};
printf("%s", err[num]);
}
The array err holds pointers to each string. As you can see, printf( )
insidesyntax_error( ) is called with a character pointer that points to
one of the variouserror messages indexed by the error number
passed to the function. For example,if numis passed a 2, the message
Write Error is displayed.
The C language gives you five ways to create a custom data type:
1. The structure, which is a grouping of variables under one name
and is called anaggregate data type. (The terms compound or
conglomerate are also commonly used.)
2. The bit-field, which is a variation on the structure and allows easy
access toindividual bits.
3. The union, which enables the same piece of memory to be defined
as two ormore different types of variables.
4. The enumeration, which is a list of named integer constants.
5. The typedef keyword, which defines a new name for an existing
type.
C++ supports all of the above and adds classes

Structures:
A structure is a collection of variables referenced under one name, providing a
convenient means of keeping related information together. A structure
declaration forms a template that may be used to create structure objects
(that is, instances of a structure). The variables that make up the structure are
called members. (Structure members are also commonly referred to as
elements or fields.)
Generally, all of the members of a structure are logically related. For example,
the name and address information in a mailing list would normally be
represented in a structure. The following code fragment shows how to declare
a structure that defines the name and address fields. The keyword struct tells
the compiler that a structure is being declared.
struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
};

Notice that the declaration is terminated by a semicolon. This is


because a structuredeclaration is a statement. The type name of the
structure is addr. As such, addridentifies this particular data
structure and is its type specifier.
At this point, no variable has actually been created. Only the form of
the data has beendefined. When you define a structure, you are
defining a compound variable type, nota variable. Not until you
declare a variable of that type does one actually exist. In C, to
declare a variable (i.e., a physical object) of type addr, write
struct addraddr_info;
This declares a variable of type addrcalled addr_info. In C++, you
may use thisshorter form.
addraddr_info;

For example,
struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
} addr_info, binfo, cinfo;
defines a structure type called addrand declares variables addr_info,
binfo, and cinfoof that type. It is important to understand that each
structure object contains its owncopies of the structure’s members.
For example, the zip field of binfois separate fromthe zip field of
cinfo. Thus, changes to zip in binfodo not affect the zip in cinfo.

Accessing Structure Members:


Individual members of a structure are accessed through the use of
the .operator(usually called the dot operator). For example, the
following code assigns the ZIPcode 12345 to the zip field of the
structure variable addr_infodeclared earlier:
addr_info.zip = 12345;
The structure variable name followed by a period and the member
name referencesthat individual member. The general form for
accessing a member of a structure is
structure-name.member-name
Therefore, to print the ZIP code on the screen, write
printf("%lu", addr_info.zip);
This prints the ZIP code contained in the zip member of the structure
variable addr_info.
In the same fashion, the character array addr_info.name can be used
to call gets( ),as shown here:
gets(addr_info.name);
This passes a character pointer to the start of name.
Structure Assignments:
The information contained in one structure may be assigned
toanother structure of thesame type using a single assignment
statement. That is, you do not need to assign thevalue of each
member separately. The following program illustrates structure
assignments:
#include <stdio.h>
int main(void)
{
struct {
int a;
int b;
} x, y;
x.a = 10;
y = x; /* assign one structure to another */
printf("%d", y.a);
return 0;
}
After the assignment, y.awill contain the value 10.
Arrays of Structures:
Perhaps the most common usage of structures is in arrays of
structures. To declarean array of structures, you must first define a
structure and then declare an arrayvariable of that type. For
example, to declare a 100-element array of structures oftype addr,
defined earlier, write
struct addraddr_info[100];
This creates 100 sets of variables that are organized as defined in the
structure addr.
To access a specific structure, index the structure name. Forexample,
to print theZIP code of structure 3, write
printf("%lu", addr_info[2].zip);
Like all array variables, arrays of structures begin indexing at 0.
Passing Entire Structures to Functions:
When a structure is used as an argument to a function, the entire
structure is passedusing the standard call-by-value method. Of
course, this means that any changesmade to the contents of the
structure inside the function to which it is passed do notaffect the
structure used as an argument.
When using a structure as a parameter, remember that the type of
the argumentmust match the type of the parameter. For example, in
the following program both theargument argand the parameter
parmare declared as the same type of structure.
#include <stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
};
void f1(struct struct_typeparm);
int main(void)
{
struct struct_typearg;
arg.a = 1000;
f1(arg);
return 0;
}
void f1(struct struct_typeparm)
{
printf("%d", parm.a);
}
Structure Pointers:
C/C++ allows pointers to structures just as it allows pointers to any
other typeof variable. However, there are some special aspects to
structure pointers thatyou should know.
Declaring a Structure Pointer:
Like other pointers, structure pointers are declared by placing * in
front of a structurevariable's name. For example, assuming the
previously defined structure addr, thefollowing declares
addr_pointeras a pointer to data of that type:
struct addr *addr_pointer;
Remember, in C++ it is not necessary to precede this declaration with
the keywordstruct.
Using Structure Pointers:
There are two primary uses for structure pointers: to pass a structure
to a function usingcall by reference, and to create linked lists and
other dynamic data structures that relyon dynamic allocation.
When a pointer to a structure is passed to a function, only the
address of thestructure is pushed on the stack. This makes for very
fast function calls. A secondadvantage, in some cases, is when a
function needs to reference the actual structureused as the
argument, instead of a copy. By passing a pointer, the function
canmodify the contents of the structure used in the call.
To find the address of a structure, place the &operator before the
structure's name.
For example, given the following fragment:
struct bal {
float balance;
char name[80];
} person;
struct bal *p; /* declare a structure pointer */
then
p = &person;
places the address of the structure person into the pointer p.
To access the members of a structure using a pointer to that
structure, you mustuse the >operator. For example, this references
the balance field:
p->balance
The >is usually called the arrow operator, and consists of the minus
sign followedby a greater-than sign. The arrow is used in place of the
dot operator when you areaccessing a structure member through a
pointer to the structure.
To see how a structure pointer can be used, examine this simple
program, whichprints the hours, minutes, and seconds on your
screen using a software timer.
/* Display a software timer. */
#include <stdio.h>
#define DELAY 128000
struct my_time {
int hours;
int minutes;
int seconds;
};
void display(struct my_time *t);
void update(struct my_time *t);
void delay(void);
int main(void)
{
struct my_timesystime;
systime.hours = 0;
systime.minutes = 0;
systime.seconds = 0;
for(;;) {
update(&systime);
display(&systime);
}
return 0;
}
void update(struct my_time *t)
{
t->seconds++;
if(t->seconds==60) {
t->seconds = 0;
t->minutes++;
}
if(t->minutes==60) {
t->minutes = 0;
t->hours++;
}
if(t->hours==24) t->hours = 0;
delay();
}
void display(struct my_time *t)
{
printf("%02d:", t->hours);
printf("%02d:", t->minutes);
printf("%02d\n", t->seconds);
}
void delay(void)
{
long int t;
/* change this as needed */
for(t=1; t<DELAY; ++t) ;
}
Arrays and Structures Within Structures:
A member of a structure may be either a simple or aggregate type. A
simple memberis one that is of any of the built-in data types, such as
integer or character. You havealready seen one type of aggregate
element: the character arrays used in addr. Otheraggregate data
types include one-dimensional and multidimensional arrays of
theother data types, and structures.
A member of a structure that is an array is treated as you might
expect from theearlier examples. For example, consider this
structure:
struct x {
int a[10][10]; /* 10 x 10 array of ints */
float b;
} y;
To reference integer 3,7 in a of structure y, write
y.a[3][7]
When a structure is a member of another structure, it is called a
nested structure.
For example, the structure address is nested inside emp in this
example:
struct emp
{
struct addraddress; /* nested structure */
float wage;
} worker;
Here, structure emp has been defined as having two members. The
first is a structureof type addr, which contains an employee's
address. The other is wage, which holdsthe employee's wage. The
following code fragment assigns 93456 to the zip elementof address.
worker.address.zip = 93456;
As you can see, the members of each structure are referenced from
outermost to innermost. C guarantees that structures can be nested
to at least 15 levels. Standard C++ suggests that at least 256 levels of
nesting be allowed.

REFERENCES:
C++ contains a feature that is related to the pointer called a reference. A
reference isessentially an implicit pointer. There are three ways that a
reference can be used: asa function parameter, as a function return value, or
as a stand-alone reference. Eachis examined here.

(i) Reference Parameter


Probably the most important use for a reference is to allow you to create
functionsthat automatically use call-by-reference parameter passing.
Arguments can be passed to functions in one of two ways: using call-by-
value orcall-by-reference. When using call-by-value, a copy of the argument
is passed to thefunction. Call-by-reference passes the address of the
argument to the function. Bydefault, C++ uses call-by-value, but it provides
two ways to achieve call-by-referenceparameter passing. First, you can
explicitly pass a pointer to the argument. Second,you can use a reference
parameter. For most circumstances the best way is to usea reference
parameter.
To fully understand what a reference parameter is and why it is valuable,
we willbegin by reviewing how a call-by-reference can be generated using a
pointer parameter.
The following program manually creates a call-by-reference parameter
using a pointerin the function called neg( ), which reverses the sign of the
integer variable pointed toby its argument.
// Manually create a call-by-reference using a pointer.
#include <iostream>
using namespace std;
void neg(int *i);
int main()
{
int x;
x = 10;
cout<< x << " negated is ";
neg(&x);
cout<< x << "\n";
return 0;
}
void neg(int *i)
{
*i = -*i;
}
In this program, neg( )takes as a parameter a pointer to the integer whose
sign itwill reverse. Therefore, neg( )must be explicitly called with the
address of x. Further,inside neg( )the * operator must be used to access the
variable pointed to by i. Thisis how you generate a "manual" call-by-
reference in C++, and it is the only way toobtain a call-by-reference using
the C subset. Fortunately, in C++ you can automatethis feature by using a
reference parameter.
To create a reference parameter, precede the parameter's name with an &.
Forexample, here is how to declare neg( )with ideclared as a reference
parameter:
void neg(int &i);
For all practical purposes, this causes ito become another name for
whatever argumentneg( )is called with. Any operations that are applied to
iactually affect the callingargument. In technical terms, iis an implicit
pointer that automatically refers tothe argument used in the call to neg( ).
Once ihas been made into a reference, it is nolonger necessary (or even
legal) to apply the * operator. Instead, each time iis used, itis implicitly a
reference to the argument and any changes made to iaffect the argument.
Further, when calling neg( ), it is no longer necessary (or legal) to precede
the argument'sname with the &operator. Instead, the compiler does this
automatically. Here is thereference version of the preceding program:
// Use a reference parameter.
#include <iostream>
using namespace std;
void neg(int &i); // i now a reference
int main()
{
int x;
x = 10;
cout<< x << " negated is ";
neg(x); // no longer need the & operator
cout<< x << "\n";
return 0;
}
void neg(int &i)
{
i = -i; // i is now a reference, don't need *
}
To review: When you create a reference parameter, it automatically refers
to (implicitlypoints to) the argument used to call the function. Therefore, in
the preceding program,the statement
i = -i ;
actually operates on x, not on a copy of x. There is no need to apply the
&operator toan argument. Also, inside the function, the reference
parameter is used directly withoutthe need to apply the * operator. In
general, when you assign a value to a reference,you are actually assigning
that value to the variable that the reference points to.
Example Progeam:
#include <iostream>
using namespace std;
void swap(int &i, int &j);
int main()
{
int a, b, c, d;
a = 1;
b = 2;
c = 3;
d = 4;
cout<< "a and b: " << a << " " << b << "\n";
swap(a, b); // no & operator needed
cout<< "a and b: " << a << " " << b << "\n";
cout<< "c and d: " << c << " " << d << "\n";
swap(c, d);
cout<< "c and d: " << c << " " << d << "\n";
return 0;
}
void swap(int &i, int &j)
{
int t;
t = i; // no * operator needed
i = j;
j = t;
}
This program displays the following:
a and b: 1 2
a and b: 2 1
c and d: 3 4
c and d: 4 3

Returning References:
A function may return a reference.For example, consider
this simple program:
#include <iostream>
using namespace std;
char &replace(int i); // return a reference
char s[80] = "Hello There";
int main()
{
replace(5) = 'X'; // assign X to space after Hello
cout<< s;
return 0;
}
char &replace(int i)
{
return s[i];
}
This program replaces the space between Hello and There with an X. That
is, theprogram displays HelloXthere. Take a look at how this is
accomplished. First, replace( )is declared as returning a reference to a
character. As replace( )is coded, it returns areference to the element of s
that is specified by its argument i. The reference returnedby replace( )is
then used in main( ) to assign to that element the character X.
One thing you must be careful about when returning references is that the
objectbeing referred to does not go out of scope after the function
terminates.
Independent References:
By far the most common uses for references are to pass an argument using
call-byreferenceand to act as a return value from a function. However, you
can declarea reference that is simply a variable. This type of reference is
called an independentreference.
When you create an independent reference, all you are creating is another
namefor an object. All independent references must be initialized when
they are created. Thereason for this is easy to understand. Aside from
initialization, you cannot changewhat object a reference variable point to.
Therefore, it must be initialized when itis declared.
The following program illustrates an independent reference:
#include <iostream>
using namespace std;
int main()
{
int a;
int &ref = a; // independent reference
a = 10;
cout<< a << " " << ref << "\n";
ref = 100;
cout<< a << " " << ref << "\n";
int b = 19;
ref = b; // this puts b's value into a
cout<< a << " " << ref << "\n";
ref--; // this decrements a
// it does not affect what ref refers to
cout<< a << " " << ref << "\n";
return 0;
}
The program displays this output:
10 10
100 100
19 19
18 18
Actually, independent references are of little real value because each one is,
literally,just another name for another variable. Having two names to
describe the same objectis likely to confuse, not organize, your program.

FLOW CONTROL STATEMENTS:


(if, switch, while, for, do, break, continue, goto statements):

If
C/C++ supports two types of selection statements: if and switch. In
addition, the ?operator is an alternative to if in certain circumstances.
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.
If expression evaluates to true (anything other than 0), the statement or
block thatforms the target of ifis executed; otherwise, the statement or
block that is the targetof else will be executed, if it exists. Remember, only
the code associated with if or thecode associated with else executes, never
both.
Program to check the eligibility to vote:
#include<iostream>
Using namespace std;
Int main()
{
Int age;
Cout<<”Enter Your Age:”;
Cin>>age;
If(age>18)
Cout<<”Your are eligible to vote”;
Return 0;
}
The next version illustrates the use of theelse statement to print a message
in response to the wrong number.
#include<iostream>
Using namespace std;
Int main()
{
Int age;
Cout<<”Enter Your Age:”;
Cin>>age;
If(age>18)
Cout<<”Your are eligible to vote”;
Else
Cout<<”Your are not eligible to vote”;
Return 0;
}
P1:Program to display a number if it is negative
P2:Check whether an integer is odd or even
P3: Find the greatest of two numbers
P4:Find whether roots of a quadratic equation are imaginary.
Nested ifs:
A nested if is an if that is the target of another if or else. Nested ifs are very
common inprogramming. In a nested if, an else statement always refers to
the nearest if statementthat 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; /* 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 C language guarantees at least 15 levels of nesting. In practice, most
compilersallow substantially more. More importantly, Standard C++
suggests that at least 256 levelsof nested ifs be allowed in a C++ program.
Programming Example 1:
int main()
    {
        int i = 10;
           if (i == 10)
        {
            // First if statement
            if (i< 15)
               cout<<"i is smaller than 15";
               // Nested - if statement
            // Will only be executed if statement above
            // it is true
            if (i< 12)
                cout<<"i is smaller than 12 too";
            else
                cout<<"i is greater than 15";
        }
          return 0;
    }
Output:
i is smaller than 15
i is smaller than 12 too
Programming Example2:
#include <iostream>
using namespace std;

int main()
{
char name;
int password;

cout<< "Enter the name: "; cin>> name;


cout<< " Enter your password: "; cin>> password;
if (name == 'GG') {
if (password == 1346) {
cout<< "Login successful";
}
else {
cout<< "Incorrect PASSWORD, Try again.";
}
}
else {
cout<< " Incorrect Login Details, Try again.";
}
}
OUTPUT:
Enter the name: GG
Enter your password: 1346
Login successful

P3:ClassAssignment

A common programming construct is the if-else-if ladder, sometimes called


the if-else-ifstaircase 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
conditionis found, the statement associated with it is executed and the rest
of the ladder isbypassed. If none of the conditions are true, the final else is
executed. That is, if allother conditional tests fail, the last else statement is
performed. If the final else is notpresent, no action takes place if all other
conditions are false.
Programming Example 1:
#include <iostream>
usingnamespace std;
int main ()
{
// declare local variable
int marks = 55;

// check the boolean condition


if( marks>= 80 )
{
// if 1st condition is true
cout<< "U are 1st class !!" <<endl;
}
elseif( marks>= 60 && marks < 80)
{
// if 2nd condition is false
cout<< "U are 2nd class !!" <<endl;
}
elseif( marks>= 40 && marks < 60)
{
// if 3rd condition is false
cout<< "U are 3rd class !!" <<endl;
}
else
{
// none of condition is true
cout<< "U are fail !!" <<endl;
}
return 0;
}
Programming Example 2:
#include<iostream>
usingnamespace std;

intmain()

{ charch;

//input a character
cout<<"Enter a character: ";
cin>>ch;

//condition to validate character is an alphabet


if( (ch>='a'&&ch<='z') || (ch>='A' &&ch<='Z'))
{
cout<<"Entered character is an alphabet";
}
//condition to validate character is a digit
elseif(ch>='0' &&ch<='9')
{
cout<<"Entered character is a digit";
}
//other characters are not valid character
else
{
cout<<"Enter a valid character";
}

cout<<endl;

return 0;
}
Programming Example 3:
Student Assignment

switch
C/C++ has a built-in multiple-branch selection statement, called switch,
whichsuccessively tests the value of an expression against a list of integer or
character constants.When a match is found, the statements associated with
that constant are executed. Thegeneral form of the switch statement is
switch (expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
...
default
statement sequence
}
Programming Example 1:
// Following is a simple C++ program 
// to demonstrate syntax of switch.
include <iostream>
using namespace std;
  
int main() {
int x ;
cout<<”Enter choice:”;
cin>>x;
    switch (x)
    {
        case 1: 
            cout<< "Choice is 1";
            break;
        case 2: 
            cout<< "Choice is 2";
            break;
        case 3: 
            cout<< "Choice is 3";
            break;
        default: 
            cout<< "Choice other than 1, 2 and 3";
            break;  
    }
return 0;
}
OUTPUT:
Enter choice:2
Choice is 2
Programming Example 2:
#include<iostream.h>
#include<conio.h>

intmain()
{
int ch;
clrscr();
cout<<"Enter any number (1 to 7)";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Today is Monday";
break;
case 2:
cout<<"Today is Tuesday";
break;
case 3:
cout<<"Today is Wednesday";
break;
case 4:
cout<<"Today is Thursday";
break;
case 5:
cout<<"Today is Friday";
break;
case 6:
cout<<"Today is Saturday";
break;
case 7:
cout<<"Today is Sunday";
break;
default:
cout<<"Only enter value 1 to 7";
}
Return 0;
}
OUTPUT:
Enter any number (1 to 7): 5
Today is Friday
Programming Example 3:
// Program to built a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main()
{
char o;
float num1, num2;

cout<< "Enter an operator (+, -, *, /): ";


cin>> o;

cout<< "Enter two operands: ";


cin>> num1 >> num2;

switch (o)
{
case '+':
cout<< num1 << " + " << num2 << " = " << num1+num2;
break;
case '-':
cout<< num1 << " - " << num2 << " = " << num1-num2;
break;
case '*':
cout<< num1 << " * " << num2 << " = " << num1*num2;
break;
case '/':
cout<< num1 << " / " << num2 << " = " << num1/num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout<< "Error! operator is not correct";
break;
}

return 0;
}
OUTPUT:
Enter an operator (+, -, *, /): +
-
Enter two operands: 2.3
4.5
2.3 - 4.5 = -2.2
The break statement is one of C/C++'s jump statements. You can use it in
loops aswell as in the switch statement. When break isencountered in a
switch, program execution "jumps" to the line of code following theswitch
statement.
There are three important things to know about the switch statement:
■ The switch differs from the if in that switch can only test for equality,
whereasif can evaluate any type of relational or logical expression.
■ No two case constants in the same switch can have identical values. Of
course,a switch statement enclosed by an outer switch may have case
constants thatare the same.
■ If character constants are used in the switch statement, they are
automaticallyconverted to integers.
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.
The for Loop:
The general form of the for statement is
for(initialization; condition; increment) statement;
The for loop allows many variations, but its most common form works like
this. Theinitialization is an assignment statement that is used to set the loop
control variable. Thecondition is a relational expression that determines
when the loop exits. The incrementdefines how the loop control variable
changes each time the loop is repeated. You mustseparate these three
major sections by semicolons. The for loop continues to executeas long as
the condition is true. Once the condition becomes false, program
executionresumes on the statement following the for.
Programming Example 1:
#include <stdio.h>
int main(void)
{
int x;
for(x=1; x <= 100; x++) printf("%d ", x);
return 0;
}
In the loop, x is initially set to 1 and then compared with 100. Since x is less
than 100,printf( )is called and the loop iterates. This causes x to be
increased by 1 and again testedto see if it is still less than or equal to 100. If
it is, printf( )is called. This process repeatsuntil x is greater than 100, at
which point the loop terminates. In this example, x is theloop control
variable, which is changed and checked each time the loop repeats.
Programming Example 2:
#include <iostream>
using namespace std;
int main(){
for(int i=1; i<=6; i++){
/* This statement would be executed
* repeatedly until the condition
* i<=6 returns false.
*/
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
OUTPUT:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6

Programming Example 3:
// C++ Program to find factorial of a number
// Factorial on n = 1*2*3*...*n
#include <iostream>
using namespace std;
int main()
{
int i, n, factorial = 1;
cout<< "Enter a positive integer: ";
cin>> n;
for (i = 1; i<= n; ++i) {
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
OUTPUT:
Enter a positive integer: 5
Factorial of 5 = 120

The Infinite Loop:


Although you can use any loop statement to create an infinite loop, for is
traditionallyused for this purpose. Since none of the three expressions that
form the for loop arerequired, you can make an endless loop by leaving the
conditional expression empty:
for( ; ; ) printf("This loop will run forever.\n");
When the conditional expression is absent, it is assumed to be true. You
may have aninitialization and increment expression, but C++ programmers
more commonly usethe for(;;) construct to signify an infinite loop.
Actually, the for(;;) construct does not guarantee an infinite loop because a
breakstatement, encountered anywhere inside the body of a loop, causes
immediatetermination.
ch = '\0';
for( ; ; ) {
ch = getchar(); /* get a character */
if(ch=='A') break; /* exit the loop */
}
printf("you typed an A");
This loop will run until the user types an A at the keyboard.

The while Loop:


The second loop available in C/C++ is the while loop. Its general form is
while(condition) statement;
where statement is either an empty statement, a single statement, or a
block ofstatements. The condition may be any expression, and true is any
nonzero value. Theloop iterates while the condition is true. When the
condition becomes false, programcontrol passes to the line of code
immediately following the loop.
Programming Example 1:
#include <iostream>
using namespace std;
int main ()
{
/* local variable Initialization */
int n = 1,times=5;
/* while loops execution */
while( n<= times )
{
cout<< "C++ while loops: " << n <<endl;
n++;
}
return 0;
}
Output:
C++ while loops:1
C++ while loops:2
C++ while loops:3
C++ while loops:4
C++ while loops:5
Programming Example 2:
#include <iostream>
using namespace std;
int main()
{
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
cout<<"Value of variable i is: "<<i<<endl; i++;
}
}
OUTPUT:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
Programming Example 3:
// C++ Program to compute factorial of a number (Factorial of n = 1*2*3...*n)

#include <iostream>
using namespace std;

int main()
{
int number, i = 1, factorial = 1;
cout<< "Enter a positive integer: ";
cin>> number;

while ( i<= number) {


factorial *= i; //factorial = factorial * i;
++i;
}

cout<<"Factorial of "<< number <<" = "<< factorial;


return 0;
}
OUTPUT:
Enter a positive integer: 4
Factorial of 4 = 24
The following example shows a keyboard input routine that simply loops
until the user types A:
char wait_for_char(void)
{
char ch;
ch = '\0'; /* initialize ch */
while(ch != 'A') ch = getchar();
return ch;
}
The do-while Loop:
Unlike for and while loops, which test the loop condition at the top of the
loop, thedo-while loop checks its condition at the bottom of the loop. This
means that a do-whileloop always executes at least once. The general form
of the do-while loop is
do {
statement;
} while(condition);
Although the curly braces are not necessary when only one statement is
present, theyare usually used to avoid confusion (to you, not the compiler)
with the while. Thedo-while loop iterates until condition becomes false.
The following do-while loop will read numbers from the keyboard until it
finds anumber less than or equal to 100.
do {
scanf("%d", &num);
} while(num> 100);
Programming Example 1:
// C++ program to add numbers until user enters 0
#include <iostream>
using namespace std;
int main()
{
float number, sum = 0.0;

do {
cout<<"Enter a number: ";
cin>>number;
sum += number;
}
while(number != 0.0);
cout<<"Total sum = "<<sum;

return 0;
}
OUTPUT 1:
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: -4
Enter a number: 2
Enter a number: 4.4
Enter a number: 2
Enter a number: 0
Total sum = 13.4
Output 2:
Enter a number: 0
Total sum = 0

You might also like