Você está na página 1de 10

Lecture Notes

Programming Concepts in C & C++


Kamlesh Tiwari (ktiwari@iitk.ac.in)

1 History • If we want to use any function we must include the


appropriate header file that containes the definitions
C was originally designed for and implemented on the of that function.
UNIX operating system on the DEC PDP-11, by Dennis
Ritchie. The C language was based on two languages: • The definitions of function printf() are found in
BCPL, written by Martin Richards, and B, written by header file named stdio.h, which is an abbriviation
Ken Thompson. American National Standards Institute for STanDard Input Output Header file.
(ANSI) adopted C in 1988. • To include stdio.h in our program we have to write
statement as
2 Features #include <stdio.h >
include statements are written in the begining of the
C is a general-purpose high-level programming language source code, generally before main() function.
with features of economy of expression, modern flow con-
trol & data structures, and a rich set of operators. it is #include<stdio.h>
not specialized to any particular area of application, the void main()
absence of restrictions and its generality make it more {
convenient and effective for many tasks than any other
powerful languages. It is not tied to any particular hard- }
ware or system, and therefore it is easy to write programs
What is this void written before the main() ? well
that will run without change on any machine that sup-
it signifies the type of return value from the main()
ports C. It is often called a middle-level computer lan-
function, for now take it as it is, we will come to it
guage because it combines the best elements of high-level
later.
languages with the control and flexibility of assembly lan-
guage. • Executable statements are plaved in between the
body of main() function, and every executable state-
ment terminates with a semicolon (;) at the end.
3 First Program
Let’s start learning by writing the typical Hello program. 3.2 Do it
Come let’s write a program that prints Hello. First of
3.1 Basics all to define precisely output, write Hello as ”Hello”,
then use the function printf() to print the output, by
• Every C program starts execution form a user de-
passing ”Hello” to is, as printf(”Hello”). Our executable
fined function called main(). this function must be
statement is ready
present in every C program. Program can have only
printf(”Hello”);
one main function.
Place this statement in the body of main()
void main() #include<stdio.h>
{ void main()
{
} printf("Hello");
}
• A function named printf() is used to send output
at VDU screen. what we want to print should be Save this program. what name you want to give this
placed in between the brackets of printf(). program ? hello.c ok no problem do it.

1
3.3 Compile and Run were defined by the original version of C, and five more
were added by the ANSI C committee: enum, const,
Next step is to check the output of the program.
signed, void, and volatile.

3.3.1 Compile auto double int struct


break else long switch
How ? well, press F10, use arrow keys to move to compile
case enum register typedef
tab, press ENTER, choose the option COMPILE again
char extern return union
press ENTER.
const float short unsigned
During the compilation the compiler will generate files
continue for signed void
with name hello.bak, hello.map, hello.obj, hello.exe. We
default goto sizeof volatile
are inerested in hello.exe, this is the executable file for
do if static while
DOS environment that will give us output.

3.3.2 Run 4.3 Basic Data Type


