38
1 SVG 216 Lecture Notes February 2012 INTRODUCTION Need for Surveying Computer Applications Automating processes or common calculations (e.g. joins, polars, resections, intersection) Analysis e.g. in GIS (through writing SQL programs for procedures such as buffering, connectivity and neighborhood functions) Simple and complex database development Programming Languages Python C C++ Java Visual Basic Visual C++ .NET Types of Programming Languages Object-oriented programming Object-oriented programming is one the newest and most powerful paradigms. In object- oriented programs, the designer specifies both the data structures and the types of operations that can be applied to those data structures. This pairing of a piece of data with the operations that can be performed on it is known as an object. A program thus becomes a collection of cooperating objects, rather than a list of instructions. Objects can store state information and interact with other objects, but generally each object has a distinct, limited role. The most famous object-oriented programming these days are C#, C, Visual Basic, Java and Python. Structured Programming Languages Structured programming is a special type of procedural programming. It provides additional tools to manage the problems that larger programs were creating. Structured programming requires that programmers break program structure into small pieces of code that are easily understood. It also frowns upon the use of global variables and instead uses variables local to each subroutine. One of the well known features of structural programming is that it does not allow the use of the GOTO statement. It is often associated with a "top-down" approach to design. The top-down approach begins with an initial overview of the system that contains minimal details about the different parts. Subsequent design iterations then add increasing detail to the components until the design is complete. The most popular structured programming languages include C, Ada and Pascal. Procedural Programming Languages Procedural programming specifies a list of operations that the program must complete to reach the desired state. This one of the simpler programming paradigms, where a program is represented much like a cookbook recipe. Each program has a starting state, a list of operations to complete, and an ending point. This approach is also known as imperative programming. Integral to the idea of procedural programming is the concept of a procedure call. Procedures, also known as functions, subroutines, or methods, are small sections of code that perform a particular function. A procedure is effectively a list of computations to be carried out. Procedural programming can be compared to unstructured programming, where all of the code resides in a single large block. By splitting the programmatic tasks into small pieces, procedural programming allows a section of code to be re-used in the program without making multiple copies. It also makes it easier for programmers to understand and maintain program

216 Lecture Notes - Welcome to Midlands State Universitymsu.ac.zw/elearning/material/1328536464216 Lecture Notes.pdf · SVG 216 Lecture Notes ... (through writing SQL programs for

  • Upload
    lycong

  • View
    225

  • Download
    0

Embed Size (px)

Citation preview

1

SVG 216 Lecture Notes February 2012 INTRODUCTION Need for Surveying Computer Applications

• Automating processes or common calculations (e.g. joins, polars, resections, intersection) • Analysis e.g. in GIS (through writing SQL programs for procedures such as buffering,

connectivity and neighborhood functions) • Simple and complex database development

Programming Languages

• Python • C • C++ • Java • Visual Basic • Visual C++ • .NET

Types of Programming Languages

• Object-oriented programming Object-oriented programming is one the newest and most powerful paradigms. In object- oriented programs, the designer specifies both the data structures and the types of operations that can be applied to those data structures. This pairing of a piece of data with the operations that can be performed on it is known as an object. A program thus becomes a collection of cooperating objects, rather than a list of instructions. Objects can store state information and interact with other objects, but generally each object has a distinct, limited role. The most famous object-oriented programming these days are C#, C, Visual Basic, Java and Python.

• Structured Programming Languages Structured programming is a special type of procedural programming. It provides additional tools to manage the problems that larger programs were creating. Structured programming requires that programmers break program structure into small pieces of code that are easily understood. It also frowns upon the use of global variables and instead uses variables local to each subroutine. One of the well known features of structural programming is that it does not allow the use of the GOTO statement. It is often associated with a "top-down" approach to design. The top-down approach begins with an initial overview of the system that contains minimal details about the different parts. Subsequent design iterations then add increasing detail to the components until the design is complete. The most popular structured programming languages include C, Ada and Pascal.

• Procedural Programming Languages Procedural programming specifies a list of operations that the program must complete to reach the desired state. This one of the simpler programming paradigms, where a program is represented much like a cookbook recipe. Each program has a starting state, a list of operations to complete, and an ending point. This approach is also known as imperative programming. Integral to the idea of procedural programming is the concept of a procedure call. Procedures, also known as functions, subroutines, or methods, are small sections of code that perform a particular function. A procedure is effectively a list of computations to be carried out. Procedural programming can be compared to unstructured programming, where all of the code resides in a single large block. By splitting the programmatic tasks into small pieces, procedural programming allows a section of code to be re-used in the program without making multiple copies. It also makes it easier for programmers to understand and maintain program

2

structure. Two of the most popular procedural programming languages are FORTRAN and BASIC.

Algorithms In mathematics and computer science, an algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function. Algorithms are used for calculation, data processing, and automated reasoning. Starting from an initial state and initial input, the instructions describe a computation that, when executed, will proceed through a finite number of well-defined successive states, eventually producing output and terminating at a final ending state. (Source: Wikipedia) Consider a program to add 2 numbers: An Algorithm to add two numbers is :-

1. Start 2. Enter 2 numbers (A and B) 3. Sum = A + B 4. Display Result 5. Stop

An example code:- #include <iostream> using namespace std; int main() { int A = 10; // Declaring variables int B = 15; int sum; sum = A + B; // Performing the arithmetic function cout <<The sum is: << sum << endl; // Printing the result return 0; } Flowchats A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-by-step solution to a given problem. Process operations are represented in these boxes, and arrows connecting them represent flow of control. Data flows are not typically represented in a flowchart, in contrast with data flow diagrams; rather, they are implied by the sequencing of operations. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields. (Source: Wikipedia)

3

4

Basic Flowchart Shapes

5

6

Structured Query Language (SQL) Parcel Parcel_ID Address Postcode Area

N1 Klip 156 8224CK 80

N2 Kustrif 44 8224AB 100

N3 Sont 28 8226AB 100

N4 Klip 56 8224CK 85

N5 Sont 22 8226AB 90 a) SELECT* FROM Parcel WHERE Postcode = '8224CK'; b) SELECT* from Parcel WHERE Area < 90

