C# programming. Introduction. By Per Laursen

Size: px
Start display at page:

Download "C# programming. Introduction. By Per Laursen"

Transcription

1 C# programming Introduction By Per Laursen

2 Indhold The Programming Process... 3 Environment... 5 Statements... 7 Programming Fundamentals... 9 Types and Variables Simple data output on the screen Logic Pre-OO programming Object-oriented (OO) Programming The Class concept Using objects of an existing class Class definition elements Instance Fields and State Methods and Behavior Class constructors Handling conditions The if-statement Multi if/else-statements Switch-statements Handling repetition The While-loop The While-loop The For-loop Advantages of the for-loop: Arrays - Motivation Arrays - Declaration Arrays Usage The foreach-statement Lists Dictionary The concept of Inheritance Base Classes and Derived Classes The Object Class Polymorphic variables and behavior

3 Abstract methods and classes Interfaces Defensive Programming Constants Static methods and classes Enumerations

4 The Programming Process If you have never tried something like programming before, it may seem like a mysterious activity what is it really that we are doing? If we focus primarily on programming as a way of defining business logic, we are usually defining and manipulating a model of a small piece of the world What does that mean more specifically? Suppose we wish to make a program for administration of a school. Then we probably need to store certain information about students (and other things) in the program. What things are relevant to know about a student? Date of birth? Shoe size? That will depend entirely on the requirements to the system, which the users of the system will have to define. The result will probably be that certain information is needed, while some information can be left out. So, the model of a student in the program may only contain certain information; the information which is relevant in relation to the requirements. Exatcly which pieces of information we include will depend on the specific situation, i.e. the specific requirements Once we have figured out what information we need to include for each concept (student, teacher, classroom,...) in the model, we need to figure out how to represent that information in our program. We get to that part very soon! In almost all cases, the information will need to be manipulated somehow. A very simple manipulation could be just to show the information to a user. A more complex manipulation could be to change the information. For a student, some information will probably never change (the date of birth), while some information will most likely change (the number of courses taken). The way information changes can range from quite simple to very complex. The simplest change could simply be to change the current value to a new, given value. Say, when a student has taken one more course, the number of courses is increased by one. Other changes are more complex. If we e.g. store an average of the exams passed by the student, then passing an additional exam will require a recalculation of the average. In any case, there will always be rules for how to manipulate the information. In programming, we then try to translate such rules (formulated in a human language) to instructions/logic written in a language the computer can understand, in this course the language C#. This will result in writing a number of statements. 3

5 When we have large collections of statements, we can organize the statements into so-called methods, which we discuss later. 4

6 Environment What is C# Object-Oriented Language Part of Microsoft.NET Technology Related to Java and C++ Most widespread tool for C# programming is Microsoft Visual Studio (newest version is 2013), abbreviated MSVS. MSVS is a professional and commercial tool (Express version somewhat scaled down) Has quite a lot of facilities, huge knowledge base (+) Has quite a lot of facilities, not that easy to master (-) We only need to use a fraction of the functionality Understand the structure of a solution or project Being able to navigate a project Understand the role of the included files Add code to a project Compile/build a project Run a project Understand error messages from MSVS Try not to be too intimidated by the environment (tunnel vision) Top level of a C# application is a solution an application is a solution A solution can contain one or more projects. A solution consists of several files; we do not need to worry about all of the files The Solution Explorer gives us an overview of the current solution. Do not worry about what is contained in the sections Properties and References Below these sections will be a list of files with the extension.cs. These files contain the actual source code of the solution 5

7 In the Sandbox project, two such files Program.cs (generated by MSVS) InsertCodeHere.cs (made by me) The files with the.cs extension contains C# classes we get back to classes later Classes contain methods, methods contains statements. A statement is one single instruction for the program about what to do next (add two numbers, print something, etc.) How do I open a Project/Solution in MSVS? Choose File Open Project Navigate to the folder where the project is (note that a C# project is contained in a single folder in the file system) Click on the file with the same name as the project, with the extension.sln (.sln for solution ) The project should now be loaded, and you can see it in the Solution Explorer Try it for the Sandbox project Before a program can be run (executed), it must be compiled and built. MSVS will Check that the code is valid (correct syntax) Compile the code into native.net code Build the project, making it executable (black magic ) Our main concern is to enter valid (and correct) code into a project. MSVS does the rest Note the difference between valid and correct code. A piece of code is valid if it obeys the syntax for C# code, which makes it possible to compile the code. However, we only consider a piece of code to be correct if it does what it is intended to do. That is an important difference! Running a program: Press the little green triangle (or press F5) 6

8 Statements At the most fundamental level, all C# programs consist of a collection of C# statements. Statements are organized into methods and classes; we get to that later Statements are instructions to the program about what to do next examples are: Do some arithmetic or logical calculation Read or write data to e.g. a file, the screen, etc. Control the flow of execution Etc. In the Sandbox project, there is essentially just one statement. In the file InsertCodeHere.cs, we find: // The FIRST line of code should be BELOW this line Console.WriteLine("Hello Class"); // The LAST line of code should be ABOVE this line The middle line is a statement! The other two lines (green) are not statements; they are comments used for explanation Only common property for all statements: they end with a ; (semicolon) Depending on their purpose, a statement has a certain syntax. The line in the example prints the text within the in a window on the screen Syntax is very important, it MUST be obeyed 100 %. If not, you will get an error message from MSVS, if you try to run the program. In fact, If a statement is not syntactically correct, you will be notified even before running the program! Wavy red lines will appear in the code. You will be annoyed by this But there is no way around it! 7

9 DO NOT ignore the red lines! They indicate that something is wrong, so fix it right away. Can be somewhat annoying that they appear as soon as you type in a statement If an error appears hover the mouse over the error indicator. A tooltip with an error description will appear. Alternatively press F6 (build solution) a list of errors will appear. Error descriptions can sometimes be more confusing than helpful best advice is to read the code again, and use common sense Good advice when programming: Fix errors as soon as possible Keep the number of open errors minimal Test whenever possible 8