How ? well, press F10, use arrow keys to move to run There are five atomic data types in C, listed below with
tab, press ENTER, choose the option RUN again press their size in byte.
ENTER.
Type Keyword Size Range
The program will get exectued. It prints the desired
valueless void 0 nil
output to output screen and then, Integrated Devel-
character char 1 -128 to 127
opment Environment (IDE) of Turbo C start once again.
integer int 2 -32768 to 32767
floating-point float 4 6 digit precision
To see the output screen press ALT + F5
double floating-point double 8 10 digit precision
Congratulation, U done it.
4.4 Modifier of Basic Data Type
4 Definitions Except for type void, the basic data types may have var-
ious modifiers preceding them. You use a modifier to
4.1 Identifier alter the meaning of the base type to fit various situa-
tions more precisely. The list of modifiers is as follows :
the names of variables, functions, labels, and various signed, unsigned, long, short
other user-defined objects are called identifiers. These
identifiers can vary from one to several characters. The
4.5 Variables
first character must be a letter or an underscore, and
subsequent characters must be either letters, digits, or A variable is a named location in memory that is used
underscores. to hold a value that may be modified by the program.
In C, identifiers may be of any length. However, not all All variables must be declared before they can be used.
characters will necessarily be significant. If the identifier The general form of a declaration is.
is not used in an external link process, then at least the
first 31 characters will be significant. In C++, there is type variable list;
no limit to the length of an identifier, and at least the
first 1,024 characters are significant. In an identifier, up- Here, type must be a valid data type plus any
per and lowercase are treated as distinct. Hence, count, modifiers, and variable list may consist of one or more
Count, and COUNT are three separate identifiers. An identifier names separated by commas. Here are some
identifier cannot be the same as a keyword, and should declarations:
not have the same name as functions that are in the li-
brary. int i,j,l;
short int si;
Correct : abcd, Var_2, _env_, envVar unsigned int ui;
Incorrect : 1abc, var-2, ab c, this, var...2 double balance, profit, loss;

Variables will be declared in three basic places: inside


4.2 Keyword
functions, in the definition of function parameters, and
C has 32 keywords that, combined with the formal C outside of all functions. These are local variables, formal
syntax, form the C programming language. Of these, 27 parameters, and global variables.

2
4.6 Access Modifiers their values between calls.When you apply the static
modifier to a local variable, the compiler creates perma-
There are two modifiers that control how variables may
nent storage for it, much as it creates storage for a global
be accessed or modified. These qualifiers are const and
variable. The key difference between a static local vari-
volatile. They must precede the type modifiers and the
able and a global variable is that the static local variable
type names that they qualify. These modifiers are also
remains known only to the block in which it is declared.
referred to as cv-qualifiers.
In simple terms, a static local variable is a local variable
that retains its value between function calls.
4.6.1 const Applying the specifier static to a global variable instructs
Variables of type const may not be changed by your the compiler to create a global variable that is known
program. (A const variable can be given an initial only to the file in which you declared it.
value, however.) The compiler is free to place variables
of this type into read-only memory (ROM). For example, 4.7.3 register

const int a=10; The register specifier requested that the compiler keep
the value of a variable in a register of the CPU rather
creates an integer variable called a, with an initial than in memory, where normal variables are stored. This
value of 10 that your program may not modify. Note meant that operations on a register variable could occur
that a constant must be initialised with value, otherwise much faster than on a normal variable because the reg-
the compiler will generate an error. ister variable was actually held in the CPU and did not
require a memory access to determine or modify its value.
const int a; // is an error
4.7.4 auto
4.6.2 volatile By default all variables are auto ( if are not static or
The modifier volatile tells the compiler that a variable’s register ), they are created on function call and destroyed
value may be changed in ways not explicitly specified by on termination of function. Normally we omit the world
the program. For example, a global variable’s address auto to declare automatic variable.
may be passed to the operating system’s clock routine
and used to hold the real time of the system.
5 Escape Sequences
4.7 Storage Class Specifier Enclosing character constants in single quotes works for
There are four storage class specifiers supported by C: most printing characters. A few, however, such as the
extern, static, register, auto carriage return, are impossible to enter into a string from
the keyboard. For this reason, C/C++ include the spe-
cial backslash character constants shown so that you may
4.7.1 extern
easily enter these special characters. These are also re-
Note that distinction between the declaration and the ferred to as Backslash Characters.
definition of a variable is that the declaration declares
the name and type of a variable, where as a definition Code Meaning
causes storage to be allocated for the variable. \b Backspace
Because C/C++ allows separate modules of a large pro- \f Form feed
gram to be separately compiled and linked together, \n New line
there must be some way of telling all the files about the \r Carriage return
global variables required by the program. \t Horizontal tab
In most cases, variable declarations are also definitions. \" Double quote
However, by preceding a variable name with the extern \’ Single quote
specifier, you can declare a variable without defining it. \0 Null
\\ Backslash
\v Vertical tab
4.7.2 static
\a Alert (Bell)
Static variables are permanent variables within their own \? Question mark
function or file. Unlike global variables, they are not \N Octal constant (N is octal)
known outside their function or file, but they maintain \xN Hexadecimal constant (N is hexadecimal)

