Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 5: How to think like a programmer, Arrays & Strings

Similar presentations


Presentation on theme: "Lecture 5: How to think like a programmer, Arrays & Strings"— Presentation transcript:

1 Lecture 5: How to think like a programmer, Arrays & Strings
B Burlingame 20 September 2017

2 Announcements Homework #3 due next week Read chapter 9

3 Constants and Variables
A data element that never changes in your program 5, 62.37, 4.219E-6, “record_string”, ‘$’ i = j + 7; /* which one is the constant? */ first_letter = ‘a’; /* which one is the constant? */ Variable A data element that can take on different values Its name represents a location (address) in memory  i = j + 7; /* which are variables? */ second_letter = ‘b’; /* which is the variable? */ Values are ‘assigned’ using a single equal sign ( = ) Read the statement: i = j + 7; 5 is an integer constant is a floating point constant E-6 is a floating point constant (written in exponential notation, which is good for really large or really small numbers). “record_string” is a string constant. ‘$’ is a character constant. Assignment, the single equals sign, means store the value of the right hand side of the equal sign to the data object (variable) on the left hand side of the equal sign. Note the semicolons at the end of the assignment statement. This is how all statements must be terminated. More on this later. Note the line i = j + 7; /* which one is the constant? */ The stuff after the i = j + 7; is a comment. Anything between /* and */ is for documentation purposes and will not affect the compiled code. Comments are stripped out during preprocessing.

4 The Plan for Today Program design process
Algorithms, decomposition, and step-wise refinement Example Program design example Introduce arrays and strings

5 Learning Objectives List and describe the steps in designing a computational solution (computer program) to a problem Articulate what is meant by an algorithm Apply the steps to a particular problem

6 Program Design Process
Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code So far we’ve mostly been dealing with getting familiar with declaring variables and formatted IO using single-statements. Now we want to learn a general method for designing more complex programs. State the problem you are trying to solve in clear and concise terms List the inputs (information needed to solve the problem) and outputs (what the program will produce) Design the solution procedure (the algorithm) Use a ‘top-down’ method: break the large task into smaller sub-tasks that perform a piece of the larger task (decomposition). Subtasks may need to be decomposed into smaller subtasks. Refine the subtasks into increasing detail (step-wise refinement), so that steps of the subtask can be readily turned into code Check the validity of the proposed algorithm by hand calculations Write the program code Test the program code

7 Program Design Process – step 1
Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code State the problem in a clear and concise manner Example Write a program to find the distance between two points Is the problem statement okay? P1 P2 P1 P2 or or P1 P2 State the problem you are trying to solve in clear and concise terms. “Write a program to find the distance between two points” is ambiguous. Need to be more specific. Better Write a program to find the straight line distance between two points

8 Program Design Process – step 2
Write a program to find the straight line distance between two points Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code Inputs Outputs List the inputs (information needed to solve the problem) and outputs (what the program will produce) What are the inputs? X and Y coordinates of the two points: x1, y1 and x2, y2 What are the outputs? The straight-line distance between the points: D

9 Program Design Process – step 3
Write a program to find the straight line distance between two points Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code Decompose Refine Design the solution procedure (the algorithm) Use a ‘top-down’ method: break the large task into smaller sub-tasks that perform a piece of the larger task (decomposition). Subtasks may need to be decomposed into smaller subtasks. Refine the subtasks into increasing detail (step-wise refinement), so that steps of the subtask can be readily turned into code.

10 Definition of an Algorithm
An algorithm is a well-ordered collection of unambiguous and effectively computable operations, that when executed, produces a result and halts in a finite amount of time. Well-ordered means the steps are in a clear order Unambiguous means the operations described are understood by a computing agent without further simplification A computing agent is the thing that is supposed to carry out the algorithm Effectively computable means the computing agent can actually carry out the operation If we can specify an algorithm to solve a problem then we can automate its solution. That which carries out the steps of an algorithm (a computing agent) just needs to be able to follow directions; not understand the concepts or ideas behind the algorithm. The word algorithm is derived from the last name of Muhammad Al-Khowarizmi (full name: Abu Ja'far Muhammad ibn-Musa Al-Khowarizmi), a famous Persian mathematician and author of the eighth and ninth centuries. (His most famous book is Kitab al jabr w'al muqabala.) This definition comes from, An Invitation to Computer Science (Gersting/Schneider) via (visited 19JUN2009)