7

C++ as a programming language C++ is a high level programming language and it is highly flexible and adaptable. C++ is an object oriented, low level ANSI and ISO standard programming language. Object oriented means that C++ supports programming styles that simplify the building of large scale, extensible programs. As a low-level language, C++ can generate very efficient, very fast programs. What is a program? A C++ program is a text file containing a sequence of C++ commands put together according to the laws of C++ grammar. This text file is known as the source file. A C++ source file carries the extension .cpp just as a Microsoft word file end with .doc or an MS-DOS batch file ends in .bat. Gramma and Syntax (C++) The actual code of your program consists of two parts: variables and executable instructions. Variables are used to hold data used by your program. Executable instructions tell the computer what to do with the data. C++ classes are a combination of data and instructions that work on the data. They provide a convenient way of packaging both instructions and data. 1. General features of C++ C++ is (lower and upper) case sensitive For example, the variable echidna is different from the variable echiDna, and the C++ command return is not equivalent to the non-existent command Return. Beginning of a statement A C++ statement or command may begin at any place in a line and continue onto the next line. In fact, a statement may take several lines of code. We say that C++ is written in free form. End of a statement The end of a statement is indicated by a semicolon “;” (statement delimiter.) Thus, we write: a=5; If we do not include the semicolon, the compiler will assume that the statement in the next line is a continuation of the statement in the present line. Multiple commands in a line Two or more statements can be placed in the same line provided they are separated with semicolons. Thus, we may write:

8

a=5; b=10; White space An empty (blank) space separates two words. The compiler ignores more than one empty space between two words. A number cannot be broken up into pieces separated by white space; thus, we may not write 92 093 instead of 92093. Statement and command blocks Blocks of statements or commands defining procedures are enclosed by curly brackets (block delimiters) { ... } In-line comments In-line comments may be inserted following the double slash “//”. For example, we may write: a = 10.0; // Initialising the variable a The text: // Initialising the variable a , is ignored by the compiler. All text enclosed between a slash-asterisk pair (/*) and the converse asterisk-slash pair (*/) is commentary and ignored by the compiler. Thus, we may write: /* ---- main program ----- */ To provide documentation at the beginning of a code, we may write: /* PROGRAM: late AUTHOR: Justin Case PURPOSE: produce an excuse for being late */ Example Program The following program prints the statement “Hello World” #include <iostream>

