text stringlengths 1 7.76k | source stringlengths 17 81 |
|---|---|
20. Arrays **m m[0] m[1] m[2] m[3] m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2] m[3][0] m[3][1] m[3][2] Figure 20.2.: Contiguous Two Dimensional Array. The initial pointer-to-pointers m is initialized to an array of pointers, m[0]..m[3] . A 4 × 3 contiguous array is created and each of the po... | ComputerScienceOne_Page_358_Chunk1901 |
21. Strings C has no built-in string type. Instead, strings are represented as arrays of char elements. They differ from, say arrays of int or double types, however, in that they are null terminated arrays. The end of the string must always be denoted with a null-terminating character, '\0' (the 0 valued character in th... | ComputerScienceOne_Page_359_Chunk1902 |
21. Strings This syntax can only be used when creating static strings (they are allocated on the stack and locally scoped). The compiler is able to scan the string literal and determine how many characters are needed and even inserts the null-terminating character for us. Thus, the length of the two strings in the exam... | ComputerScienceOne_Page_360_Chunk1903 |
21.2. String Library on the right-hand-side is copied into the variable on the left-hand-side). Moreover, the second argument has been marked as const indicating that it will not be changed. The contents of the first argument will be changed since we are copying a string into it, erasing whatever contents it had prior. ... | ComputerScienceOne_Page_361_Chunk1904 |
21. Strings function provided by the string library to determine its length, size_t strlen(const char *s); Recall that size_t can essentially be treated as an integer, indicating the number of bytes in the passed string. Since a character is a single byte, this function tells us how many character are in the given stri... | ComputerScienceOne_Page_362_Chunk1905 |
21.2. String Library Byte-Limited Versions C also provides several byte-limited versions of the copy and concatenation functions: char *strncpy(char *dest, const char *src, size_t n); char *strncat(char *dest, const char *src, size_t n); They work similarly in that they copy/concatenate the source, src string into the ... | ComputerScienceOne_Page_363_Chunk1906 |
21. Strings using the referencing operator, we can turn the 8th character into a character pointer, &name[7] . A full example: 1 char name[] = "Thomas Alan Waits"; 2 char *middleName = (char *) malloc(sizeof(char) * 5); 3 strncpy(middleName, &name[7], 5); 4 middleName[4] = '\0'; 5 //middleName now holds "Alan" In the c... | ComputerScienceOne_Page_364_Chunk1907 |
21.4. Comparisons 11 strcpy(names[3], "Marie Curie"); 12 strcpy(names[4], "Hedy Lamarr"); 21.4. Comparisons When comparing strings in C, we cannot use the numerical comparison operators such as == , or < . Because strings are represented as arrays, using these operators actually compares the variable’s memory addresses... | ComputerScienceOne_Page_365_Chunk1908 |
21. Strings 4 x = strcmp("Hello", "Hello"); //x is zero 5 6 //shorter strings precede longer strings: 7 x = strcmp("apple", "apples"); //x is negative 8 //uppercase precede lowercase: 9 x = strcmp("Apple", "apple"); //x is negative In the last example, "Apple" precedes "apple" since uppercase letters are ordered before... | ComputerScienceOne_Page_366_Chunk1909 |
21.6. Tokenizing The sscanf() function differs in its first argument: the string that contains the value you want to parse. Otherwise, the second two arguments are as in scanf() : the format (as a string) and the variable(s) that the results should be stored in (passed by reference). Likewise, there is a companion sprint... | ComputerScienceOne_Page_367_Chunk1910 |
21. Strings more tokens are in the string. This logic can be used to write a while loop to iterate over each token. Consider the following example. 1 char data[] = "Smith,Joe,12345678,1985-09-08"; 2 char *token = NULL; 3 //make the initial call to strtok: 4 token = strtok(data, ","); 5 while(token != NULL) { 6 printf("... | ComputerScienceOne_Page_368_Chunk1911 |
22. File I/O C provides several functions to manipulate and process files. Like other I/O functions, these are all defined in the standard input/output library, stdio.h . Writing binary or plaintext data is determined by which functions you use. Whether or not a file input/output stream is buffered or unbuffered is determin... | ComputerScienceOne_Page_369_Chunk1912 |
22. File I/O 12 fprintf(stderr, "Unable to open output file"); 13 exit(1); 14 } The two checks above check that the file opened successfully. If the file opening failed, fopen() returns NULL . Opening a file can fail for a number of reasons. On POSIX systems for example, additional information can be obtained by accessing... | ComputerScienceOne_Page_370_Chunk1913 |
22.2. Reading & Writing 5 fprintf(output, "Hello World!\n"); 6 fprintf(output, "x = %d, y = %f\n", x, y); 7 8 //read from a plaintext file 9 fscanf(input, "%d", &x); 10 fscanf(input, "%lf", &y); 11 12 //these are equivalent to printf, scanf: 13 fprintf(stdout, "Please enter an integer:"); 14 fscanf(stdin, "%d", &x); Us... | ComputerScienceOne_Page_371_Chunk1914 |
22. File I/O 4 //read the first line 5 char *s = fgets(line, 1000, input); 6 while(s != NULL) { 7 8 //chomp the endline character from line: 9 line[strlen(line)-1] = '\0'; 10 11 //process the current buffer 12 //for demonstration, we simply print it: 13 printf("line = %s\n", line); 14 15 //read the next line 16 s = fge... | ComputerScienceOne_Page_372_Chunk1915 |
22.3. Closing Files accommodate the data you are reading into it. 1 int x = 10; 2 3 FILE *binaryOutputFile = fopen("demo.bin", "w"); 4 5 //write a single int to a file: 6 fwrite(&x, sizeof(int), 1, binaryOutputFile); 7 8 FILE *binaryInputFile = fopen("input.bin", "r"); 9 10 //read a single int from the file: 11 fread(&... | ComputerScienceOne_Page_373_Chunk1916 |
23. Structures Strictly speaking, C is not an object-oriented programming language, it is an imperative (or, relatedly a structured or procedural) programming language. This means that C can be characterized as a language that changes a program’s state through statements and the use of function calls. Though C does not... | ComputerScienceOne_Page_375_Chunk1917 |
23. Structures • The elements of the structure (also referred to as components or members) are included inside curly brackets, delimited using semicolons (in contrast to an enu- merated type which is a list, these elements do not constitute a list). • A structure may contain any number of elements of any type. • The na... | ComputerScienceOne_Page_376_Chunk1918 |
23.1. Defining Structures 1 typedef struct Student { 2 ... 3 } Student; Which places the Student identifier in both the global space and in the “structure” space. Which style of declaration you use depends on several factors, but for simplicity we’ll stick with the first style. In addition, you may see some older naming c... | ComputerScienceOne_Page_377_Chunk1919 |
23. Structures 1 typedef struct { 2 int id; 3 char *firstName; 4 char *lastName; 5 double gpa; 6 Date dateOfBirth; 7 } Student; Code Sample 23.1.: A Student structure declaration 1 typedef struct { 2 int year; 3 int month; 4 int date; 5 } Date; Once we have defined a structure we can use it as we would a normal variable... | ComputerScienceOne_Page_378_Chunk1920 |
23.2. Usage These static declarations will allocate enough space on the stack to hold all of the data associated with the structures (the two char * pointers, int , and double and the three int variables in the Date structure). However, the values stored in each of the structure’s member variables are undefined. With th... | ComputerScienceOne_Page_379_Chunk1921 |
23. Structures Student *s = (Student *) malloc(sizeof(Student) * 1); The multiplication by 1 in this example is not strictly necessary, but emphasizes the fact that we are allocating space for one structure and not an array of structures. Initializing a dynamically allocated structure like this does not initialize any ... | ComputerScienceOne_Page_380_Chunk1922 |
23.2. Usage we have to change the pointer into a “normal” structure by dereferencing it, then we can use the dot operator. However, the dot operator has a higher order of precedence than the dereferencing operator, thus parentheses are required: 1 Student *s = ...; 2 (*s).id = 87654321; This can be a bit unwieldy, so C... | ComputerScienceOne_Page_381_Chunk1923 |
23. Structures 23.3. Arrays of Structures Just as we can create arrays of built-in types such as integers, we can also create arrays of our user-defined structures. As an example, the following creates an array of 10 Student structures. Once created, we can treat them like any other array. 1 Student *roster = (Student *... | ComputerScienceOne_Page_382_Chunk1924 |
23.3. Arrays of Structures 3 roster[i] = (Student *) malloc(sizeof(Student) * 1); 4 } 5 6 //access each as pointers and use the arrow operator 7 roster[0]->id = 87654321; 8 roster[0]->gpa = 4.0; 9 10 //swap the first two *pointers*: 11 Student *temp = roster[0]; 12 roster[0] = roster[1]; 13 roster[1] = temp; As in the ... | ComputerScienceOne_Page_383_Chunk1925 |
23. Structures Student *roster roster[0] (Student) roster[1] (Student) roster[2] (Student) ... roster[n-1] (Student) 40 bytes 40 bytes 40 bytes 40 bytes Figure 23.1.: An array of structures. Each record is stored in a contiguous manner one after the other. Student **roster roster[0] (Student*) roster[1] (Student*) rost... | ComputerScienceOne_Page_384_Chunk1926 |
23.4. Using Structures With Functions Then, we can declare an array of Student pointers as well. 1 Student **roster = (Student **) malloc(n * sizeof(Student *)); But now we need to make each roster[i] pointer point to the i-th record in rosterData . Each record, rosterData[i] is a regular structure, but we need a point... | ComputerScienceOne_Page_385_Chunk1927 |
23. Structures Student **roster roster[0] (Student*) roster[1] (Student*) roster[2] (Student*) ... roster[n-1] (Student*) Student *rosterData roster[0] (Student) roster[1] (Student) roster[2] (Student) ... roster[n-1] (Student) 40 bytes 40 bytes 40 bytes 40 bytes 8 bytes Figure 23.3.: Hybrid Array of Structures. The ro... | ComputerScienceOne_Page_386_Chunk1928 |
23.4. Using Structures With Functions 23.4.1. Factory Functions Properly creating and initializing structure instances can be a complex and tedious task. However, it is likely that we will need to repeat this operation over and over. We can simplify our task if we write a utility function that creates a structure insta... | ComputerScienceOne_Page_387_Chunk1929 |
23. Structures function. 1 /** 2 * This function creates a new, deep copy of a Student 3 * structure . 4 */ 5 Student * copyStudent(const Student *s) { 6 return createStudent(s->firstName, s->lastName, s->id, s->gpa); 7 } 23.4.2. To String Functions Another common operation with structures is to output their data as a ... | ComputerScienceOne_Page_388_Chunk1930 |
23.4. Using Structures With Functions 19 } Here, we’ve utilized a variation on the familiar printf() function, sprintf() which “prints” the result not to the standard output or a file, but to a string, specified as the first argument. This function would end up returning a string similar to the following for our previous ... | ComputerScienceOne_Page_389_Chunk1931 |
23. Structures 4 */ 5 double computeAverageGpa(const Student **roster, int n) { 6 double sum = 0.0; 7 int i; 8 for(i=0; i<n; i++) { 9 sum += roster[i]->gpa; 10 } 11 return sum / n; 12 } The only difference here is in how we access the gpa member variable using the arrow operator instead of the dot operator. 356 | ComputerScienceOne_Page_390_Chunk1932 |
24. Recursion C supports recursion with no special syntax necessary. However, as a structured, procedural language, 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 C. The first example of... | ComputerScienceOne_Page_391_Chunk1933 |
24. Recursion This example was not tail-recursive as the recursive call was not the final operation (the sum was the final operation). To make this function tail recursive, we can carry the summation through to each function call ensuring that the summation is done prior to the recursive function call. 1 int recSumTail(c... | ComputerScienceOne_Page_392_Chunk1934 |
6 } else if(table[n] > 0) { 7 return table[n]; 8 } else { 9 int a = fibonacciMemoization(n-1, table); 10 int b = fibonacciMemoization(n-2, table); 11 int result = (a + b); 12 table[n] = result; 13 return result; 14 } 15 } It is the responsibility of the calling function to ensure that the table array is large enough to... | ComputerScienceOne_Page_393_Chunk1935 |
25. Searching & Sorting The standard C library provides several functions to search and sort arrays of any type of element including int , double , or even user-defined structures such as our Student example from Chapter 23. These functions are able to operate on any type of array because they take generic void * pointe... | ComputerScienceOne_Page_395_Chunk1936 |
25. Searching & Sorting – It returns something positive, > 0 if a comes after b (that is, a > b) Note that there is no guarantee on the value’s magnitude, it does not necessarily return −1 or +1; it just returns something negative or positive. We’ve previously seen this pattern when comparing strings. The standard stri... | ComputerScienceOne_Page_396_Chunk1937 |
25.1. Comparator Functions 4 if(*x < *y) { 5 return -1; 6 } else if(*x == *y) { 7 return 0; 8 } else { 9 return 1; 10 } 11 } What if we wanted to order integers in the opposite order? We could write another comparator in which the comparisons or values are reversed. Even simpler, we could reuse the comparator above and... | ComputerScienceOne_Page_397_Chunk1938 |
25. Searching & Sorting Sample 23.1. The following code samples demonstrate various ways of ordering Student structures based on one or more of their components. 1 /** 2 * A comparator function to order Student structures by 3 * last name/first name in alphabetic order 4 */ 5 int studentByNameCmp(const void *s1, const ... | ComputerScienceOne_Page_398_Chunk1939 |
25.2. Function Pointers 12 } else { 13 return 1; 14 } 15 } 1 /** 2 * A comparator function to order Student structures by 3 * GPA in descending order 4 */ 5 int studentGpaCmp(const void *s1, const void *s2) { 6 const Student *a = (const Student *)s1; 7 const Student *b = (const Student *)s2; 8 if(a->gpa > b->gpa) { 9 r... | ComputerScienceOne_Page_399_Chunk1940 |
25. Searching & Sorting reference a memory location that, instead of containing variables, contains executable code, in particular a function. This is what a function pointer does: it points to a memory location where the code for the function is stored. To declare a function pointer, we need to specify more informatio... | ComputerScienceOne_Page_400_Chunk1941 |
25.2. Function Pointers event. Suppose we create a button; we need to be able to specify what happens when that button gets clicked. We do so by providing a function as a callback to a registration function that associates the “click” event with the provided function. Thus, whenever a user clicks the button, the callba... | ComputerScienceOne_Page_401_Chunk1942 |
25. Searching & Sorting There are a couple of issues here that we have to deal with. When working with generic void * pointers in C and using arrays, you cannot simply index using the usual 0, 1, 2, etc. indices. Recall that when elements are stored in an array, the index represents an offset of a memory address. If the... | ComputerScienceOne_Page_402_Chunk1943 |
25.2. Function Pointers 1 int getMax(const void *arr, int n, size_t size, 2 int(*cmp)(const void *, const void *)) { 3 int i, maxIndex = 0; 4 for(i=1; i<n; i++) { 5 if(cmp(arr + maxIndex * size, arr + i * size) < 0) { 6 //we've found something larger, update the max_index: 7 maxIndex = i; 8 } 9 } 10 return maxIndex; 11... | ComputerScienceOne_Page_403_Chunk1944 |
25. Searching & Sorting Thus the code above will return an index corresponding to the last student in lexicographic ordering of their name. Similarly, if we had used the studentGpaCmp() comparator instead, getMax() would have returned an index for the student with the lowest GPA as this comparator ordered highest to lo... | ComputerScienceOne_Page_404_Chunk1945 |
25.2. Function Pointers 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int function01(int a, double b); 5 void function02(double x, char y); 6 7 void runAFunction(int (*theFunc)(int, double)); 8 9 int main(int argc, char **arg) { 10 11 int i = 5; 12 double d = 3.14; 13 char c = 'Q'; 14 15 //calling a function normally.... | ComputerScienceOne_Page_405_Chunk1946 |
25. Searching & Sorting 25.3. Searching & Sorting We now turn our attention to the search and sorting functions provided by the standard library. Each function is a generic implementation that takes advantage of function pointers and comparator functions. 25.3.1. Searching Linear Search The C search library, search.h p... | ComputerScienceOne_Page_406_Chunk1947 |
25.3. Searching & Sorting In the same library, there is another linear search function: 1 void *lsearch(const void *key, 2 void *base, 3 size_t *nmemb, 4 size_t size, 5 int(*compar)(const void *, const void *)); It differs in that if it does not find a matching element, it still returns NULL but also attempts to insert t... | ComputerScienceOne_Page_407_Chunk1948 |
25. Searching & Sorting 25.3.2. Sorting The standard library also provides a generic sorting function, qsort() . Though the name suggests a Quick Sort implementation, it does not necessarily have to be (it was when the function was originally designed). Modern implementations of qsort() may implement alternatives such ... | ComputerScienceOne_Page_408_Chunk1949 |
25.3. Searching & Sorting 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <search.h> 4 5 #include "student.h" 6 7 int main(int argc, char **argv) { 8 9 int n = 0; 10 Student *roster = loadStudents("student.data", &n); 11 int i; 12 size_t numElems = n; 13 14 15 printf("Roster: \n"); 16 printStudents(roster, n); 17... | ComputerScienceOne_Page_409_Chunk1950 |
25. Searching & Sorting 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #include "student.h" 5 6 7 int main(int argc, char **argv) { 8 9 int n = 0; 10 Student *roster = loadStudents("student.data", &n); 11 int i; 12 size_t numElems = n; 13 14 printf("Roster: \n"); 15 printStudents(roster, n); 16 17 printf("\n\n\nSorted ... | ComputerScienceOne_Page_410_Chunk1951 |
25.4. Other Considerations 25.4. Other Considerations 25.4.1. Sorting Pointers to Elements Recall that it is sometimes preferable to maintain an array of pointers to structures rather than an array of structures. Sorting is a scenario where this is particularly true. When sorting an array of structure elements, the ent... | ComputerScienceOne_Page_411_Chunk1952 |
25. Searching & Sorting instead of the entire structure. This is far cheaper as a memory address is likely to be far smaller than the actual structure it points to. This is essentially equivalent to the string scenario: we have an array of pointers to be sorted, our comparator function then needs to deal with pointers ... | ComputerScienceOne_Page_412_Chunk1953 |
25.4. Other Considerations elements. That is, we could order all NULL pointers before non- NULL elements (and consider all NULL pointers to be equal). An example with respect to our Student structure is given in Code Snippet 25.6. 1 int studentPtrLastNameCmpWithNulls(const void *s1, const void *s2) { 2 const Student *a... | ComputerScienceOne_Page_413_Chunk1954 |
Part II. The Java Programming Language 381 | ComputerScienceOne_Page_415_Chunk1955 |
26. Basics The Java programming language was developed in the early 1990s at Sun Microsystems by James Gosling, Mike Sheridan, and Patrick Naughton. Its original intention was to enable cable box sets to be more interactive. By the mid-90s, Java was retargeted toward the WWW. The first public release came on May 23, 199... | ComputerScienceOne_Page_417_Chunk1956 |
26. Basics 1 package unl.cse; //package declaration 2 3 //imports would go here 4 5 /** 6 * A basic hello world program in Java 7 */ 8 public class HelloWorld { 9 10 //static main method 11 public static void main(String args[]) { 12 System.out.println("Hello World!"); 13 } 14 15 } Code Sample 26.1.: Hello World Progra... | ComputerScienceOne_Page_418_Chunk1957 |
26.2. Basic Elements We will not focus on any particular development environment, code editor, or any particular operating system, compiler, or ancillary standards in our presentation. However, as a first step, you should be able to write, compile, and run the above program on the environment you intend to use for the r... | ComputerScienceOne_Page_419_Chunk1958 |
26. Basics blocks. • Variables are scoped to the code block in which they are declared and are only valid within that code block. • In general, whitespace between coding elements is ignored. Though not a syntactic requirement, the proper use of whitespace is important for good, readable code. Code inside code blocks is... | ComputerScienceOne_Page_420_Chunk1959 |
26.2. Basic Elements names of the directories that the file is located in, separated by a period. The declaration is terminated by a semicolon. For example, the package declaration, package unl.cse; would indicate that the file belongs in the directory cse which is a subdirectory of the directory unl . The absence of a p... | ComputerScienceOne_Page_421_Chunk1960 |
26. Basics Function Description Math.abs(x) Absolute value function, |x|a Math.ceil(x) Ceiling function, ⌈46.3⌉= 47.0 Math.floor(x) Floor function, ⌊46.3⌋= 46.0 Math.cos(x) Cosine functionb Math.sin(x) Sine functionb Math.tan(x) Tangent functionb Math.exp(x) Exponential function, ex, e = 2.71828 . . . Math.log(x) Natur... | ComputerScienceOne_Page_422_Chunk1961 |
26.2. Basic Elements 26.2.3. The main() Method Every executable program has to have a beginning: a point at which the program starts to execute. In Java, a class may contain many variables and methods, but a class is only executable if it contains a main() method. When a Java class is compiled and the JVM is started, t... | ComputerScienceOne_Page_423_Chunk1962 |
26. Basics 1 //this is a single line comment 2 int x; //this is also a single line comment, but after some code 3 4 /* 5 This is a comment that can 6 span multiple lines to format the comment 7 message more clearly 8 */ 9 double y; Most code editors and IDEs will present comments in a special color or font to distingui... | ComputerScienceOne_Page_424_Chunk1963 |
26.3. Variables Type Description Wrapper Class byte 8-bit signed 2s complement integer Byte short 16-bit signed 2s complement integer Short int 32-bit signed 2s complement integer Integer long 64-bit signed 2s complement integer Long float 32-bit IEEE 754 floating point number Float double 64-bit floating point number Do... | ComputerScienceOne_Page_425_Chunk1964 |
26. Basics 1 numUnits = 42; 2 costPerUnit = 32.79; 3 firstInitial = 'C'; 4 isStudent = true; For brevity, Java allows you to declare a variable and immediately assign it a value on the same line. So these two code blocks could have been more compactly written as: 1 int numUnits = 42; 2 double costPerUnit = 32.79; 3 cha... | ComputerScienceOne_Page_426_Chunk1965 |
26.4. Operators 26.4. Operators Java supports the standard arithmetic operators for addition, subtraction, multiplication, and division using + , - , * , and / respectively. Each of these operators is a binary operator that acts on two operands which can either be literals or other variables and follow the usual rules ... | ComputerScienceOne_Page_427_Chunk1966 |
26. Basics 3 4 //int and Integer can be mixed: 5 c = a + b; 6 7 double x = 3.14, z; 8 Double y = 2.71; 9 //double and Double can be mixed: 10 z = x + y; 11 12 //all types can be mixed: 13 double u = a + x + b + y; 14 15 //Be careful: 16 Integer d = null; 17 c = a + d; //NullPointerException This works because of a mech... | ComputerScienceOne_Page_428_Chunk1967 |
26.5. Basic I/O Assigning a floating point number to an integer is not allowed in Java and attempting to do so will be treated as a compiler error. This is because Java does not support implicit type casts. However, you can do so if you provide an explicit type cast as in the code above, d = (int) (b + y); In this code,... | ComputerScienceOne_Page_429_Chunk1968 |
26. Basics 1 Scanner s = new Scanner(System.in); 2 int a; 3 System.out.println("Please enter a number: "); 4 a = s.nextInt(); 5 System.out.printf("Great, you entered %d\n", a); Code Sample 26.2.: Basic Input/Output in Java code. Scanner s = new Scanner(System.in); The variable s is now active and can be read from. You ... | ComputerScienceOne_Page_430_Chunk1969 |
26.6. Examples 1 package unl.cse; 2 3 import java.util.Scanner; 4 5 /** 6 * This program converts Fahrenheit temperatures to 7 * Celsius 8 */ 9 public class TemperatureConverter { 10 11 public static void main(String args[]) { 12 13 //TODO: implement this 14 15 } 16 } It is common for programmers to use a comment along... | ComputerScienceOne_Page_431_Chunk1970 |
26. Basics 8 */ 9 public class TemperatureConverter { 10 11 public static void main(String args[]) { 12 13 //TODO: implement this 14 //1. Prompt the user for input in Fahrenheit 15 //2. Read the Fahrenheit value from the standard input 16 //3. Compute the degrees Celsius 17 //4. Print the result to the user 18 19 } 20 ... | ComputerScienceOne_Page_432_Chunk1971 |
26.6. Examples Try typing and running the program as defined above and you’ll find that you don’t get correct answers. In fact, you’ll find that no matter what values you enter, you get zero. This is because of the calculation using (5 / 9) : recall what happens with integer division: truncation! This will always end up b... | ComputerScienceOne_Page_433_Chunk1972 |
26. Basics 26.6.2. Computing Quadratic Roots Some programs require the user to enter multiple inputs. The prompt-input process can be repeated. In this example, consider asking the user for the coefficients, a, b, c to a quadratic polynomial, ax2 + bx + c and computing its roots using the quadratic formula, x = −b ± √ b2... | ComputerScienceOne_Page_434_Chunk1973 |
26.6. Examples 1 a = Double.parseDouble(args[0]); 2 b = Double.parseDouble(args[1]); 3 c = Double.parseDouble(args[2]); Finally, think about the possible inputs a user could provide that may cause problems for this program. For example: • What if the user entered zero for a? • What if the user entered some combination ... | ComputerScienceOne_Page_435_Chunk1974 |
26. Basics 1 package unl.cse; 2 3 import java.util.Scanner; 4 5 /** 6 * This program computes the roots to a quadratic equation 7 * using the quadratic formula. 8 */ 9 public class QuadraticRoots { 10 11 public static void main(String args[]) { 12 13 double a, b, c, root1, root2; 14 Scanner s = new Scanner(System.in); ... | ComputerScienceOne_Page_436_Chunk1975 |
27. Conditionals Java supports the basic if, if-else, and if-else-if conditional structures as well as switch statements. Java has Boolean types and logical statements are built using the standard logical operators for numeric comparisons as well as logical operators such as negations, And, and Or that can be used with... | ComputerScienceOne_Page_437_Chunk1976 |
27. Conditionals Name Operator Syntax Examples Value Equals == a == 10 true b == 10 false a == b false a == c true Not Equals != a != 10 false b != 10 true a != b true a != c false Strictly Less Than < a < 15 true a < 5 false a < b true a < c false Less Than Or Equal To <= a <= 15 true a <= 5 false a <= b true a <= c t... | ComputerScienceOne_Page_438_Chunk1977 |
27.1. Logical Operators Operator Operator Syntax Examples Values Negation ! !x false !y true And && x && true true x && y false Or || x || false true x || y true !x || y false Table 27.2.: Logical Operators in Java with x = true and y = false both being Boolean variables. Operator(s) Associativity Notes Highest ++ , --... | ComputerScienceOne_Page_439_Chunk1978 |
27. Conditionals 27.1.2. Comparing Strings and Characters The comparison operators in Table 27.1 can also be used for single characters because of the nature of the ASCII text table (see Table 2.4). Each alphanumeric character, including the various symbols and whitespace characters, is associated with an integer 0– 12... | ComputerScienceOne_Page_440_Chunk1979 |
27.2. If, If-Else, If-Else-If Statements 1 //example of an if statement: 2 if(x < 10) { 3 System.out.println("x is less than 10"); 4 } 5 6 //example of an if-else statement: 7 if(x < 10) { 8 System.out.println("x is less than 10"); 9 } else { 10 System.out.println("x is 10 or more"); 11 } 12 13 //example of an if-else-... | ComputerScienceOne_Page_441_Chunk1980 |
27. Conditionals 1 int x = 15; 2 if(x < 10); { 3 System.out.println("x is less than 10"); 4 } Some compilers may give a warning, but this is valid Java; it will compile and it will run. However, it will end up printing x is less than 10 , even though x = 15! Recall that a conditional statement binds to the executable s... | ComputerScienceOne_Page_442_Chunk1981 |
27.3. Examples logarithms can be in any base b > 1.1 What if we wanted to compute log2 (x)? Or logπ (x)? Let’s write a program that will prompt the user for a number x and a base b and computes logb (x). Arbitrary bases can be computed using the change of base formula: logb(x) = loga (x) loga (b) If we can compute some... | ComputerScienceOne_Page_443_Chunk1982 |
27. Conditionals Code Sample 27.2. The program also takes the input as command line arguments. Now that we have conditionals, we can actually check that the correct number of arguments was provided by the user and quit in the event that they don’t provide the correct number. 27.3.2. Life & Taxes Let’s adapt the conditi... | ComputerScienceOne_Page_444_Chunk1983 |
27.3. Examples Next we compute the child tax credit, taking care that it does not exceed $3,000. A conditional based on the number of children should suffice as at this point in the program we already know it is zero or greater. 1 if(numChildren <= 3) { 2 credit = numChildren * 1000; 3 } else { 4 credit = 3000; 5 } Final... | ComputerScienceOne_Page_445_Chunk1984 |
27. Conditionals 1 /** 2 * This program computes the logarithm base b (b > 1) 3 * of a given number x > 0 4 */ 5 public class Logarithm { 6 7 public static void main(String args[]) { 8 9 double b, x, result; 10 if(args.length != 2) { 11 System.out.println("Usage: b x"); 12 System.exit(1); 13 } 14 15 b = Double.parseDou... | ComputerScienceOne_Page_446_Chunk1985 |
27.3. Examples 1 import java.util.Scanner; 2 3 public class Taxes { 4 5 public static void main(String args[]) { 6 7 Scanner s = new Scanner(System.in); 8 double income, baseTax, totalTax, numChildren, credit; 9 10 System.out.println("Please enter your Adjusted Gross Income: "); 11 income = s.nextDouble(); 12 13 System... | ComputerScienceOne_Page_447_Chunk1986 |
27. Conditionals 1 /** 2 * This program computes the roots to a quadratic equation 3 * using the quadratic formula. 4 */ 5 public class Roots { 6 7 public static void main(String args[]) { 8 double a, b, c, root1, root2; 9 10 if(args.length != 3) { 11 System.err.println("Usage: a b c\n"); 12 System.exit(1); 13 } 14 15 ... | ComputerScienceOne_Page_448_Chunk1987 |
28. Loops Java supports while loops, for loops, and do-while loops using the keywords while , for , and do (along with another while ). Continuation conditions for loops are enclosed in parentheses, (...) and the blocks of code associated with the loop are enclosed in curly brackets. 28.1. While Loops Code Sample 28.1 ... | ComputerScienceOne_Page_449_Chunk1988 |
28. Loops 1 int i = 1; 2 boolean flag = true; 3 while(flag) { 4 //perform some action 5 i++; //iteration 6 if(i>10) { 7 flag = false; 8 } 9 } Code Sample 28.2.: Flag-controlled While Loop in Java A similar problem occurs: the while keyword and continuation condition bind to the next executable statement or code block. ... | ComputerScienceOne_Page_450_Chunk1989 |
28.2. For Loops 28.2. For Loops For loops in Java use the familiar syntax of placing the initialization, continuation condition, and iteration on the same line as the keyword for . An example can be found in Code Sample 28.3. 1 for(int i=1; i<=10; i++) { 2 //perform some action 3 } Code Sample 28.3.: For Loop in Java S... | ComputerScienceOne_Page_451_Chunk1990 |
28. Loops 1 int i; 2 do { 3 //perform some action 4 i++; 5 } while(i <= 10); Code Sample 28.4.: Do-While Loop in Java 28.4. Enhanced For Loops Java also supports foreach loops (which were introduced in JDK 1.5.0) which Java refers to as “Enhanced For Loops.” Foreach loops allow you to iterate over each element in a col... | ComputerScienceOne_Page_452_Chunk1991 |
28.5. Examples 1 List<Integer> list = Arrays.asList(10, 20, 8, 42); 2 int sum = 0; 3 for(Integer a : list) { 4 sum += a; 5 } Code Sample 28.6.: Enhanced For Loops in Java Example 2 28.5. Examples 28.5.1. Normalizing a Number Let’s revisit the example from Section 4.1.1 in which we normalize a number by continually divi... | ComputerScienceOne_Page_453_Chunk1992 |
28. Loops 1 int sum = 0; 2 for(int i=1; i<=10; i++) { 3 sum += i; 4 } Code Sample 28.8.: Summation of Numbers using a For Loop in Java 1 for(int i=1; i<=n; i++) { 2 sum += i; 3 } 28.5.3. Nested Loops Recall that you can write loops within loops by nesting them. The inner loop will execute fully for each iteration of th... | ComputerScienceOne_Page_454_Chunk1993 |
28.5. Examples 28.5.4. Paying the Piper Let’s adapt the solution for the loan amortization schedule we developed in Section 4.7.3. First, we’ll read the principle, terms, and interest as command line inputs. Adapting the formula for the monthly payment and using the math library’s Math.pow() function, we have the follo... | ComputerScienceOne_Page_455_Chunk1994 |
28. Loops 1 public class LoanAmortization { 2 3 public static void main(String args[]) { 4 5 if(args.length != 4) { 6 System.err.println("Usage: principle apr terms"); 7 System.exit(1); 8 } 9 10 double principle = Double.parseDouble(args[0]); 11 double apr = Double.parseDouble(args[1]); 12 int n = Integer.parseInt(args... | ComputerScienceOne_Page_456_Chunk1995 |
29. Methods As an object-oriented programming language, functions in Java are usually referred to as methods and are essential to writing programs. The distinction is that a function is usually a standalone element while methods are functions that are members of a class. In Java, since everything is a class or belongs ... | ComputerScienceOne_Page_457_Chunk1996 |
29. Methods As of Java 5, you can write and use vararg methods. The System.out.printf() method is a prime example of this. However, we will not discuss in detail how to do this. Instead, refer to standard Java documentation. Finally, parameters are not optional in Java. This is because Java supports method overloading.... | ComputerScienceOne_Page_458_Chunk1997 |
29.1. Defining Methods 23 double yDiff = (y1-y2); 24 return Math.sqrt( xDiff * xDiff + yDiff * yDiff); 25 } 26 27 /** 28 * Computes a monthly payment for a loan with the given 29 * principle at the given APR (annual percentage rate) which 30 * is to be repaid over the given number of terms. 31 * @param principle - the a... | ComputerScienceOne_Page_459_Chunk1998 |
29. Methods 29.1.1. Void Methods The keyword void can be used in Java to indicate a method does not return a value, in which case it is called a “void method.” Though it is not necessary, it is still good practice to include a return statement. 1 public static void printCopyright() 2 System.out.println("(c) Bourke 2015... | ComputerScienceOne_Page_460_Chunk1999 |
29.1. Defining Methods The Utils.methodName() syntax is used because the methods are static –they belong to the class and so must be invoked through the class using the class’s name. We’ve previously seen this syntax when using System. or Math. with the standard JDK library functions. 29.1.3. Passing By Reference Java d... | ComputerScienceOne_Page_461_Chunk2000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.