Professional Documents
Culture Documents
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.
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.
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.
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.
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.
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.
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.
unary operators and ?, associate from left to right. The unary operators(*, &, -) and ? associate
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 an int is multiplied by a float, what data type will the result be?
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.
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
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”:
// 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.
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];
balance[3] = 12.23;
#include <stdio.h>
int main(void)
int t;
/* display contents of x */
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:
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;
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].
int main(void)
int i[10];
func1(i);
.
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.
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;
};
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.
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.
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.
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;
P3:ClassAssignment
intmain()
{ charch;
//input a character
cout<<"Enter a character: ";
cin>>ch;
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;
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
#include <iostream>
using namespace std;
int main()
{
int number, i = 1, factorial = 1;
cout<< "Enter a positive integer: ";
cin>> number;
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