Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Arrays CprE 185: Intro to Problem Solving Iowa State University, Ames, IA Copyright © Alexander Stoytchev
Administrative Stuff HW5 is due 8pm. HW6 is due next Wednesday (Oct 8pm. HW7 is out. Due next Friday (Oct 8pm.
Administrative Stuff Midterm 2 is coming up in two weeks Same format as before: Lab exam during your regular lab time (Oct 27 or Oct 28) Lecture exam on Oct 28 The exam will be cumulative with emphasis on conditional statements (if, if-else, switch), loops (do, while, for), arrays (to be covered), and searching and sorting algorithms (to be covered).
Quick Review of the Last Lecture
Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { printf ("Here"); count2++; } count1++; } 10 * 20 = 200 © 2004 Pearson Addison-Wesley. All rights reserved
Analogy for Nested Loops
Analogy for Nested Loops Inner Loop Outer Loop
Break and Continue
Chapter 8 (Arrays)
Problem: Read 10 numbers from the keyboard and store them
// solution #1 int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9; printf(“Enter a number: “); scanf(“ %d”, &a0); printf(“Enter a number: “); scanf(“ %d”, &a1); //… printf(“Enter a number: “); scanf(“ %d”, &a9);
Arrays Arrays are C data types that help us organize large amounts of information
Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9 © 2004 Pearson Addison-Wesley. All rights reserved
An array with 8 elements of type double [Figure 8.1 in the textbook]
Problem: Read 10 numbers from the keyboard and store them // solution #2 int a[10]; // use an array for(i=0; i< 10; i++) { printf(“Enter a number: “); scanf(“ %d”, &a[i]); }
Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) That expression represents a place to store a single integer and can be used wherever an integer variable can be used © 2004 Pearson Addison-Wesley. All rights reserved
Arrays For example, an array element can be assigned a value, printed, or used in a calculation : scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; printf ("Top = %d“, scores[5]); © 2004 Pearson Addison-Wesley. All rights reserved
Arrays The values held in an array are called array elements An array stores multiple values of the same type – the element type The element type can be a primitive type Therefore, we can create an array of integers, an array of floats, an array of doubles. © 2004 Pearson Addison-Wesley. All rights reserved
Arrays Another way to depict the scores array: scores © 2004 Pearson Addison-Wesley. All rights reserved
Declaring Arrays It is possible to initialize an array when it is declared: float prices[3] = {1.0, 2.1, 2.0}; Or to initialize it later: int a[6]; a[0]=3; a[1]=6;
Declaring Arrays Declaring an array of characters of size 3: char letters[3] = {‘a’, ‘b’, ‘c’}; Or we can skip the 3 and leave it to the compiler to estimate the size of the array: char letters[] = {‘a’, ‘b’, ‘c’};
For loops and arrays #define N 10 int a[N]; int i; … for(i=0; i < N; i++) printf(“%d\n”, a[i]); for(i=0; i <= N; i++) // this is an error printf(“%d\n”, a[i]); // out of bounds
For loops and arrays #define N 10 int a[N+1]; int i; … for(i=0; i <= N; i++) printf(“%d\n”, a[i]);
Questions?
THE END
Other Stuff that we could not cover last time
Comparing Float Values You should rarely use the equality operator ( == ) when comparing two floating point values ( float or double ) Two floating point values are equal only if their underlying binary representations match exactly Computations often result in slight differences that may be irrelevant In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal © 2004 Pearson Addison-Wesley. All rights reserved
Comparing Float Values To determine the equality of two floats, you may want to use the following technique: if (fabs(f1 - f2) < TOLERANCE) printf ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as © 2004 Pearson Addison-Wesley. All rights reserved
Comparing Characters As we've discussed, C character data is based on the ASCII character set ASCII establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering For example, the character '+' is less than the character ' J' because it comes before it in the ASCII character set © 2004 Pearson Addison-Wesley. All rights reserved
ASCII Table
Extended ASCII Codes
Comparing Characters In ASCII (and Unicode) the digit characters (0-9) are contiguous and in order Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order CharactersUnicode Values 0 – 948 through 57 A – Z65 through 90 a – z97 through 122 © 2004 Pearson Addison-Wesley. All rights reserved
The Conditional Operator C has a conditional operator that uses condition to determine which of two expressions is evaluated Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression
The Conditional Operator The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger ; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands
Boolean Expressions in C C does not have a boolean data type. Therefore, C compares the values of variables and expressions against 0 (zero) to determine if they are true or false. If the value is 0 then the result is implicitly assumed to be false. If the value is different from 0 then the result is implicitly assumed to be true. C++ and Java have boolean data types.
Relational Operators A condition often uses one of C's equality operators or relational operators == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator ( == ) and the assignment operator ( = ) © 2004 Pearson Addison-Wesley. All rights reserved
Logical Operators Boolean expressions can also use the following logical operators: ! Logical NOT && Logical AND || Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) © 2004 Pearson Addison-Wesley. All rights reserved
Logical NOT The logical NOT operation is also called logical negation or logical complement If some condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table a!a truefalse true © 2004 Pearson Addison-Wesley. All rights reserved
Logical AND and Logical OR The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a || b is true if a or b or both are true, and false otherwise © 2004 Pearson Addison-Wesley. All rights reserved
Logical Operators Expressions that use logical operators can form complex conditions if (total < MAX+5 && !found) printf ("Processing…"); All logical operators have lower precedence than the relational operators Logical NOT has higher precedence than logical AND and logical OR © 2004 Pearson Addison-Wesley. All rights reserved
Logical Operators A truth table shows all possible true-false combinations of the terms Since && and || each have two operands, there are four possible combinations of conditions a and b aba && ba || b true false true falsetruefalsetrue false © 2004 Pearson Addison-Wesley. All rights reserved
Boolean Expressions Specific expressions can be evaluated using truth tables total < MAXfound!foundtotal < MAX && !found false truefalse truefalse truefalsetrue false © 2004 Pearson Addison-Wesley. All rights reserved
Short-Circuited Operators The processing of logical AND and logical OR is “short-circuited” If the left operand is sufficient to determine the result, the right operand is not evaluated This type of processing must be used carefully The outcome may be compiler dependent!!! if (count != 0 && total/count > MAX) printf ("Testing…"); © 2004 Pearson Addison-Wesley. All rights reserved