SVG 216 Lecture Notes February 2012

Size: px
Start display at page:

Download "SVG 216 Lecture Notes February 2012"

Transcription

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 objectoriented 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 1

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

3 3

4 Basic Flowchart Shapes 4

5 5

6 Structured Query Language (SQL) Parcel Parcel_ID Address Postcode Area N1 Klip CK 80 N2 Kustrif AB 100 N3 Sont AB 100 N4 Klip CK 85 N5 Sont AB 90 a) SELECT* FROM Parcel WHERE Postcode = '8224CK'; b) SELECT* from Parcel WHERE Area < 90 6

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

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 instead of 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 ; 8

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 */ 9

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: or int i; int j; int i, j; int account_number; int balance_owned; // Index for account table // 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. 10

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

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

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 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 Output: 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; 13

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

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

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 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]; 16

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

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

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

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 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::endl; 7: return 0; 8: 20

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 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). 21

22 From now on we are going to assume that andy is placed during runtime in the memory address 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 andy = 25; 2 fred = andy; 3 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

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 beth = ted; // beth equal to ted ( 1776 ) 2 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 andy = 25; 2 ted = &andy; Right after these two statements, all of the following expressions would give true as result: 1 andy == 25 2 &andy == ted == *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 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 23

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 int * number; 2 char * character; 3 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: // 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 24

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: // 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. 25

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: For example: if (condition) statement1 else statement2 26

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

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

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 () return 0; for (int n=10; n>0; n--) cout << n << ", "; 29

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

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

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

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 33

34 The New Project Dialogue appears. The visual basic templates are displayed. 3. Click the + next to visual basic under project types 34

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 Move the cursor over the Toolbox tab. The list of tools appears. 35

36 3. Drag the Label control on to the blank form. 4. Click the label on the form and type Hello World. 36

37 The properties window is displayed, and Hello World appears alongside the Text property. 5. Press F5 to run the application 37

38 The Hello World form is displayed on the screen. 6. Click the close box. Your application stops running. 38

Pointers. Reference operator (&) ted = &andy;

Pointers. Reference operator (&)  ted = &andy; Pointers We have already seen how variables are seen as memory cells that can be accessed using their identifiers. This way we did not have to care about the physical location of our data within memory,

More information

Reference operator (&)

Reference operator (&) Pointers 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

More information

12. Pointers Address-of operator (&)

12. Pointers Address-of operator (&) 12. Pointers In earlier chapters, variables have been explained as locations in the computer's memory which can be accessed by their identifer (their name). This way, the program does not need to care

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

Programming with C++ Language

Programming with C++ Language Programming with C++ Language Fourth stage Prepared by: Eng. Samir Jasim Ahmed Email: engsamirjasim@yahoo.com Prepared By: Eng. Samir Jasim Page 1 Introduction: Programming languages: A programming language

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Fifth week Control Structures A program is usually not limited to a linear sequence of instructions. During its process

More information

Object oriented programming C++

Object oriented programming C++ http://uranchimeg.com Object oriented programming C++ T.Uranchimeg Prof. Dr. Email uranchimeg@must.edu.mn Power Engineering School M.EC203* -- OOP (C++) -- Lecture 07 Subjects Pointers Pointer and array

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

Professor Terje Haukaas University of British Columbia, Vancouver C++ Programming

Professor Terje Haukaas University of British Columbia, Vancouver  C++ Programming C++ Programming C++ code is essentially a collection of statements terminated by a semicolon, such as (spaces not needed): a = b + c; Most C++ code is organized into header files and cpp files, i.e., C++

More information

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 1 Introduction and Background Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Scientific Computing

Scientific Computing Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course

More information

4. Structure of a C++ program

4. Structure of a C++ program 4.1 Basic Structure 4. Structure of a C++ program The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which

More information

Unit 1 : Principles of object oriented programming

Unit 1 : Principles of object oriented programming Unit 1 : Principles of object oriented programming Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) Divided Into Importance Procedure Oriented Programming In

More information

8. Control statements

8. Control statements 8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon

More information

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Lecture 2 Tao Wang 1

Lecture 2 Tao Wang 1 Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

COMPUTER APPLICATION

COMPUTER APPLICATION Total No. of Printed Pages 16 HS/XII/A.Sc.Com/CAP/14 2 0 1 4 COMPUTER APPLICATION ( Science / Arts / Commerce ) ( Theory ) Full Marks : 70 Time : 3 hours The figures in the margin indicate full marks for

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