10 Programming Fundamentals What is programming? Presentation and Manipulation of data! In Web-programming terms Presentation: Front-End Manipulation (Calculation): Back-End Data manipulation can (a bit abstract) be broken down to: Receive the data needed for the calculation Store the data in memory, in suitable data structures Perform manipulation, according to business logic Store the result in suitable data structures Enable the user to access the result In back-end programming, we concentrate on: Data representation, using suitable data structures Data manipulation, using suitable methods What types of data do we wish to manipulate Numeric data Text data Logical data (true/false, Boolean logic) (Binary data, e.g. pictures) not the primary focus 9

11 Types and Variables How does a program store the data it needs to manipulate? Data is stored in the memory of the computer (RAM) What is computer memory actually? Just a lot of elements (so-called bits), each of which can be either 0 or 1. We refer to a collection of eight bit as a byte. 256 possible distinct bytes. Each byte in memory has an address. A modern computer has billions of bytes (one billion bytes = Gigabyte). Raw storage of data no matter the type amounts to setting the value of certain bytes at certain addresses in memory. This is possible, but somewhat tedious. Almost all programming languages therefore support the use of so-called variables. What is a variable actually? It is a piece of memory; i.e. a certain amount of bytes, located at a certain address in memory. In order to make it easy for humans to use variables, we can give a variable a name, instead of having to refer to the actual address in memory. Also, we do not need to define the actual address of the variable ourselves the program does that for us! In addition to this, we must choose a type for the variable. This defines the kind of data the variable can store Some types for storing data ( primitive types built-in): int : Whole numbers (no decimals), from about -2,000,000,000 to 2,000,000,000. Uses 32 bits = 4 bytes double: decimal numbers, with high precision. Why not exact values? Uses 64 bits = 8 bytes bool: A true/false value. Usually uses 4 bytes, even though it in theory should use much less 10

12 string: A text of arbitrary length. Uses one byte for each character in the string. The great advantage of having types is that we do not have to convert the data from the human type (e.g. a string) to the computer type, which is always 0/1 values. Declaration of a variable in C#: // Reserve space in memory for an int, // refer to the address by the name age int age; // Put the value 24 in the bytes // referred to by age age = 24; Note that the above types can also be written like Boolean (for bool), Int32 (for int), Double (for double) and String (for string). Choose the name that you prefer. Arithmetic A very important part of most programming tasks is arithmetic. Almost all programming languages support arithmetic, since much data manipulation has an arithmetic nature we perform calculations. The specific syntax may vary somewhat C# supports most common arithmetic operations, but there are certain operations that differ from classic arithmetic. We have already seen assignment: int age; age = 24; // Assignment, NOT an expression Very important to note that this means, set age equal to 24. It does NOT mean age is equal to 24 (which may be true or false). Simple arithmetic: int age; age = ; // Now age is 56 11

13 age = age + 10; // Now age is 66 int legalage = 18; age = legalage + 10; // Now age is 28 The right-hand side is always evaluated first, and the result can e.g. be stored in a variable. The same variable can occur on both sides of the = (assignment) sign. Note that the exact type is important. Consider this assignment: int a = 7; int b = 4; int c = a/b; // a divided by b The result is NOT 1.75 as you might expect, but 1. When doing arithmetic with integers, the result will also be an integer. Note also that there is no rounding of the result. It might seem more natural that c should become 2, but it doesn t! There are some non-standard operators in C#, for instance the remainder operator % (or modulo ) int a = 7 % 4; The result of the above is 3 the remainder when dividing 7 with 4 (integer division) Usual rules for precedence apply, so e.g. int a = 2*3+4; // This is 10, NOT 14 Some forms of conversion between types are possible, like: int a = 7; double b = a; // b is now double c = b / 4; // c is now 1.75 Type conversion is a larger subject short story: you can convert automatically when you do not lose information (7 -> 7.0 OK, 7.4 -> 7 not OK) 12

14 Use of brackets is also allowed, and follows standard rules. Good idea to use brackets to increase readability, even if they are not strictly necessary. 13

15 Simple data output on the screen Even though Back-End programming is not about GUI, we still need as part of learning about programming to output data to the screen, so we can see if our program works as expected. We have actually seen this already: Console.WriteLine("Hello Class"); So, the statement Console.WriteLine will output something on the screen. In the above example, it will output: Hello Class In general, Console.WriteLine will output the data we specify in the brackets () following the Console.WriteLine words themselves. If we write some within quotation marks, like Hello Class, then this is interpreted as data of the type string, and the string (minus the quotation marks themselves) is printed. However, Console.WriteLine is rather flexible. Consider the below piece of code: int age = 21; Console.WriteLine(age); If you execute this piece of code, the program will print: 21 Why did it not print the word age instead? In general, Console.WriteLine will print a string. If we put something else in the bracket, the program will try to convert it to a string. That is, not the variable itself, but the value of the variable. In fact, all values can be converted to a string! What was actually printed in the example is the string 21, because the value 21 was converted to the string 21. This can be done for all types of values. Also very useful is the ability to chain together values, for instance like: int age = 21; Console.WriteLine("The age is " + age); 14

16 If you execute this piece of code, the program will print: The age is 21 What is going on inside the brackets? Actually several things. First, it seems we are adding two things a string and an int. Can we even do that? In general, you can only add things of the same type. But since any value can be converted into a string, the value of age (21) can be converted into a string. So, we are then trying to add The age is and 21. Since addition of two string is defined as concatenating the string (writing the first string after the other), the result of the addition is The age is 21, which is then printed to the screen. This ability if chaining together several values (you can add as many values as you like inside the brackets) is very useful for outputting a message on the screen. 15

17 Logic The ability to work with Boolean logic is also a very important feature of C#. Boolean logic: expressions can evaluate to true or false, Becomes very important for controlling the flow of execution through control statements (later). The most common use of boolean logic is when testing for equality or testing for a relation (strictly speaking, equality is also a type of relation ) Testing for equality: Are two entities (e.g. numbers) equal to each other, or different from each other Testing for relation: Do two entities (e.g. numbers) have a particular relation to each other, like e.g. the first being greater than the other Just like for arithmetic, there are a number of relational (or logic) operators available in C# == means equal to (notice two equal-signs!!)!= means not equal to > means greater than < means smaller than >= means greater than or equal to <= means smaller than or equal to Notice that we use these operators to compare values, NOT to change values! Any expression using these relational operators will evaluate to either True or False, which are exactly the values a variable of type bool can have. int a = 7; bool b = (a == 7); bool c = (a < 7); bool d = (a <= 7); // b will be True // c will be False // d will be True 16

