Presentation is loading. Please wait.

Presentation is loading. Please wait.

CprE 185: Intro to Problem Solving (using C)

Similar presentations


Presentation on theme: "CprE 185: Intro to Problem Solving (using C)"— Presentation transcript:

1 CprE 185: Intro to Problem Solving (using C)
Instructor: Alexander Stoytchev

2 Administrative Stuff HW6 is due this Wednesday (Oct 21) @ 8pm.
HW7 is due this Friday (Oct 8pm.

3 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).

4 Study Group

5 Searching Algorithms CprE 185: Intro to Problem Solving
Iowa State University, Ames, IA Copyright © Alexander Stoytchev

6 Quick Review of the Last Lecture

7 Problem: Read 10 numbers from the keyboard and store them

8 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); scanf(“ %d”, &a1); //… scanf(“ %d”, &a9);

9 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]); }

10 Each value has a numeric index
Arrays An array is an ordered list of values scores The entire array has a single name Each value has a numeric index An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9 © 2004 Pearson Addison-Wesley. All rights reserved

11 An array with 8 elements of type double
[Figure 8.1 in the textbook]

12 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

13 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

14 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

15 Arrays Another way to depict the scores array: 79 87 94 82 67 98 81 74
91 © 2004 Pearson Addison-Wesley. All rights reserved

16 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;

17 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’};

18 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

19 For loops and arrays #define N 10 int a[N+1]; int i; …
for(i=0; i <= N; i++) printf(“%d\n”, a[i]);

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 <stdio.h> #include <stdlib.h>
// 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 <stdio.h> #include <stdlib.h>
// 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 Other stuff that is not in the textbook (but is very useful)

25 Random Numbers in C

26 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 If you need to generate large number (> 20,000) of random values this may not be the right function to use!!!

27 Examples rand()%10;  random in the interval [0, 9]

28 What about random real numbers?
r = ((double)rand()/((double)(RAND_MAX)+(double)(1))); [

29 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.

30 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.

31 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 <stdlib.h> #include <time.h> int main() { srand ( time(NULL) ); }

32 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 1st, 1970 GMT (or 7pm, December 31st, 1969 EST) (or 6pm, December 31st, Iowa time)  Sun Oct 19 20:34:

33 Let’s check this 60*60*24= 86400 seconds per day
86400* = 31,557,600 seconds per year ( so we don’t have to deal with leap years) Let’s check this  Sun Oct 19 20:34: 1,224,466,481/ 31,557,600 = years

34 Using time functions #include <stdio.h>
#include <stdlib.h> #include <time.h> 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(&lt)); // 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"); }

35 Using time functions #include <stdio.h>
#include <stdlib.h> #include <time.h> // 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"); }

36 Other stuff that we did not cover last time

37 Printing an Arrays using a Function
#include <stdio.h> #include <stdlib.h> #include <time.h> 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]; srand(time(NULL)); for(i=0; i<10; i++) // initialize a[i]=rand()%10 +1; print_array(a, 10); system("pause");

38 Printing an Array #include <stdio.h> #include <stdlib.h>
#include <time.h> 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"); }

39 Chapter 8 (Searching)

40 Search [

41 Problem: Find the minimum number in an array of unsorted integers find_minimum.c

42 find_minimum.c #include <stdio.h> #include <stdlib.h>
#define N 12 int main() { int a[N] = { 14, 21, 36, 14, 12, 9, 8, 22, 7, 81, 77, 10}; int i; // Find The Minimum Element int min=a[0]; // pick the first number as the current minimum for(i=1; i< N; i++) if(a[i] < min) min=a[i]; } printf("The minumum value in the array is %d.\n\n", min);

43 Problem: Find the minimum number (and its index) in an array of unsorted integers find_minimum_and_index.c

44 find_minimum_and_index.c
#include <stdio.h> #include <stdlib.h> #define N 12 int main() { int a[N] = { 14, 21, 36, 14, 12, 9, 8, 22, 7, 81, 77, 10}; int i, min; // Find The Minimum Element and it index min= a[0]; // initial guess: a[0] is the minimum value int idx=0; // initial guess: the minimum value is at index 0 for(i=0; i< N; i++) if(a[i] < min) min=a[i]; idx=i; } printf("The minumum value in the array is %d.\n\n", min); printf("It is located at index: %d \n\n", idx);

45 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

46 Example: Successful Linear Search
[

47 Example: Failed Linear Search
[

48 Problem: Find the index of a number in an unsorted array of integers linear_search.c

49 Linear_Search.c #include <stdio.h> #include <stdlib.h>
#define N 12 int main() { int a[N] = { 4, 21, 36, 14, 62, 91, 8, 22, 7, 81, 77, 10}; int i; int target = 62; //int target = 72; // Try this next int idx=-1; for(i=0; i< N; i++) printf(".\n"); if(a[i] == target) idx=i; break; } if(idx == -1) printf("Target not found.\n\n"); else printf("Target found at index: %d \n\n", idx);

50 Problem: Find the all occurrences of a number in an array and replace it with a new value. search_and_replace.c

51 Linear_Search.c #include <stdio.h> #include <stdlib.h>
#define N 12 int main() { int a[N] = { 4, 21, 36, 14, 62, 91, 8, 22, 7, 81, 62, 10}; int i; int target = 62; int newValue = 65; int count=0; int idx[5]; // a helper array that keeps the indexes of all entries == target value int found=0; for(i=0; i< N; i++) if(a[i] == target) found = 1; idx[count] = i; count++; } if(found == 0) printf("Not found!\n\n"); else printf("Found it a total of %d times.\n", count); for(i=0; i< count; i++) printf("\t index %d \n", idx[i]); // Now replace all found occurences with a nother number a[ idx[i] ] = newValue; system("pause");

52 Linear Search in a Sorted Array

53 Problem: Find the index of a number in a sorted array of integers LinearSearch_InSortedArray.c

54 LinearSearch_InSortedArray.c
#include <stdio.h> #include <stdlib.h> #define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; int target = 62; //int target = 72;// Try this target next int i, idx=-1; for(i=0; i< N; i++) if(a[i] == target) idx=i; break; } else if(a[i]>target) break; // we can stop here if(idx == -1) printf("Target not found.\n\n"); else printf("Target found at index: %d. \n\n", idx);

55 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?

56 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 [

57 Example: Successful Binary Search
[

58 Example: BinarySearch.c

59 Binary_Search.c #include <stdio.h> #include <stdlib.h>
#define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; //sorted in increasing order int i; int target = 22; //int target = 72; // Try this target next int idx=-1; // if the target is found its index is stored here int first=0; // initial values for the three search varaibles int last= N-1; int mid= (first + last)/2; while(last >= first) if( a[mid] == target) idx=mid; // Found it! break; // exit the while loop } else if(a[mid] > target) // don't search in a[mid] ... a[last] last = mid-1; else // don't search in a[first] ... a[mid] first = mid +1; // recalculate mid for the next iteration mid = (first + last)/2; // integer division! } // end of while loop if(idx == -1) printf("Target not found.\n\n"); printf("Target found at index: %d \n\n", idx);

60

61 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)

62 Questions?

63 THE END


Download ppt "CprE 185: Intro to Problem Solving (using C)"

Similar presentations


Ads by Google