int main() { // Tell the world Hello std::cout <<”Hello World\n”;

9

return (0); }

To write a program, you must have a clear idea of what you are going to do. One of the best ways to organize your thoughts is to write them down in a language that is clear and easy to understand. Once the process has been clearly stated, it can be translated into a computer program. Your program should read like an essay. It should be as clear and easy to understand as possible. At the beginning of a program is a comment block that contains information about the program. Problems 1. How many commands are executed in the following line? a=3.0; // b=4.0; 2. How does the compiler interpret the following line? /* my other /* car is */ a vartburg */

10

2. Data Types Numerical variable declaration: Every numerical variable must be declared either as an integer (whole number) or as a real (floating point) number registered in single or double precision. Suppose that a is an integer, b is a real number registered in single precision, and c is a real number registered in double precision. The statements declaring these variables are: int a; float b; double c; Suppose that i is an integer and j is another integer. We can declare in either of the following ways: int i; int j; or int i, j; int account_number; // Index for account table int balance_owned; // Total owed (in dollars) Once declared, a numerical variable can be initialized or evaluated. For example, we may write: int a; a=875; // declare a variable and set it to 1 long value; value = 1; Declaration and initialization can be combined into a single statement: int a = 875; Naming Style Names can contain both uppercase and lowercase letters. All uppercase is reserved for constants (e.g., MAX_ITEMS, SCREEN_WIDTH). This convention is the classic convention followed by most C and C++ programs. Many newer programs use mixed-case names (e.g. RecordsInFile). Sometimes they use the capitalization of the first letter to indicate information about the variable. Indentation and Code Format To make programs easier to understand, most programmers indent their programs. The general rule for a C++ program is to indent one level for each new block or condition. Clarity A program should read like a technical paper, organized into sections and paragraphs. You should organize your code into paragraphs, beginning a paragraph with a topic sentence comment and separating it from other paragraphs with a blank line.

11

Boolean variables A Boolean variables can be either false or true. When a Boolean variable is printed, it appears as 1 or 0, respectively, for true and false. The following statements declare and initialize the Boolean variable hot: bool hot; hot = true; Characters The following statements declare and initialize a character: char a; a = 66; Strings A string is an array of characters. The following statements define and initialize a string: string name; name = "Kolokotronis"; Note the mandatory use of double quotes. Constants To fix the value of a variable and thus render the variable a constant, we include the keyword const. For example, we may declare const float temperature; Constants are variables that, once evaluated, remain fixed and thus cease to be variables. Problems 1. Declare and initialize at the value of 77 the integer a 2. What are the values of the integers c and d evaluated by the following statements? char a = ’=’; int c = a; char b = ’1’; int d = b;

12

Vectors, arrays, and composite data types An array is a sequence of variables that share the same name and are referenced using an index. Arrays are useful little critters that allow you to store large values that are related in some way e.g. the batting averages of all players on the same team might be a good candidate for storage within an array. Arrays can be multidimensional too, allowing you for example to store an array of batting averages of the team as they occur per month. An array is simply a number of memory locations, each of which can store an item of data of the same data type and which are all referenced through the same variable name. Array may be defined abstractly as finite order set of homogeneous elements. So we can say that there are finite numbers of elements in an array and all the elements are of same data type. Also array elements are ordered i.e. we can access a specific array element by an index. The general form of declaring a simple (one dimensional) array is

array_type variable_name[array_size];

in your C++ program you can declare an array like

int Age[10];

Here array_type declares base type of array which is the type of each element in array. In our example array_type is int and its name is Age. Size of the array is defined by array_size i.e. 10. We can access array elements by index, and first item in array is at index 0. First element of array is called lower bound and its always 0. Highest element in array is called upper bound.

In C programming language upper and lower bounds cannot be changed during the execution of the program, so array length can be set only when the program in written.

Age 0 Age 1 Age 2 Age 3 Age 4 Age 5 Age 6 Age 7 Age 8 Age 9

30 32 54 32 26 29 23 43 34 5

Array has 10 elements

Note: One good practice is to declare array length as a constant identifier. This will minimise the required work to change the array size during program development.

Considering the array we declared above we can declare it like