INTRODUCTION TO PROGRAMMING

INTRODUCTION TO PROGRAMMING FIRST SEMESTER INTRODUCTION TO PROGRAMMING COMPUTER SIMULATION LAB DEPARTMENT OF ELECTRICAL ENGINEERING Prepared By: Checked By: Approved By Engr. Najeeb Saif Engr. M.Nasim Kha Dr.Noman Jafri Lecturer

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to C++ Programming Pearson Education, Inc. All rights reserved. 1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Chapter 1 INTRODUCTION

Chapter 1 INTRODUCTION Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

6.096 Introduction to C++

6.096 Introduction to C++ MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.096 Lecture 3 Notes

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

CSc Introduction to Computing

CSc Introduction to Computing CSc 10200 Introduction to Computing Lecture 2 Edgardo Molina Fall 2011 - City College of New York Thursday, September 1, 2011 Introduction to C++ Modular program: A program consisting of interrelated segments

More information

Understanding main() function Input/Output Streams

Understanding main() function Input/Output Streams Understanding main() function Input/Output Streams Structure of a program // my first program in C++ #include int main () { cout

More information

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as: 11. Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example,

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm. CHAPTER 1&2 OBJECTIVES After completing this chapter, you will be able to: Understand the basics and Advantages of an algorithm. Analysis various algorithms. Understand a flowchart. Steps involved in designing

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Chapter 2: Overview of C++

Chapter 2: Overview of C++ Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

The Warhol Language Reference Manual

The Warhol Language Reference Manual The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

9. Arrays. Compound Data Types: type name [elements]; int billy [5];

9. Arrays. Compound Data Types: type name [elements]; int billy [5]; - 58 - Compound Data Types: 9. Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

More information

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

LAB: INTRODUCTION TO FUNCTIONS IN C++

LAB: INTRODUCTION TO FUNCTIONS IN C++ LAB: INTRODUCTION TO FUNCTIONS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 2 Introduction This lab will provide students with an

More information

Computing and Statistical Data Analysis Lecture 3

Computing and Statistical Data Analysis Lecture 3 Computing and Statistical Data Analysis Lecture 3 Type casting: static_cast, etc. Basic mathematical functions More i/o: formatting tricks Scope, namspaces Functions 1 Type casting Often we need to interpret

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING KEY CONCEPTS COMP 10 EXPLORING COMPUTER SCIENCE Lecture 2 Variables, Types, and Programs Problem Definition of task to be performed (by a computer) Algorithm A particular sequence of steps that will solve

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Typescript on LLVM Language Reference Manual

Typescript on LLVM Language Reference Manual Typescript on LLVM Language Reference Manual Ratheet Pandya UNI: rp2707 COMS 4115 H01 (CVN) 1. Introduction 2. Lexical Conventions 2.1 Tokens 2.2 Comments 2.3 Identifiers 2.4 Reserved Keywords 2.5 String

More information

Mirage. Language Reference Manual. Image drawn using Mirage 1.1. Columbia University COMS W4115 Programming Languages and Translators Fall 2006

Mirage. Language Reference Manual. Image drawn using Mirage 1.1. Columbia University COMS W4115 Programming Languages and Translators Fall 2006 Mirage Language Reference Manual Image drawn using Mirage 1.1 Columbia University COMS W4115 Programming Languages and Translators Fall 2006 Prof. Stephen Edwards Team Members: Abhilash I ai2160@columbia.edu

More information

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Functions. Lecture 6 COP 3014 Spring February 11, 2018 Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its

More information

Introduction to C ++

Introduction to C ++ Introduction to C ++ Thomas Branch tcb06@ic.ac.uk Imperial College Software Society October 18, 2012 1 / 48 Buy Software Soc. s Free Membership at https://www.imperialcollegeunion.org/shop/ club-society-project-products/software-products/436/

More information

Chapter 2. C++ Basics

Chapter 2. C++ Basics Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

More information

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur Lecture 04 Demonstration 1 So, we have learned about how to run Java programs

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Input And Output of C++

Input And Output of C++ Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

Introduction to the C++ Programming Language

Introduction to the C++ Programming Language LESSON SET 2 Introduction to the C++ Programming Language OBJECTIVES FOR STUDENT Lesson 2A: 1. To learn the basic components of a C++ program 2. To gain a basic knowledge of how memory is used in programming

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information