18 Fairly straightforward for integers, slightly more tricky for double (decimal numbers) is NOT equal to (but maybe it is close enough?) Comparing strings is also done using the == operator How can we test, if the value of a variable is inside an interval, e.g. between 10 and 20 (included)? int a = 14; bool lowlimitok = (a >= 10); bool highlimitok = (a <= 20); bool isininterval = lowlimitok && highlimitok; Notice the operator && this means and. The expression A && B is only true if A is true and b is true as well. We also have an operator this means or The expression A B is true if A is true or b is true. Note that the expression is also true if both A and B are true Finally, we have the! operator this means not The expression!a is true if A is false, and vice versa. The! operator can be said to reverse the value of an expression. or is obviously more forgiving than and. By using the operators, we can combine expressions to form quite complicated expressions bool isok = ((a < 20) && (a > 10)) (a > 60); Logical expressions become harder and harder to understand as they grow in length, beware Another way to look at the values these operators produce is to use a so-called truth table: A B A && B A B!A True True True True False 17

19 True False False True False False True False True True False False False False True Pre-OO programming We have now been introduced to types and variables, plus basic arithmetic and logic statements. In the old days of computer programming (before 1990) before so-called Object- Oriented programming this was more or less the level of abstraction programs were written at. Good: Using variables and types allows us not to worry about details of data representation and memory management. Bad: Still quite far between real-life concepts such as Student, Employee, Animal, and data representation. Note that it is quite possible to make very complex software using this old school style. Still, it was recognised that a different paradigm would make it possible to create better representations of real-life concepts in software. Object-oriented (OO) Programming In non-oo programming, data and procedures are separated No encapsulation, data belonging to the same conceptual entity is spread out over multiple data structures. In OO, data and procedures are joined into objects. The state (data) and behavior (methods) of objects of a certain type are specified in a class definition. Advantages: Code structure will be more similar to conceptual models. 18

20 Encapsulation the user of a certain class only gets to know what the user needs to know. There is freedom to change the internal structure of a class. Reuse OO contains facilities that allows reuse of code through e.g. inheritance. NOTE: OO is still just a tool for helping human beings in developing computer programs internal representation in memory is the same as before. The Class concept A class definition is a recipe or blueprint that defines how an object of this particular class will behave. It defines the objects interface to the outside world, by defining methods that a user of the object can invoke on the object. Methods are collections of statements, such that a sequence of statements can easily be executed by calling the method. By calling we mean that somebody invokes the method, thereby executing the statements in the method. It defines the internal structure of the object, more specifically the state of the object, which is represented by one or more instance fields (a special kind of variables). It may also define some internal methods, that can help the object perform its tasks, without being directly available to an external user of the object. The interface to the external user should preferably not change. If it changes, the user of the object may have to change his code, and we wish to avoid that. As long as the interface does not change, we have freedom to change the internal structure, without affecting an external user. Using objects of an existing class It is possible to start using classes without actually knowing anything about how to define classes. 19

21 We use a class by creating an object of that class. That is, an object which will behave as specified in the class definition. // Create a new Student object Student s1 = new Student(); Note that this is actually quite similar to a statement like: int age = 19; On the left-hand side, we have the declaration of a variable, consisting of a type and a name of the variable. On the right-hand side, we have an actual value which we assign to the variable. In the new case, that value is actually a new object of the type Student. The keyword new is always used when creating a new object, followed by the name of the relevant class (here Student). Now the variable s1 refers (points to) to an object of type Student, and we can begin to call methods on the object. When a variable refers to an object of a certain type, we can call methods on that object by using the so-called dot syntax: // Call a public method s1.printname(); Notice the dot (full stop) that follows the variable name. After the dot, we write the name of the method we wish to use. How can we know what methods that are available? If we have written the method ourselves; look in the code. In a more professional system, there will be some documentation of the available methods, that you can refer to. In Visual Studio, you will see that a list box of available methods pops up, as soon as you type the dot. Don t be confused! In general, in order to call a method on an object, we must suppy 20

22 The method name Any parameters needed (the parameter list) Some method may require information from the caller in order to do its job. We could imagine a method on a Student object: s1.settestresult( English, 80); This method requires the caller to provide two parameters: A string (the name of the subject which was tested for), and an int (the result of the test). Parameters are always provided inside the brackets () that follows the method name, must be provided in the correct order, and must have the correct type. Other methods may return information to the caller. This is called a return value. This will be indicated in the documentation. The special return value void means no return value. It may seem strange that you have to specify that a method does not return any information couldn t we just not write anything? The syntax of C# is so that you must specifiy what a method will return to the caller, so the word void has this special meaning of indicating that nothing comes back when calling this method. If we want to use the return value for something (we usually do), we need to pick it up in a variable: int average = s1.getaveragetestscore(); Now the variable average will have the value which was returned by the method call. Note that when a method call returns a value, that value can be used directly just as a simple variable, e.g. like: Console.WriteLine(s1.GetAverageTestScore()); We can not, however, make assignment in this way: // NOTE: This will NOT work! 21

23 s1.getaveragetestscore() = 75; Class definition elements A definition of a class is placed in a separate file, which has the extension.cs. The class definition itself must contain: The signature of the class definition. The first line will contain the name of the class; the rest of the definition (the body) must follow inside the area delimited by and public class Student // Rest of class definition is here Zero or more instance fields. An instance field is a variable, which belong specifically to an individual object. Each object of a given class will have its own set of instance fields. Setting the values of the instance fields on one object will not affect the values of the instance fields in another object. One or more public methods. The public methods are the methods that a user of the class can invoke on the object. These mehtods fall in two categories: Those that ask a question to the object (accessor), and those that may change the state of the object (mutators). Note that a method definition is also delimited by and. The collection of statements inside the delimiters is called the body of the method. Zero or more private methods. The private methods are helper methods, that help the public methods complete their tasks. They are not available to an external user. One or more constructors. A constructor is a special kind of method, that is invoked when the object is created. Its primary purpose is to ensure that the object is created in a well-defined state, i.e. give the instance variables well-defined values. 22