3
6 Operator c int; single character
s char *; print string
There are four main classes of operators: arithmetic, re- f double; [-]m.dddddd,
lational, logical, and bitwise. In addition, there are some e,E double; [-]m.dddddd[e/E]+/-xx
special operators for particular tasks. Following is the p void *; pointer
operator preceding table. % no argument is converted; print a %
Highest ( ) [ ] -> .
! ~ ++ (type) * & sizeof 7.2 scanf
* / %
+ - The function scanf is the input analog of printf, provid-
<< >> ing many of the same conversion facilities in the opposite
< <= > >= direction.
== != int scanf(char *format, ...)
& scanf reads characters from the standard input, inter-
^ prets them according to the specification in format, and
| stores the results through the remaining arguments.scanf
&& stops when it exhausts its format string, or when some
|| input fails to match the control specification. It returns
?: as its value the number of successfully matched and as-
= += -=*= /= etc. signed input items.
Lowest ,
#includ<stdio.h>
void main(){
7 Input Output int x;
printf("Enter value :);
The ANSI standard defines standard library, and a set scanf("%d",&x);
of functions that provide input and output, string han- printf("You entered %d, it’s double : %d"’,x,2*x);
dling, storage management.one of the standard library is }
stdio.h.
The simplest input mechanism is to read one character at
a time from the standard input, normally the keyboard, 8 Statements
with getchar
char ch= getchar(); In the most general sense, a statement is a part of your
In the same way the function int putchar(int) is used for program that can be executed. That is, a statement spec-
output: ifies an action. categories of statements are: Selection,
putchar(’c’) Iteration, Jump, Label, Expression, Block
puts the character c on the standard output, which is by
default the screen.
8.1 Selection
7.1 printf C/C++ supports two types of selection statements: if
and switch. In addition, the ? operator is an alternative
The output function printf is used to print some value at
to if in certain circumstances.
screen, the suntax of printf() is
int printf(char *format, arg1, arg2, ...);
printf converts, formats, and prints its arguments on the 8.1.1 if
standard output under control of the format. It returns
the number of characters printed. The general form of the if statement is

if (expression) statement;
7.1.1 Format Specifiers
else statement;
Character Argument type; Printed As
d,i int; decimal number 8.1.2 switch
o int; unsigned octal number
x,X int; unsigned hexadecimal number C/C++ has a built-in multiple-branch selection state-
u int; unsigned decimal number ment, called switch, which successively tests the value of

4
an expression against a list of integer or character con- do-while loop always executes at least once. The general
stants. When a match is found, the statements associ- form of the do-while loop is
ated with that constant are executed. The general form
of the switch statement is do{
statement;
switch (expression) } while(condition);
{
case constant1: statement sequence 8.3 Jump
break;
case constant2: statement sequence There are four statements that perform an unconditional
break; branch: return, goto, break, and continue. Of these, you
case constant3: statement sequence may use return and goto anywhere in your program. You
break; may use the break and continue statements in conjunc-
. tion with any of the loop statements.
..
default : statement sequence 8.3.1 return
}
The return statement is used to return from a function.
It is categorized as a jump statement because it causes
8.2 Iteration execution to return (jump back) to the point at which
the call to the function was made. A return may or
iteration statements (also called loops) allow a set of in- may not have a value associated with it. If return has a
structions to be executed repeatedly until a certain con- value associated with it, that value becomes the return
dition is reached. This condition may be predefined (as value of the function. In C, a non-void function does not
in the for loop), or open-ended (as in the while and do- technically have to return a value. If no return value is
while loops). specified, a garbage value is returned. However, in C++,
a non-void function must return a value. That is, in
8.2.1 for C++, if a function is specified as returning a value, any
return statement within it must have a value associated
The general design of the for loop is reflected in some
with it. (Even in C, if a function is declared as returning
form or another in all procedural programming lan-
a value, it is good practice to actually return one.) The
guages. However, in C/C++, it provides unexpected
general form of the return statement is
flexibility and power. The general form of the for
statement is
return expression;
for(initialization; condition; increment) statement;
8.3.2 goto

8.2.2 while Since C/C++ has a rich set of control structures and al-
lows additional control using break and continue, there
The general form is is little need for goto. Most programmers’ chief concern
about the goto is its tendency to render programs un-
while(condition) statement; readable. Nevertheless, although the goto statement fell
out of favor some years ago, it occasionally has its uses.
where statement is either an empty statement, a There are no programming situations that require goto.
single statement, or a block of statements. The con- Rather, it is a convenience, which, if used wisely, can be
dition may be any expression, and true is any nonzero a benefit in a narrow set of programming situations, such
value. The loop iterates while the condition is true. as jumping out of a set of deeply nested loops. The goto
When the condition becomes false, program control is not used outside of this section. The goto statement
passes to the line of code immediately following the requires a label for operation. (A label is a valid identi-
loop. fier followed by a colon.) Furthermore, the label must be
in the same function as the goto that uses ityou cannot
8.2.3 do while jump between functions. The general form of the goto
statement is
Unlike for and while loops, which test the loop condi-
tion at the top of the loop, the do-while loop checks its goto label;
condition at the bottom of the loop. This means that a ..

5
. of their first element. Therefore, the declared array has
label: 100 elements, balance[0] through balance[99].

8.3.3 break 9.2 Multi Dimension Array


The break statement has two uses. You can use it to C/C++ supports multidimensional arrays. The sim-
terminate a case in the switch statement (covered in the plest form of the multidimensional array is the two-
section on switch earlier in this chapter). You can also dimensional array. A two-dimensional array is, essen-
use it to force immediate termination of a loop, bypass- tially, an array of one-dimensional arrays. Syntax to de-
ing the normal loop conditional test. When the break clare a two-dimensional integer array D of size 10,20, is
statement is encountered inside a loop, the loop is im- int D[10][20];
mediately terminated and program control resumes at To access point 1,12 of array D, you would use D[0][11].
the next statement following the loop.

8.3.4 continue
10 Functions
The continue statement works somewhat like the break In C, a function is equivalent to a subroutine or func-
statement. Instead of forcing termination, however, con- tion in Fortran, or a procedure or function in Pascal. A
tinue forces the next iteration of the loop to take place, function provides a convenient way to encapsulate some
skipping any code in between. For the for loop, con- computation, which can then be used without worrying
tinue causes the conditional test and increment portions about its implementation. With properly designed func-
of the loop to execute. For the while and do-while loops, tions, it is possible to ignore how a job is done; knowing
program control passes to the conditional tests. what is done is sufficient. C makes the sue of functions
easy, convinient and efficient.
Let us write a function that calculates squire a integer
9 Array number.
int squire(int x){
array is a collection of variables of the same type that are
int sqr;
referred to through a common name. A specific element
sqr = x*x;
in an array is accessed by an index. In C/C++, all ar-
return sqr;
rays consist of contiguous memory locations. The lowest
}
address corresponds to the first element and the high-
void main(){
est address to the last element. Arrays may have from
int x;
one to several dimensions. The most common array is
x=10;
the null-terminated string, which is simply an array of
printf("\n Squire of %d is %d",x,squire(x));
characters terminated by a null.
}

9.1 Single Dimension Array


The general form for declaring a single-dimension array 10.1 Parameter Passing Mechanicm
is In C/C++ we have two parameter passing mechanism,
type var name[size]; Call By Value and Call By Reference. Call By Value
Like other variables, arrays must be explicitly declared so means that the called function is given the values of its
that the compiler may allocate space for them in memory. arguments in temporary variables rather than the origi-
Here, type declares the base type of the array, which is nals,therefore any change maid in the variable value will
the type of each element in the array, and size defines not effect the original variable. Where as in call by refer-
how many elements the array will hold. For example, to ence the address of the original variable is pssed,therefore
declare a 100-element array called balance of type float, any change maid in the variable value will also effect the
use this statement: original variable.
float balance[100];
An element is accessed by indexing the array name. This // call by value function
is done by placing the index of the element within square void fun1(int x){
brackets after the name of the array. For example, x=5;
balance[3] = 12.23; assigns element number 3 in balance }
the value 12.23. In C/C++, all arrays have 0 as the index

6
// call by reference function name for convenient handling. Structures help to orga-
void fun2(int &x){ nize complicated data, particularly in large programs,
x=15; because they permit a group of related variables to be
} treated as a unit instead of as separate entities.

// call by pointer function struct student{


// same as call by reference char name[30];
void fun3(int *x){ char phone[12];
*x=25; int age,height;
} float weight
};
void main(){
int x; void main(){
x=10; student amit;
printf(" %d",x); // prints :10 strcpy(amit.name,"Amit");
fun1(x); // Call by value strcpy(amit.phone,"940123123");
printf(" %d",x); // prints :10 amit.age=19;
fun2(x); // Call by reference amit.height=2.3;
printf(" %d",x); // prints :15 amit.weight=51;
fun2(&x); // Call by pointer
printf(" %d",x); // prints :25 printf(" %d", sizeof(student));// prints:50
} }

