text
stringlengths
1
7.76k
source
stringlengths
17
81
40. Functions Functions are essential in PHP programming. PHP provides a large library of standard functions to perform basic input/output, math, and many other functions. PHP also provides the ability to define and use your own functions. PHP does not support function overloading, so when you define a function and give ...
ComputerScienceOne_Page_569_Chunk2101
40. Functions 1 /** 2 * Computes the sum of the two arguments. 3 */ 4 function sum($a, $b) { 5 return ($a + $b); 6 } 7 8 /** 9 * Computes the Euclidean distance between the 2-D points, 10 * (x1,y1) and (x2,y2). 11 */ 12 function getDistance($x1, $y1, $x2, $y2) { 13 $xDiff = ($x1-$x2); 14 $yDiff = ($y1-$y2); 15 return s...
ComputerScienceOne_Page_570_Chunk2102
40.1. Defining & Using Functions value (you do not use the keyword void ). In practice, however, the function ends up returning null when doing this. 40.1.2. Organizing Functions There are many coding standards that guide how PHP code should be organized. We’ll only discuss a simple mechanism here. One way to organize f...
ComputerScienceOne_Page_571_Chunk2103
40. Functions 40.1.4. Passing By Reference By default, all types (including numbers, strings, etc.) are passed by value. To be able to pass arguments by reference, we need to use slightly different syntax when defining our functions. To specify that a parameter is to be passed by reference, we place an ampersand, & in fr...
ComputerScienceOne_Page_572_Chunk2104
40.1. Defining & Using Functions variables. The output to this code is as follows. x = 10, y = 20 x = 10, y = 20 x = 20, y = 10 Observe that when we invoked the function, swapByRef($x, $y); we used the same syntax as the pass by value version. The only syntax needed to pass by reference is in the function signature itse...
ComputerScienceOne_Page_573_Chunk2105
40. Functions 6 print $x."\n"; //198.01 7 8 //apr will be 0.05, terms will be 60 9 $x = getMonthlyPayment(10000); 10 print $x."\n"; //188.71 11 12 //balance will be null (0), apr will be 0.05, terms will be 60 13 $x = getMonthlyPayment(); 14 print $x."\n"; //0 but also a warning It would not be possible to invoke getMo...
ComputerScienceOne_Page_574_Chunk2106
40.2. Examples the ability to write a function to do this for us. Before we do, however, let’s think more generally. What if we wanted to round to the nearest tenth? Or what if we wanted to round to the nearest 10s or 100s place? Let’s write a general purpose rounding function that allows us to specify which decimal pl...
ComputerScienceOne_Page_575_Chunk2107
40. Functions the contents of them, thereby communicating (though not strictly returning) multiple values. Consider again the problem of computing the roots of a quadratic equation, ax2 + bx + c = 0 using the quadratic formula, x = −b ± √ b2 −4ac 2a Since there are two roots, we may have to write two functions, one for...
ComputerScienceOne_Page_576_Chunk2108
41. Error Handling & Exceptions Modern versions of PHP support error handling through the use of exceptions. PHP has several different predefined types of exceptions and also allows you to define your own exception types by creating new classes that inherit from the generic Exception class. PHP uses the standard try-catch...
ComputerScienceOne_Page_577_Chunk2109
41. Error Handling & Exceptions Elsewhere in the code, we can surround a call to readNumber() in a try-catch statement. 1 try { 2 readNumber(); 3 } catch(Exception $e) { 4 printf("Error: exception encountered: " . $e->getMessage()); 5 exit(1); 6 } In this example, we’ve simply displayed an error message to the standard...
ComputerScienceOne_Page_578_Chunk2110
41.3. Creating Custom Exceptions Now in our code we can catch and even throw this new type of exception. 1 if( $b*$b - 4*$a*$c < 0) { 2 throw new ComplexRootException("Cannot Handle complex roots"); 3 } 1 try { 2 $r1 = getRoot($a, $b, $c); 3 } catch(ComplexRootException $e) { 4 //handle here 5 } catch(Exception $e) { 6...
ComputerScienceOne_Page_579_Chunk2111
42. Arrays PHP allows you to use arrays, but PHP arrays are actually associative arrays. Though you can treat them as regular arrays and use contiguous integer indices, they are more flexible than that. Integer indices need to be contiguous or start at zero and you can use strings as indices. In addition, since PHP is d...
ComputerScienceOne_Page_581_Chunk2112
42. Arrays 1 //create an array with elements 10, 20, 30: 2 $arr = array(10, 20, 30); 3 4 //get the first element: 5 $x = $arr[0]; //x has value 10 6 7 //change the 3rd element to 5: 8 $arr[2] = 5; 9 10 //print the 2nd element: 11 printf("$arr[1] = %d\n", $arr[1]); Attempting to access an element at an invalid index doe...
ComputerScienceOne_Page_582_Chunk2113
42.2. Indexing 42.2.1. Strings as Indices Since arrays in PHP are associative arrays, keys are not limited to integers. You can also use strings as keys to index elements. 1 $arr = array(); 2 $arr[0] = 5; 3 $arr["foo"] = 10; 4 $arr["hello"] = "world"; 5 6 print "value = " . $arr["hello"]; Note that strings that contain...
ComputerScienceOne_Page_583_Chunk2114
42. Arrays 5 "baz" => "ten" 6 ); 42.3. Useful Functions There are dozens of useful functions PHP defines that can be used with arrays. We’ll only highlight a few of the more useful ones. First, the count() function can be used to compute how many elements are stored in the array. 1 $arr = array(10, 20, 30); 2 $n = count...
ComputerScienceOne_Page_584_Chunk2115
42.4. Iteration 1 $keys = array_keys($arr); 2 $vals = array_values($arr); 3 print_r($keys); 4 print_r($vals); would print Array ( [0] => foo [1] => 4 [2] => 0 [3] => baz ) Array ( [0] => 5 [1] => bar [2] => 3.14 [3] => ten ) Finally, you can use the equality operators, == and === to compare arrays. The first is the loos...
ComputerScienceOne_Page_585_Chunk2116
42. Arrays 1 //for each key value pair: 2 foreach($arr as $key => $val) { 3 print "$key maps to $val \n"; 4 } This syntax gives you access to both the key and the value for each element in the array $arr . The keyword as is used to denote the variable names $key and $val that will be changed on each iteration of the lo...
ComputerScienceOne_Page_586_Chunk2117
42.6. Removing Elements 1 $arr = array(10, 20, 30); 2 $arr[] = 5; 3 $arr[] = 15; 4 $arr[] = 25; 5 print_r($arr); By using the assignment operator but not specifying the index, the element will be added to the next available integer index. Since there were already 3 elements in the array, each subsequent element is inse...
ComputerScienceOne_Page_587_Chunk2118
42. Arrays unset($arr); destroys the entire array. It does not merely empty the array, but it unsets the variable $arr itself. 42.7. Using Arrays in Functions By default, all arguments to a function in PHP are passed by value; this includes arrays. Thus, if you make any changes to an array passed to a function, the cha...
ComputerScienceOne_Page_588_Chunk2119
42.8. Multidimensional Arrays 6 print_r($arr); 7 setFirst($arr); 8 print_r($arr); This now results in the original array being changed: Array ( [0] => 10 [1] => 20 [2] => 30 ) Array ( [0] => 5 [1] => 20 [2] => 30 ) 42.8. Multidimensional Arrays PHP supports multidimensional arrays in the sense that elements in an array...
ComputerScienceOne_Page_589_Chunk2120
42. Arrays [1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) [2] => Array ( [0] => 70 [1] => 80 [2] => 90 ) ) Alternatively, you can use two indices to get and set values from a 2-dimensional array. 1 for($i=0; $i<3; $i++) { 2 for($j=0; $j<4; $j++) { 3 $mat[$i][$j] = ($i+$j)*3; 4 } 5 } which results in: Array ( [0] => Arr...
ComputerScienceOne_Page_590_Chunk2121
43. Strings As we’ve previously seen, PHP has a built-in string type. Internally, PHP strings are simply a sequence of bytes, but for our purposes we can treat it as a 0-indexed character array. PHP strings are mutable and can be changed, but it is considered best practice to treat them as immutable and rely on the man...
ComputerScienceOne_Page_591_Chunk2122
43. Strings The last line extends the string by adding an additional character. You can even remove characters by setting them to the empty string. 1 $a = "Apples!"; 2 $a[5] = ""; 3 //a is now "Apple!" 43.2. String Functions PHP provides dozens of convenient functions that allow you to process and modify strings. We hi...
ComputerScienceOne_Page_592_Chunk2123
43.2. String Functions This would print the following fullName[0] = T fullName[1] = o fullName[2] = m fullName[3] = fullName[4] = W fullName[5] = a fullName[6] = i fullName[7] = t fullName[8] = s Concatenation PHP has a concatenation operator built into the language. To concatenate one or more strings together, you can...
ComputerScienceOne_Page_593_Chunk2124
43. Strings 1 $name = "Thomas Alan Waits"; 2 3 $firstName = substr($name, 0, 6); //"Thomas" 4 $middleName = substr($name, 7, 4); //"Alan" 5 $lastName = substr($name, 12); //"Waits" In the final example, omitting the optional length parameter results in the entire remainder of the string being returned as the substring. ...
ComputerScienceOne_Page_594_Chunk2125
43.5. Tokenizing 3 $x = strcmp("Hello", "Hello"); //x is zero 4 5 //shorter strings precede longer strings: 6 $x = strcmp("apple", "apples"); //x is negative 7 8 $x = strcmp("Apple", "apple"); //x is negative In the last example, "Apple" precedes "apple" since uppercase letters are ordered before lowercase letters acco...
ComputerScienceOne_Page_595_Chunk2126
43. Strings example, the complex expression ^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$ will match any valid numerical value including scientific notation. We will not cover regular expressions in depth, but to demonstrate their usefulness, here’s an example by which you can split a string along any and all whitespace: 1 ...
ComputerScienceOne_Page_596_Chunk2127
44. File I/O Because of the history of PHP, file functions, just like string functions, were mostly influenced by the C standard library functions and have very similar naming and usage. Writing binary or plaintext data is determined by which functions you use. In general whether or not a file input/output stream is buffer...
ComputerScienceOne_Page_597_Chunk2128
44. File I/O 1 $h = fopen("input.data", "r"); 2 while(!feof($h)) { 3 //read the next line: 4 $line = fgets($h); 5 //trim it: 6 $line = trim($line); 7 //process it, we'll just print it 8 print $line; 9 } Code Sample 44.1.: Processing a file line-by-line in PHP The two conditionals above check that the file opened successf...
ComputerScienceOne_Page_598_Chunk2129
44.2. Reading & Writing error). 1 $x = 10; 2 $y = 3.14; 3 4 //write to a plaintext file 5 fwrite($output, "Hello World!\n"); 6 fwrite($output, "x = $x, y = $y\n"); 44.2.1. Using URLs A nice feature of PHP is that you can use URLs as file names to read and write to a URL. “Reading” from a URL mean connecting to a remote ...
ComputerScienceOne_Page_599_Chunk2130
45. Objects Object-oriented features have been continually added to PHP with each new version. Starting with version 5, PHP has had a full, class-based object-oriented programming support, meaning that it facilitates the creation of objects through the use of classes and class declarations. Classes are essentially “blu...
ComputerScienceOne_Page_601_Chunk2131
45. Objects 45.1. Data Visibility Recall that encapsulation involves not only the grouping of data, but the protection of data. The class declaration above achieves the grouping of data. To provide for the protection of data, PHP defines several visibility keywords that specify what segments of code can “see” the variab...
ComputerScienceOne_Page_602_Chunk2132
45.2. Methods variables in order allow or restrict access to the methods. With methods, visibility and access determine whether or not the method may be invoked. We add to our example by providing two public methods that compute and return a result on the member variables. We also use javadoc-style comments to document...
ComputerScienceOne_Page_603_Chunk2133
45. Objects (more below) and reference the member variable via its identifier but with no dollar sign.2 45.2.1. Accessor & Mutator Methods Since we have made all the member variables private , no code outside the class may access or modify their values. It is generally good practice to make member variables private to r...
ComputerScienceOne_Page_604_Chunk2134
45.3. Constructors 11 throw new Exception("GPAs must be in [0, 4.0]"); 12 } else { 13 $this->gpa = $gpa; 14 } 15 } Controlling access of member variables through getters and setters is good encapsulation. Doing so makes your code more predictable and more testable. Making your member variables public means that any pie...
ComputerScienceOne_Page_605_Chunk2135
45. Objects 6 } Though we cannot define multiple constructors, we can use the default value feature of PHP functions to allow a user to call our constructor with a different number of parameters. For example, 1 public function __construct($firstName, $lastName, 2 $id = 0, $gpa = 0.0) { 3 $this->firstName = $firstName; 4 ...
ComputerScienceOne_Page_606_Chunk2136
45.5. Common Methods 45.5. Common Methods Another useful magic method is the __toString() method which returns a string representation of the object. Unlike the constructor method, there is no default behavior with the __toString() method. If you do not define this function, it cannot be used (and any attempts to do so ...
ComputerScienceOne_Page_607_Chunk2137
45. Objects A more flexible approach might be to allow the construction of a Student instance without having to provide a course schedule. Instead, we could add a method that allowed the outside code to add a course to the student. For example, 1 public function addCourse($c) { 2 $this->schedule[] = $c; 3 } This adds so...
ComputerScienceOne_Page_608_Chunk2138
45.7. Example 1 <?php 2 class Student { 3 4 private $firstName; 5 private $lastName; 6 private $id; 7 private $gpa; 8 private $dateOfBirth; 9 private $schedule; 10 11 public function __construct($firstName, $lastName, $id = 0, $gpa = 0.0, 12 $dateOfBirth = null, $schedule = array()) { 13 $this->firstName = $firstName; ...
ComputerScienceOne_Page_609_Chunk2139
45. Objects 47 return $this->lastName; 48 } 49 50 public function getId() { 51 return $this->id; 52 } 53 54 public function getGpa() { 55 return $this->gpa; 56 } 57 58 public function addCourse($c) { 59 $this->schedule[] = $c; 60 } 61 62 } 63 64 ?> Code Sample 45.1.: The completed PHP Student class. 576
ComputerScienceOne_Page_610_Chunk2140
46. Recursion PHP supports recursion with no special syntax necessary. However, recursion is generally expensive and iterative or other non-recursive solutions are generally preferred. We present a few examples to demonstrate how to write recursive functions in PHP. The first example of a recursive function we gave was ...
ComputerScienceOne_Page_611_Chunk2141
46. Recursion the recursive function call. 1 function recSumTail($arr, $i, $sum) { 2 if($i === count($arr)) { 3 return $sum; 4 } else { 5 return recSumTail($arr, $i+1, $sum + $arr[$i]); 6 } 7 } As a final example, consider the following PHP implementation of the naive recursive Fibonacci sequence. An additional conditio...
ComputerScienceOne_Page_612_Chunk2142
14 } 15 } 579
ComputerScienceOne_Page_613_Chunk2143
47. Searching & Sorting PHP provides over a dozen different sorting functions each with different properties and behavior. Recall that PHP has associative arrays which store elements as key-value pairs. Some functions sort by keys, others sort by the value (with some in ascending order, others in descending order). Some ...
ComputerScienceOne_Page_615_Chunk2144
47. Searching & Sorting that encapsulate more complex logic. As a simple first example, let’s write a comparator function that orders numbers in ascending order. 1 function cmpInt($a, $b) { 2 if($a < $b) { 3 return -1; 4 } else if($a === $b) { 5 return 0; 6 } else { 7 return -1; 8 } 9 } What if we wanted to order intege...
ComputerScienceOne_Page_616_Chunk2145
47.1. Comparator Functions 1 /** 2 * A comparator function to order Student instances by 3 * last name/first name in reverse alphabetic order 4 */ 5 function studentByNameCmpDesc($a, $b) { 6 return studentByNameCmp($b, $a); 7 } 1 /** 2 * A comparator function to order Student instances by 3 * id in ascending numerical ...
ComputerScienceOne_Page_617_Chunk2146
47. Searching & Sorting 47.1.1. Searching PHP provides a linear search function, array_search() that can be used to search for an element in an array. The array can be specified to use loose comparisons (default) or strict comparisons. It returns the key (i.e. index) of the first matching element it finds and false if the...
ComputerScienceOne_Page_618_Chunk2147
47.1. Comparator Functions name of the comparator function we wish to use. Recall that function names in PHP are case insensitive, though it is still best practice to match the naming. Several examples of the usage of this function are presented in Code Sample 47.1. 1 $arr = array(10, 8, 3, 12, 4, 42, 7, 108); 2 usort(...
ComputerScienceOne_Page_619_Chunk2148
Glossary abstraction a technique for managing complexity whereby levels of complexity are established so that higher levels do not see or have to worry about details at lower levels. acceptance testing a phase of software testing that is tested, usually by humans, for acceptability and whether or not it fulfills the bus...
ComputerScienceOne_Page_621_Chunk2149
Glossary bike shedding a phenomenon in projects where a disproportionate amount of time is spent on trivial matters at the expense of spending adequate resources on more important matters. The term was applied to software development by Kamp [24] but derives from Parkinson’s law of triviality [31]. bit the basic unit o...
ComputerScienceOne_Page_622_Chunk2150
Glossary closure a function with its own environment in which variables exist. 485 code smell a symptom or common pattern in source code that is usually indicative of a deeper problem or design flaw; smells are usually not bugs and may not cause problems in and of themselves, but instead indicate a pattern of carelessne...
ComputerScienceOne_Page_623_Chunk2151
Glossary dangling pointer when a reference to dynamically allocated memory is lost and the memory can no longer be deallocated, resulting in a memory leak. Alternatively, when a reference points to memory that gets deallocated or reallocated but the pointer remains unmodified, still referencing the deallocated memory. 1...
ComputerScienceOne_Page_624_Chunk2152
Glossary flowchart a diagram that represents an algorithm or process, showing steps as boxes connected by arrows which establish an order or flow. 17 foo along with “bar,” “baz,” and the full “foobar”, foo is a commonly used placeholder name in programming used to denote generic variables, functions, etc. Usually these t...
ComputerScienceOne_Page_625_Chunk2153
Glossary idiom in the context of programming, an idiom is a commonly used pattern, expression or way of structuring code that is well-understood for users of the language. For example, a for-loop structure that iterates over elements in an array. May also refer to a programming design pattern.. 315, immutable an object...
ComputerScienceOne_Page_626_Chunk2154
Glossary magic number a value used in a program with unexplained, undocumented, or am- biguous meaning, usually making the code less understandable. 258, 309, 310, 437 mantissa the part of a floating-point number consisting of its significant digits (called a significand in scientific notation). 25 map a data structure tha...
ComputerScienceOne_Page_627_Chunk2155
Glossary persistence the characteristic of data that outlives the process or program that created it; the saving of data across multiple runs of a program. 183 pointer a reference to a particular memory location in a computer. 30, 295 polymorphism an object oriented programming concept that allows you to treat a variab...
ComputerScienceOne_Page_628_Chunk2156
Glossary regression testing a type of software testing that tests software that previously passed testing but that was changed or refactored in some way. Regression testing tests to see if the software still passes the tests or not in which case it is said to have “regressed”. regular expression a sequence of character...
ComputerScienceOne_Page_629_Chunk2157
Glossary stack overflow when a program runs out of stack space, it may result in a stack overflow and the termination of the program. 205 static analysis the analysis of software that is performed on source (or object) code without actually running or compiling a program usually by using an automated tool that can detect...
ComputerScienceOne_Page_630_Chunk2158
Glossary two’s complement A way of representing signed (positive and negative) integers using the first bit as a sign bit (0 for positive, 1 for negative) and where negative numbers are represented as the complement with respect to 2n (the result of subtracting the number from 2n) . 24 type a variable’s type is the clas...
ComputerScienceOne_Page_631_Chunk2159
Acronyms ACID Atomicity Consistency Isolation Durability. ACM Association for Computing Machinery. ALU Arithmetic and Logic Unit. 4 ANSI American National Standards Institute. 253 API Application Programmer Interface. 15, 184, 436 ASCII American Standard Code for Information Interchange. 27, 66, 183, 187, 260, 325, 332...
ComputerScienceOne_Page_633_Chunk2160
Acronyms DRY Don’t Repeat Yourself. 292 EB Exabyte. ECMA European Computer Manufacturers Association. EDI Electronic Data Interchange. EOF End Of File. 184 FIFO First-In First-Out. FOSS Free and Open Source Software. FUD Fear Uncertainty Doubt. GB Gigabyte. GCC GNU Compiler Collection. GDB GNU Debugger. GIF Graphics In...
ComputerScienceOne_Page_634_Chunk2161
Acronyms JEE Java Enterprise Edition. JIT Just In Time. 12 JPEG Joint Photographic Experts Group. 183 JRE Java Runtime Environment. JSON JavaScript Object Notation. 185, 565 JVM Java Virtual Machine. 12, 383, 384, 389, 423, 431, 435, 440, 442, 449, 467, 470, 484 KB Kilobyte. 162, 460 KISS Keep It Simple, Stupid. LIFO L...
ComputerScienceOne_Page_635_Chunk2162
Acronyms POJO Plain Old Java Object. POSIX Portable Operating System Interface. 259, 306, 336, 343 RAM Random Access Memory. 5 REPL Read-Eval-Print Loop. RGB Red-Green-Blue. ROM Read-Only Memory. RTFM Read The “Freaking” Manual. RTM Read The Manual. SD Software Development. SDK Software Development Kit. 443, 444 SE Sof...
ComputerScienceOne_Page_636_Chunk2163
Acronyms UX User Experience. VLSI Very Large Scale Integration. 4 W3C World Wide Web Consortium. WWW World Wide Web. 181, 383, 497 XML Extensible Markup Language. 21, 185, 565 YAGNI You Ain’t Gonna Need It. 603
ComputerScienceOne_Page_637_Chunk2164
Index aggregation, 199 algorithm, 215 anonymous class, 484 arrays, 159 in C, 313 in Java, 439 in PHP, 547 indexing, 160 iteration, 161 multidimensional, 166 static, see static array160 arrow operator, 347 assignment operator, 33 associative arrays, 168 bandwidth, 5 basic input, 41 basic output, 41 binary, 4, 23 countin...
ComputerScienceOne_Page_639_Chunk2165
Index constructor, 199, 467 contradiction, 72 control flow, 17 copy constructor, 468 De Morgan’s laws, 72 debugger, 152 debugging, 46, 49 deep copy, 166, 353 defensive programming, 48, 84, 153 disjunction, see logical operators–or do-while loop, 100 dot operator, 346 dynamic memory, 164 dynamic programming, 208 dynamic ...
ComputerScienceOne_Page_640_Chunk2166
Index strings, 449 kilobyte, 4 lambda expression, 493 linear search, 212 C, 372 linked list, 167 linter, 152 list in Java, 444 lists, 167 literal, 34 logic errors, 48 logical operators, 65 and, 69 negation, 68 or, 70 loops, 95 do-while loop, 100 for loop, 99 foreach loop, 102 in C, 283 in Java, 415 in PHP, 527 infinite ...
ComputerScienceOne_Page_641_Chunk2167
Index loops, 527 magic method, 571 recursion, 577 strings, 557 pointers, 295 pollute the namespace, 33 polymorphism, 374 preprocessor directive, 255 primitive types, 30 printf, 43 problem solving, 2 procedural abstraction, 134, 301 program stack, 137 pseudocode, 13, 50 Quick Sort, 227 recursion, 203 C, 357 in Java, 479...
ComputerScienceOne_Page_642_Chunk2168
Index underflow, 39 underscore casing, 20 unicode, 29 upper camel casing, 20 use case, 3 vararg function, 145, 424 variable, 18 identifier, 18 naming conventions, 19 naming rules, 19 scope, 32 types, 22 variable argument function, see vararg function variables C, 260 visibility, 197, 424, 462 while loop, 97 609
ComputerScienceOne_Page_643_Chunk2169
Bibliography [1] Mars climate orbiter. http://mars.jpl.nasa.gov/msp98/orbiter/, 1999. [Online; accessed 17-March-2015]. [2] Moth in the machine: Debugging the origins of ‘bug’. Computer World Magazine, September 2011. [3] errno.h: system error numbers - base definitions reference. http://pubs.opengroup. org/onlinepubs/9...
ComputerScienceOne_Page_645_Chunk2170
Bibliography [13] Edsger W. Dijkstra. Why numbering should start at zero. https://www.cs.utexas. edu/users/EWD/transcriptions/EWD08xx/EWD831.html, 1982. [Online; accessed September 25, 2015]. [14] Bruce Eckel. Thinking in Java. Prentice Hall PTR, Upper Saddle River, NJ, USA, 4th edition, 2005. [15] Internet Goons. Do i...
ComputerScienceOne_Page_646_Chunk2171
Bibliography [29] M. V. Wilkes, D. J. Wheeler and S. Gill. The preparation of programs for an electronic digital computer, with special reference to the EDSAC and the use of a library of subroutines. Addison-Wesley Press, Cambridge, Mass., 1951. [30] United States Government Accountability Office. COLLEGE TEXTBOOKS: Stu-...
ComputerScienceOne_Page_647_Chunk2172
ELECTROMAGNETICS STEVEN W. ELLINGSON VOLUME 2
Electromagnetics_Vol2_Page_1_Chunk2173
ELECTROMAGNETICS VOLUME 2
Electromagnetics_Vol2_Page_2_Chunk2174
Publication of this book was made possible in part by the Virginia Tech University Libraries’ Open Education Initiative Faculty Grant program: http://guides.lib.vt.edu/oer/grants Books in this series Electromagnetics, Volume 1, https://doi.org/10.21061/electromagnetics-vol-1 Electromagnetics, Volume 2, https://doi.org/...
Electromagnetics_Vol2_Page_3_Chunk2175
ELECTROMAGNETICS STEVEN W. ELLINGSON VOLUME 2
Electromagnetics_Vol2_Page_4_Chunk2176
Copyright © 2020 Steven W. Ellingson iv This work is published by Virginia Tech Publishing, a division of the University Libraries at Virginia Tech, 560 Drillfield Drive, Blacksburg, VA 24061, USA (publishing@vt.edu). Suggested citation: Ellingson, Steven W. (2020) Electromagnetics, Vol. 2. Blacksburg, VA: Virginia Tec...
Electromagnetics_Vol2_Page_5_Chunk2177
v Features of This Open Textbook Additional Resources The following resources are freely available at http://hdl.handle.net/10919/93253 Downloadable PDF of the book LaTeX source files Slides of figures used in the book Problem sets and solution manual Review / Adopt /Adapt / Build upon If you are an instructor reviewin...
Electromagnetics_Vol2_Page_6_Chunk2178
Contents Preface ix 1 Preliminary Concepts 1 1.1 Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3 Coordinate Systems . . . . . . . . . . . . . . . . . . ....
Electromagnetics_Vol2_Page_7_Chunk2179
. . . . . . . . . 37 3.8 Decibel Scale for Power Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.9 Attenuation Rate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.10 Poor Conductors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....
Electromagnetics_Vol2_Page_7_Chunk2180
CONTENTS vii 5.5 Decomposition of a Wave into TE and TM Components . . . . . . . . . . . . . . . . . . . . . 70 5.6 Plane Waves at Oblique Incidence on a Planar Boundary: TE Case . . . . . . . . . . . . . . . 72 5.7 Plane Waves at Oblique Incidence on a Planar Boundary: TM Case . . . . . . . . . . . . . . . 76 5.8 Angl...
Electromagnetics_Vol2_Page_8_Chunk2181
7.2 Microstrip Line Redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 7.3 Attenuation in Coaxial Cable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 7.4 Power Handling Capability of Coaxial Cable . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 7....
Electromagnetics_Vol2_Page_8_Chunk2182
169 10.4 Reactance of the Electrically-Short Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 10.5 Equivalent Circuit Model for Transmission; Radiation Efficiency . . . . . . . . . . . . . . . . 173 10.6 Impedance of the Electrically-Short Dipole . . . . . . . . . . . . . . . . . . . . . . . . . . . 17...
Electromagnetics_Vol2_Page_8_Chunk2183
viii CONTENTS 10.7 Directivity and Gain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 10.8 Radiation Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 10.9 Equivalent Circuit Model for Reception . . . . . . . . . . . . . . . . . . . . . ....
Electromagnetics_Vol2_Page_9_Chunk2184
Preface About This Book [m0213] Goals for this book. This book is intended to serve as a primary textbook for the second semester of a two-semester course in undergraduate engineering electromagnetics. The presumed textbook for the first semester is Electromagnetics Vol. 1,1 which addresses the following topics: electri...
Electromagnetics_Vol2_Page_10_Chunk2185
x PREFACE engineering electromagnetics, nominally using Vol. 1. However, the particular topics and sequence of topics in Vol. 1 are not an essential prerequisite, and in any event this book may be useful as a supplementary reference when a different textbook is used. It is assumed that readers are familiar with the fun...
Electromagnetics_Vol2_Page_11_Chunk2186
xi Also, thanks are due to the students of the Fall 2019 section of ECE3106 at Virginia Tech who used the beta version of this book and provided useful feedback. Finally, we acknowledge all those who have contributed their art to Wikimedia Commons (https://commons.wikimedia.org/) under open licenses, allowing their wor...
Electromagnetics_Vol2_Page_12_Chunk2187
xii PREFACE About the Author [m0153] Steven W. Ellingson (ellingson@vt.edu) is an Associate Professor at Virginia Tech in Blacksburg, Virginia, in the United States. He received PhD and MS degrees in Electrical Engineering from the Ohio State University and a BS in Electrical and Computer Engineering from Clarkson Univ...
Electromagnetics_Vol2_Page_13_Chunk2188
Chapter 1 Preliminary Concepts 1.1 Units [m0072] The term “unit” refers to the measure used to express a physical quantity. For example, the mean radius of the Earth is about 6,371,000 meters; in this case, the unit is the meter. A number like “6,371,000” becomes a bit cumbersome to write, so it is common to use a prefi...
Electromagnetics_Vol2_Page_14_Chunk2189
2 CHAPTER 1. PRELIMINARY CONCEPTS meters and t is in seconds, in which case “3” really means “3 m/s.” However, if it is intended that l is in kilometers and t is in hours, then “3” really means “3 km/h,” and the equation is literally different. To patch this up, one might write “l = 3t m/s”; however, note that this doe...
Electromagnetics_Vol2_Page_15_Chunk2190
1.2. NOTATION 3 1.2 Notation [m0005] The list below describes notation used in this book. • Vectors: Boldface is used to indicate a vector; e.g., the electric field intensity vector will typically appear as E. Quantities not in boldface are scalars. When writing by hand, it is common to write “E” or “−→ E ” in lieu of “...
Electromagnetics_Vol2_Page_16_Chunk2191
4 CHAPTER 1. PRELIMINARY CONCEPTS 1.3 Coordinate Systems [m0180] The coordinate systems most commonly used in engineering analysis are the Cartesian, cylindrical, and spherical systems. These systems are illustrated in Figures 1.1, 1.2, and 1.3, respectively. Note that the use of variables is not universal; in particul...
Electromagnetics_Vol2_Page_17_Chunk2192
1.4. ELECTROMAGNETIC FIELD THEORY: A REVIEW 5 1.4 Electromagnetic Field Theory: A Review [m0179] This book is the second in a series of textbooks on electromagnetics. This section presents a summary of electromagnetic field theory concepts presented in the previous volume. Electric charge and current. Charge is the ulti...
Electromagnetics_Vol2_Page_18_Chunk2193
6 CHAPTER 1. PRELIMINARY CONCEPTS Magnetostatics. Magnetostatics is the theory of the magnetic field in response to steady current or the intrinsic magnetization of materials. Intrinsic magnetization is a property of some materials, including permanent magnets and magnetizable materials. Like the electric field, the magn...
Electromagnetics_Vol2_Page_19_Chunk2194
1.4. ELECTROMAGNETIC FIELD THEORY: A REVIEW 7 Electrostatics / Time-Varying Magnetostatics (Dynamic) Electric & magnetic independent possibly coupled fields are... Maxwell’s eqns. H S D · ds = Qencl H S D · ds = Qencl (integral) H C E · dl = 0 H C E · dl = −∂ ∂t R S B · ds H S B · ds = 0 H S B · ds = 0 H C H · dl = Ienc...
Electromagnetics_Vol2_Page_20_Chunk2195
8 CHAPTER 1. PRELIMINARY CONCEPTS units of Hz). In regions which are free of sources (i.e., charges and currents) and consisting of loss-free media (i.e., σ = 0), these equations reduce to the following: ∇· eE = 0 (1.23) ∇× eE = −jωµ eH (1.24) ∇· eH = 0 (1.25) ∇× eH = +jωǫeE (1.26) where we have used the relationships ...
Electromagnetics_Vol2_Page_21_Chunk2196
1.4. ELECTROMAGNETIC FIELD THEORY: A REVIEW 9 • Isotropy. A material that is isotropic behaves in precisely the same way regardless of how it is oriented with respect to sources, fields, and other materials. • Linearity. A material is said to be linear if its properties do not depend on the sources and fields applied to ...
Electromagnetics_Vol2_Page_22_Chunk2197
10 CHAPTER 1. PRELIMINARY CONCEPTS Image Credits Fig. 1.1: c⃝K. Kikkeri, https://commons.wikimedia.org/wiki/File:M0006 fCartesianBasis.svg, CC BY SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). Fig. 1.2: c⃝K. Kikkeri, https://commons.wikimedia.org/wiki/File:M0096 fCylindricalCoordinates.svg, CC BY SA 4.0 (htt...
Electromagnetics_Vol2_Page_23_Chunk2198
Chapter 2 Magnetostatics Redux 2.1 Lorentz Force [m0015] The Lorentz force is the force experienced by charge in the presence of electric and magnetic fields. Consider a particle having charge q. The force Fe experienced by the particle in the presence of electric field intensity E is Fe = qE The force Fm experienced by ...
Electromagnetics_Vol2_Page_24_Chunk2199
12 CHAPTER 2. MAGNETOSTATICS REDUX c⃝M. Biaek CC BY-SA 4.0. Figure 2.2: Electrons moving in a circle in a magnetic field (cyclotron motion). The electrons are produced by an electron gun at bottom, consisting of a hot cath- ode, a metal plate heated by a filament so it emits elec- trons, and a metal anode at a high volta...
Electromagnetics_Vol2_Page_25_Chunk2200