24 Instance Fields and State Class definition (part of ) public class Student private string name; private int yearofbirth; private int teststaken; private bool ismale; The four lines between the and the define four instance fields, that are not directly available for a user; this is indicated by the private keyword in front of each definition. In Object-Oriented programming, an instance field is typically made private, since an external user should not manipulate the values of the instance fields directly, but rather do it indirectly by calling methods. All of the values for the instance fields define the state of a specific object. Recall that state is indeed object-specific. Two different objects of the same class will have the same set of instance fields, but the values of the instance fields may be different: State of one object: John, 1988, 3, True State of a different object: Susan, 1984, 0, False 23

25 Methods and Behavior Class definition (part of ) public class Student public void PrintName() Console.WriteLine(Name); public void IncreaseTestsTaken(int NewTests) TestsTaken = TestsTaken + NewTests; public int GetTestsTaken() return TestsTaken; public bool IsStudentMale() return ismale; A method definition consists of access specifier return type method name parameters Some methods return information about the state of the object. This could simply be the value of an instance field, or it could be a compound or calculated value. Note that when a method does not return any value, we indicate this by using the void return value. 24

26 Methods that return information are often called accessors, while methods that change the state are called mutators. Some methods are neither accessors or mutators, but have some kind of side effect, like printing something (not very common in back-end). Also, some methods may both be an accessor and a mutator. Usually not recommended, since it may indicate too many responsibilities for the mehod. Note that we use the keyword public to indicate that a method is available to an external user. Only methods that an external user is intended use should be marked public. A private method can only be used by other methods in the class itself. Instance fields are usually private. We want to encapsulate the true representation. Users do not need to know that representation, and we then can change it without affecting the user. Note that we can use local variables inside a method. They are used to make caluclations easier, and are only alive while the method executes. They can not be accessed by other methods in the class, or by external users. Class constructors A constructor is invoked when we create a new instance of a class, i.e. when we create an object: // We call a constructor without parameters Student s1 = new Student(); The primary purpose of the constructor is to set the state of the object to something sensible and well-defined. In many cases, it will not make sense to create an object without having certain information available, like name and birth for a Student. We would then use a constructor with parameters: // We call a constructor with parameters Student s1 = new Student( Per, 1967, True); 25

27 We define constructors! And we may define as many as we want; one without parameters, and one (or more) with parameters. Note that if we do not define any constructors at all, there will still exist a default constructor with zero parameters, that does nothing. This is usually not a recommended approach. In general, if it does not make sense to create an object without certain information, the constructor should include parameters that represent this information. This prevents that objects can be created without this information. Example of a constructor for the Student class: public class Student public Student(string s_name, int s_yearofbirth, bool s_ismale) name = s_name; yearofbirth = s_yearofbirth; ismale = s_ismale; teststaken = 0;... // Methods will follow here Note two very important features for a constructor: It looks like a method, but it always has the same name as the class itself It has no return type You can always recognize a constructor by these features. The statements inside the constructor do exactly what we stated before: set the values of the instance fields to well-defined values. Some of these values are given from the outside, in this case name, year of birth, and the gender indicator (is male or not), while the number of tests taken is set to 0. The first three values will thus be individual for each new object, while the last one will always be set to 0 for all new Student objects. This is very typical; some initial values are individual and 26

28 require information from the caller, while other values have a sensible initial value which is the same for all objects of that class. Note also the names of the parameters in the constructor (s_ and then something). Why did we not just write the constructor like: public Student(string name, int yearofbirth, bool ismale) name = name; yearofbirth = yearofbirth; ismale = ismale; teststaken = 0; If we did this (it is actually legal syntax), then we suddenly have two things with the same name; the instance field name and the parameter name. The program cannot figure out that the left-hand side should be the instance field, while the right-hand side should be the parameter. In this case, it will use the parameter on both sides, which is not what we want. In order to solve this, we can do two things. We can use different names as in the s_ example, or we can use the keyword this. That is very commonly used, and looks like: public Student(string name, int yearofbirth, bool ismale) this.name = name; this.yearofbirth = yearofbirth; this.ismale = ismale; this.teststaken = 0; The keyword this should be understood as this specific object, so writing this-dotsomething will refer to elements inside this specific object, in this case the instance fields. It is just a matter of taste if you prefer to use the different names for instance fields and parameters approach, or the using the this keyword 27

29 approach. The latter approach is however very common used in real life, so you should know about it. Handling conditions So far, we can only define deterministic sequences of statements, that will always be executed in the same order. This sets significant constraints on the complexity of code we can write. To create more complex code, we also need statements that control the flow of other statements; that is, the order in which other statements are executed. These statements are called control statements main types of control statements are: Conditional statements Repetition statements In the category of conditional statements, the if-statement is the most prominent member Other conditional statements: if/else-statement Switch-statement The if-statement The business logic we are trying to implement will very often contain conditions. Examples: Only allow withdrawal from a bank account if the balance if larger than the amount to withdraw A car is defined as being a family car if it has at least four seats and has air conditioning The C# syntax for a conditional statement is: 28

30 if (condition) // sequence of statements Three elements in an if-statement: The keyword if The logical condition (which is a boolean expression) inside the brackets The code block inside the and Remember that a boolean (or logical) expression will always evaluate to true or false. The expression can be simple or very complex, but it must always evaluate to either true or false How will the withdraw method from the BankAccount class look, if we add the condition that the balance must be larger than or equal to the amount we are trying to withdraw? if (balance >= amount) balance = balance amount; It is very important to understand the main properties of the if-statement If the condition evaluates to true, the code inside the code block will be executed once, and the program will then continue with the statements following the ifstatement If the condition evaluates to false, the code inside the code block will be skipped (i.e. not executed), and the program will immediately continue with the statements following the if-statement If the code block only consists of one line, it is possible to write the code like this: if (balance >= amount) balance = balance amount; For readability, it is however recommended always to use the and to delimit the code block 29

