· 8 years ago · Mar 19, 2018, 01:04 PM
11.1 Understand computer storage and data types
2
3This objective may include but is not limited to: how a computer stores programs and the instructions in computer memory; memory stacks and heaps; memory size requirements for the various data storage types; numeric data and textual data.
4Computer programs, software, applications, and more
5
6You've probably heard the terms computer program, software, software programs, applications (and probably several other similar terms), and wondered what they were, or how they are different from each other.
7
8Well, essentially, they are all the same. To make a computer do anything, you have to write a computer program. A computer program is a sequence of step-by-step instructions telling it exactly what you want it to do. The computer then "executes" the program, following each step mechanically to accomplish the end goal. Computer programs are commonly termed "Software", and are written in a programming language (more on that to come).
9
10An application is a program or group of programs designed for end users. An application is usually targeted in its purpose, such as word processing, CRM, financial reporting, etc.
11Working of a computer program
12
13The first step, of course, is to actually write the program. Most of today's programming languages somewhat resemble human communication in English, but not quite! Application programmers use a language such as C, C++, or Java (there are several other languages) to create these programs. Other programs then translate the instructions into a language that a computer can understand. Smart as they seem, computers are still machines and as such, can only understand machine language. It's the software that makes the computer appear smart. Programs are stored on permanent media such as a hard disk. Upon startup, they are loaded into the computer's memory (RAM) to be executed by the computer's processor (CPU), which executes each instruction in the program.
14Types of software
15
16
17
18There are two main classes of software:
19
20Applications software and Systems software.
21
22Applications software is designed for use by end users. Examples of applications software are word processors, email tools, spreadsheets, and more. Think Microsoft Word, Outlook, Excel, Quicken, the Oracle database, web browsers, iTunes, and so on. Remember, applications software is usually intended to do a specific task. They have indirect access to the hardware via systems software.
23
24Systems software is typically written using low-level programming languages, intended to interact with computer hardware. Examples include operating systems (Windows, Linux, UNIX, Mac OS X), compilers, and utilities for managing these resources. System software controls the functioning of the computer itself, including writing to disk, reading from disk, managing computer resources, and processing other programs.
25Computer 'speak'/lingo: Machine and assembly languages, compilers, and more
26
27So, now that we know a little about the various types of software and programs, let's get acquainted with the language that the computer actually understands. The only language a computer understands is machine language. A computer executes machine language programs mechanically - that is without understanding them or thinking about them - simply because of the way it is physically put together. Machine language instructions are expressed as a sequence of entirely 0s and 1s, known as binary numbers. A computer can work directly with binary numbers because switches can easily represent these numbers: turn the switch on to represent a one and turn it off to represent a zero. So, a machine language instruction is just a sequence of zeros and ones, which corresponds to switches on the computer's motherboard - on and off. As a computer computes, these switches turn each other on or off in a pattern determined both by the way they are wired together and by the program that the computer is executing.
28
29When a machine language instruction is loaded into the CPU, all that happens is that certain switches are turned on or off in the pattern that encodes that particular instruction. The CPU is built to respond to this pattern by executing the instruction it encodes; it does this simply because of the way all the other switches in the CPU are wired together. Machine language is made up entirely of 0s and 1s. Each type of computer has its own unique machine language.
30
31Lying between machine languages and high-level programming languages is assembly language. Assembly language contains the same instructions as machine language, but the instructions and variables have names or mnemonics instead of being just 0s and 1s. Unless you want to become a systems programmer, you probably won't have much to do with an assembler.
32
33A compiler is a special program that processes programming language code into machine language that a particular type of computer can understand. All programming language "source code" (code written by a programmer) needs to be "compiled", to turn into machine language so that your CPU can actually execute the program as per instructions given.
34Programming languages
35
36A programming language is a high-level language designed to communicate instructions to a computer. Programming languages are used to create programs - either systems software or applications software. There are literally hundreds of programming languages to-date, but each has its strengths, and a few are more popular than others for a variety of reasons. The programming language to choose would depend on the type of application, the type of computer it is to run on, and of course, the expertise of the programmer!
37
38BASIC was one of the earliest programming languages. C, C++, COBOL, Java, PHP, and others are a few popular examples. Most programming languages have two components: the syntax, which is the form, and the semantics, which is the meaning. Each language has a unique set of keywords (words designed to do a task that the language understands) and a special syntax for organizing program instructions.
39C# (C sharp)
40
41C# (pronounced "C sharp") is a high-level programming language that leverages Microsoft's .NET framework. The .NET Framework is a popular development platform for building apps for Windows based platforms, and includes, the C# and Visual Basic programming languages, the common language runtime, and an extensive class library. It is designed to be a platform-independent language although it is implemented primarily on Windows. It combines features and syntax from the traditional C, C++ and Java programming languages. C# is designed to be an object-oriented language (more on that to come).
42Common Language Runtime (CLR)
43
44The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET framework and is responsible for managing the execution of .NET programs. In a process known as Just-in-time compilation, the compiled code is converted into machine instructions that, in turn, are executed by the computer's CPU. All programs written for the .NET framework are executed by the CLR.
45Pseudocode
46
47Pseudocode is a kind of structured English for describing a program. It allows us to focus on the logic of the program without being distracted by details of programming language syntax. Pseudocode should not be confused for a vague sequence of steps to achieve a task. Rather, it should describe the entire logic of what the program needs to do so that implementation becomes almost a rote mechanical task of translating each line of the pseudocode into programming code.
48
49For example, let's say you wanted to calculate the area of a circle whose radius would be input when the program is executed (at runtime). The pseudocode might read like this:
50
51SET PI = 3.14
52READ radius (r) of circle
53COMPUTE area as PI*r*r
54
55Pseudocode is easy for humans to read as compared to normal programming language code. While there is no set syntax for pseudocode, programmers do follow some general best practices. For example:
56Operation type Common Keywords
57Input READ, OBTAIN, GET
58Output PRINT, DISPLAY, SHOW
59Compute COMPUTE, CALCULATE, DETERMINE
60Initialize SET, INIT
61Add one INCREMENT, BUMP
62
63You may be wondering if anyone still writes pseudocode. While many computer science majors learn it, several experienced professionals find themselves occasionally going back to pseudocode to look at a problem from a high level, divide it into smaller levels and continue breaking it down until it's obvious to them how it will code. Most programmers agree that whether their pseudocode would depend on the scope of the programming involved. While it may be unnecessary for small projects, it could be an absolute necessity for larger ones.
64Programs and Primary storage
65
66Primary computer storage (RAM) holds data that is being actively used/processed by the Central Processing Unit (CPU). It is high-speed, relatively small, and usually volatile. The more RAM you have, the faster your programs will usually run. This is because with more RAM, you reduce the number of times your CPU must read data from your hard disk.
67
68If your CPU had to constantly access the hard drive to retrieve every piece of data it needs, it would operate very slowly. When the information is kept in memory, the CPU can access it much more quickly, making your program run faster.
69
70When a program is loaded into RAM, it makes a request for a contiguous sequence of slots, or memory cells. All types of data, including integers, decimals, character strings, true/false values, large text and images can be stored in memory cells.
71
72Here's a high level view of how a program and its variables are stored in RAM:
73
74
75Data types
76
77In the programming world, a data type is an attribute that specifies the type of data that a variable can hold: numeric data, or character data, date data and so on. Each programming language supports a variety of data types, the common ones being: Integer, Character, Decimal, Date and time, Monetary, Image, and so on. The data type determines the amount of memory that will be allocated to store corresponding data values.
78Data types in C#
79
80C# is a strongly typed language; therefore, every variable and object must have a declared type. C# supports both built-in and user defined data types. Built-in or standard data types that can be used right out of the box include, int (integer) or character (char), Boolean (true/false), decimal, and more. Examples of user-defined data types are classes or interfaces. We will be learning more about these in the chapter on object-oriented programming.
81
82Here's a list of the standard (elementary) C# and Visual Basic data types.
83Short Name Type Width (bits) Range (bits)
84byte Unsigned integer 8 0 to 255
85sbyte Signed integer 8 -128 to 127
86int Signed integer 32 -2,147,483,648 to 2,147,483,647
87uint Unsigned integer 32 0 to 4294967295
88short Signed integer 16 -32,768 to 32,767
89ushort Unsigned integer 16 0 to 65535
90long Signed integer 64 -922337203685477508 to 922337203685477507
91ulong Unsigned integer 64 0 to 18446744073709551615
92float Single-precision floating point type 32 -3.402823e38 to 3.402823e38
93double Double-precision floating point type 64 -1.79769313486232e308 to 1.79769313486232e308
94char A single Unicode character 16 Unicode symbols used in text
95string A single Unicode character 16 A string can theoretically contain up to approximately 2 billion (2 ^ 31) Unicode characters.
96bool Logical Boolean type 8 True or false
97object Object 4 Any type can be of type Object
98
99As you will see in the table above, there are several options for numeric data types. Integral types that represent only whole numbers can be of type short, integer, long and byte, while non-integral (numbers with both integer and fractional parts) types are represented by decimal, single and double data types.
100Variables
101
102So far, we've learned that programs use memory to store data and that data is categorized into data types. But how do we actually store data values and retrieve or manipulate them within the program? This is where variables come in. Think of variables like, named containers, in the computer's memory. Every variable has a name associated with it and a type.
103Local and Global variables
104
105Program variables can be either local or global in scope. A local variable is a variable that is accessible from only within a function or block in which it is declared. That is, these variables are local in scope. Local variables are declared, read, and updated without any risk of side-effects to functions outside of the block in which they are declared. Variable names may be reused in different functions.
106
107Global variables as their name suggest are accessible by every function in the program. Their scope is global from the perspective of the program. In general, the practice of using local variables is recommended over that of using global variables. The use of global variables makes programs harder to read and understand, as the value of the global variable can be changed anywhere, at any time in the program. However, they can be used effectively when accessed through special methods called access routines. These methods provide another layer of abstraction over how you use the global variables.
108Constants
109
110A constant is an immutable value that never changes during the course of program execution. This is contrast to variables whose values frequently change during a program run. In C#, constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const.
111
112For example,
113
114public const int days_week = 7;
115
116defines a constant variable of type 'int' with an assigned value of 7. This value will hold constant through the life of the program's execution.
117Type conversions
118
119We know that variables are used to store/access/manipulate some data. C# allows us to create variables of many types but, being a statically typed language, it does not allow us to assign the value of one type of variable into another type of variables. Sometimes it makes sense to convert one type to another. In fact, many programming languages do automatic conversions. This is called implicit casting or implicit conversion.
120
121For example, built in numeric types can be assigned to each other if a narrow type is being assigned to wider type. This is possible because the compiler knows that the only problem in such operations is no data will be truncated or lost, although more memory will be required to store this type. Here's an example of an implicit cast:
122
123int i = 100;
124long j = i;
125Type Casting
126
127On the other hand, if the compiler thinks that the conversion has a risk of losing information, it will not do the conversion automatically. You as a programmer will need to perform an explicit conversion called a cast or type cast. The explicit call for a conversion lets the compiler know that you are aware of the conversion request and are also aware that there could be a risk of data loss.
128
129To perform a cast in C#, specify the type that you are casting to in parentheses in front of the value or variable to be converted. For example, the code snippet below type casts a wider data type (double) to a narrower data type (int). If you didn't perform the cast, the compiler will raise an error.
130
131double x =120.45;
132int i;
133
134// Cast double to int.
135i = (int)x;
136Value and Reference types
137
138C# also supports Value and Reference types. Variables that are based on value types directly contain a value. Assigning one value type variable to another copies the contained value. For example,
139
140integer age = 10;
141
142declares a variable called 'age' of type 'integer' and assigns a value of 10 to this variable. Reference type variables are different from value type variables. Reference type variables make a copy of the reference to the variable (think of it as a pointer). You aren't copying what the pointer points to, but are making a copy of the pointer itself. This way, when the value referenced by the pointer changes, the reference variable sees it as well (the value variable won't unless the new value is specifically assigned to it).
143Memory consumption of standard data types
144
145Every standard data type is associated with a nominal storage allocation. For example, the 'int' data type's typical storage allocation is 4 bytes. When a variable of standard data type is declared, the natural assumption might be that its memory consumption is the same as its nominal storage allocation. However, this is not always the case. Platform considerations, as well as CLR's (common language runtime) memory assignment might vary. Storage assignment on 64-bit platforms is almost always different than on a 32-bit platform. In addition, depending on the circumstance, CLR might pack your declared elements as closely together as possible, or choose to align their memory addresses to natural hardware boundaries. Arrays have their own special considerations. For example, an array uses extra memory for the array itself and also for each dimension. On a 32-bit platform, the current overhead is a minimum of 20 bytes (12 bytes plus 8 bytes for each dimension). 64-bit platforms would need double the storage. Bottom line, don't calculate your storage consumption by simply adding together the nominal storage allocations of the components.
146Abstract data types
147
148While variables and arrays play a very useful role in storing data for a program's execution, they don't always work in large programs in the real world. This is because these programs evolve as a result of new requirements or constraints. A modification to a program commonly requires a change in one or more of its data structures. For example, a new attribute may be added to a customer record, or a data type may need to be changed. Rewriting every piece of code that uses these data types or variables could become a huge undertaking depending on how large and complex your code is. What we need is for a way to separate the use of a data structure from the details of its implementation.
149
150Enter the abstract data type. There are three common abstract data types, of which we will be discussing the first two shortly and in chapter 4.
151Stack
152Queues
153Search structure
154Queue
155
156A queue is a linear data type that adopts a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that once a new element is added, all elements that were added before have to be removed before the new element can be removed.
157Heap
158
159The heap is an area of primary memory (RAM) that is used for dynamic memory allocation. While using heap, blocks of memory are allocated and freed in an arbitrary order. The programmer is not aware about the pattern of allocation and size of blocks until run time. The heap is an efficient implementation of a queue.
160
161Reference type variables are stored in the heap. Variables on the heap must be destroyed manually and never fall out of scope. The data must be explicitly freed by the programmer with a delete or free command.
162Stack
163
164A stack is the Last-In-First-Out (LIFO) abstract data type and data structure. It is also an area in the RAM. It can have any abstract data types as an element. However, a stack is characterized by only two basic operations: push and pop. The push operation is used to add an item to the top of the stack, hiding any items already on the stack, or initializing the stack if it is empty. The pop operation is used to remove an item from the top of the stack, and returns this value to the caller. A pop either exposes previously hidden items or results in an empty stack.
165
166In most languages, local and value type variables are stored on the stack directly. Once the variables go out of scope, the memory allocated to them is automatically freed.
167Importance of program design
168
169When you're just starting to program, you want to jump right into coding. And that's fine if you are building small programs as part of your learning. But once you start building real world applications, take a step back and give some (a good deal actually) thought to the design. Good program design is a real challenge. Knowing how to think about programming is just one thing and easier to learn than knowing how to put programs together in a way that makes it easy to modify them later.
170
171You may hear things like "comment your code", "put in good error and exception handling", "encapsulation", "data hiding", "interfaces" from veteran programmers. However, unless you've gone through the pain of debugging a badly designed piece of code, you won't know the value of these terms. Think of good design this way -design and code in a way that when the future brings changes (which it will), your program is flexible enough to accommodate new changes without tearing your hair out. Bad design will result in inflexible code that may be impossible to keep pace with changing business requirements, and/or be impossible to understand even for your future self.
1721.2 Understand computer decision structures
173
174This objective may include but is not limited to: various decision structures used in all computer programming languages; If decision structures; multiple decision structures such as If Else and switch/Select Case; reading flowcharts; decision tables; evaluating expressions.
175Basic structure of a C# program
176
177// Namespace Declaration
178using System;
179
180// Program start class
181class SayHello
182{
183// Main begins program execution.
184public static void Main()
185{
186// Write to console
187Console.Writeline("Hello world!");
188}
189}
190
191First, all comments are preceded by //. This tells the compiler to ignore the rest of the line. Comments are for humans to understand the purpose of a piece of code.
192
193The System namespace is a commonly-used subset of the types in the .NET Framework. Namespaces are used to organize classes and uniquely identify them. The 'console' class is an example of a standard namespace class, which provides functionality for console input and output. The Writeline method is part of this class which displays the string within "".
194
195Every C# application must contain a single Main method specifying where program execution is to begin. Note that in C#, Main is capitalized.
196
197The curly braces { } define a logical block of code.
198
199Click to play video
200Classes: The Basics
201
202A class is a fundamental unit of object-oriented programming. It's a template definition (a blueprint) that enables you to create your own custom types by grouping together variables of other types, methods, and events.
203
204The first word in the class definition (preceding the keyword class) defines the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.
205
206Example of a class
207
208public class Employee
209{
210//Fields, properties, methods and events go here...
211}
212Methods: The Basics
213
214A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name. When that name is encountered in a program the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.
215
216In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.
217Comparison operators
218
219In the coming sections, we will be learning about decision structures that will help a programmer branch to a particular piece of code upon evaluating a Boolean (true or false) condition. Comparison operators help in evaluating an expression to test a condition. Here are some common comparison operators.
220Operator Meaning
221= (Equals) Equal to
222> (Greater Than) Greater than
223< (Less Than) Less than
224>= (Greater Than or Equal To) Greater than or equal to
225<= (Less Than or Equal To) Less than or equal to
226<> (Not Equal To) Not equal to
227!= (Not Equal To) Not equal to (not ISO standard)
228!< (Not Less Than) Not less than (not ISO standard)
229!> (Not Greater Than) Not greater than (not ISO standard)
230Decision structures
231
232Programming languages use control structures for decision making and for controlling the flow of a program. Decision making, as the name suggests, allows you to branch to the required section of code based on whether the controlling condition evaluates to true or false. The values in a condition are compared by using one of the comparison operators we discussed.
233
234The control structures used in C# are:
235if statements
236if-then-else statements
237switch-case statements
238The if statement
239
240The if statement is a simple decision-making statement that is used to apply conditions in the program. If a condition is true, the statement in the if block is executed; otherwise, the statement following the 'if' block is executed.
241
242The syntax of the if statement is as follows:
243
244if(condition)
245{
246//statements
247}
248
249The following example demonstrates the use of the if statement:
250
251int num1 = 10;
252if (num1 <= 10)
253{
254Console.WriteLine("Variable num1 has a value less than or equal to 10. ");
255}
256
257The above code will execute, as the value of "num1" is 10. When the program executes, it encounters the if statement and looks for a condition. The condition is that the if block will execute only if the value in the variable "num1" is less than or equal to 10. This is a Boolean condition that evaluates to TRUE in this case, so the statement within the "if true" block executes and prints out the line within quotes.
258
259Click to play video
260The if-then-else statement
261
262What if we wanted the code to do something else if the value of num1 > 10? Here's where the else part of the "if-then-else" decision structure comes in.
263
264if (num1 <= 10)
265{
266Console.WriteLine("Variable num1 has a value less than or equal to 10. ");
267}
268else
269{
270Console.WriteLine("The value in variable num1 is greater than ten. ");
271}
272
273In this case, the else block will be executed only if the value of the variable "num1" is changed to be > 10.
274
275Click to play video
276The switch statement
277
278What if you wanted multiple conditions and multiple paths? While you could technically continue to check for additional if-then-else statements within the scope of the first if statement, nested ifs can get cumbersome and confusing. It might be time to use a switch statement. Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths, and provides more clarity when reading the code.
279
280Syntax:
281
282switch ( expression )
283{
284case first-constant-expression :
285If true, execute statements in this block until the break statement
286break;
287case nth-constant-expression :
288If true, execute statements in this block until the break statement
289break;
290default :
291execute this block of statements if the switch expression does not equal any of the other constant expressions.
292}
293
294Example:
295
296Char c;
297//get the user to input a value for variable 'c'
298
299switch (c)
300{
301case 'a':
302Console.WriteLine("You entered 'a'!");
303break;
304case 'b':
305Console.WriteLine("You entered 'b'!");
306break;
307case 'c':
308Console.WriteLine("You entered 'c'!");
309break;
310
311default:
312Console.WriteLine("You entered a character other than a-b-c!");
313break;
314}
315
316
317Click to play video
318The break statement
319
320In our switch example, we introduced the break statement. The break is also known as a jump statement, which terminates the execution of the nearest enclosing looping construct or the switch statement in which it appears. Control passes to the statement that follows the terminated statement.
321The exit statement
322
323Where the break statement breaks a loop, the exit() statement terminates the program. Use this statement if you want to terminate the program under exceptional conditions.
324Flowcharts
325
326A flowchart is a graphical alternative to pseudocode that exposes an algorithm/process. It shows the steps in a process and the control flow using different types of boxes connected by arrows. A flowchart makes a process easily understood and also demonstrates the relationships between the elements of the process. Here's a simple example of a flowchart:
327
328
329
330Flowcharts do have standard symbols and shapes. Here are a few:
331Rectangle
332
333
334Alternate process
335
336
337Decision
338
339
340Data
341
342
343Document
344
345
346Multidocument
347
348
349Predefined process
350
351
352Terminator
353
354
355Manual input
356
357
358Why use flowcharts? Well, frequently it's just more effective to visualize something graphically that it is to describe it with words. Flowcharts explain a process clearly through symbols and text, providing a gist of the process flow in a single glance. Another common use for flowcharts is to create process documentation.
359Decision tables
360
361Decision tables, like flowcharts and if-then-else and switch-case statements, associate conditions with actions to perform, but in many cases do so in a more elegant way. These tables are composed of rows and columns. Each row corresponds to a single rule, with the columns defining the conditions and actions of the rules. You can add new rows to a decision table and fill in its cells to create new rules. When the rules are executed, if the conditions of a given row are met, the actions in that row are performed. A decision table is divided into four quadrants. The upper half lists the conditions being tested while the lower half lists the possible actions to be taken. Each column represents a certain type of condition or rule.
362
363Layout of a decision table:
364Condition being tested Condition Statements Condition Entries
365Possible actions to take Action Statements Action Entries
366Ternary operator (?:)
367
368A ternary operator (?:) in C and C-like languages takes the form of conditional expressions. It is called the conditional expression operator, ?:, which makes use of the following template:
369
370 (condition)?(evaluate if condition was true):(evaluate if condition was false)
371
372It means that conditions can be in-lined into expressions contrasting the 'if' statements, as shown below using C syntax:
373
374//Invalid in most programming languages
375
376 variable = if(x > 100) { "Large" } else { "Small" };
377
378//Valid
379
380 variable = (x > 100)?"Large":"Small";
381
382To accomplish a similar task as in the correct line above, use a standard if/else statement which will take more than one line of code as given below:
383
384 if (x > 100)
385 variable = Large;
386else
387 variable = Small;
388End if
389Evaluating expressions
390
391An expression is a sequence of one or more operands and zero or more operators that can be evaluated to a single value, object, method, or namespace. Here are a few examples of expressions:
392(x > 5)
393((x == 5) || ( x == 15)) && ((y > 20) && (x < 25))
394Expressions can consist of a variable, numeric constants, string literals, and other programming language specific types. They typically use or more of the comparison operators above to help with decision making in a program. Because expressions can use operators that in turn use other expressions as parameters, they can be very simple or very complex.
3951.3 Identify the appropriate method for handling repetition
396
397This objective may include but is not limited to: For loops, While loops, Do-while loops, and recursion.
398Control Structures - Loops
399
400A loop is a programming language construct that allows programmers to repeat a block of code as many times as required. The block of code can be a statement or a set of statements that will get executed several times. How many times? That depends on the type of loop. There are two major types common to most programming languages:
401Condition tested loops
402Counted Loops
403The while and do loops are examples of condition tested loops. The for and foreach loops are examples of counted loops.
404Condition tested loops
405
406A condition tested loop is one which repeats a set of instructions until a certain condition is reached. The test can be performed at the start of the loop (before any of the instructions are executed), during the loop, or at the end of the loop.
407
408The while and do loops are examples of condition tested loops.
409The while loop
410
411A while loop will check a condition before executing a block of statements. The block will be executed only if the condition evaluates true. Once the statements have executed, control returns to the beginning of the while loop to test the condition again.
412
413Because the test of a conditional expression occurs before the execution of the loop, a while statement executes zero or more times.
414
415Syntax:
416
417while (condition is true)
418{
419// statements
420
421}
422
423Example:
424
425i = 1;
426while (i <= 5)
427{
428Console.WriteLine("Hello!");
429i = i + 1;
430}
431
432In this example, the while loop will run until the value of the controlling variable i is <= 10. Initially, the value of i is 1, so when the condition is tested, it evaluates to true, entering the statement block. There are two statements in the block. It prints the first "Hello!" and then increments the value of i by 1. The loop repeats until the value of i is > 5, which translates to five "Hello!"s being printed.
433
434Click to play video
435The do..while loop
436
437The do..while loop is a programming construct that is used to execute a block of statements any number of times, but at least once. The condition will be tested only at the end of the loop. The do..while loop starts before checking a condition, executing the statements of the block at least once until it encounters the conditional statement, upon evaluation of which it will either continue or terminate the loop. The loop will be repeated while the controlling condition is true. If it becomes false, the loop is terminated and the control goes to the next statement that follows the while block.
438
439Because the test of a conditional expression occurs at the end of the loop execution, a while statement executes one or more times.
440
441Syntax:
442
443do
444{
445//statements
446} while (condition is true);
447
448Example:
449
450i = 6;
451do
452{
453Console.WriteLine ("Hello!");
454i = i + 1;
455} while (i <3);
456
457In this example, the initial value of i is 6, which is actually greater than the value being tested by the controlling condition, which says i must be < 3. This means "Hello!" will be printed at least once before the condition is checked and found to be false upon which the loop will be terminated. Use the do..while loop when you want a certain set of instructions executed at least once (and perhaps more, but a minimum of one).
458
459Click to play video
460Counted loops
461
462A counted loop is one which allows the programmer to instruct the computer to perform a set of instructions x times, where x is usually an integer value. The for and foreach loops are examples of counted loops.
463The for loop
464
465The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is useful for iterating over arrays and for sequential processing.
466
467Syntax:
468
469for (condition)
470{
471// statements
472}
473
474Because the test of a conditional expression occurs before the execution of the loop, a for statement executes zero or more times.
475
476Example:
477
478for (int i = 1; i <= 5; i++)
479{
480Console.WriteLine(i);
481}
482
483In this example, the counter has a start value of 1 and a limit of 5, so as long as the value of i is less than or equal to 5, the loop will continue to be executed. In this case, the loop will be executed a max of 5 times because when i is greater than 5, the condition becomes false and the loop is terminated. Control will pass to the next statement outside of the loop. The output of the following example would be the numbers 1 to 5 written one per line.
484
485Click to play video
486The foreach loop
487
488A foreach loop is used to iterate through the items in a list, such as an array or collections such as the ArrayList. The foreach statement is used to iterate through the array or collection to get the information needed. Note that you cannot use the foreach loop to add or remove items from the source collection to avoid unpredictable side effects. While iterating through the items of a list with a foreach loop, the list is read-only. This means that you can't modify the iteration variable within a foreach loop.
489
490Syntax:
491foreach (variable in array_list)
492{
493//statements
494}
495
496Example:
497int[] int_array = new int[] { 0, 1, 2, 3, 4, 5};
498
499foreach (int i in int_array)
500{
501System.Console.WriteLine(i);
502}
503
504Given there are 6 elements in the array, the loop will run through each element in the array and print out the numbers in the array. The counter variable can be non-integers as well.
505
506Example 2:
507string[] names = {"Sam", "Bill", "Bob", "Bonnie"};
508foreach (string empname in names)
509{
510Console.WriteLine("{0} ", empname);
511}
512Note: {0} is the placeholder for the first argument after the format string, {1} is the second, and so on. This is called composite formatting in .NET-land. For more detail refer: https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting
513Click to play video
514Recursion
515
516Recursion is a method in which solution to a problem depends on solutions to smaller instances of identical problems.
517
518"The power of recursion lies in the possibility of defining infinite sets of objects by a finite statement. Similarly, an infinite number of computations can be described by a finite recursive program, even if this program holds no explicit repetitions."
519
520Most high-level computer programming languages support recursion by letting a function call itself inside the program text. Many functional programming languages do not define looping constructs, but rely on recursion to repeatedly call code. The computability theory proves that these recursive-only languages are mathematically correspondent to the imperative languages. This means they can solve similar problems even without the control structures, such as "while" and "for".
521
522Click to play video
5231.4 Understand error handling
524
525This objective may include but is not limited to: structured exception handling.
526Error handling
527
528Error handling is an important aspect of any programming language. All good code must plan for exceptions and handle them gracefully. A good error handling mechanism will make it easier for the programmers of that language to write robust applications.
529
530With traditional programming languages such as C or Pascal, error handling was primarily handled using 'if then' statements to catch errors and then have the code branch out depending on the error. This made it very difficult for programmers particularly when they were dealing with large and complex programs.
531
532With modern programming languages such as Java and .NET (C# or VB), the approach to error handling is different. Part of the code that could potentially lead to an error is isolated in a block, and should an error occur, this error is caught and handled locally.
533Exceptions
534
535In object oriented programming, you will frequently hear the term throwing exceptions thrown around (literally!) quite a bit. So what exactly are exceptions and how are they different than errors? Exceptions are unexpected or exceptional situations that occur when a program is running.
536
537While the two are often used interchangeably, and there are multiple opinions about their differences, technically speaking there is a clear distinction. Exceptions are an abnormal condition or state of execution. Exceptions are exceptional and should be treated as such. If something exceptional happens, something that is generally "not supposed to ordinarily happen", then an exception is a reasonable thing to do. Exceptions shouldn't be coded for ordinary things that happen all the time. If we did, then they should be called 'ordinaries'.
538
539Exceptions interrupt execution up the stack until caught. An exception can be used to convey an error, but more generally is used to convey that something exceptional has occurred. An exception is usually not expected and is an out of the ordinary situation.
540
541An error on the other hand, is a known workflow within the application. For example: Username not provided during authentication is an error. A well written application will anticipate these situations and be able to handle them, usually with error codes and messages or follow a different processing route.
542
543As a rule of thumb, if you know a particular use case exists because of which the application cannot proceed normally, then consider it an error and handle the case gracefully.
544
545In C#, we use a try..catch..finally to handle errors. The first step to trapping an error is to catch it. Code that could result in an error condition is placed in the try block. If one of the statements causes an exception, the control moves to a catch block to handle that exception. Each catch block can be customized to handle a given exception to perform different logic when different exceptions occur. When an error does happen, the catch part comes into play. After all of the statements in the try block are executed successfully, control moves to the finally block which always executes even if no exception occurred.
546
547The finally part of the clause is executed regardless of whether an error occurred or not.
548
549Syntax:
550
551try
552{
553// Statements that could trigger error conditions
554}
555catch (Exception Type [ variable ])
556{
557// Statements to be executed WHEN an error occurs
558}
559finally //this block is optional
560{
561// statements that are to be run at the end of the try-catch block.
562// Remember, this block will execute regardless of whether an error has occurred.
563}
564
565Example:
566
567int[] array = new int[5];
568try
569{
570for (int i = 0; i < 6; i++)
571{
572System.Console.WriteLine(array[i]);
573}
574}
575
576catch(ArrayIndexOutOfBoundsException e){
577
578
579System.Console.WriteLine ("Oops, we went past the last element in the array! ");
580}
581
582finally //this block is optional
583{
584System.Console.WriteLine ("This is the finally block. You will see this statement regardless of whether there is an error or not.");
585}
586Structured Exception Handling
587
588An exception is an event that occurs during the execution of a program. It requires the execution of code outside the normal flow of control.
589The following are two kinds of exceptions:
590Hardware exceptions: Hardware exceptions are initiated by the CPU. They can result from the execution of certain instruction sequences, such as an attempt to access an invalid memory address.
591Software exceptions: Software exceptions are initiated explicitly by applications or the operating system.
592Structured exception handling is a mechanism used for handling both software and hardware exceptions. Structured exception handling provides support for debuggers. It is used across all programming languages and machines.
593
594Vectored exception handling is an extension to structured exception handling. The system also supports termination handling, which ensures that whenever a guarded body of code is executed, a specified block of termination code is also executed. The termination code is executed regardless of how the flow of control leaves the guarded body.
595
596Structured exception handling and termination handling mechanisms are used to create consistently robust and reliable applications.
597Chapter Summary
598
599In this chapter, we learned about:
600Understand computer storage and data types
601Understand computer decision structures
602Identify the appropriate method for handling repetition
603Understand error handling
604Glossary
605Constant
606
607A constant is an immutable value that never changes during the course of program execution.
608Data type
609
610A data type is an attribute that specifies the type of data that a variable can hold: numeric data, or character data, date data and so on. The data type determines the amount of memory that will be allocated to store corresponding data values.
611Exceptions
612
613Exceptions are unexpected or exceptional situations that occur when a program is running.
614Flowchart
615
616A flowchart is a graphical alternative to pseudocode that exposes an algorithm/process.
617Programming language
618
619A programming language is a high-level language designed to communicate instructions to a computer.
620Recursion
621
622Recursion is a method in which solution to a problem depends on solutions to smaller instances of identical problems.