11 Program Design Process – step 3,cont.
Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code Two approaches are often used to help think through the steps to be carried out by the program code: Pseudocode Flow Charts We’ll use the pseudocode method first. Design the solution procedure (the algorithm) Use a ‘top-down’ method: break the large task into smaller sub-tasks that perform a piece of the larger task (decomposition). Subtasks may need to be decomposed into smaller subtasks. Refine the subtasks into increasing detail (step-wise refinement), so that steps of the subtask can be readily turned into code. 11

12 Pseudocode Pseudocode (also called Program Design Language, PDL) is English-like statements that precisely describe specific operations1: Action statements Focuses on the logic of the program Avoids language-specific elements Written at a level so that code can be generated almost automatically. Will likely need to refine in more and more detail 1This definition comes from, McConnel, S. (1993). Code Complete, Microsoft Press, Redmond, WA, p. 54.

13 Pseudocode – First Pass
Write a program to find the straight line distance between two points Prompt user to enter points Get points from user Calculate the straight line distance Return distance Comments High level – just the major steps Focus on the logic

14 Pseudocode - Refinement
Write a program to find the straight line distance between two points Start Declare variables: X1, Y1, X2, Y2, Distance Prompt user to enter X1 and Y1 Prompt user to enter X2 and Y2 Calculate the straight line distance Return Distance Stop Comments Refine high level ideas down to computable actions What could still be refined?

15 Calculating the Distance, D
Write a program to find the straight line distance between two points Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code P1 P2 X1 X2 Y1 Y2 D How do you find D? Design the solution procedure (the algorithm) Use a ‘top-down’ method: break the large task into smaller sub-tasks that perform a piece of the larger task (decomposition). Subtasks may need to be decomposed into smaller subtasks. Refine the subtasks into increasing detail (step-wise refinement), so that steps of the subtask can be readily turned into code. Some possible subtasks are computing the lengths of the x and y legs of the triangle, then the length of the hypotenuse. In this problem, it is easy enough to combine this all into one formula. P1 P2 D X Y

16 Program Design Process – step 4
Write a program to find the straight line distance between two points Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code What values of Xi, Yi (where i=1, 2) would be good to test the algorithm with? Check the validity of the proposed algorithm by hand calculations It is advisable to test with values and methods that you know are correct. Also, it is important to test the ‘boundary’ cases, that is with data at the maximum and minimum ranges of the inputs. Also look at special cases. Does your solution work if the two points are located along a line parallel to one of the axes? I know from geometry that if X=3, Y=4, then D=5. Therefore, choose X2=3, X1=0; Y2=4, Y1=0. D=sqrt((3-0)^2 + (4-0)^2) = sqrt(9+16) = sqrt(25) = 5. The algorithm appears to work!

17 Program Design Process – step 5
Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code If you have refined your algorithm sufficiently, writing the code should proceed straightforwardly from it. If not, continue refining the algorithm until you can write the code directly from it. Your pseudocode can be turned into the comments for your code. Write the program code /* * File Name : straight-line_distance.c * Title : Straight-line Distance Calculation Program * Author : Buff Furman * Created : 18AUG2009 * Revised : 05SEP2009 * Version : 1.1 * Description : Calculates the straight-line distance between two points * Inputs : x and y ordered pairs for two points: x1, y1 and x2, y2 * Outputs : straight-line distance between the two points * Method : Get points (X1, Y1) and (X2, Y2) from the user * Echo what was entered to the monitor * Calculate the distance, D=sqrt((x2-x1)^2 + (y2-y1)^2) * Display D to the monitor * Revision History: * Date Who Description of Change * * 05SEP2009 BF Modified comments * 18AUG2009 BF Created program */ /* Include Files */ #include <stdio.h> /* standard IO library routines, like printf(), scanf() */ #include <math.h> /* standard math library routines, like sqrt() */ /* Body of Program Code */ int main(void) { double X1, X2, Y1, Y2; /* variables for the xy coordinates of P1 and P2 */ double D; /* distance between P1 and P2 */ /* Prompt user for X1 and Y1 */ printf("\nEnter the first point, P1, in the form, x1 y1> "); scanf("%lf%lf", &X1, &Y1); /* Echo X1 and Y1 to the monitor */ printf(" You entered: P1 = (%g, %g)\n", X1, Y1); /* Prompt user for X2 and Y2 */ printf("\nEnter the second point, P2, in the form, x2 y2> "); scanf("%lf%lf", &X2, &Y2); /* Echo X2 and Y2 to the monitor */ printf(" You entered: P2 = (%g, %g)\n", X2, Y2); /* Calculate the straight-line distance between P1 and P2 */ D = sqrt(pow((X2-X1),2) + pow((Y2-Y1),2)); /* Display the distance to the monitor */ printf("\nThe straight-line distance between P1 and P2 is %.4f \n\n", D); return 0; }