31 WATCH OUT: Do not put a semicolon right after the condition. This is an error, but not a syntax error! The if-statement will then do nothing no matter the value of the condition. The if/else-statement In many situations, there will also be a natural alternative action if the condition evaluates to false. We could write this as: if (balance >= amount) balance = balance amount; if (balance < amount) Console.Writeline( ERROR!! ); This is possible, but somewhat dangerous. Can we be absolutely sure that the two conditions are mutually exclusive, and that one will always be executed? It is more convenient (and safe) to include the alternative as an integrated part of the if-statement itself this is done by adding an else-part to the statement: if (balance >= amount) balance = balance amount; else Console.Writeline( ERROR!! ); This is a safer approach; we are guaranteed that exactly one of the statements is always executed. Never zero, never both! 30

32 Nested if-statement It is also possible to nest if-statements within each other. We could e.g. have a condition like: if ((age >= 18) && (nationality == Danish )) Console.Writeline( You can vote! ); This is perfectly legal, but could also be written as: if (age >= 18) if (nationality == Danish ) Console.Writeline( You can vote! ); Notice the indentation it makes the code easier to read! In general, the code block can contain any code you want, for instance additional conditional statements, like above. Watch out for very complex combinations, though You can, of course, also nest if/else-statements 31

33 Multi if/else-statements Often you will have more than two possible alternatives. For instances translation of scores to grades: If score is above 90, grade is A If score is above 75, grade is B If score is above 55, grade is C If none of the above, grade is D This can be written as a nested if/else-statement: if (score > 90) grade = A ; else if (score > 75) grade = B ; else if (score > 55) grade = C ; else grade = D ; An alternative way of writing this is: if (score > 90) 32

34 grade = A ; else if (score > 70) grade = B ; else if (score > 55) grade = C ; else grade = D ; They are logically equivalent, but the latter can be easier to read. Mostly a matter of style and preferences. Switch-statements Sometimes the business logic has a nature where there is a distinct outcome for each possible specific value of a variable. Maybe the logic for calculating child support could be like this: Number of children Child support (kr. per month) > There is no simple formula for this dependency, so we could write it as a nested or multi if/else-statement. However, the switch-statement allows us to directly choose an alternative based on a specific value: switch (noofchildren) 33

35 case 0: childsupport = 0; break; case 1: childsupport = 1200; break; case 2: childsupport = 2000; break; case 3: childsupport = 2600; break; default: childsupport = 3000; break; There are several important properties to note about the switch-statement: At the outermost level, we use the keyword switch, followed by the expression (typically just a variable) that we switch on in brackets (). We write a case statement for each of the cases that we wish to handle individually, using the keyword case followed by the actual value, followed by : (colon, not semicolon!) Each case contains a sequence of statements, concluded by a break statement. The break statement indicates that no more of the code within the case statement should be executed. It is perfectly legal to include if-statements, etc. in the code before the break statement, but often you will put just a single line of code. If the value is not handled explicitly by a matching case statement, it is caught in the default statement, and the lines of code specified here are executed Again, there is nothing you can do in a switch-statement that you cannot do in a ifstatement; they are logically equivalent. Choose the type of statement that you feel fits the problem best, and makes the code easier to understand. 34

36 Handling repetition The if-statement allows some control of execution flow, but we still cannot easily repeat a block of statements In practice, we very often need to repeat a block of code multiple times, while some condition is true. For that purpose we have loop statements, aka repetition statements Common features: the condition! Types of repetition statements While-statement For-statement Foreach-statement The foreach-statement is closely related to so-called collections, so we only look at while- and for-statement for now. The While-loop The basic structure of the while-loop: while (condition) // Code block The code block can contain any C# code, including other control statements (code nesting) The condition is the same type as we saw for if-statements; a logical condition, that evaluates to true or false. 35

37 If the condition is true, the statements in the code block are executed once. This is called an iteration. After an iteration, the condition is checked again. If it is still true, another iteration is performed. If it is false, the code block is skipped, and the statements after the while-statement are executed. How can the value of the condition change? The value of the condition is evaluated after each execution of the code block, so some of the statements in the code block must affect the value of the condition. If no action in the code body can affect the condition, we have an infinite loop The While-loop Typical variants of while-loops: Counter-controlled while-loop: int counter = 1; while (counter < 10) // Do something... counter = counter + 1; Appropriate when we wish to repeat the code a fixed (either at compile-time or at run-time) number of times Sentinel-controlled while-loop: int grade = getgradefromuser(); while (grade >= 0) // Do something... grade = getgradefromuser(); 36

38 Appropriate when some external source (e.g. the user) controls how many times we need to execute the code. Execution stops when the user inputs a certain flag value. NB: A flag value must not also be a valid data value! Note that four properties are common for both types of loops Initialisation: Before the loop itself is entered, we usually but not always initialise some variable that is also used as part of the condition Condition: The logical condition itself, which is evaluated before performing another iteration of the loop Change: Since the condition itself is fixed, at least one of the values of the variables in the condition must have the chance to change during an iteration. Otherwise, we have an infinite loop. Formally put, the probability that something changes must be larger than 0 (zero). Code block: The sets of statements that are executed during an iteration. Some of those statements must cause the change mentioned above. The For-loop As mentioned above, a counter-controlled while-loop has four components: int counter = 1; // Initialisation while (counter < 10) // Condition // Do something... // Code block counter = counter + 1; // Change This construction is so commonly used, that another repetition statement the forloop is available for this purpose. This is the generic structure of the for-loop: for (initialisation; condition; change) // Code block 37

