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

Slides:



Advertisements
Similar presentations
Lecture 2: Developing Procedural Thinking (How to think like a programmer) BJ Furman 06FEB2012.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 10.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
Chapter 1 Program Design
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Input, Output, and Processing
Lecture 5: Developing Procedural Thinking (How to think like a programmer) B Burlingame 30 Sept 2015.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
Lecture 13: Arrays, Pointers, Code examples B Burlingame 2 Dec 2015.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
ALGORITHMS AND FLOWCHARTS. Why Algorithm is needed? 2 Computer Program ? Set of instructions to perform some specific task Is Program itself a Software.
Lecture 3: Developing Procedural Thinking (How to think like a programmer) B Burlingame 16 Feb 2016.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Lecture 7: Arrays BJ Furman 06OCT2012. The Plan for Today Announcements Review of variables and memory Arrays  What is an array?  How do you declare.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Lecture 6: More Decisions & Arrays B Burlingame 9 March 2016.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
Arithmetic Expressions
CS1010 Programming Methodology
Topics Designing a Program Input, Processing, and Output
User-Written Functions
Strings CSCI 112: Programming in C.
EGR 2261 Unit 10 Two-dimensional Arrays
Chapter 4 C Program Control Part I
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
© 2016 Pearson Education, Ltd. All rights reserved.
Functions, Part 2 of 2 Topics Functions That Return a Value
C Programming Tutorial – Part I
ALGORITHMS AND FLOWCHARTS
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
ICS103 Programming in C Lecture 3: Introduction to C (2)
Lecture 13 & 14.
A First Book of ANSI C Fourth Edition
Arrays in C.
CS 240 – Lecture 11 Pseudocode.
Lecture 11: Strings B Burlingame 11 April 2018.
Lecture 10: Strings B Burlingame 4 April 2018.
IPC144 Introduction to Programming Using C Week 2 – Lesson 1
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Lecture 8b: Strings BJ Furman 15OCT2012.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
7 Arrays.
A First Book of ANSI C Fourth Edition
EKT150 : Computer Programming
Defining methods and more arrays
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Programming We have seen various examples of programming languages
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Basic Concepts of Algorithm
Programming Languages and Paradigms
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Functions, Part 2 of 3 Topics Functions That Return a Value
Presentation transcript:

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

Announcements Homework #3 due next week Read chapter 9

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. 62.37 is a floating point constant. 4.219E-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.

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

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

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

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

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

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.

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 http://www.cs.xu.edu/csci170/08f/sect01/Overheads/WhatIsAnAlgorithm.html (visited 19JUN2009)

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

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.

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

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?

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

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!

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

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.

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: http://www.engr.sjsu.edu/bjfurman/courses/ME30/source/miles_to_kilometers.c

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.

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 ? 6. add 1 to counter 7. get number 8. is (number > max) ? 9. max = number 10. go to line 5 11. otherwise 12. print max 13.end Flowchart Notice the loops!

Find average

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]); printf(" @ 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'

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

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]); printf(" @ 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]?

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]); printf(" @ 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.

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.

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

ASCII Table

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

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. http://www.cplusplus.com/reference/cstring/ 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) }

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

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

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

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

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 &

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

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