11.2 Union
10.2 Recurtion A union is a variable that may hold (at different times)
Recurtion is the mechanism by which a function calles objects of different types and sizes, with the compiler
itself, it is a very stromg tool in the hands of program- keeping track of size and alignment requirements. Unions
mers. By using recurtion complex logic can easily be provide a way to manipulate different kinds of data in a
written. The use of recurtion improves the readability of single area of storage, without embedding any machine-
the program, but the overhead of processor is increased. dependent information in the program.

// recursive function for factorial union un{


void fact(int x){ int a;
if(x<=1) return 1; char b;
return x*fact(x-1); float c;
} };

// recursive function for fibonnaci series void main(){


void fibonnaci(int x){ printf(" %d", sizeof(un));// prints:4
if(x<=2) return 1; }
return fibonnaci(x-1)+fibonnaci(x-2);
}
12 File Handling
void main(){
Let us write a program to open a file report.txt and the
printf("\n fact(10) : %d",fact(10));
print it’s contents at screen , as well as copy the contents
printf("\n fibonnaci(10) : %d",fibonnaci(10));
in a new file report2.txt.
}
#include<stdio.h>
void main(){
11 Structure and Union char ch;
FILE *fp,*fp2;
11.1 Structure
fp =fopen("report.txt" ,"r");
A structure is a collection of one or more variables, pos- fp2=fopen("report2.txt","w");
sibly of different types, grouped together under a single fread((void*)&ch,1,1,fp);

7
while(!feof(fp)){ int *ptr1,*ptr2;
printf("%c",ch);
fwrite((void*)&ch,1,1,fp2); // uninitialized space for 10 element
fread((void*)&ch,1,1,fp); // integer array is created by
} ptr1=(int*) malloc(10);
fclose(fp); fclose(fp2);
} // initialized space for 10 element
// integer array is created by
ptr2=(int*) calloc(10,sizeof(int));
13 Pointers
free(ptr1); free(ptr2);
A pointer is a variable that holds a memory address. }
This address is the location of another object (typically
another variable) in memory. If one variable contains the
address of another variable, the first variable is said to
point to the second one. A pointer declaration consists 15 C++
of a base type, an *, and the variable name. The general
form for declaring a pointer variable is
C++ began as an expanded version of C. The C++
type *name;
extensions were first invented by Bjarne Stroustrup in
where type is the base type of the pointer and may be any
1979 at Bell Laboratories in Murray Hill, New Jer-
valid type. The name of the pointer variable is specified
sey.Most additions made by Stroustrup to C support
by name.
object-oriented programming, sometimes referred to as
#include<stdio.h> OOP.C++’s object-oriented features were inspired by
void main(){ another object-oriented language called Simula67.The
int x=5,y=10; first revision of C++ was in 1985 and the second in
int *ptr; // ptr is a pointer of type int 1990.The final draft of the C++ standard, by ANSI/ISO
was passed out on November 14, 1997.
ptr=&x;
printf("%d",*ptr);// printf :5
15.1 OOP’S
ptr=&y;
printf("%d",*ptr);// printf :10 OOP is a powerful way to approach the job of
} programming.Object-oriented programming took the
best ideas of structured programming and combined
them with several new concepts. The result was a dif-
14 Storage Management ferent way of organizing a program. In the most gen-
The functions malloc and calloc obtains blocks of eral sense, a program can be organized in one of two
memory dynamically. ways: around its code (what is happening) or around its
data (who is being affected). Using only structured pro-
void *malloc(size t n) gramming techniques, programs are typically organized
returns a pointer to n bytes of uninitialized storage, or around code. This approach can be thought of as ”code
NULL if the request cannot be satisfied. acting on data.” For example, a program written in a
structured language such as C is defined by its functions,
void *calloc(size t n, size t size) any of which may operate on any type of data used by
returns a pointer to enough free space for an array of the program. Object-oriented programs work the other
n objects of the specified size, or NULL if the request way around. They are organized around data, with the
cannot be satisfied. The storage is initialized to zero. key principle being ”data controlling access to code.” In
an object-oriented language, you define the data and the
free(p) is the converse of malloc and calloc, it frees routines that are permitted to act on that data. Thus,
the space pointed to by it’s parameter p, where p was a data type defines precisely what sort of operations can
originally obtained by a call to malloc or calloc. be applied to that data.
To support the principles of object-oriented program-
#include<stdio.h> ming, all OOP languages have three traits in common:
void main(){ encapsulation, polymorphism, and inheritance.

8
15.1.1 Encapsulation x = length*length ;
x += bredth*bredth ;
Encapsulation is the mechanism that binds together code x += height*height ;
and the data it manipulates, and keeps both safe from return pow(x,0.5);
outside interference and misuse. In an object-oriented }
language, code and data may be combined in such a way };
that a self-contained ”black box” is created. When code
and data are linked together in this fashion, an object void main(){
is created. In other words, an object is the device that box a(10,20,30);
supports encapsulation. cout<<a.surfaceArea()
Within an object, code, data, or both may be private to <<a.volume()
that object or public. Private code or data is known to <<a.diagonal();
and accessible only by another part of the object. That }
is, private code or data may not be accessed by a piece of
the program that exists outside the object. When code or
data is public, other parts of your program may access it 15.1.2 Inheritance
even though it is defined within an object. Typically, the Inheritance is the process by which one object can ac-
public parts of an object are used to provide a controlled quire the properties of another object. This is important
interface to the private elements of the object. because it supports the concept of classification. If you
For all intents and purposes, an object is a variable of think about it, most knowledge is made manageable by
a user-defined type. It may seem strange that an object hierarchical classifications. For example, a Red Delicious
that links both code and data can be thought of as a apple is part of the classification apple, which in turn is
variable. However, in object-oriented programming, this part of the fruit class, which is under the larger class food.
is precisely the case. Each time you define a new type of Without the use of classifications, each object would have
object, you are creating a new data type. Each specific to define explicitly all of its characteristics. However,
instance of this data type is a compound variable. through the use of classifications, an object need only de-
fine those qualities that make it unique within its class.
#include<iostream.h> It is the inheritance mechanism that makes it possible
#include<math.h> for one object to be a specific instance of a more general
case. As you will see, inheritance is an important aspect
class box{ of object-oriented programming.
private :
int length,bredth,height; class A
{
public: public :
box(int a,int b,int c){ int l,b;
length=a;
bredth=b; A(int x,int y){ l=x; b=y; }
height=c; int area(){ return l*b; }
} };

int surfaceArea(){ class B : public A


int x; {
x = length*bredth ; public :
x += length*height ; int h;
x += bredth*height ;
return 2*x; B(int x,int y,int z){ A(x,y); h=z; }
}
int surfaceArea()
int volume(){ { return 2*(l*l + b*b + h*h); }
return length*bredth*height; int volume(){ return l*b*h; }
} int diagonal()
{ return pow(l*l + b*b + h*h,0.5); }
int diagonal(){ };
int x;

9
void main(){ }
B a(10,20,30);
cout<<a.surfaceArea()
<<a.volume() 16 Appendix
<<a.diagonal();
} 16.1 Algorithms
An algorithm is a finite list of well-defined instructions
15.1.3 Polymorphism for accomplishing some task that, given an initial state,
will proceed through a well-defined series of successive
Object-oriented programming languages support poly-
states, eventually terminating in an end-state. In other
morphism, which is characterized by the phrase ”one
worlds we can say it is an ordered sequence of unam-
interface, multiple methods.” In simple terms, polymor-
biguous and well-defined instructions that performs some
phism is the attribute that allows one interface to control
task and halts in finite time.
access to a general class of actions. The specific action
Let’s examine the four parts of this definition more
selected is determined by the exact nature of the sit-
closely
uation. For example, you might have a program that
defines three different types of stacks. One stack is used • an ordered sequence means that you can number the
for integer values, one for character values, and one for steps
floating-point values. Because of polymorphism, you can
define one set of names, push() and pop() , that can be • unambiguous and well-defined instructions means
used for all three stacks. In your program you will cre- that each instruction is clear, do-able, and can be
ate three specific versions of these functions, one for each done without difficulty
type of stack, but names of the functions will be the same. • performs some task
The compiler will automatically select the right function
based upon the data being stored. Thus, the interface to • halts in finite time (algorithms terminate!)
a stackthe functions push() and pop() are the same no
there is generally no formal specification to write an algo-
matter which type of stack is being used. The individual
rithm, therefore we can use any language syntax or sym-
versions of these functions define the specific implemen-
bol to express an algorithm, such an unristricted syntax
tations (methods) for each type of data.
code is called pseudo code. Many time we say that the
Polymorphism helps reduce complexity by allowing the
algorithm is written by using pseudo code.
same interface to be used to access a general class of ac-
tions. It is the compiler’s job to select the specific action
(i.e., method) as it applies to each situation. You, the 16.2 Flow Chart
programmer, don’t need to do this selection manually. A flowchart is a schematic representation of an algorithm
You need only remember and utilize the general inter- or a process. A flowchart is one of the seven basic tools
face. The first object-oriented programming languages of quality control, which also includes the histogram,
were interpreters, so polymorphism was, of course, sup- Pareto chart, check sheet, control chart, causeandeffect
ported at run time. However, C++ is a compiled lan- diagram, and scatter diagram. They are commonly used
guage. Therefore, in C++, both run-time and compile- in business/economic presentations to help the audience
time polymorphism are supported. visualize the content better, or to find flaws in the pro-
cess.
15.2 cin & cout
input and Output in C++ is fairly very simple. we use 17 References
the oblect cout to sent output and cin to read input,
library file <iostream.h > must be included. consider • Schaum’s Outline of Theory and Problems of Pro-
following example. gramming with C -by Byron S. Gottfried [TMH]

#include<iostream.h> • C++ The Complete Reference - by Herbert Schildt


void main(){ [TMH]
int x;
• Let Us C - by Yashavant Kanetkar [BPB]
cout<<"Enter a number :";
cin>> x; • Prigramming in ANSI C - by E Balagurusamy
cout<<"Double of " <<x [TMH]
<<" is "<< 2*x;

10

Você também pode gostar