39 A very typical for-loop: for (int counter = 1; counter <= 10; counter++) // Code block Note that counter++ means increase the value of the variable counter by one Advantages of the for-loop: Statement header takes care of all Harder to forget e.g. the change statement Except for some very special cases, for-loops and while-loops are equivalent you can write any repetition statement as either a for-loop or a while-loop. However, using for-loops in the case of counter controlled repetitions is the common recommendation. Legal, but not advisable: for ( int grade = getgradefromuser(); grade >= 0; grade = getgradefromuser()) // Do something... In general: Use for-loops for counter-controlled repetitions Use while-loops for sentinel-controlled repetitions 38

40 Arrays - Motivation We will very often need to represent multiple entities of the same type, say collections of Integer measurement results Student objects Names as text strings Using a single variable for each instance quickly becomes quite unmanageable. Imagine having to represent 100 students in your program, and having variables like: Student s1 = ; Student s2 = ; Student s3 = ; // and so on, and so on Student s100 = ; An array object can store many instances of identical type, and still allows manipulation of individual elements. This is a much more flexible solution. Arrays - Declaration Since an array is indeed an object, it is Created with a new statement Referred to by a variable (by reference) The variable is declared as follows: int[] numberarray; // Declares a variable The creation of the array itself looks like: // Array with 10 elements numberarray = new int[10]; It is important to notice the use of []. Also note that the actual size of the array is specified in the creation, not the declaration. 39

41 An array has a fixed size, but it can be changed by using the resize method, defined in the Array class: // Resize array to 20 elements Array.resize(ref numberarray, 20); Resizing is somewhat expensive, so we should avoid it. There are other and much better ways to deal with the situation where the number of elements is not know in advance, and we will discuss them later. Arrays Usage Once the array contains elements (see later), we can use each element just as it was an ordinary variable. Each specific element is specified by its position in the array; we usually call this the index. // Add 2 to the fifth element in the array numberarray[4] = numberarray[4] + 2; Catch! The first element in the array has index 0 (zero). In an array of 10 elements, the last element has index 9! Notice that we can use array elements both on the left-hand side and the right-hand side in an expression; they act just as any other variable of that type. We can initialise an array directly in the code, if the values for all elements are fixed: // Initialises the array to five elements int[] numberarray = 12, 42, -9, 34, 10; We will very often use arrays together with some type of repetition statement int[]numberarray = new int[10]; // Do some initialisation... 40

42 for (int index = 0; index < 10; index++) Console.WriteLine(numberArray[index]); This will print out the values of each element in the array, starting from the element with index 0, up to the element with index 9 (not 10). We can ask an array how long it is, giving us some more robust code (in the sense that if we changed the length of the array in the array creation statement, we don t have to remember to change the value in the condition as well): for (int index = 0; index < numberarray.length; index++) Console.WriteLine(numberArray[index]); If we try to use an index which is out of bounds (negative or greater than the index of the last element), the code will generate a so-called exception, indicating that an error occurred during the execution of the program. The foreach-statement Iterating through all elements of an array or any type of collection is a very common task in programming. So common, that a special type of repetition statement exists for that purpose; the foreach statement Purpose; for each element in the collection, do a certain action. Syntax (example): foreach (int number in numberarray) Console.WriteLine(number); 41

43 Here the variable number will take on the value of each of the elements in the collection in this case, the type is int, but it can be anything. It is syntactically simpler, and there is no risk of getting the initialization and/or condition wrong. However, it is not as versatile as the general for-loop; use only in connection with processing of collections, and typically if we wish to do something for all the elements in the collection. Lists Arrays are useful, but they are a bit old-school in their style. Fixed-size (or resize manually ) Not much help with common tasks (insertion, search, ) The.NET Framework Class Library which is a large set of predefined classes available to the programmer provides a number of classes for handling collections of objects (so-called collection classes), which provide methods for these tasks. We do not need to worry about size issues; collections are automatically resized for us. We have many methods available for us (Add, Clear, Remove, ) One of the simplest of these collection classes is the List class. When declaring a List object, we must provide the type of the elements in the list as a parameter to the List type: List<int> numberlist; // A list of integers When we create a List object, we do not need to specify any size: numberlist = new List<int>(); 42

44 We can now call various methods on the List object, like Add Clear Contains Count Remove Note that the List class actually uses an array under the covers. Most common method is Add, this adds an element to the back of the list (list gets longer). We can use Insert to insert an element at a specific position We get hold of an element in the same way as for arrays: we use the [] notation. Again index 0 for the first element! numberlist[2] // The element with index 2 The method Contains can tell us if a specific element is contained in the list: // Is an element with value 77 in the list? numberlist.contains(77); Many useful methods in the List class; see documentation or read in pop-up list. Dictionary The List class is a significant improvement of old-school arrays, but some tasks are still somewhat difficult. We very often have classes where one instance field serves as a key to the data (i.e. uniquely identifies it). CPR for a person, license plate for a car, ISBN for a book, etc.. Very common task: Given the key, find the corresponding object. 43

45 This is a bit hard to do efficiently when using lists; you have to search through the list step by step, until you either find the correct element, or can conclude that it is not there. Code must be explicitly written, and can be rather slow (has to search through much data). The Dictionary class allows us to store a Key-Value relationship. When declaring a Dictionary object, we must provide the type of the Key and the type of the Value as parameters to the Dictionary type: // Key is String (CPR) // Value is Student object Dictionary<String, Student> students; When we wish to add a Key-Value pair to the dictionary, we use the Add method, which now takes two parameters: students.add( ,aStudent); When we wish to remove something from the dictionary, we only need to provide the key! students.remove( ); If we want to retrieve data about a student, we also only need to provide the key. The Dictionary class can then retrieve the data, and do so very efficiently! The syntax is similar to the List syntax, but instead of a numerical index, we use the key value as index: Student astudent = students[ ]; Note that if no student with that specific key exists, we get an error! We can use the method ContainsKey to check if the dictionary contains the key at all. If not, we should not try to look up the value in this way. In general, you use List: if you can look up the data by numerical index, or do not have any particular need for looking up data 44