18 Program Design Process – step 6
Define the problem List the inputs and outputs Design the solution algorithm Check the algorithm by hand Write the program code Test the program code Test your code with cases that you know the answer to. Try the ‘boundary’ cases to make sure your code works for them too. Test the program code Try (x1, y1)=(0,0) and (x2, y2)=(3,4) It is advisable to test with values and methods that you know are correct. Also, it is important to test the ‘boundary’ cases, that is with data at the maximum and minimum ranges of the inputs. Also look at special cases. Does your solution work if the two points are located along a line parallel to one of the axes? I know from geometry that if X=3, Y=4, then D=5.

19 Algorithm Practice Find the maximum of n values
This is intended to be an interactive exercise with the class. The idea is to have them go through the process of developing an algorithm and writing the code. This problem has lots of similarity the example, so hopefully they can get the hang of it. Notes to the instructor: Have the students go through the program development method and record the steps of the process on their lab report sheet Have them write the program from scratch starting with the program template from:

20 Algorithm – Items to Consider
Is the problem statement clear and concise? Could be better: Return the maximum numerical value amongst n floating point numbers What are the inputs? n floating point numbers What are the outputs? The largest value Cover this after they have had a chance to work on their own for a while on the problem or if they are struggling.

21 Algorithm – Possible Solution
Pseudocode 1. Start 2. Initialize number = 0, counter = 0, n = 0, max = -∞ 3. Get the quantity of numbers from user 4. Store that quantity in n 5. Is counter > n ? add 1 to counter get number is (number > max) ? max = number go to line 5 11. otherwise print max 13.end Flowchart Notice the loops!

22 Find average

23 What is an Array? So far we've dealt with scalar variables
contain just one value Arrays are collections of data of the same type that occupy contiguous memory locations Individual values in the collection are called elements of the array Need to declare before use: #include <stdio.h> int main() { int i=0; double test[4] = {0}; test[0]=95.5; test[1]=74.0; test[2]=88.5; test[3]=91.0; for(i=0; i<4; i++) printf("test[%d]=%lf",i,test[i]); 0x%p\n",&test[i]); } return 0; Run array_practice2.c in ChIDE. Format (1D array) type array_name [num_elements]; Ex. Array of 4 doubles named, 'test'

24 What is an array? - 2 int nums [10] = {0};
10 element array of integers Element no. 3 is accessed by: nums [2] because indexing begins at 0

25 Accessing Array Elements
#include <stdio.h> #define SIZE_OF_TEST 4 int main() { int i=0; double test[SIZE_OF_TEST]={0}; test[0]=95.5; test[1]=74.0; test[2]=82.75; test[3]=91.5; for(i=0; i < SIZE_OF_TEST; i++) printf("test[%d]=%lf",i,test[i]); 0x%p\n",&test[i]); } return 0; Individual elements of an array are accessed by their index number ** Important Note** Array indexing starts at zero (take note of this, it is easy to forget!) char test[4]; the first element is test [0] the fourth element is test [3] Be careful! The C compiler may not stop you from indexing beyond the boundary of your array. (What could happen?) What is test[4]?

26 Initializing Array Elements
/* array_practice3.c */ #include <stdio.h> #define SIZE_OF_NUMS int main() { int i=0; int nums[SIZE_OF_NUMS]={0,1,2,3,4}; for(i=0; i < SIZE_OF_NUMS; i++) printf("nums[%d]=%d",i,nums[i]); 0x%p\n",&nums[i]); if(3 == nums[i]) printf(“Three!”); } return 0; Use braces to enclose the elements Separate elements by commas Can set number of elements in declaration: Explicit: int nums[5] = { 0 }; Implicit: int imp[ ] = {1, 2}; int imp[2] = {1, 2}; Don’t use implicit declarations Run array_practice3.c in ChIDE. Point out addresses for int array elements. Four bytes each! Run array_practice4.c in ChIDE to show my version of keyboard entry.

