Download presentation
Presentation is loading. Please wait.
Published byPhyllis Ford Modified over 8 years ago
1
Instructor: Alexander Stoytchev http://www.cs.iastate.edu/~alex/classes/2008_Fall_185/ CprE 185: Intro to Problem Solving (using C)
2
Administrative Stuff Midterm 2 is next week!!! Same format as before: Lab exam during your regular lab time (Oct 28 or Oct 29) Lecture exam on Oct 29 (10-11am) Note: There will be NO night exam. 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).
3
Administrative Stuff HW7 is out today. It’s due next Monday @ 8pm. HW6 is due this Friday (Oct 24) @ 8pm.
4
Searching Algorithms CprE 185: Intro to Problem Solving Iowa State University, Ames, IA Copyright © Alexander Stoytchev
5
Quick Review of the Last Lecture
6
Problem: Read 10 numbers from the keyboard and store them
7
// 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);
8
Problem: Read 10 numbers from the keyboard and store them // solution #2 int a[10]; for(i=0; i< 10; i++) { printf(“Enter a number: “); scanf(“ %d”, &a[i]); }
9
Arrays An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 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
10
An array with 8 elements of type double [Figure 8.1 in the textbook]
11
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
12
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
13
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
14
Arrays Another way to depict the scores array: scores 79 87 94 82 67 98 87 81 74 91 © 2004 Pearson Addison-Wesley. All rights reserved
15
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;
16
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’};
17
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
18
For loops and arrays #define N 10 int a[N+1]; int i; … for(i=0; i <= N; i++) printf(“%d\n”, a[i]);
19
Other stuff that we did not cover last time
20
Using Uninitialized Array Entries Error This is a common error that may be hard to find. int a[10]; printf(“%d \n”, a[5]); // a[5] is not initialized // The result is unpredictable a[5] = a[4] + a[7]; // both a[4] and a[7] are undefined
21
Out of Bounds Error This is an error but the compiler may or may not catch it. Worst of all it amy or may not be a run- time error. This is really hard to trace. int a[10]; a[0]=3; a[10]=6; // element 10 in not defined a[15]=7; // element 15 in not defined
22
Out of Bounds Error #include // This program works OK on my machine even though // it tries to access element a[10] which is not defined. int main() { int a[10]; a[0]=4; a[10]=5; // element 10 in not defined printf("%d\n", a[0]); printf("%d\n", a[10]); system("pause"); }
23
Out of Bounds Error #include // This program generates a runtime error on my machine // when it tries to access element a[100] which is not // defined. int main() { int a[10]; a[0]=4; a[100]=5; // element 10 in not defined run-time error system("pause"); }
24
Printing an Arrays using a Function #include void print_array(int a[], int n) { int i; for(i=0; i<n; i++) printf("a[%d]=%d\n", i, a[i]); } int main() { int a[10]; int i; srand(time(NULL)); for(i=0; i<10; i++) // initialize a[i]=rand()%10 +1; print_array(a, 10); system("pause"); }
25
Printing an Array #include int main() { int a[10]; int i; srand(time(NULL)); for(i=0; i<10; i++) // initialize a[i]=rand()%10 +1; for(i=0; i< 10; i++) // print once printf("a[%d]=%d\n", i, a[i]); system("pause"); }
26
Other stuff that is not in the textbook (but is very useful)
27
Random Numbers in C
28
int rand ( void ); Generates a random number. Defined in stdlib.h The number returned is an integer in the range 0 to RAND_MAX (inclusive). The value of RAND_MAX is library dependent. In other words different implementations of the C libraries may have a different value for it It is guaranteed to be at least 32767. If you need to generate large number (> 20,000) of random values this may not be the right function to use!!!
29
Examples rand()%10; random in the interval [0, 9] rand()%10 +1; random in the interval [1, 10] rand()%10 +5; random in the interval [5, 14] rand()%10 - 20; random in the interval [-20, -11]
30
What about random real numbers? r r = ((double)rand()/((double)(RAND_MAX)+(double)(1))); [http://members.cox.net/srice1/random/crandom.html]
31
Pseudo Random Numbers It is possible that if you run your program twice you will get the same random sequence!!! To avoid that you need to initialize the random number generator. You can do this by calling the srand function.
32
void srand ( unsigned int seed ); Initializes the random number generator by giving it a new seed value. Defined in stdlib.h Usage: srand(100); srand(50); You’ll have to change the seed value every time you run your program to avoid getting the same random sequence.
33
Use the current time as a seed value The randomness of your sequence depends on the randomness of your seed value. One common source of “random” seed values is the internal system clock. This code uses the seconds elapsed since January 1, 1970 as the seed value. This value is different every second. #include int main() { srand ( time(NULL) ); }
34
Time in C time_t time(time_t *ptr); The meaning of time_t is identical to int Returns the number of seconds elapsed since midnight January 1 st, 1970 GMT (or 7pm, December 31 st, 1969 EST) (or 6pm, December 31 st, 1969 Iowa time) 1224466481 Sun Oct 19 20:34:41 2008
35
Let’s check this 60*60*24= 86400 seconds per day 86400*365.25 = 31,557,600 seconds per year (365.25 so we don’t have to deal with leap years) Let’s check this 1224466481 Sun Oct 19 20:34:41 2008 1,224,466,481/ 31,557,600 = 38.80 years
36
Using time functions #include int main() { time_t lt; lt = time(NULL); // get the current time in sec since Jan. 1, 1970 printf("%d\n", lt); // print the number of seconds printf(ctime(<)); // print it in human readable format srand ( time(NULL) ); // initialize the random number generator int r = rand()%10+1; // generate a random number from 1 to 10 printf("r=%d\n", r); // print r system("pause"); }
37
Using time functions #include // this program demonstrates how to measure the run time of a program (in seconds) int main() { time_t startTime; time_t endTime; startTime = time(NULL); // get the current time // do some busy work here int i; for(i=0; i< 10000; i++) printf("%d\n", i); endTime = time(NULL); // get the current time again time_t elapsedTime = endTime - startTime; printf("This program took %d seconds to run.\n", elapsedTime); system("pause"); }
38
Chapter 8 (Searching)
39
Problem: Find the minimum number in an array of unsorted integers find_minimum.c
40
Search [http://web.ics.purdue.edu/~cs154/lectures/lecture011.htm]
41
Linear Search The most basic Very easy to implement The array DOESN’T have to be sorted All array elements must be visited if the search fails Could be very slow
42
Example: Successful Linear Search [http://web.ics.purdue.edu/~cs154/lectures/lecture011.htm] Example: Successful Linear Search
43
[http://web.ics.purdue.edu/~cs154/lectures/lecture011.htm] Example: Failed Linear Search
44
Problem: Find the index of a number in an unsorted array of integers linear_search.c
45
Problem: Find the all occurrences of a number in an array and replace it with a new value. search_and_replace.c
46
Linear Search in a Sorted Array
47
Problem: Find the index of a number in a sorted array of integers LinearSearch_InSortedArray.c
48
Analysis If the list is unsorted we have to search all numbers before we declare that the target is not present in the array. Because the list is sorted we can stop as soon as we reach a number that is greater than our target Can we do even better?
49
Binary Search At each step it splits the remaining array elements into two groups Therefore, it is faster than the linear search Works only on an already SORTED array Thus, there is a performance penalty for sorting the array [http://web.ics.purdue.edu/~cs154/lectures/lecture011.htm]
50
Example: Successful Binary Search
51
Example: BinarySearch.c
53
Analysis of Searching Methods For an array of size n Sequential Search (Average-Case) n/2 Sequential Search (Worst-Case) n Binary Search (Average-Case) log(n)/2 Binary Search (Worst-Case) log(n)
54
Questions?
55
THE END
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.