46 Dictionary: If you need to look up data often, and there is a natural key for the data Remember to check the documentation of available methods when using these classes The concept of Inheritance Another feature of OO is code reuse we can (possibly) reuse code when we define new classes. This allows us to implement class hierarchies in C#. A derived class should have an is-a relationship to the base class. What is an is-a relationship? Consider the concepts Vehicle and Car. A car is definitely a special type of vehicle; in other words: a car is a vehicle. So Car has an isa relationship to Vehicle. This is different than the relationship between, say, Car and Wheel. A wheel is not a special type of car, but a car definitely has wheels. We say that Car has a has-a relationship to Wheel. The mechanism for implementing an is-a relationship in code is the concept inheritance; a class may inherit from a base class, meaning that all methods and instance fields in the base class are also included in the derived class Base Classes and Derived Classes Syntax for a derived class: // This class inherits from Student class GraduateStudent : Student... The derived class can use all public methods in the base class, just as any other user. It can not use private methods and instance fields, however! 45

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Introduction to Python

Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

More information

Visual Logic Instructions and Assignments

Visual Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Understanding class definitions

Understanding class definitions OFWJ_C02.QXD 2/3/06 2:28 pm Page 17 CHAPTER 2 Understanding class definitions Main concepts discussed in this chapter: fields methods (accessor, mutator) constructors assignment and conditional statement

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

3 Improving the Crab more sophisticated programming

3 Improving the Crab more sophisticated programming 3 Improving the Crab more sophisticated programming topics: concepts: random behavior, keyboard control, sound dot notation, random numbers, defining methods, comments In the previous chapter, we looked

More information

Programming in Access VBA

Programming in Access VBA PART I Programming in Access VBA In this part, you will learn all about how Visual Basic for Applications (VBA) works for Access 2010. A number of new VBA features have been incorporated into the 2010

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

Concepts and terminology in the Simula Programming Language

Concepts and terminology in the Simula Programming Language Concepts and terminology in the Simula Programming Language An introduction for new readers of Simula literature Stein Krogdahl Department of Informatics University of Oslo, Norway April 2010 Introduction

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

The first program: Little Crab

The first program: Little Crab CHAPTER 2 The first program: Little Crab topics: concepts: writing code: movement, turning, reacting to the screen edges source code, method call, parameter, sequence, if-statement In the previous chapter,

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

2 The first program: Little Crab

2 The first program: Little Crab 2 The first program: Little Crab topics: concepts: writing code: movement, turning, reacting to the screen edges source code, method call, parameter, sequence, if statement In the previous chapter, we

More information

Exercise 4 Learning Python language fundamentals

Exercise 4 Learning Python language fundamentals Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Python Loops and String Manipulation

Python Loops and String Manipulation WEEK TWO Python Loops and String Manipulation Last week, we showed you some basic Python programming and gave you some intriguing problems to solve. But it is hard to do anything really exciting until

More information

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction Standard 2: Technology and Society Interaction Technology and Ethics Analyze legal technology issues and formulate solutions and strategies that foster responsible technology usage. 1. Practice responsible

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly

More information

Part 1 Foundations of object orientation

Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 1 Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 2 1 OFWJ_C01.QXD 2/3/06 2:14 pm Page 3 CHAPTER 1 Objects and classes Main concepts discussed

More information

Course Title: Software Development

Course Title: Software Development Course Title: Software Development Unit: Customer Service Content Standard(s) and Depth of 1. Analyze customer software needs and system requirements to design an information technology-based project plan.

More information

#820 Computer Programming 1A

#820 Computer Programming 1A Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement Semester 1

More information

Introduction to Python

Introduction to Python Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

More information

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved. 1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,

More information

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,

More information

CS 111 Classes I 1. Software Organization View to this point:

CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Exercise 1: Python Language Basics

Exercise 1: Python Language Basics Exercise 1: Python Language Basics In this exercise we will cover the basic principles of the Python language. All languages have a standard set of functionality including the ability to comment code,

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources

More information

Programming and Software Development CTAG Alignments

Programming and Software Development CTAG Alignments Programming and Software Development CTAG Alignments This document contains information about four Career-Technical Articulation Numbers (CTANs) for Programming and Software Development Career-Technical

More information

CS106A, Stanford Handout #38. Strings and Chars

CS106A, Stanford Handout #38. Strings and Chars CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

Visual Basic Programming. An Introduction

Visual Basic Programming. An Introduction Visual Basic Programming An Introduction Why Visual Basic? Programming for the Windows User Interface is extremely complicated. Other Graphical User Interfaces (GUI) are no better. Visual Basic provides

More information

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT, 15.1200.40

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT, 15.1200.40 SOFTWARE DEVELOPMENT, 15.1200.40 STANDARD 1.0 APPLY PROBLEM-SOLVING AND CRITICAL THINKING SKILLS TO INFORMATION 1.1 Describe methods of establishing priorities 1.2 Prepare a plan of work and schedule information

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

Python Lists and Loops

Python Lists and Loops WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show

More information

Curriculum Map. Discipline: Computer Science Course: C++

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

Math Review. for the Quantitative Reasoning Measure of the GRE revised General Test

Math Review. for the Quantitative Reasoning Measure of the GRE revised General Test Math Review for the Quantitative Reasoning Measure of the GRE revised General Test www.ets.org Overview This Math Review will familiarize you with the mathematical skills and concepts that are important

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

Software Engineering Techniques

Software Engineering Techniques Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Java CPD (I) Frans Coenen Department of Computer Science

Java CPD (I) Frans Coenen Department of Computer Science Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials

More information

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459) Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459) Class Time: 6:00 8:05 p.m. (T,Th) Venue: WSL 5 Web Site: www.pbvusd.net/mis260 Instructor Name: Terrell Tucker Office: BDC 127

More information

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python Introduction Welcome to our Python sessions. University of Hull Department of Computer Science Wrestling with Python Week 01 Playing with Python Vsn. 1.0 Rob Miles 2013 Please follow the instructions carefully.

More information

Computer Programming I & II*

Computer Programming I & II* Computer Programming I & II* Career Cluster Information Technology Course Code 10152 Prerequisite(s) Computer Applications, Introduction to Information Technology Careers (recommended), Computer Hardware

More information

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping 3.1.1 Constants, variables and data types Understand what is mean by terms data and information Be able to describe the difference