27 Initializing Array Elements
/* array_practice3.c */ #include <stdio.h> #define BIG_INDEX = 5000; int main() { int i=0; int nums[BIG_INDEX]={0}; for(i=0; i < BIG_INDEX; i++) nums[i] = 34; } return 0; For long, non-zero initializations, for loop is usually more efficient to program Note the use of a variable index Run array_practice3.c in ChIDE. Point out addresses for int array elements. Four bytes each! Run array_practice4.c in ChIDE to show my version of keyboard entry.

28 Strings Strings are encoded arrays of characters designed to hold language Recall that all characters are encoded as numeric values Most modern systems use a variant of ASCII or Unicode We’ll assume ASCII

29 ASCII Table

30 Strings By convention, strings in C are a null terminated array of characters There is no intrinsic string datatype Null equals character value 0 i.e. char z = 0; z has a null character written \0 Declaration: char string[] = “Hello world”; Stored: Hello World\0 (ie 12 characters) All string handling expects this

31 Working with strings Much like working with pointers and arrays
Many helper routines in string.h strcmp – tests strings for equivalence strcat – concatenates two strings strstr – locates a string within a string Etc. char string[20] = “Hello World”; for( int i = 0; string[i] != 0 ; ++i ) { if( string[i] >= ‘A’ && string[i] <= ‘Z’ ) string[i] = string[i] + (‘a’ – ‘A’); //string[i] + (97 – 65) }

32 Formatted Input (1) We use two commands to properly obtain input from the keyboard fgets & sscanf fgets places data collected form the keyboard into a buffer stored as a character string up to and including a carriage return (when the user presses return or enter) fgets( buffer, sizeof(buffer), stdin );

33 Formatted Input (2) sscanf splits the input into variables
Space delimited Uses conversion metasymbols like printf sscanf( buffer, “%d %f”, &x, &y); Note the ambersands (&) & is commonly required for input & is not required for strings sscanf( buffer, “%s %s”, &city, &state);

34 Formatted Input (3) #include <stdio.h>
#define BUFF_SIZE 100 //const int BUFF_SIZE = 100; // obtain a float from the user int main( void ) { float x = 0; float y = 0; char buffer[BUFF_SIZE] = { 0 }; printf( "Enter two floats(x y): "); fgets( buffer, sizeof(buffer), stdin ); sscanf( buffer, "%f %f", &x, &y );

35 Formatted Input (4) #include <stdio.h> #define BUFF_SIZE 100
#define NUM_SIZE 100 // obtain NUM_SIZE floats from the user int main( void ) { float x[NUM_SIZE] = { 0 }; char buffer[BUFF_SIZE] = { 0 }; for( int i=0; i < NUM_SIZE; ++i ) printf("Enter entry %d: ", i ); fgets( buffer, sizeof(buffer), stdin ); sscanf( buffer, "%f", &x[i]); }

36 Formatted Input (5) #include <stdio.h> #define BUFF_SIZE 100
#define NAME_SIZE 100 // obtain a string from the user int main( void ) { char name[NAME_SIZE] = { 0 }; char buffer[BUFF_SIZE] = { 0 }; printf("Enter name:” ); fgets( buffer, sizeof(buffer), stdin ); sscanf( buffer, "%s", name); // note, no &

37 Formatted Input (5) #include <stdio.h> #define BUFF_SIZE 100
#define NAME_SIZE 100 #define NAME_QTY 5 // obtain NAME_QTY strings from the user int main( void ) { char names[NAME_QTY][NAME_SIZE] = { 0 }; char buffer[BUFF_SIZE] = { 0 }; for( int i=0; i < NAME_QTY; ++i ) printf("Enter entry %d: ", i ); fgets( buffer, sizeof(buffer), stdin ); sscanf( buffer, "%s", names[i]); }

38 References Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York, p. 327. Kochan, S.G. (2014), Programming in C, 4th ed., Addison-Wesley, Indianapolis, IN, ch. 6 & 9


Download ppt "Lecture 5: How to think like a programmer, Arrays & Strings"

Similar presentations


Ads by Google