#define NUM_EMPLOYEE 10

int Age[NUM_EMPLOYEE];

Initialisation of array is very simple in c programming. There are two ways you can initialise arrays.

• Declare and initialise array in one statement.

• Declare and initialise array separately.

13

Look at the following C code which demonstrates the declaration and initialisation of an array.

int Age [5] = {30, 22, 33, 44, 25};

int Age [5];

Age [0]=30;

Age [1]=22;

Age [2]=33;

Age [3]=44;

Age [4]=25;

Array can also be initialised in a ways that array size is omitted, in such case compiler automatically allocates memory to array.

int Age [] = {30, 22, 33, 44, 25};

Let’s write a simple program that uses arrays to print out number of employees having salary

more than 3000.

� The following example prints the 3 x 3 array’s subscript and their element. // printing 3x3 array's subscript and their element #include <iostream> using namespace std; #define m 3 #define n 3 int main() { int i, j; int x[m][n]={{10,25,33}, {21,32,43},{20,42,51}}; cout<<"\n3x3 arrays' subscripts and\n"; cout<<"their respective elements\n"; cout<<"--------------------------\n"; // the outer for loop, reading the row by row... for(i=0; i<m; i++) // the inner loop, for every row, read every column by column... for(j=0; j<n; j++) cout<<"["<<i<<"]"<<"["<<j<<"]"<<"="<<x[i][j]<<"\n"; return 0; }

Output:Output:Output:Output:

14

� The following program example illustrates the use of two-dimensional arrays. This program

calculates the average of all the elements in the integer array named x. The program uses two nested for loops.

� The outer loop with index i provides the row subscript. The nested for loops therefore accesses each element of the array and the inner loop with index j provides the column subscript.

// using two-dimensional array to compute the // average of all the elements in array named x #include <iostream>

using namespace std; #define m 4 #define n 5 int main() { int i, j, total = 0; // a 4x5 or [4][5] array variable... int q[m][n]={{4,5,6,2,12},{10,25,33,22,11}, {21,32,43,54,65},{3,2,1,5,6}}; float average; // the outer for loop, read row by row... for(i=0; i<m; i++) // the inner for loop, for every row, read column by column for(j=0; j<n; j++) // the get the summation of the array elements. { // the display the array... cout<<"q["<<i<<"]["<<j<<"] = "<<q[i][j]<<endl; total=total + q[i][j]; } // calculate the average, notice the simple typecast casted from int to float... average = (float)total/(float) (m*n); cout<<"\nThis program will calculate the average of the"; cout<<"\n4 x 5 array, which means the sum of the"; cout<<"\narray's element, divide the number of the"; cout<<"\narray's element...."; cout<<"\nProcessing.... PLEASE WAIT\n"; // display the average cout<<"Average = "<<total<<"/"<<m*n<<endl; cout<<"\nThe Average = "<<average<<endl; return 0; }

15

Output:

� Study the program's source code and the output.

Vectors In C++, a one-dimensional array (vector) vi is declared as v[n], where n is an integer, and i = 0, . . . , n − 1. Thus, the lower limit of an array index is always 0. For example, a vector v with thirty slots occupied by real numbers registered in double precision, beginning at v[0] and ending at v[29], is declared as: double v[30]; Note that the elements of the vector are denoted using square brackets, v[i], not parentheses, v(i). Parentheses in C++ enclose function arguments. Similarly, we can declare: char a[19]; and

string a[27]; Successive elements of a vector are stored in consecutive memory blocks whose length depends on the data type. In C++ jargon, the term “vector” sometimes implies a one-dimensional array with variable length.

16

Matrices A two-dimensional array (matrix) Aij is declared as A[m][n], where n and m are two integers, i = 0, 1, . . . , m − 1 and j = 0, 1, . . . , n − 1. The lower limit of both indices is 0. For example, the two indices of the 15 × 30 matrix A[15][30] begin at i, j = 0 and end, respectively, at i = 14 and j = 29. If the elements of this matrix are integers, we declare: int A[15][30]; Note that the elements of the matrix are denoted as v[i][j], not v(i,j). The individual indices of a matrix are individually enclosed by square brackets. Similarly, we can declare the array of characters: char A[13][23];

17

