Edu I CCJAVA rxj0cp PDF

You might also like

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

Edu - I Academy’s

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.

All the best!

Introduction:

This course can be read simply as a text; however it is intended to be


interactive. That is, you should be compiling, modifying and using the programs
that are presented herein. All the programs have been tested using the HiTech C
compiler, and we assume that you have a copy of this. In addition, you should
have a copy of various updates and header files for the C compiler, which
appear on Applix User disks. You can use either the built-in Applix 1616/OS
editor edit, or the $30 Dr Doc editor in non-document mode. Dr Doc is
somewhat more powerful, however as it loads from disk, it is slightly slower to
get started. The source code has been edited to suit a tab setting of 5, so invoke
your editor with tabs set to a spacing of 5. For example, edit sourcecode.c 5
would let you edit a file called sourcecode.c. Before you can really use C, there
are certain equipment requirements that must be met. You must have a disk co-
processor card, and at least one disk drive. If your drives are smaller than 800k,
you will probably require two disk drives. We assume you either have 1616/OS
Version 4 multitasking, or else have an assign MRD available on your boot
disk. You should make use of the xpath, and the assign commands to set up
your boot disk in a form suitable for use with C. This should be done in the
autoexec.shell file on your boot disk, as set out below.

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

Your First C Program

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

Print Some Numbers

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;

printf("The value of the index is %d\n",index);

index = 27;

printf("The valve of the index = %d\n",index);

index = 10;

printf("The value of the index = %d\n",index);

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

1. Write a program to display your name on the monitor.

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.

/* This is an example of a "while" loop */

main( )

int count;

count = 0;