More information

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction AppendixA1A1 Java Language Coding Guidelines A1.1 Introduction This coding style guide is a simplified version of one that has been used with good success both in industrial practice and for college courses.

More information

Part I. Multiple Choice Questions (2 points each):

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

More information

Problem Solving Basics and Computer Programming

Problem Solving Basics and Computer Programming Problem Solving Basics and Computer Programming A programming language independent companion to Roberge/Bauer/Smith, "Engaged Learning for Programming in C++: A Laboratory Course", Jones and Bartlett Publishers,

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

csce4313 Programming Languages Scanner (pass/fail)

csce4313 Programming Languages Scanner (pass/fail) csce4313 Programming Languages Scanner (pass/fail) John C. Lusth Revision Date: January 18, 2005 This is your first pass/fail assignment. You may develop your code using any procedural language, but you

More information

Computer Science for San Francisco Youth

Computer Science for San Francisco Youth Python for Beginners Python for Beginners Lesson 0. A Short Intro Lesson 1. My First Python Program Lesson 2. Input from user Lesson 3. Variables Lesson 4. If Statements How If Statements Work Structure

More information

Assignment # 2: Design Patterns and GUIs

Assignment # 2: Design Patterns and GUIs CSUS COLLEGE OF ENGINEERING AND COMPUTER SCIENCE Department of Computer Science CSc 133 Object-Oriented Computer Graphics Programming Spring 2014 John Clevenger Assignment # 2: Design Patterns and GUIs

More information

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Developed By Brian Weinfeld Course Description: AP Computer

More information

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities The classroom is set up like a traditional classroom on the left side of the room. This is where I will conduct my

More information

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc. WA2099 Introduction to Java using RAD 8.0 Student Labs Web Age Solutions Inc. 1 Table of Contents Lab 1 - The HelloWorld Class...3 Lab 2 - Refining The HelloWorld Class...20 Lab 3 - The Arithmetic Class...25

More information

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 1 Goals of the Lecture Present an introduction to Objective-C 2.0 Coverage of the language will be INCOMPLETE

More information

EKT150 Introduction to Computer Programming. Wk1-Introduction to Computer and Computer Program

EKT150 Introduction to Computer Programming. Wk1-Introduction to Computer and Computer Program EKT150 Introduction to Computer Programming Wk1-Introduction to Computer and Computer Program A Brief Look At Computer Computer is a device that receives input, stores and processes data, and provides

More information

Encoding Text with a Small Alphabet

Encoding Text with a Small Alphabet Chapter 2 Encoding Text with a Small Alphabet Given the nature of the Internet, we can break the process of understanding how information is transmitted into two components. First, we have to figure out

More information

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science updated 03/08/2012 Unit 1: JKarel 8 weeks http://www.fcps.edu/is/pos/documents/hs/compsci.htm

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

A Simple Introduction to Game Programming With C# and XNA 3.1

A Simple Introduction to Game Programming With C# and XNA 3.1 A Simple Introduction to Game Programming With C# and XNA 3.1 No Previous Programming Experience Required Curtis Bennett xnagamemaking.com A Simple Introduction to Game Programming With C# and XNA 3.1

More information

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions COMP209 Object Oriented Programming Designing Classes 2 Mark Hall Programming by Contract (adapted from slides by Mark Utting) Preconditions Postconditions Class invariants Programming by Contract An agreement

More information

Writing Simple Programs

Writing Simple Programs Chapter 2 Writing Simple Programs Objectives To know the steps in an orderly software development process. To understand programs following the Input, Process, Output (IPO) pattern and be able to modify

More information

CS193j, Stanford Handout #10 OOP 3

CS193j, Stanford Handout #10 OOP 3 CS193j, Stanford Handout #10 Summer, 2003 Manu Kumar OOP 3 Abstract Superclass Factor Common Code Up Several related classes with overlapping code Factor common code up into a common superclass Examples

More information

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June 2014. Dr.-Ing.

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June 2014. Dr.-Ing. Computers An Introduction to Programming with Python CCHSG Visit June 2014 Dr.-Ing. Norbert Völker Many computing devices are embedded Can you think of computers/ computing devices you may have in your

More information

PGR Computing Programming Skills

PGR Computing Programming Skills PGR Computing Programming Skills Dr. I. Hawke 2008 1 Introduction The purpose of computing is to do something faster, more efficiently and more reliably than you could as a human do it. One obvious point

More information

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings Object Calisthenics 9 steps to better software design today, by Jeff Bay http://www.xpteam.com/jeff/writings/objectcalisthenics.rtf http://www.pragprog.com/titles/twa/thoughtworks-anthology We ve all seen

More information

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2 Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit

More information

JetBrains ReSharper 2.0 Overview Introduction ReSharper is undoubtedly the most intelligent add-in to Visual Studio.NET 2003 and 2005. It greatly increases the productivity of C# and ASP.NET developers,

More information

Base Conversion written by Cathy Saxton

Base Conversion written by Cathy Saxton Base Conversion written by Cathy Saxton 1. Base 10 In base 10, the digits, from right to left, specify the 1 s, 10 s, 100 s, 1000 s, etc. These are powers of 10 (10 x ): 10 0 = 1, 10 1 = 10, 10 2 = 100,

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

More information

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example Overview Elements of Programming Languages Lecture 12: Object-oriented functional programming James Cheney University of Edinburgh November 6, 2015 We ve now covered: basics of functional and imperative

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT, 15.1200.40

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT, 15.1200.40 SOFTWARE DEVELOPMENT, 15.1200.40 1.0 APPLY PROBLEM-SOLVING AND CRITICAL THINKING SKILLS TO INFORMATION TECHNOLOGY 1.1 Describe methods and considerations for prioritizing and scheduling software development

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Computer Programming C++ Classes and Objects 15 th Lecture

Computer Programming C++ Classes and Objects 15 th Lecture Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline

More information

Computer Programming I

Computer Programming I Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement (e.g. Exploring

More information

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code 1 Introduction The purpose of this assignment is to write an interpreter for a small subset of the Lisp programming language. The interpreter should be able to perform simple arithmetic and comparisons

More information