3. System header files An include statement asks the preprocessor to attach at the location of the statement a copy of a header file containing the definition of a desired class of system or user-defined functions. Both are regarded as external implementations. The system header files reside in a subdirectory of a directory where the C++ compiler was installed, whereas the user-defined header files reside in user-specified directories. For example, putting at the beginning of the code the statement: #include <iostream> instructs the C++ preprocessor to attach a header file containing the definition, but not the implementation, of functions in the input/output stream library. Thus, the main function of a code that uses this library has the general structure: #include <iostream> ... int main() { ... return 0; } where the three dots denote additional lines of code. Similarly, putting at the beginning of a source code the statement: #include <cmath> ensures the availability of the C++ mathematical library. In this case, cmath is a header file containing the definition, but not the implementation, of mathematical functions. Thus, the main function of a code that uses both the input/output and the mathematical libraries has the general syntax: #include <iostream> #include <cmath> ...

18

int main() { ... return 0; } where the three dots denote additional lines of code. Standard namespace Immediately after the include statements, we state: using namespace std; which declares that the names of the functions defined in the standard std system library will be adopted in the code. This means that the names will be stated plainly and without reference to the std library. Thus, the main function of a code that uses the standard input/output library and the mathematical library has the general form: #include <iostream> #include <cmath> using namespace std; ... int main() { ... return 0; } Problems 1. Write a program that prints on the screen the name of a person that you most admire. 2. Investigate whether the following statement is permissible:

19

cout << int a=3; 3. What is the output of the following program? #include <iostream> using namespace std; int main() { string first name; string last name; first name = "Mother"; last name = "Theresa"; string name = first name + " " + last name; cout << name << endl; }

20

4. Pointers

Essentially, the computer's memory is made up of bytes. Each byte has a number, an address, associated with it.

The picture below represents several bytes of a computer's memory. In the picture, addresses 924 through 940 are shown.

1:#include <iostream> 2:int main() 3:{ 4: float fl=3.14; 5: std::cout << fl << std::endl; 6: return 0; 7:}

At line (4) in the program above, the computer reserves memory for fl. In our examples, we'll assume that a float requires 4 bytes. Depending on the computer's architecture, a float may require 2, 4, 8 or some other number of bytes.

When fl is used in line (5), two distinct steps occur:

1. The program finds and grabs the address reserved for fl--in this example 924.

2. The contents stored at that address are retrieved

To generalize, whenever any variable is accessed, the above two distinct steps occur to retrieve the contents of the variable.

1: #include <iostream> 2: int main() 3: { 4: float fl=3.14; 5: unsigned int addr= (unsigned int) &fl; 6: std::cout << "fl's address=" << addr << std::e ndl; 7: return 0; 8: }

21

The above code shows that there is nothing magical about addresses. They are just simple numbers that can be stored in integer variables.

The unsigned keyword at the start of line (5) simply means that the integer will not hold negative numbers. As before, the (unsigned int) phrase has been shown in gray. It must be included for the code to compile, but is not relevant to this discussion. It will be discussed later.

The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte). These single-byte memory cells are numbered in a consecutive way, so as, within any block of memory, every cell has the same number as the previous one plus one. This way, each cell can be easily located in the memory because it has a unique address and all the memory cells follow a successive pattern. For example, if we are looking for cell 1776 we know that it is going to be right between cells 1775 and 1777, exactly one thousand cells after 776 and exactly one thousand cells before cell 2776.

Reference operator (&) As soon as we declare a variable, the amount of memory needed is assigned for it at a specific location in memory (its memory address). We generally do not actively decide the exact location of the variable within the panel of cells that we have imagined the memory to be - Fortunately, that is a task automatically performed by the operating system during runtime. However, in some cases we may be interested in knowing the address where our variable is being stored during runtime in order to operate with relative positions to it. The address that locates a variable within memory is what we call a reference to that variable. This reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator, and which can be literally translated as "address of". For example: ted = &andy;

This would assign to ted the address of variable andy, since when preceding the name of the variable andy with the reference operator (&) we are no longer talking about the content of the variable itself, but about its reference (i.e., its address in memory).

22

From now on we are going to assume that andy is placed during runtime in the memory address 1776. This number (1776) is just an arbitrary assumption we are inventing right now in order to help clarify some concepts in this tutorial, but in reality, we cannot know before runtime the real value the address of a variable will have in memory. Consider the following code fragment: 1 2 3

