Professional Documents
Culture Documents
Edu I CCJAVA rxj0cp PDF
Edu I CCJAVA rxj0cp PDF
Edu I CCJAVA rxj0cp PDF
C, C++, JAVA
Programming
EDU-i ACADEMY License to your Future
C, c++, java
The Exam link is provided at the end of this document.
The questions will be purely based upon the content of this material.
Take exams seriously and don‘t try to copy it from the course material.
Introduction:
C Boot Disk Make a new, bootable copy of your 1616 User disk, following the
directions in your User‘s Manual. To ensure sufficient space, delete any
obviously unwanted files you notice on the copy. Copy the contents of your
HiTech C distribution disk to the new disk, keeping the subdirectories the same
as on the HiTech disk. If you have received any updated C header files or other
updates, copy these also to their respective subdirectories on your new disk.
Using edit, alter the xpath and assign commands in your autoexec.shell file in
the root directory of your new disk. Your xpath should include /F0/bin (if it is
not already included). Add the following lines to your autoexec.shell, to recreate
the environment used by Tim Ward when originally running these programs.
assign /hitech /f0/bin assign /sys /f0/include assign /temp /rd this will allow
code to be written without regard to where you actually put your files. If you are
using a second drive, or a hard disk, simply change the assign to point /hitech to
the correct drive. C tends to use temporary files extensively. If you have
sufficient memory available on your ram disk, use /rd for temporary files. If not,
use the current drive and directory, as indicated by the assign /temp. Make sure
you copy the new C pre-processor relcc.xrel from the user disk into the /bin
subdirectory of your new C disk.
Note that relccexpects by default to find its C library files on the current drive in
the /hitech directory. It also expects to find it‘s include files on the current drive
in the /hitech/include directory. We will explain what this means later, and there
is a detailed discussion of the HiTech C compiler at the end of the tutorial. If all
is correct, you can now compile a C file by typing relcc -v file.c the -v flag is to
invoke the verbose mode, which produces the maximum information from the
compiler. If you are experimenting, you may prefer to capture any errors
encountered in a file, for later study. If so, use relcc -v file.c} error file
Identifier
Before you can do anything in any language, you must at least know how you
name an identifier. An identifier is used for any variable, function, data
definition, etc. In the programming language C, an identifier is a combination of
alphanumeric characters, the first being a letter of the alphabet or an underline,
and the remaining being any letter of the alphabet, any numeric digit, or the
underline. Two rules must be kept in mind when naming identifiers. 1. The case
of alphabetic characters is significant. Using "INDEX" for a variable is not the
same as using "index" and neither of them is the same as using "InDex" for a
variable. All three refer to different variables. 2. As C is defined, up to eight
significant characters can be used and will be considered significant. If more
than eight are used, they may be ignored by the compiler. This may or may not
be true of your compiler. You should check your reference manual to find out
how many characters are significant for your compiler. The HiTech C compiler
used with the Applix 1616 allows 31 significant characters, and prepends an
underscore (_) It should be pointed out that some C compilers allow use of a
dollar sign in an identifier name, but since it is not universal, it will not be used
anywhere in this tutorial. Check your documentation to see if it is permissible
for your particular compiler.
Keywords
The following list shows the reserved words in C. These reserved words may
not be used as constant or variable or any other identifier names.
Auto, else, Long, switch, break, enum, register, typedef, case, extern, return,
union, char, float, short, unsigned, const, for, signed, void, continue, goto,
sizeof, volatile, default, if, static, while, do, int, struct, _packed, double
You are looking at the simplest possible C program. There is no way to simplify
this program, or to leave anything out. Unfortunately, the program doesn‘t do
anything.
main()
{}
The word "main" is very important, and must appear once, and only once, in
every C program. This is the point where execution is begun when the program
is run. We will see later that this does not have to be the first statement in the
program, but it must exist as the entry point. Following the "main" program
name is a pair of parentheses, which are an indication to the compiler that this is
a function. We will cover exactly what a function is in due time. For now, I
suggest that you simply include the pair of parentheses. The two curly brackets
{ }, properly called braces, are used to define the limits of the program itself.
The actual program statements go between the two braces and in this case, there
are no statements because the program does absolutely nothing. You can
compile and run this program, but since it has no executable statements, it does
nothing. Keep in mind however, that it is a valid C program
Load the file named oneint.c and display it on the monitor for our first example
of how to work with data in a C program.
main( )
int index;
index = 13;
index = 27;
index = 10;
The entry point "main" should be clear to you by now as well as the
beginning brace. The first new thing we encounter is the line containing "int
index;", which is used to define an integer variable named "index". The "int" is
a reserved word in C, and can therefore not be used for anything else. It defines
a variable that can have a value from -32768 to 32767 on most MS-DOS
microcomputer implementations of C. It defines a variable with a value from -
2147483648 to 2147483647 in HiTech C.
Programming Exercises
2. Modify the program to display your address and phone number on separate
lines by adding two additional "printf" statements.
While Loop
The C programming language has several structures for looping and conditional
branching. We will cover them all in this chapter and we will begin with the
while loop. The while loop continues to loop while some condition is true.
When the condition becomes false, the looping is discontinued. It therefore does
just what it says it does, the name of the loop being very descriptive.
Load the program while.c and display it for an example of a while loop.
main( )
int count;
count = 0;
count = count + 1;
Do-While Loop
A variation of the while loop is illustrated in the program dowhile.c, which you
should load and display.
main( )
int i;
i = 0;
do {
i = i + 1;
This program is nearly identical to the last one except that the loop begins with
the reserved word "do", followed by a compound statement in braces, then the
reserved word "while", and finally an expression in parentheses. The statements
in the braces are executed repeatedly as long as the expression in parentheses is
true. When the expression in parentheses becomes false, execution is
terminated, and control passes to the statements following this statement.
For Loop
The "for" loop is really nothing new, it is simply a new way of describe the
"while" loop. Load and edit the file named forloop.c for an example of a
program with a "for" loop.
main( )
int index;
The "for" loop consists of the reserved word "for" followed by a rather large
expression in parentheses. This expression is really composed of three fields
separated by semi-colons. The first field contains the expression "index = 0" and
is an initializing field. Any expressions in this field are executed prior to the
first pass through the loop. There is essentially no limit as to what can go here,
but good programming practice would require it to be kept simple. Several
initializing statements can be placed in this field, separated by commas.
The second field, in this case containing "index < 6", is the test which is done at
the beginning of each loop through the program. It can be any expression which
will evaluate to a true or false. (More will be said about the actual value of true
and false in the next chapter.)
The expression contained in the third field is executed each time the loop is
executed but it is not executed until after those statements in the main body of
the loop are executed. This field, like the first, can also be composed of several
operations separated by commas.
If Statement
Load and display the file ifelse.c for an example of our first conditional
branching statement, the "if".
main()
int data;
if (data == 2)
if (data < 5)
else
Notice first, that there is a "for" loop with a compound statement as its
executable part containing two "if" statements. This is an example of how
statement can be nested. It should be clear to you that each of the "if" statements
will be executed 10 times.
Consider the first "if" statement. It starts with the keyword "if" followed by an
expression in parentheses. If the expression is evaluated and found to be true,
the single statement following the "if" is executed. If false, the following
statement is skipped. Here too, the single statement can be replaced by a
compound statement composed of several statements bounded by braces.
If-Else
The second "if" is similar to the first, with the addition of a new reserved word,
the "else", following the first printf statement. This simply says that, if the
expression in the parentheses evaluates as true, the first expression is executed,
otherwise the expression following the "else" is executed. Thus, one of the two
expressions will always be executed, whereas in the first example the single
expression was either executed or skipped. Both will find many uses in your C
programming efforts. Compile and run this program to see if it does what you
expect.
Load the file named breakcon.c for an example of two new statements.
main( )
int xx;
if (xx == 8)
break;
if (xx == 8)
continue;
Notice that in the first "for" there is an if statement that calls a break if xx
equals 8. The break will jump out of the loop you are in and begin executing the
statements following the loop, effectively terminating the loop. This is a
valuable statement when you need to jump out of a loop depending on the value
of some results calculated in the loop. In this case, when xx reaches 8, the loop
is terminated and the last value printed will be the previous value, namely 7.
The next "for" loop, contains a continue statement which does not cause
termination of the loop but jumps out of the present iteration. When the value of
xx reaches 8 in this case, the program will jump to the end of the loop and
continue executing the loop, effectively eliminating the printf statement during
the pass through the loop when xx is eight. Compile and run the program to see
if it does what you expect.
Programming Exercises
1. Write a program that writes your name on the monitor ten times. Write this
program three times, once with each looping method.
2. Write a program that counts from one to ten, prints the values on a separate
line for each, and includes a message of your choice when the count is 3 and a
different message when the count is 7.
Data types
Data types refer to an extensive system used for declaring variables or functions
of different types. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted.
Basic Types: They are arithmetic types and consists of the two types: (a)
integer types and (b) floatingpoint types.
Enumerated types: They are again arithmetic types and they are used to
define variables that can only be assigned certain discrete integer values
throughout the program.
The type void: The type specifier void indicates that no value is
available.
Derived types: They include (a) Pointer types, (b) Array types, (c)
Structure types, (d) Union types and (e) Function types. The array types
and structure types are referred to collectively as the aggregate types. The
type of a function specifies the type of the function's return value.
The void type specifies that no value is available. It is used in three kinds of
situations:
Variable
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size
and layout of the variable's memory; the range of values that can be stored
within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C is case-sensitive. Based on the basic
types explained in previous chapter, there will be the following basic variable
types:
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double,
bool or any userdefined object, etc., and variable_list may consist of one or
more identifier names separated by commas. Some valid declarations are shown
here:
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j and k of type int.
Logical Evaluation
Another useful but cryptic operator is the arithmetic operator. This operator is
used to modify any variable by some constant value. The first statement of the
"arithmetic operator" group of statements simply adds 12 to the value of the
variable "a". The second statement does the same, but once again, it is not
intuitive that they are the same. Any of the four basic functions of arithmetic,
"+", "-", "x", or "/", can be handled in this way, by putting the function desired
in front of the equal sign and eliminating the second reference to the variable
name. It should be noted that the expression on the right side of the arithmetic
operator can be any valid expression, the examples are kept simple for your
introduction to this new operator. Justliketheincrementing anddecrementing
operators, thearithmetic operator is used extensively by experienced C
programmers and it would pay you well to understand it.
The conditional expression is just as cryptic as the last two, but once again it
can be very useful so it would pay you to understand it. It consists of three
expressions within parentheses separated by a question mark and a colon. The
expression prior to the question mark is evaluated to determine if it is not true,
the expression following the colon is evaluated. The result of the evaluation is
used for the assignment. The final result is identical to that of an "if" statement
with an "else" clause. This is illustrated by the second example in this group.
The conditional expression has the added advantage of more compact code that
will compile to fewer machine instructions in the final program.
Programming Exercises
1. Write a program that will count from 1 to 12 and print the count, and its
square, for each count. 1 1 2 4 3 9 etc..
2. Write a program that counts from 1 to 12 and prints the count and its
inversion to 5 decimal places for each count. This will require a floating point
number. 1 1.00000 2 .50000 3 .33333 4 .25000 etc.
3. Write a program that will count from 1 to 100 and print only those values
between 32 and 39, one to a line.
Static Variables
Every compiler comes with some standard predefined functions which are
available for your use. These are mostly input/ouput functions, character and
string manipulation functions, and math functions. We will cover most of these
in subsequent chapters. In addition, most compilers have additional functions
predefined that are not standard but allow the programmer to get the most out of
his particular computer. In the case of the IBM-PC and compatibles, most of
these functions allow the programmer to use the BIOS services available in the
operating system, or to write directly to the video monitor or to any place in
memory. The Applix equivalents are included in the header files mentioned
elsewhere. These will not be covered in any detail as you will be able to study
the unique aspects of your compiler on your own
Recursion
main( )
int index;
index = 8;
count_dn(index);
count_dn(count)
int count;
count--;
if (count > 0)
count_dn(count);
Programming Exercises
String
Array
An array is a series of homogeneous pieces of data that are all identical in type,
but the type can be quite complex as we will see when we get to the chapter of
this tutorial discussing structures. A string is simply a special case of an array.
The best way to see these principles is by use of an example, so load the
program chrstrg.c and display it on your monitor.
main( )
name[0] = ‘D‘;
name[1] = ‘a‘;
name[2] = ‘v‘;
name[3] = ‘e‘;
The first thing new is the line that defined a "char" type of data entity. The
square brackets define an array subscript in C, and in the case of the data
definition statement, the 5 in the brackets defines 5 data fields of type "char" all
defined as the variable "name". In the C language, all subscripts start at 0 and
increase by 1 each step up to the maximum which in this case is 4. We therefore
have 5 "char" type variables named, "name[0]", "name[1]", "name[2]",
"name[3]", and "name[4]". You must keep in mind that in C, the subscripts
actually go from 0 to one less than the number defined in the definition
statement
main( )
char name1[12],name2[12],mixed[25];
char title[20];
strcpy(name1,"Rosalinda");
strcpy(name2,"Zeke");
printf(" %s\n\n"title);
printf("Name 1 is %s\n",name1);
printf(Name 2 is %s\n",name2);
strcpy(mixed,name1);
else
strcpy(mixed,name2);
strcpy(mixed,name1);
strcat(mixed," ");
strcat(mixed,name2);
}
First we define four strings. Next we come to a new function that you will find
very useful, the "strcpy" function, or string copy. It copies from one string to
another until it comes to the NULL character. It is easy to remember which one
gets copies to which is you think of them like an assignment statement. Thus if
you were to say, for example, "x = 23;", the data is copied from the right entity
to the left one. In the "strcpy" function, the data is also copied from the right
entity to the left, so that after execution of the first statement, name1 will
contain the string "Rosalinda", but without the double quotes, they are the
complier‘s way of knowing that you are defining a string.
main( )
int i,j;
printf("%5d ",big[i][j]);
1. Write a program with three short strings, about 6 characters each, and use
"strcpy" to copy "one", "two", and "three" into them. Concatenate the three
strings into one string and print the result out 10 times.
2. Define two integer arrays, each 10 elements long, called "array1" and
"array2". Using a loop, put some kind of nonsense data in each and add them
term for term into another 10 element array named "arrays". Finally print all
results in a table with an index number. 1 2 + 10 = 12 2 4 + 20 = 24 3 6 + 30 =
36 etc.
Hint; The print statement will be similar to: printf("%4d %4d + %4d =
%4d\n",index,array1[index], array2[index],arrays[index]);
Pointer
int index,*pt1,*pt2;
pt2 = pt1;
The following two rules are very important when using pointers and must be
thoroughly understood. 1. A variable name with an ampersand in front of it
defines the address of the variable and therefore points to the variable. You can
therefore read line six as "pt1 is assigned the value of the address of "index".
2. A pointer with a "star" in front of it refers to the value of the variable pointed
to by the pointer. Line nine of the program can be read as "The stored (starred)
value to which the pointer "pt1" points is assigned the value 13". Now you can
see why it is convenient to think of the asterisk as a star, it sort of sounds like
the word store.
The Stdio.H Header File
Load the file simpleio.c for our first look at a file with standard I/O. Standard
I/O refers to the most usual places where data is either read from, the keyboard,
or written to, the video monitor. Since they are used so much, they are used as
the default I/O devices and do not need to be named in the Input/Output
instructions. This will make more sense when we actually start to use them so
lets look at the file in front of you.
main( )
char c;
do {
printf("\nEnd of program.\n");
The first thing you notice is the first line of the file, the #include
"stdio.h" line. This is very much like the #define we have already studied,
except that instead of a simple substitution, an entire file is read in at this point.
The system will find the file named "stdio.h" and read its entire contents in,
replacing this statement. Obviously then, the file named "stdio.h" must contain
valid C source statements that can be compiled as part of a program. This
particular file is composed of several standard #defines to define some of the
standard I/O operations. The file is called a header file and you will find several
different header files on the source disks that came with your compiler. Each of
the header files has a specific purpose and any or all of them can be included in
any program. Most C compilers use the double quote marks to indicate that the
"include" file will be found in the current directory. A few use the "less than"
and "greater than" signs to indicate that the file will be found in a standard
header file. Nearly all MSDOS C compilers use the double quotes, and most
require the "include" file to be in the default directory. All of the programs in
this tutorial have the double quotes in the "include" statements. If your compiler
uses the other notation, you will have to change them before compiling.
Input/Output Operations In C
You should print out the file named "stdio.h" and spend some time
studying it. There will be a lot that you will not understand about it, but parts of
it will look familiar. The name "stdio.h" is sort of cryptic for "standard
input/output header", because that is exactly what it does. It defines the standard
input and output functions in the form of #defines and macros. Don‘t worry too
much about the details of this now. You can always return to this topic later for
more study if it interests you, but you will really have no need to completely
understand the "stdio.h" file. You will have a tremendous need to use it
however, so these comments on its use and purpose are necessary.
Structure
A structure is a user defined data type. You have the ability to define a new type
of data considerably more complex than the types we have been using. A
structure is a combination of several different previously defined data types,
including other structures we have defined. An easy to understand definition is,
a structure is a grouping of related data in a way convenient to the programmer
or user of the program. The best way to understand a structure is to look at an
example, so if you will load and display struct1.c, we will do just that.
main( )
struct {
} boy,girl;
boy.initial = ‘R‘;
boy.age = 15;
boy.grade = 75;
girl.age = boy.age - 1; /* she is one year younger */
girl.grade = 82;
girl.initial = ‘H‘;
girl.initial,girl.age,girl.grade);
The program begins with a structure definition. The key word "struct" is
followed by some simple variables between the braces, which are the
components of the structure. After the closing brace, you will find two variables
listed, namely "boy", and "girl". According to the definition of a structure,
"boy" is now a variable composed of three elements, "initial", "age", and
"grade". Each of the three fields are associated with "boy", and each can store a
variable of its respective type. The variable "girl" is also a variable containing
three fields with the same names as those of "boy" but are actually different
variables. We have therefore defined 6 simple variables.
Using the above definition, we can assign a value to each of the three fields of
"boy" and each of the three fields of "girl". Note carefully that "boy.initial" is
actually a "char" type variable, because it was assigned that in the structure, so
it must be assigned a character of data. Notice that "boy.initial" is assigned the
character ‘R‘ in agreement with the above rules. The remaining two fields of
"boy" are assigned values in accordance with their respective types. Finally the
three fields of girl are assigned values but in a different order to illustrate that
the order of assignment is not critical.
C++
C & C++ are mostly same they differ by few advantages: let us see them
Similarities:
Both the languages have a similar syntax.
Code structure of both the languages are same.
The compilation of both the languages is similar.
They share the same basic syntax. Nearly all of C‘s operators and
keywords are also present in C++ and do the same thing.
C++ has a slightly extended grammar than C, but the basic grammer is the
same.
Basic memory model of both is very close to the hardware.
Same notions of stack, heap, file-scope and static variables are present in
both the languages.
C++ can be said a superset of C. Major added features in C++ are Object-
Oriented Programming, Exception Handling and rich C++ Library.
C++ is a superset of C, and that virtually any legal C program is a legal C++
program.
Note: A programming language is said to use static typing when type checking
is performed during compile-time as opposed to run-time.
1.Object-Oriented Programming
Encapsulation
Data hiding
Inheritance
Polymorphism
2.Standard Libraries
The core language giving all the building blocks including variables, data
types and literals, etc.
The C++ Standard Library giving a rich set of functions manipulating files,
strings, etc.
Learning C++
Use of C++
C++ is being highly used to write device drivers and other software that rely on
direct manipulation of hardware under real-time constraints.
C++ is widely used for teaching and research because it is clean enough for
successful teaching of basic concepts.
Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are
written in C++.
3. BASIC SYNTAX
Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - wagging, barking, and eating. An object is an
instance of a class.
Instant Variables - Each object has its unique set of instant variables. An
object's state is created by the values assigned to these instant variables.
Let us look at a simple code that would print the words Hello World.
#include <iostream>
int main()
return 0;
4. The line int main() is the main function where program execution
begins.
5. The next line cout << "This is my first C++ program."; causes the
message "This is my first C++ program" to be displayed on the screen.
Classes (I)
Classes are generally declared using the keyword class, with the following
format:
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
All is very similar to the declaration on data structures, except that we can
now include also functions and members, but also this new thing called
access specifier. An access specifier is one of the following three
keywords: private, public or protected. These specifiers modify the access
rights that the members following them acquire:
• Finally, public members are accessible from anywhere where the object
is visible.
By default, all members of a class declared with the class keyword have
private access for all its members. Therefore, any member that is declared
before one other class specifier automatically has private access.
class CRectangle {
int x, y;
public:
} rect;
Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of
this class called rect. This class contains four members: two data members of
type int (member x and member y) with private access (because private is the
default access level) and two member functions with public access: set_values()
and area(), of which for now we have only included their declaration, not their
definition.
Notice the difference between the class name and the object name: In the
previous example, CRectangle was the class name (i.e., the type), whereas rect
was an object of type CRectangle. It is the same relationship int and a have in
the following declaration:
int a;
where int is the type name (the class) and a is the variable name (the object).
After the previous declarations of CRectangle and rect, we can refer within the
body of the program to any of the public members of the object rect as if they
were normal functions or normal variables, just by putting the object's name
followed by a dot (.) and then the name of the member. All very similar to what
we did with plain data structures before. For example:
rect.set_values (3,4);
myarea = rect.area();
The only members of rect that we cannot access from the body of our program
outside the class are x and y, since they have private access and they can only
be referred from within other members of that same class.
Like any other function, a constructor can also be overloaded with more
than one function that have the same name but different types or number of
parameters. Remember that for overloaded functions the compiler will call the
one whose parameters match the arguments used in the function call. In the case
of constructors, which are automatically called when an object is created, the
one executed is the one that matches the arguments passed on the object
declaration.
Important: Notice how if we declare a new object and we want to use its
default constructor (the one without parameters), we do not include parentheses
()
Pointers to classes
CRectangle * prect;
*x pointed by x
&x address of x
Classes (II)
Overloading operators
int a, b, c;
a = b + c;
This is obviously valid code in C++, since the different variables of the addition
are all fundamental types. Nevertheless, it is not so obvious that we could
perform an operation similar to the following one:
struct {
string product;
float price;
} a, b, c;
a = b + c;
In fact, this will cause a compilation error, since we have not defined the
behavior our class should have with addition operations. However, thanks to the
C++ feature to overload operators, we can design classes able to perform
operations using standard operators.
Friend functions
The class CPolygon would contain members that are common for both types of
polygon. In our case: width and height. And CRectangle and CTriangle would
be its derived classes, with specific features that are different from one type of
polygon to the other.
Classes that are derived from others inherit all the accessible members of the
base class. That means that if a base class includes a member A and we derive it
to another class with another member called B, the derived class will contain
both members A and B.
In order to derive a class from another, we use a colon (:) in the declaration of
the derived class using the following format:
Polymorphism
Before getting into this section, it is recommended that you have a proper
understanding of pointers and class inheritance. If any of the following
statements seem strange to you, you should review the indicated sections
One of the key features of derived classes is that a pointer to a derived class is
type-compatible with a pointer to its base class. Polymorphism is the art of
taking advantage of this simple but powerful and versatile feature, that brings
Object Oriented Methodologies to its full potential.
We are going to start by rewriting our program about the rectangle and the
triangle of the previous section taking into consideration this pointer
compatibility property:
In function main, we create two pointers that point to objects of class CPolygon
(ppoly1 and ppoly2). Then we assign references to rect and trgl to these
pointers, and because both are objects of classes derived from CPolygon, both
are valid assignment operations.
The only limitation in using *ppoly1 and *ppoly2 instead of rect and trgl is that
both *ppoly1 and *ppoly2 are of type CPolygon* and therefore we can only use
these pointers to refer to the members that CRectangle and CTriangle inherit
from CPolygon. For that reason when we call the area() members at the end of
the program we have had to use directly the objects rect and trgl instead of the
pointers *ppoly1 and *ppoly2.
In order to use area() with the pointers to class CPolygon, this member should
also have been declared in the class CPolygon, and not only in its derived
classes, but the problem is that CRectangle and CTriangle implement different
versions of area, therefore we cannot implement it in the base class. This is
when virtual members become handy:
Abstract base classes are something very similar to our CPolygon class of our
previous example. The only difference is that in our previous example we have
defined a valid area() function with a minimal functionality for objects that were
of class CPolygon (like the object poly), whereas in an abstract base classes we
could leave that area() member function without implementation at all. This is
done by appending =0 (equal to zero) to the function declaration.
Templates
Function templates
Function templates are special functions that can operate with generic types.
This allows us to create a function template whose functionality can be adapted
to more than one type or class without repeating the entire code for each type.
The format for declaring function templates with type parameters is:
The only difference between both prototypes is the use of either the keyword
class or the keyword typename. Its use is indistinct, since both expressions have
exactly the same meaning and behave exactly the same way.
To use this function template we use the following format for the function call:
When the compiler encounters this call to a template function, it uses the
template to automatically generate a function replacing each appearance of
myType by the type passed as the actual template parameter (int in this case)
and then calls it. This process is automatically performed by the compiler and is
invisible to the programmer.
Class templates
We also have the possibility to write class templates, so that a class can have
members that use template parameters as types. For example:
class mypair {
T values [2];
public:
values[0]=first; values[1]=second;
};
The class that we have just defined serves to store two elements of any valid
type. For example, if we wanted to declare an object of this class to store two
integer values of type int with the values 115 and 36 we would write:
this same class would also be used to create an object to store any other type:
The only member function in the previous class template has been defined
inline within the class declaration itself. In case that we define a function
member outside the declaration of the class template, we must always precede
that definition with the template prefix
Template specialization
For example, let's suppose that we have a very simple class called mycontainer
that can store one element of any type and that it has just one member function
called increase, which increases its value. But we find that when it stores an
element of type char it would be more convenient to have a completely different
implementation with a function member uppercase, so we decide to declare a
class template specialization for that type
Templates and multiple-file projects
From the point of view of the compiler, templates are not normal functions or
classes. They are compiled on demand, meaning that the code of a template
function is not compiled until an instantiation with specific template arguments
is required. At that moment, when an instantiation is required, the compiler
generates a function specifically for those arguments from the template. When
projects grow it is usual to split the code of a program in different source code
files. In these cases, the interface and implementation are generally separated.
Taking a library of functions as example, the interface generally consists of
declarations of the prototypes of all the functions that can be called. These are
generally declared in a "header file" with a .h extension, and the implementation
(the definition of these functions) is in an independent file with c++ code.
Because templates are compiled when required, this forces a restriction for
multi-file projects: the implementation (definition) of a template class or
function must be in the same file as its declaration. That means that we cannot
separate the interface in a separate header file, and that we must include both
interface and implementation in any file that uses the templates. Since no code
is generated until a template is instantiated when required, compilers are
prepared to allow the inclusion more than once of the same template file with
both declarations and definitions in a project without generating linkage errors.
Namespaces
Namespaces allow to group entities like classes, objects and functions under a
name. This way the global scope can be divided in "sub-scopes", each one with
its own name.
The format of namespaces is:
namespace identifier
entities
Where identifier is any valid identifier and entities is the set of classes, objects
and functions that are included within the namespace.
using
The keyword using is used to introduce a name from a namespace into the
current declarative region
Namespace alias
Namespace std
All the files in the C++ standard library declare all of its entities within the std
namespace. That is why we have generally included the using namespace std;
statement in all programs that used any entity defined in iostream.
Exceptions
C++ provides the following classes to perform output and input of characters
to/from files:
These classes are derived directly or indirectly from the classes istream, and
ostream. We have already used objects whose types were these classes: cin is an
object of class istream and cout is an object of class ostream. Therfore, we have
already been using classes that are related to our file streams. And in fact, we
can use our file streams the same way we are already used to use cin and cout,
with the only difference that we have to associate these streams with physical
files.
Open a file
Closing a file
When we are finished with our input and output operations on a file we shall
close it so that its resources become available again. In order to do that we have
to call the stream's member function close(). This member function takes no
parameters, and what it does is to flush the associated buffers and close the file:
myfile.close();
Once this member function is called, the stream object can be used to open
another file, and the file is available again to be opened by other processes.
In case that an object is destructed while still associated with an open file, the
destructor automatically calls the member function close().
Text files
Text file streams are those where we do not include the ios::binary flag in their
opening mode. These files are designed to store text and thus all values that we
input or output from/to them can suffer some formatting transformations, which
do not necessarily correspond to their literal binary value.
Data output operations on text files are performed in the same way we operated
with cout:
Checking state flags
In addition to eof(), which checks if the end of file has been reached, other
member functions exist to check the state of a stream (all of them return a bool
value):
bad()
fail()
Returns true in the same cases as bad(), but also in the case that a format
error happens, like when an alphabetical character is extracted when we are
trying to read an integer number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which
calling any of the previous functions would return true.
In order to reset the state flags checked by any of these member functions we
have just seen we can use the member function clear(), which takes no
parameters.
Binary files
In binary files, to input and output data with the extraction and insertion
operators (<< and >>) and functions like getline is not efficient, since we do not
need to format any data, and data may not use the separation codes used by text
files to separate elements (like space, newline, etc...).
File streams include two member functions specifically designed to input and
output binary data sequentially: write and read. The first one (write) is a
member function of ostream inherited by ofstream. And read is a member
function of istream that is inherited by ifstream. Objects of class fstream have
both members. Their prototypes are:
When we operate with file streams, these are associated to an internal buffer of
type streambuf. This buffer is a memory block that acts as an intermediary
between the stream and the physical file. For example, with an ofstream, each
time the member function put (which writes a single character) is called, the
character is not written directly to the physical file with which the stream is
associated. Instead of that, the character is inserted in that stream's intermediate
buffer.
When the buffer is flushed, all the data contained in it is written to the physical
medium (if it is an output stream) or simply freed (if it is an input stream). This
process is called synchronization and takes place under any of the following
circumstances:
• When the file is closed: before closing a file all buffers that have not yet
been flushed are synchronized and all pending data is written or read to the
physical medium.
• When the buffer is full: Buffers have a certain size. When the buffer is
full it is automatically synchronized.
• Explicitly, with manipulators: When certain manipulators are used on
streams, an explicit synchronization takes place. These manipulators are: flush
and endl.
We have covered the things that are different from c, still looking for
deep, take our advanced course for better learning.
*****End of C++******
Java
In Java, every source file usually contains exactly one class. The file must have
the same name as the class; a class named TurtleMaze would be stored in the
source file TurtleMaze.java. This source file can then be compiled using the
javac compiler:
% javac TurtleMaze.java
The output of the compiler is a file with the same name as the source file, but
with the extension .class instead of .java (i.e., TurtleMaze.class in the above
example). That class file contains the byte code mentioned earlier, so it cannot
be executed right away. Instead it is executed using the JVM (byte code
interpreter) as follows:
% java TurtleMaze
This command loads the TurtleMaze class and executes its main method (that
is, starts the program). If the TurtleMaze class in turn uses other classes, these
are loaded automatically when needed.
Since every class should be in its own file, several files can need to be
recompiled at the same time. The javac compiler has a special option -depend to
compile all files that depend on a particular file. The command
will compile not only TurtleMaze.java, but also all changed files it depends
upon.
We begin our exploration of Java with the problem that has become traditional
for such beginnings: to write a program that displays the message ―Hello
World!‖. This might seem like a trivial problem, but getting a computer to do
this is really a big first step in learning a new programming language (especially
if it‘s your first programming language). It means that you understand the basic
process of: 1. getting the program text into the computer, 2. compiling the
program, and 3. running the compiled program. The first time through, each of
these steps will probably take you a few tries to get right. I won‘t go into the
details here of how you do each of these steps; it depends on the particular
computer and Java programming environment that you are using. See Section
2.6 for information about creating and running Java programs in specific
programming environments. But in general, you will type the program using
some sort of text editor and save the program in a file. Then, you will use some
command to try to compile the file. You‘ll either get a message that the program
contains syntax errors, or you‘ll get a compiled version of the program. In the
case of Java, the program is compiled into Java bytecode, not into machine
language. Finally, you can run the compiled program by giving some
appropriate command. For Java, you will actually use an interpreter to execute
the Java bytecode. Your programming environment might automate some of the
steps for you, but you can be sure that the same three steps are being done in the
background. Here is a Java program to display the message ―Hello World!‖.
Don‘t expect to understand what‘s going on here just yet—some of it you won‘t
really understand until a few chapters from now:
System.out.println("Hello World!");
When you run this program, the message ―Hello World!‖ (without the
quotes) will be displayed on standard output.
Simple declarations
Java supports the usual set of simple types, such as integer, boolean, and
real variables. Here are a few of the most common ones: int m, n; // Two
integer variables double x, y; // Two real coordinates boolean b; // Either
‗true‘ or ‗false‘ char ch; // A character, such as ‗P‘ or ‗@‘
Numeric expressions and assignments
n = 3 * (5 + 2);
x = y / 3.141592653;
b = true;
ch = ‗x‗;
Note: the assignment is written using ‗=‘ as opposed to ‗:=‘ in many other
languages. Another symbol, ‗==‘, is used to compare two values to each other.
If you try to compare two values using ‗=‘ you will get an error.
double f = 0.57;
The Java division operator (‗/‘) can actually mean two different things: real
division for real numbers, and integer division for integers. Usually this is not a
problem, but it can occasionally lead to some surprising results:
double f;
f = 1 / 3; // f is now 0.0
f = 1.0 / 3.0; // f is now 0.33333333...
In the first case an integer division is performed, giving an integer result (0). To
get the result 0.33333, the 1 and 3 are expressed as real values (1.0 and 3.0),
which means the division becomes a real division.
Java does not perform all such conversions automatically. Instead the
programmer must indicate where the conversions must be made by writing the
desired type in parentheses before the expression. In Java, such a conversion is
called a cast. Example:
double radians;
int degrees;
...
Variables in Programs
A variable can be used in a program only if it has first been declared. A variable
declaration statement is used to declare one or more variables and to give them
names. When the computer executes a variable declaration, it sets aside memory
for the variable and associates the variable‘s name with that memory. A simple
variable declaration takes the form:
{type-name} {variable-name-or-names};
Statements
Java statements are written in much the same way as in other languages. Just
like in Simula or Pascal, statements can be grouped together in blocks using ‗{‗
and ‗}‘ (corresponding to begin and end in these languages).
if (n == 3)
x = 3.2;
Note:
if (x != 0)
y = 3.0 / x; // Executed when x is non-zero
else
Note that, unlike Simula and Pascal, there should be a semicolon before the else
keyword in the example above.
However, when one uses braces (‗{‗ and ‗}‘) to form a block of statements, the
right brace should NOT be followed by a semicolon. (In fact, a right brace is
never followed by a semicolon in Java.)
if (x != 0) {
y = 3.0 / x;
x = x + 1;
y = 1;
It is common practice to always include the braces, even if they only contain a
single statement. This avoids forgetting them whenever another statement is
added.
and &&
or ||
not !
For example:
int x, y;
boolean b;
...
b = true;
int k = 1;
term = term / k;
As the example shows, there is nothing special about Java‘s while statement.
The for statement is quite general and can be used in some very advanced ways.
However, the most common use is to repeat some statement a known number of
times:
// Calculate 1 + (1/2) + (1/3) + ... + (1/100)
int i;
i = i + 1;
i++;
++i;
i += 1;
As long as these statements are not used as parts of a larger expression, they
mean exactly the same thing. There corresponding operators for decrementing
variables are -- and -=.
Classes
class Turtle {
protected int x, y;
The private and protected keywords require some explanation. The private
declaration means that those attributes cannot be accessed outside of the class.
In general, attributes should be kept private to prevent other classes from
accessing them directly.
There are two other related keywords: public and protected. The public keyword
is used to declare that something can be accessed from other classes. The
protected keyword specifies that something can be accessed from within the
class and all its subclasses, but not from the outside.
Methods
In Java, functions and procedures are called methods. Methods are declared as
follows:
class Turtle {
x = newX;
y = newY;
}
public int getX() {
return x;
This example contains two methods. The first is called jumpTo and has two
integer parameters, newX and newY.
The second method is called getX, has no parameters, and returns an integer.
Note that the empty pair of parentheses must be present.
Both method declarations begin with the keyword public, to make sure they can
be accessed from other classes. (It is however possible to declare methods
private or protected, which can be useful for internal methods which should not
be used from other classes.)
Before the method‘s name, a type is written to indicate the method‘s return
type. The jumpTo method does not return a value (i.e., it is a procedure, not a
function). For this reason, it is declared as void (meaning ‗nothing‘). The getX
method returns an integer, so it is declared as int.
Using objects
The new operator is used to create objects in much the same way as in other
languages. If we assume the Turtle class requires two integer parameters (say, X
and Y coordinates) a Turtle object can be created as follows:
Turtle t;
The first line is a declaration of a reference variable to a Turtle object, just like a
ref(Turtle) declaration in Simula. The second line creates a new Turtle object
and sets the t variable to refer to it.
There‘s nothing strange about calling methods in objects, as the following
examples show.
int a = t.getX();
t.jumpTo(300, 200);
In Java, statements can only be written within methods in classes. This means
that there must be some method which is called by the system when the
program starts executing. This method is called main and must be declared in
the class which is started from the command line (for example, in the
TurtleMaze class if one runs java TurtleMaze).
A main method usually creates a few objects and does some small work to get
things going. For Turtle a simple main method may look as follows:
t.right(90);
t.forward(2);
There are two new things about main, which can both safely be ignored for
now. The first is the static keyword. It means that when the main method is
called, it is not associated with an object, but with the class. (This implies that
the method cannot access any attributes.) The other new thing is the parameter
named args. If the Java interpreter is given any more information than the class
name, this data is passed on to the main method in this parameter.
An interface can be used to specify that a class has to provide a certain set of
methods. This can be useful in a number of situations and is perhaps best shown
with an example as follows.
Programs with graphical user interfaces often need to be informed whenever the
mouse is clicked. Usually the program has some method which should be
automatically called by the system whenever the user clicks the mouse.
Java provides a very flexible way of specifying an object and a method to call in
such situations. Suppose the window system declares an interface, written as
follows:
interface MouseListener {
Exceptions
Many things can go wrong during the execution of a program. These run-time
errors can be divided into two broad categories:
• Things out of the program‘s control, such as a user entering a garbage on the
keyboard when the program expects a positive integer.
The latter category is the one that programmers usually take care of. The
traditional way of handling these errors is to put the code in question in some
method which returns a value to indicate whether whings went well or not. A
method to read a positive integer from the keyboard could, for instance, look
like this:
Suppose the special value -1 is used to indicate that an invalid number was
entered by the user. The code that calls this method would then have to check
the return value with an if statement. If that code is part of some method, that
method may in turn have to return some value to indicate that things went
wrong. This kind of programming can easily turn into a lot of if statements and
special return values, and very few statements that actually do something.
Miscellaneous
This section contains a few details about Java that might be useful to know
when writing Java programs.
Comments One kind of comments has already been shown: the line comment,
which starts with ‗//‘ and extends to the end of a line. Multi-line comments are
written using ‗/*‘ and ‗*/‘ as follows:
/* This is a comment
Some of the library classes, as well as some of the help classes for the
laboratories, are provided in packages. To use the classes from a package, they
must be imported.
For instance, many of the classes used for graphical user interfaces in Java
(AWT, or Abstract Window Toolkit) belong to the java.awt package. To use
these classes, the following must be written first in the source file:
import java.awt.*;
Arrays
Since these variables are only references to arrays, the array sizes are not given
in the declarations, but when the arrays are actually created.
The array elements can then be used as any simple scalar variables. (Note that
indices always start at 0 and end at the size minus one, so the elements of the
someInts array have the indices 0 to 29.)
int i;
someInts[i] = i * i;
}
The expression someInts.length means in the length of the vector, 30 in this
case.
To write something to the terminal, call one of the methods print and
println in the object System.out. They both write the argument (a String) to the
terminal. The latter method, println, also ends the line. Example:
System.out.println(―i en svamp―);
int a;
a = 6 * 7;
System.out.println(―6 * 7 = ― + a);