while (count < 6) {

printf("The value of count is %d\n",count);

count = count + 1;

We begin with a comment and the program name, then go on to define an


integer variable "count" within the body of the program. The variable is set to
zero and we come to the while loop itself. The syntax of a while loop is just as
shown here. The keyword "while" is followed by an expression of something in
parentheses, followed by a compound statement bracketed by braces. As long as
the expression in parentheses is true, all statements within the braces will be
executed. In this case, since the variablecount is incremented byone every
timethe statements areexecuted, and the loop will be terminated. The program
control will resume at the statement following the statements in braces.

Do-While Loop

A variation of the while loop is illustrated in the program dowhile.c, which you
should load and display.

/* This is an example of a do-while loop */

main( )

int i;

i = 0;

do {

printf("the value of i is now %d\n",i);

i = i + 1;

} while (i < 5);

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.

/* This is an example of a for loop */

main( )

int index;

for(index = 0;index < 6;index = index + 1)

printf("The value of the index is %d\n",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".

/* This is an example of the if and if-else statements */

main()

int data;

for(data = 0;data < 10;data = data + 1) {

if (data == 2)

printf("Data is now equal to %d\n",data);

if (data < 5)

printf("Data is now %d, which is less than 5\n",data);

else

printf("Data is now %d, which is greater than 4\n",data); }

/* end of for loop */

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.

Break And Continue

Load the file named breakcon.c for an example of two new statements.

main( )

int xx;

for(xx = 5;xx < 15;xx = xx + 1){

if (xx == 8)

break;

printf("in the break loop, xx is now %d\n",xx);


}

for(xx = 5;xx < 15;xx = xx + 1){

if (xx == 8)

continue;

printf("In the continue loop, xx is the now %d\n",xx);

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.

The types in C can be classified as follows:

 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

The void type specifies that no value is available. It is used in three kinds of
situations:

 Function returns as void There are various functions in C which do not


return value or you can say they return void. A function with no return
value has the return type as void. For example, void exit (int status);
 Function arguments as void There are various functions in C which do
not accept any parameter. A function with no parameter can accept as a
void. For example, int rand(void);
 Pointers to void A pointer of type void * represents the address of an
object, but not its type. For example, a memory allocation function void
*malloc( size_t size ); returns a pointer to void which can be casted to any
data type.

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:

Char: Typically a single octet(one byte). This is an integer type.

Int: The most natural size of integer for the machine.

Float: A single-precision floating point value.

Double: A double-precision floating point value.

Void: Represents the absence of type.

C programming language also allows to define various other types of variables,


which we will cover in subsequent chapters like Enumeration, Pointer, Array,
Structure, Union, etc. For this chapter, let us study only basic variable types.
A variable definition means to tell the compiler where and how much to create
the storage for the variable. A variable definition specifies a data type and
contains a list of one or more variables of that type as follows:

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

When a compound expression is evaluated, the evaluation proceeds from left to


right and as soon as the result of the outcome is assured, evaluation stops.
Namely, in the case of an "AND" evaluation, when one of the terms evaluates to
"false", evaluation is discontinued because additional true terms cannot make
the result ever become "true". In the case of an "OR" evaluation, if any of the
terms is found to be "true", evaluation stops because it will be impossible for
additional terms to cause the result to be "false". In the case of additionally
nested terms, the above rules will be applied to each of the nested levels.
Precedence Of Operators

The question will come up concerning the precedence of operators. Which


operators are evaluated first and which last? There are many rules about this
topic, which your compiler will define completely, but I would suggest that you
don‘t worry about it at this point. Instead, use lots of parentheses to group
variables, constants, and operators in a way meaningful to you. Parentheses
always have the highest priority and will remove any question of which
operations will be done first in any particular statements. Goingon tothe next
example ingroup three, we find three simple variables used in the conditional
part of the compare. Since all three are non-zero, all three are "true", and
therefore the "AND" of the three variables are true, leading to the result being
"true", and "z" being assigned the value of 11. Note the since the variables, "r",
"s", and "t" are "float" type variables, they could not be used this way, but they
could each be compared to zero and the same type of expression could be used.
Continuing on to the fourth example of the third group we find three assignment
statements in the compare part of the "if" statement. If you understood the
above discussion, you should have no difficulty understanding that the three
variables are assigned their respective new values, and the result of all three are
non-zero, leading to a resulting value of "TRUE".

The Cryptic Arithmetic Operator

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

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

An additional variable type must be mentioned at this point, the "static"


variable. By putting the reserved word "static" in front of a variable declaration
within a function, the variable or variables in the declaration are static variables
and will stay in existence from call to call of the particular function. By putting
the same reserved word in front of an external variable, one outside of any
function, it makes the variable private and not accessible to use in any other file.
This implies that it is possibletorefer to external variables inother separately
compiledfiles, andthat is true.

Standard Function Libraries

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

Recursion is another of those programming techniques that seem very


intimidating the first time you come across it, but if you will load and display
the example program named recurson.c, we will take all of the mystery out of it.
This is probably the simplest recursive program that it is possible to write and it
is therefore a stupid program in actual practice, but for purposes of illustration,
it is excellent.

main( )

int index;

index = 8;

count_dn(index);

count_dn(count)

int count;

count--;

printf("The value of the count is %d\n",count);

if (count > 0)

count_dn(count);

printf("Now the count is %d\n",count);

Recursion is nothing more than a function that calls itself. It is therefore in a


loop which must have a way of terminating. In the program on your monitor,
the variable "index" is set to 8, and is used as the argument to the function
"count_dn". The function simply decrements the variable, prints it out in a
message, and if the variable is not zero, it calls itself, where it decrements it
again, prints it, etc. etc. etc. Finally, the variable will reach zero, and the
function will not call itself again. Instead, it will return to the prior time it called
itself, and return again, until finally it will return to the main program and will
return to DOS.

Programming Exercises

1. Rewrite tempconv.c, from an earlier chapter, and move the temperature


calculation to a function. 2. Write a program that writes your name on the
monitor 10 times by calling a function to do the writing. Move the called
function ahead of the "main" function to see if your compiler will allow it.

String

A string is a group of characters, usually letters of the alphabet. In order to


format your printout in such a way that it looks nice, has meaningful titles and
names, and is esthetically pleasing to you and the people using the output of
your program, you need the ability to output text data. Actually you have
already been using strings, because the second program in this tutorial, way
back in Chapter 2, output a message that was handled internally as a string. A
complete definition is a series of "char" type data terminated by a NULL
character, which is a zero. When C is going to use a string of data in some way,
either to compare it with another, output it, copy it to another string, or
whatever, the functions are set up to do what they are called to do until a NULL,
which is a zero, is detected.

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( )

char name [5]; /* define a string of characters */

name[0] = ‘D‘;

name[1] = ‘a‘;

name[2] = ‘v‘;

name[3] = ‘e‘;

name[4] = 0; /* Null character - end of text */

printf("The name is %s\n",name);

printf("One letter is %c\n",name[2]);

printf("Part of the name is %s\n",&name[1]);

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

Some String Subroutines


Load the example program strings.c for an example of some ways to use strings.

main( )

char name1[12],name2[12],mixed[25];

char title[20];

strcpy(name1,"Rosalinda");

strcpy(name2,"Zeke");

strcpy(title,"This is the title.");

printf(" %s\n\n"title);

printf("Name 1 is %s\n",name1);

printf(Name 2 is %s\n",name2);

if(strcmp(name1,name2)>0) /* return 1 if name1 > name2 */

strcpy(mixed,name1);

else

strcpy(mixed,name2);

printf("The biggest name alphabetically is %s\n",mixed);

strcpy(mixed,name1);

strcat(mixed," ");

strcat(mixed,name2);

printf("Both names are %s\n",mixed);

}
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.

Multiply Dimensioned Arrays


Load and display the file named multiary.c for an example of a program with
doubly dimensioned arrays.

main( )

int i,j;

int big[8][8], huge[25][12];

for (i = 0;i < 8;i++)

for (j = 0;j < 8;j++)

big[i][j] = i * j; /* This is a multiplication table */

for (i = 0;i < 25;i++)

for (j = 0;j < 12;j++)

huge[i][j] = i + j; /* This is an addition table */

big[2][6] = huge[24][10] *22;


big[2][2] = 5;

big[big][2][2]...big[2][2]. = 177; /* this is big[5][5] = 177; */

for (i = 0;i < 8;i++) {

for (j = 0;j < 8;j++)

printf("%5d ",big[i][j]);

printf("\n"); /* newline for each increase in i */

The variable "big" is an 8 by 8 array that contains 8 times 8 or 64


elements total. The first element is "big[0][0]", and the last is "big[7][7]".
Another array named "huge" is also defined which is not square to illustrate that
the array need not be square. Both are filled up with data, one representing a
multiplication table and the other being formed into an addition table. To
illustrate that individual elements can be modified at will, one of the elements of
"big" is assigned the value from one of the elements of "huge" after being
multiplied by 22. Next "big[2][2]" is assigned the arbitrary value of 5, and this
value is used for the subscripts of the next assignment statement. The third
assignment statement is in reality "big[5][5] = 177" because each of the
subscripts contain the value 5. This is only done to illustrate that any valid
expression can be used for a subscript. It must only meet two conditions, it must
be an integer (although a "char" will work just as well), and it must be within
the range of the subscript it is being used for. The entire matrix variable "big" is
printed out in a square form so you can check the values to see if they did get
set the way you expected them to.
Programming Exercises

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

Simply stated, a pointer is an address. Instead of being a variable, it is a pointer


to a variable stored somewhere in the address space of the program. It is always
best to use an example so load the file named pointer.c and display it on your
monitor for an example of a program with some pointers in it.

main( ) /* illustratrion of pointer use */

int index,*pt1,*pt2;

index = 39; /* any numerical value */

pt1 = &index; /* the address of index */

pt2 = pt1;

printf("The value is %d %d %d\n",index,*pt1,*pt2);

*pt1 = 13; /* this changes the value of index */


printf("The value is %d %d %d\n",index,*pt1,*pt2);

For the moment, ignore the declaration statement where we define


"index" and two other fields beginning with a star. It is properly called an
asterisk, but for reasons we will see later, let‘s agree to call it a star. If you
observe the first statement, it should be clear that we assign the value of 39 to
the variable "index". This is no surprise, we have been doing it for several
programs now. The next statement however, says to assign to "pt1" a strange
looking value, namely the variable "index" with an ampersand in front of it. In
this example, pt1 and pt2 are pointers, and the variable "index" is a simple
variable. Now we have problem. We need to learn how to use pointers in a
program, but to do so requires that first we define the means of using the
pointers in the program. The following two rules will be somewhat confusing to
you at first but we need to state the definitions before we can use them. Take
your time, and the whole thing will clear up very quickly.

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.

# include "/sys/stdio.h" /* standard header for input/output */

main( )

char c;

printf("Enter any characters, X = halt program.\n");

do {

c = getchar(); /* Get a character from the kb */

putchar(c); /* Display the character on the monitor */

} while (c != ‘X‘); /* Until and X is hit */

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

Actually the C programming language has no input or output operations


defined as part of the language, they must be user defined. Since everybody
does not want to reinvent his own input and output operations, the compiler
writers have done a lot of this for us and supplied us with several input
functions and several output functions to aid in our program development. The
functions have become a standard, and you will find the same functions
available in nearly every compiler. In fact, the industry standard of the C
language definition has become the book written by Kernigan and Ritchie, and
they have included these functions in their definition. You will often, when
reading literature about C, find a reference to K & R. This refers to the book
written by Kernigan and Ritchie. You would be advised to purchase a copy for
reference.

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 {

char initial; /* last name initial */

int age; /* childs age */

int grade; /* childs grade in school */

} 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‘;

printf("%c is %d years old and got a grade of %d\n",

girl.initial,girl.age,girl.grade);

printf("%c is %d years old and got a grade of %d\n", boy.initial, boy.age,


boy.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.

Assigning Values To The 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.

Still looking for more try out our advanced courses.

************ END OF C **************

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.

Differences between C and C++ are:

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

C++ fully supports object-oriented programming, including the four pillars of


object-oriented development:

 Encapsulation

 Data hiding

 Inheritance

 Polymorphism

2.Standard Libraries

Standard C++ consists of three important parts:

 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.

 The Standard Template Library (STL) giving a rich set of methods


manipulating data structures, etc.

Learning C++

The most important thing while learning C++ is to focus on concepts.

The purpose of learning a programming language is to become a better


programmer; that is, to become more effective at designing and implementing
new systems and at maintaining old ones.
C++ supports a variety of programming styles. You can write in the style of
Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims
effectively while maintaining runtime and space efficiency.

Use of C++

C++ is used by hundreds of thousands of programmers in essentially every


application domain.

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

When we consider a C++ program, it can be defined as a collection of objects


that communicate via invoking each other's methods. Let us now briefly look
into what a class, object, methods, and instant variables mean.

 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.

 Class - A class can be defined as a template/blueprint that describes the


behaviors/states that object of its type support.
 Methods - A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated and
all the actions are executed.

 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.

C++ Program Structure

Let us look at a simple code that would print the words Hello World.

#include <iostream>

using namespace std;

// main() is where program execution begins.

int main()

cout << "Hello World"; // prints Hello World

return 0;

Let us look at the various parts of the above program:

1. The C++ language defines several headers, which contain information


that is either necessary or useful to your program. For this program,
the header is needed.
2. The line using namespace std; tells the compiler to use the std
namespace. Namespaces are a relatively recent addition to C++.
3. The next line ‗// main() is where program execution begins.‘ is a
single-line comment available in C++. Single-line comments begin
with // and stop at the end of the line.

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.

6. The next line return 0; terminates main() function and causes it to


return the value 0 to the calling process.
C++ Keywords:

C++ contains 52 keywords

Object Oriented Programming

Classes (I)

A class is an expanded concept of a data structure: instead of holding only data,


it can hold both data and functions.
An object is an instantiation of a class. In terms of variables, a class would be
the type, and an object would be the variable.

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;

Where class_name is a valid identifier for the class, object_names is an


optional list of names for objects of this class. The body of the declaration
can contain members, that can be either data or function declarations, and
optionally access specifiers.

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:

• private members of a class are accessible only from within other


members of the same class or from their friends.
• protected members are accessible from members of their same class and
from their friends, but also from members of their derived classes.

• Finally, public members are accessible from anywhere where the object
is visible.

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:

void set_values (int,int);

int area (void);

} 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.

Constructors and destructors

Objects generally need to initialize variables or assign dynamic memory


during their process of creation to become operative and to avoid returning
unexpected values during their execution. For example, what would happen if in
the previous example we called the member function area() before having called
function set_values()? Probably we would have gotten an undetermined result
since the members x and y would have never been assigned a value. In order to
avoid that, a class can include a special function called constructor, which is
automatically called whenever a new object of this class is created. This
constructor function must have the same name as the class, and cannot have any
return type; not even void.
Overloading Constructors

Like any other function, a constructor can also be overloaded with more
than one function that have the same name but different types or number of
parameters. Remember that for overloaded functions the compiler will call the
one whose parameters match the arguments used in the function call. In the case
of constructors, which are automatically called when an object is created, the
one executed is the one that matches the arguments passed on the object
declaration.

Important: Notice how if we declare a new object and we want to use its
default constructor (the one without parameters), we do not include parentheses
()

Pointers to classes

It is perfectly valid to create pointers that point to classes. We simply


have to consider that once declared, a class becomes a valid type, so we can use
the class name as the type for the pointer. For example:

CRectangle * prect;

is a pointer to an object of class CRectangle.

As it happened with data structures, in order to refer directly to a member


of an object pointed by a pointer we can use the arrow operator (->) of
indirection.

*x pointed by x

&x address of x

x.y member y of object x

x->y member y of object pointed by x


(*x).y member y of object pointed by x (equivalent to the previous one)

x[0] first object pointed by x

x[1] second object pointed by x

x[n] (n+1)th object pointed by x

Classes (II)

Overloading operators

C++ incorporates the option to use standard operators to perform operations


with classes in addition to with fundamental types. For example:

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

In principle, private and protected members of a class cannot be accessed


from outside the same class in which they are declared. However, this rule does
not affect friends.

Friends are functions or classes declared as such.

If we want to declare an external function as friend of a class, thus


allowing this function to have access to the private and protected members of
this class, we do it by declaring a prototype of this external function within the
class, and preceding it with the keyword friend

Inheritance between classes

A key feature of C++ classes is inheritance. Inheritance allows to create classes


which are derived from other classes, so that they automatically include some of
its "parent's" members, plus its own. For example, we are going to suppose that
we want to declare a series of classes that describe polygons like our
CRectangle, or like CTriangle. They have certain common properties, such as
both can be described by means of only two sides: height and base.
This could be represented in the world of classes with a class CPolygon from
which we would derive the two other ones: CRectangle and CTriangle.

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:

class derived_class_name: public base_class_name { /*...*/ };

Where derived_class_name is the name of the derived class and


base_class_name is the name of the class on which it is based. The public
access specifier may be replaced by any one of the other access specifiers
protected and private. This access specifier describes the minimum access level
for the members that are inherited from the base class.

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

int a::b(c) {}; Classes

a->b Data Structures

class a: public b; Friendship and inheritance


Pointers to base class

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

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.

In C++ this can be achieved using template parameters. A template parameter


is a special kind of parameter that can be used to pass a type as argument: just
like regular function parameters can be used to pass values to a function,
template parameters allow to pass also types to a function. These function
templates can use these parameters as if they were any other regular type.

The format for declaring function templates with type parameters is:

template <class identifier> function_declaration;

template <typename identifier> function_declaration;

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:

function_name <type> (parameters);

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:

template <class T>

class mypair {

T values [2];

public:

mypair (T first, T second)


{

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:

mypair myobject (115, 36);

this same class would also be used to create an object to store any other type:

mypair myfloats (3.0, 2.18);

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

If we want to define a different implementation for a template when a specific


type is passed as template parameter, we can declare a specialization of that
template.

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

We can declare alternate names for existing namespaces according to the


following format:

namespace new_name = current_name;

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

Exceptions provide a way to react to exceptional circumstances (like runtime


errors) in our program by transferring control to special functions called
handlers. To catch exceptions we must place a portion of code under exception
inspection. This is done by enclosing that portion of code in a try block. When
an exceptional circumstance arises within that block, an exception is thrown that
transfers the control to the exception handler. If no exception is thrown, the
code continues normally and all handlers are ignored. A exception is thrown by
using the throw keyword from inside the try block. Exception handlers are
declared with the keyword catch, which must be placed immediately after the
try block.

Input/Output with files

C++ provides the following classes to perform output and input of characters
to/from files:

• ofstream: Stream class to write on files

• ifstream: Stream class to read from files

• fstream: Stream class to both read and write from/to 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

The first operation generally performed on an object of one of these classes is to


associate it to a real file. This procedure is known as to open a file. An open file
is represented within a program by a stream object (an instantiation of one of
these classes, in the previous example this was myfile) and any input or output
operation performed on this stream object will be applied to the physical file
associated to it. In order to open a file with a stream object we use its member
function open(): open (filename, mode); Where filename is a null-terminated
character sequence of type const char * (the same type that string literals have)
representing the name of the file to be opened, and mode is an optional
parameter.

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()

Returns true if a reading or writing operation fails. For example in the


case that we try to write to a file that is not open for writing or if the device
where we try to write has no space left.

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:

write ( memory_block, size );

read ( memory_block, size );

Buffers and Synchronization

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.

• Explicitly, with member function sync(): Calling stream's member


function sync(), which takes no parameters, causes an immediate
synchronization. This function returns an int value equal to -1 if the stream has
no associated buffer or in case of failure. Otherwise (if the stream buffer was
successfully synchronized) it returns 0.

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

The Java Virtual Machine

Machine language consists of very simple instructions that can be


executed directly by the CPU of a computer. Almost all programs, though, are
written in high-level programming languages such as Java, Pascal, or C++. A
program written in a high-level language cannot be run directly on any
computer. First, it has to be translated into machine language. This translation
can be done by a program called a compiler. A compiler takes a high-level-
language program and translates it into an executable machine-language
program. Once the translation is done, the machine-language program can be
run any number of times, but of course it can only be run on one type of
computer (since each type of computer has its own individual machine
language). If the program is to run on another type of computer it has to be re-
translated, using a different compiler, into the appropriate machine language.
There is an alternative to compiling a high-level language program.
Instead of using a compiler, which translates the program all at once, you can
use an interpreter, which translates it instruction-by-instruction, as necessary.
An interpreter is a program that acts much like a CPU, with a kind of fetch-and-
execute cycle. In order to execute a program, the interpreter runs in a loop in
which it repeatedly reads one instruction from the program, decides what is
necessary to carry out that instruction, and then performs the appropriate
machine-language commands to do so.

One use of interpreters is to execute high-level language programs. For


example, the programming language Lisp is usually executed by an interpreter
rather than a compiler. However, interpreters have another purpose: they can let
you use a machine-language program meant for one type of computer on a
completely different type of computer. For example, there is a program called
―Virtual PC‖ that runs on Macintosh computers. Virtual PC is an interpreter that
executes machine-language programs written for IBM-PC-clone computers. If
you run Virtual PC on your Macintosh, you can run any PC program, including
programs written for Windows. (Unfortunately, a PC program will run much
more slowly than it would on an actual IBM clone.

What is Java, and why?

The Java programming language was developed at Sun Microsystems and


originally became popular as a language for Internet applications (applets).
Such applets are embedded within WWW pages and executed in the user‘s
browser. A special format called byte code is used instead of ordinary machine
code, and by using a special Java interpreter program that code can be executed
on any computer. Such an interpreter is called a Java Virtual Machine (JVM)
and is available for most modern computer systems. (There is nothing about the
Java language itself that enforces the byte code technique – there are actually
some compilers who generate real machine code, known as native code,
directly.) The Java language is not limited to Internet applications. It is a
complete general objectoriented language and can be used to develop many
kinds of applications. Although the syntax of Java is very similar to that of C++,
many complicated and error-prone features of C++ have been removed. The
result can be described as a Simula with C++ syntax. Sun Microsystems (who
created the Java language) provide free tools for developing Java software. The
Java home page has links to Java compilers for most computer systems (such as
Unix and Microsoft Windows), as well as a lot of documentation. It is possible
to download a Java compiler and use it for free.

Compiling and running Java programs

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

% javac -depend TurtleMaze.java

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:

// A program to display the message

// "Hello World!" on standard output

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello World!");

} // end of class HelloWorld

The command that actually displays the message is:


System.out.println("Hello World!"); This command is an example of a
subroutine call statement. It uses a ―built-in subroutine‖ named
System.out.println to do the actual work. Recall that a subroutine consists
of the instructions for performing some task, chunked together and given
a name. That name can be used to ―call‖ the subroutine whenever that
task needs to be performed. A built-in subroutine is one that is already
defined as part of the language and therefore automatically available for
use in any program.

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

Numeric expressions are written in much the same way as in other


languages.

n = 3 * (5 + 2);

x = y / 3.141592653;

n = m % 8; // Modulo, i.e. n is now (m mod 8)

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.

It is possible to assign a variable an initial value directly when declaring it.


Example:

double f = 0.57;

boolean flag = true;

Unlike Simula, the initial value of a local variable is undefined (unless, of


course, an initial value is explicitly given as just shown).

Pitfall: differences between integer and real division

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.

Type conversion (casting)

In some languages it is possible to assign, for instance, a real value to an integer


variable. The value is then automatically converted (in this case, rounded) to the
right type.

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;

...

degrees = radians * 180 / 3.141592653; // Error

degrees = (int) (radians * 180 / 3.141592653); // OK

It is, however, possible to assign an integer value to a real variable without


casting. In general, no cast is necessary as long as the conversion can be made
without any loss of information.

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};

The {variable-name-or-names] can be a single variable name or a list of


variable names separated by commas. (We‘ll see later that variable declaration
statements can actually be somewhat more complicated than this.) Good
programming style is to declare only one variable in a declaration statement,
unless the variables are closely related in some way.

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 statements and boolean expressions

A simple if statement is written as follows:

if (n == 3)

x = 3.2;

Note:

• There is no then keyword

• The condition must be of boolean type and written within parentheses

• Comparison is made using ‗==‘

There are of course a number of other comparison operators, such as ‗‘,


‗<=‘, ‗>=‘, and so on. The only one that looks different from Simula and Pascal
is the ‗not equals‘ operator ‗!=‘, which is used in the example below.

if (x != 0)
y = 3.0 / x; // Executed when x is non-zero

else

y = 1; // Executed when x is zero

semicolons and ‘else’ statements

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;

} else // <--- Note: no semicolon

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.

More about boolean expressions

For boolean expressions, one needs to use logical operators corresponding to


‗and‘, ‗or‘, and ‗not‘. In Java, they are written as follows:

and &&

or ||
not !

For example:

int x, y;

boolean b;

...

if ((x <= 9 || y > 3) && !b) {

b = true;

While and for statements

// Calculate exp(1). End when the term is less than 0.00001

double sum = 0.0;

double term = 1.0;

int k = 1;

while (term >= 0.00001) {

sum = sum + term;

term = term / k;

k++; // Shortcut for ‗k = k + 1‘

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;

double sum = 0.0;

for (i = 1; i <= 100; i++) {

sum = sum + 1.0 / i;

As indicated in these examples, the statement i++ is a shortcut for i = i + 1.


Actually, there are at least four ways to increment an integer variable1:

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 and objects

As already mentioned, one file normally contains one class.

Classes

A class declaration typically contains a set of attributes (sometimes called


instance variables) and functions (called methods in Java). So far a Java class
declaration is very similar to one in Simula. Attributes are declared almost as
usual:

class Turtle {

private boolean penDown;

protected int x, y;

// Declare some more stuff

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 {

// Attribute declarations, as above

public void jumpTo(int newX, int newY) {

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;

t = new Turtle(100, 100);

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);

Java has garbage collection, so there is no need to destroy objects manually.

The main method

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:

public static void main(String[] args) {

Turtle t = new Turtle(100, 200);

t.right(90);

while (t.getX() < 150) {

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.

Interfaces and listeners

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 {

void processMouseClick(int x, int y);

This declaration essentially says that if an object should be used to handle


mouse clicks, its class should contain a processMouseClick method with two
integer parameters.

Exceptions

Many things can go wrong during the execution of a program. These run-time
errors can be divided into two broad categories:

• Faults introduced by the programmer, such as division by zero or calling a


method with a null reference.

• 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:

public int getNatural() { ... }

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

which continues on to a second line */

(A special case of such multi-line comments are the documentation comments.


They are written immediately before classes and methods and begin with ‗/**‘
(two asterisks) and end, as usual, with ‗*/‘ (one asterisk). Such comments are
used by a special tool, javadoc, to automatically generate low-level
documentation of the program.)
Using packages

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

A Java array is similar to an object in some ways. It is for example accessed


using reference variables. Array references can be declared as follows:

int[] someInts; // An integer array

Turtle[] turtleFarm; // An array of references to Turtles

Since these variables are only references to arrays, the array sizes are not given
in the declarations, but when the arrays are actually created.

someInts = new int[30];

turtleFarm = new Turtle[100];

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;

for (i = 0; i < someInts.length; i = i + 1) {

someInts[i] = i * i;

}
The expression someInts.length means in the length of the vector, 30 in this
case.

Writing to the terminal

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.print(―Jag vill bo ―);

System.out.println(―i en svamp―);

System.out.println(―Annars får jag kramp―);

The resulting output is:

Jag vill bo i en svamp

Annars får jag kramp

Variable values can be printed like this:

int a;

a = 6 * 7;

System.out.println(―6 * 7 = ― + a);

A complete Java program

The following example program displays a window with graphical figures


(squares and circles). The program is not intended to be useful in any way
except as an example of a complete Java program.
***End of java***
Take your test HERE!
Are you fond of learning more!
See our courses section for more!
Stay Connected with us!
Visit us on – www.eduiacademy.online

You might also like