andy = 25; fred = andy; ted = &andy;

The values contained in each variable after the execution of this, are shown in the following diagram:

First, we have assigned the value 25 to andy (a variable whose address in memory we have assumed to be 1776). The second statement copied to fred the content of variable andy (which is 25). This is a standard assignment operation, as we have done so many times before. Finally, the third statement copies to ted not the value contained in andy but a reference to it (i.e., its address, which we have assumed to be 1776). The reason is that in this third assignment operation we have preceded the identifier andy with the reference operator (&), so we were no longer referring to the value of andy but to its reference (its address in memory). The variable that stores the reference to another variable (like ted in the previous example) is what we call a pointer. Pointers are a very powerful feature of the C++ language that has many uses in advanced programming. Farther ahead, we will see how this type of variable is used and declared.

Dereference operator (*) We have just seen that a variable which stores a reference to another variable is called a pointer. Pointers are said to "point to" the variable whose reference they store. Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by". Therefore, following with the values of the previous example, if we write: beth = *ted;

(that we could read as: "beth equal to value pointed by ted") beth would take the value 25, since ted is 1776, and the value pointed by 1776 is 25.

23

You must clearly differentiate that the expression ted refers to the value 1776, while *ted (with an asterisk * preceding the identifier) refers to the value stored at address1776, which in this case is 25. Notice the difference of including or not including the dereference operator (I have included an explanatory commentary of how each of these two expressions could be read): 1 2

beth = ted; // beth equal to ted ( 1776 ) beth = *ted; // beth equal to value pointed by ted ( 25 )

Notice the difference between the reference and dereference operators:

• & is the reference operator and can be read as "address of"

• * is the dereference operator and can be read as "value pointed by"

Thus, they have complementary (or opposite) meanings. A variable referenced with & can be dereferenced with *. Earlier we performed the following two assignment operations: 1 2

andy = 25; ted = &andy;

Right after these two statements, all of the following expressions would give true as result: 1 2 3 4

andy == 25 &andy == 1776 ted == 1776 *ted == 25

The first expression is quite clear considering that the assignment operation performed on andy was andy=25. The second one uses the reference operator (&), which returns the address of variable andy, which we assumed it to have a value of 1776. The third one is somewhat obvious since the second expression was true and the assignment operation performed on ted was ted=&andy. The fourth expression uses the dereference operator (*) that, as we have just seen, can be read as "value pointed by", and the value pointed by ted is indeed 25. So, after all that, you may also infer that for as long as the address pointed by ted remains unchanged the following expression will also be true: *ted == andy

24

Declaring variables of pointer types Due to the ability of a pointer to directly refer to the value that it points to, it becomes necessary to specify in its declaration which data type a pointer is going to point to. It is not the same thing to point to a char as to point to an int or a float. The declaration of pointers follows this format: type * name; where type is the data type of the value that the pointer is intended to point to. This type is not the type of the pointer itself! but the type of the data the pointer points to. For example: 1 2 3

int * number; char * character; float * greatnumber;

These are three declarations of pointers. Each one is intended to point to a different data type, but in fact all of them are pointers and all of them will occupy the same amount of space in memory (the size in memory of a pointer depends on the platform where the code is going to run). Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an int, the second one to a char and the last one to a float. Therefore, although these three example variables are all of them pointers which occupy the same size in memory, they are said to have different types: int*, char* and float* respectively, depending on the type they point to. I want to emphasize that the asterisk sign (*) that we use when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator that we have seen a bit earlier, but which is also written with an asterisk (*). They are simply two different things represented with the same sign. Now have a look at this code:

1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17

// my first pointer #include <iostream> using namespace std; int main () { int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; }

firstvalue is 10 secondvalue is 20

Notice that even though we have never directly set a value to either firstvalue or secondvalue, both end up with a value set indirectly through the use of mypointer. This is the procedure: First, we have assigned as value of mypointer a reference to firstvalue using the reference operator (&). And then we have assigned the value 10 to the memory location pointed by mypointer, that

25

because at this moment is pointing to the memory location of firstvalue, this in fact modifies the value of firstvalue. In order to demonstrate that a pointer may take several different values during the same program I have repeated the process with secondvalue and that same pointer, mypointer. Here is an example a little bit more elaborated:

1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20

// more pointers #include <iostream> using namespace std; int main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed by p1 = 10 *p2 = *p1; // value pointed by p2 = value pointed by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed by p1 = 20 cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; }

firstvalue is 10 secondvalue is 20

I have included as a comment on each line how the code can be read: ampersand (&) as "address of" and asterisk (*) as "value pointed by". Notice that there are expressions with pointers p1 and p2, both with and without dereference operator (*). The meaning of an expression using the dereference operator (*) is very different from one that does not: When this operator precedes the pointer name, the expression refers to the value being pointed, while when a pointer name appears without this operator, it refers to the value of the pointer itself (i.e. the address of what the pointer is pointing to). Another thing that may call your attention is the line: int * p1, * p2;

This declares the two pointers used in the previous example. But notice that there is an asterisk (*) for each pointer, in order for both to have type int* (pointer to int). Otherwise, the type for the second variable declared in that line would have been int (and not int*) because of precedence relationships. If we had written: int * p1, p2;

p1 would indeed have int* type, but p2 would have type int (spaces do not matter at all for this purpose). This is due to operator precedence rules. But anyway, simply remembering that you have to put one asterisk per pointer is enough for most pointer users.

26

5. Operators Operators apply to one variable or a group of variables to carry out arithmetic and logical tasks. Assignation The equal sign (=) is the assignation or right-to-left copy operator. Thus, the statement a = b; means “replace the value of a with the value of b”, and the statement a = a+5; means “replace the value of a with itself augmented by 5”. int var1 = 10; int var2 = -var1 The latter expression uses the unary operator (-) to calculate the value negative 10. Control Structures Conditional Structure: if and else The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if (condition) statement Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure. For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: if (x == 100) cout << "x is 100"; If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }: if (x == 100) { cout << "x is "; cout << x; } We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is: if (condition) statement1 else statement2 For example:

27

if (x == 100) cout << "x is 100"; else cout << "x is not 100"; prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100. Iteration Structures (Loops) Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. The while loop Its format is: while (expression) statement and its functionality is simply to repeat statement while the condition set in expression is true. For example, we are going to make a program to countdown using a while-loop: // custom countdown using while #include <iostream> using namespace std; int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } return 0; } When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true. The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities: * condition is true: statement is executed (to step 3) *condition is false: ignore statement and continue after it (to step 5)

28

3. Execute statement: cout << n << ", "; --n; prints the value of n on the screen and decreases n by 1) 4. End of block. Return automatically to step 2 5. End Program The do-while loop Its format is: do statement while (condition); Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0. // number echoer #include <iostream> using namespace std; int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: "<< n << "\n"; } while (n != 0); return 0; } The for loop Its format is: for (initialization; condition; increase) statement; and its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. It works in the following way: 1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.

29

2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed).

3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.

4. finally, whatever is specified in the increase field is executed and the loop gets back to step (2).

Here is an example of countdown using a for loop: // countdown using a for loop #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { cout << n << ", "; } return 0; }

30

6. Creating Functions Developers often need the ability to break programs up into smaller chunks that are easier to develop. Without this ability to divide up the program into parts, developing such large programs would quickly become impossible. C++ allows programmers to divide their code up into chunks known as functions. A function with a simple description and a well defined interface to the outside world can be written and debugged without worrying about the code that surrounds it. A good function can be described using a single sentence that contains a minimum number of ORs and ANDs. For example, the function sumSequence accumulates a sequence of integer values entered by the user. This definition is concise and clear. Functions are so fundamental to the creating of C++ programs that understanding the details of defining, creating and testing functions is critical. A function is a logically separated block of C++ code. The function construct has the following form:

<return type> name(<arguments to the function>) {

// …. return <expression;>

} The arguments to a function are the values that can be passed for the function to use as input. The return value is a value that the function returns. For example, in the call to the function square(10), the value 10 is an argument to the function square(). The returned value is 100. Both the arguments and the return value are optional. If either is absent, the keyword void is used instead. That is, if a function has a void argument list, the function does not take any arguments when called. If the return type is void, the function does not return a value to the caller. Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++. A function is a group of statements that is executed when it is called from some point of the program. The following is its format: type name ( parameter1, parameter2, ...) { statements } where:

• type is the data type specifier of the data returned by the function.

• name is the identifier by which it will be possible to call the function.

• parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

• statements is the function's body. It is a block of statements surrounded by braces { }.

31

// function example #include <iostream> using namespace std; int addition ( int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; }

The result is 8. The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition. At the point at which the function is called from within main, the control is lost by main and passed to function addition. The value of both arguments passed in the call (5and 3) are copied to the local variables int a and int b within the function. Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8. The following line of code: return (r); finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows its regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call.

Scope of variables

The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them. For example, in the previous example it would have been impossible to use the variables a, b or r directly in function main since they were variables local to function addition. Also, it would have been impossible to use the variable z directly within function addition, since this was a variable local to the function main.

32

Therefore, the scope of local variables is limited to the same block level in which they are declared. Nevertheless, we also have the possibility to declare global variables; These are visible from any point of the code, inside and outside all functions. In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program. // function example #include <iostream> using namespace std; int subtraction ( int a, int b) { int r; r=a-b; return (r); } int main () { int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n' ; cout << "The second result is " << subtraction (7,2) << '\n' ; cout << "The third result is " << subtraction (x,y) << '\n' ; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n' ; return 0; }

33

7. Object Oriented Programming Introduction To Visual Basic

What is Visual Basic?

VISUAL BASIC is a high level programming language which evolved from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. Visual Basic (VB) is an event driven programming language and associated development environment created by Microsoft. In business programming, it has one of the largest user bases. It is a very easy programming language to learn. The code look a lot like English Language. Different software companies produced different versions of BASIC, such as Microsoft QBASIC, QUICKBASIC, GWBASIC ,IBM BASICA and so on. However, people prefer to use Microsoft Visual Basic today, as it is a well developed programming language and supporting resources are available everywhere. Now, there are many versions of VB exist in the market, the most popular one and still widely used by many VB programmers is none other than Visual Basic 6. We also have VB.net, VB2005, VB2008 and the latest VB2010. Both Vb2008 and VB2010 are fully object oriented programming (OOP) language.

VISUAL BASIC is a VISUAL and events driven Programming Language. These are the main divergence from the old BASIC. In BASIC, programming is done in a text-only environment and the program is executed sequentially. In VB, programming is done in a graphical environment. In the old BASIC, you have to write program code for each graphical object you wish to display it on screen, including its position and its color. However, In VB , you just need to drag and drop any graphical object anywhere on the form, and you can change its color any time using the properties windows.

On the other hand, because the user may click on a certain object randomly, so each object has to be programmed independently to be able to response to those actions (events). Therefore, a VB Program is made up of many subprograms, each has its own program code, and each can be executed independently and at the same time each can be linked together in one way or another.

What programs can you create with Visual Basic

With VB 6, you can create any program depending on your objective. For example, if you are a college or university lecturer, you can create educational programs to teach business, economics, engineering, computer science, accountancy , financial management, information system and more to make teaching more effective and interesting. If you are in business, you can also create business programs such as inventory management system, point-of-sale system, payroll system, financial program as well as accounting program to help manage your business and increase productivity. For those of you who like games and working as games programmer, you can create those programs as well. Indeed, there is no limit to what program you can create! There are many such programs in this tutorial, so you must spend more time on the tutorial in order to learn how to create those programs.

7.1 Creating a New Project

1. Click File 2. Click New Project

34

The New Project Dialogue appears.

The visual basic templates are displayed.

3. Click the + next to visual basic under project types

35

4. Click Windows Application 5. Click OK

A blank Windows application form appears.

6. Click Save. 7. Type a name for your project. 8. Click Save

The project files are saved to your project directory.

7.2 Create a ‘Hello World’ Application

1. Open a new Visual Basic windows application as demonstrated in section 7.1 2. Move the cursor over the Toolbox tab.

The list of tools appears.

36

3. Drag the Label control on to the blank form.

4. Click the label on the form and type Hello World .

37

The properties window is displayed, and “Hello World” appears alongside the Text property.

5. Press F5 to run the application

38

The Hello World form is displayed on the screen.

6. Click the close box. Your application stops running.