CS1010 Programming Methodology

Slides:



Advertisements
Similar presentations
WEEK 5 Class Activities Lecturer’s slides.
Advertisements

CS1010 Programming Methodology
UNIT 4 Top-Down Design & Functions.
CS1010: Programming Methodology
CS1010 Programming Methodology
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
Display a 12-Month Calendar CS-2301 D-term Programming Assignment #2 12-Month Calendar CS-2301 System Programming C-term 2009 (Slides include materials.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Introduction to Computers and Programming Class 6 Introduction to C Professor Avi Rosenfeld.
Assignment #2, 12- month Calendar CS-2301, B-Term Programming Assignment #2 12-Month Calendar CS-2301, System Programming for Non-Majors (Slides.
WEEK 9 Class Activities Lecturer’s slides.
UNIT 7 Testing and Debugging.
CS1101: Programming Methodology Aaron Tan.
C programming: Variables, Expressions part II. Data Types of Arithmetic Expressions Relational Expressions Logical Expressions Multiple Assignments Compound.
CS1101: Programming Methodology Aaron Tan.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Agenda  Commenting  Inputting Data from Keyboard (scanf)  Arithmetic Operators  ( ) * / + - %  Order of Operations  Mixing Different Numeric Data.
Computer programming Lecture 4. Lecture 4: Outline Making Decisions [chap 6 – Kochan] –The if Statement –The if-else Construct –Logical Operators –Boolean.
CS1010: Programming Methodology
WEEK 4 Class Activities Lecturer’s slides.
Flow of Control Part 1: Selection
CS1101: Programming Methodology Aaron Tan.
UNIT 14 Functions with Pointer Parameters.
C++ Programming Language Lecture 2 Problem Analysis and Solution Representation By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
CS1010: Programming Methodology
COP 3275 COMPUTER PROGRAMMING USING C Instructor: Diego Rivera-Gutierrez
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
UNIT 5 Selection Statements.
Homework #2: Functions and Arrays By J. H. Wang Mar. 20, 2012.
WEEK 6 Class Activities Lecturer’s slides.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
UNIT 11 Random Numbers.
WEEK 8 Class Activities Lecturer’s slides.
WEEK 1 Class Activities.
DATA TYPE, MEMORY, AND FUNCTION Dong-Chul Kim BioMeCIS UTA 2/18/
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
CS1010: Programming Methodology
C Building Block Chapter 2. Variables A variable is a space in the computer’s memory set aside for a certain kind of data and given a name for easy reference.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
WEEK 10 Class Activities Lecturer’s slides.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Week 12 Class Activities.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CS1010 Discussion Group 11 Week 5 – Functions, Selection, Repetition.
CS1010 Programming Methodology
CS1010 Programming Methodology
CS1010 Programming Methodology
CS1010 Programming Methodology
ICS103 Programming in C Lecture 3: Introduction to C (2)
CS1010 Programming Methodology
CS1010 Programming Methodology
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Looping.
Learning to Program in Python
Introduction to C++ Programming
Programming Funamental slides
CSCE 206 Lab Structured Programming in C
1) C program development 2) Selection structure
Conversion Check your class notes and given examples at class.
CSCE 206 Lab Structured Programming in C
DATA TYPES There are four basic data types associated with variables:
Presentation transcript:

CS1010 Programming Methodology Lecturer’s slides http://www.comp.nus.edu.sg/~cs1010/ WEEK 3 Class Activities

Week 3: Writing Functions and Selection Statements CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Week 3: Writing Functions and Selection Statements Functions Ex #1: A Simple “Drawing” Program Ex #2: Tracing Functions Ex #3: Writing Pre-condition Ex #4: Cohesion Pop Quiz #1 Ex #5: Magic Number Selection Statements Pop Quiz #2 Example: Hi-Lo Game Ex #6: Leap Year Ex #7: NRIC Check Code Ex #8: Taxi Fare – Continue at home

Ex #1: A Simple “Drawing” Program (1/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Ex #1: A Simple “Drawing” Program (1/4) Problem: Write a program Unit4_DrawFigures.c to draw a rocket ship (which is a triangle over a rectangle, over an inverted V), a male stick figure (a circle over a rectangle over an inverted V), and a female stick figure (a circle over a triangle over an inverted V) rocket male female Analysis: No particular input needed, just draw the needed 3 figures There are common shapes shared by the 3 figures Design: Algorithm (view in words): Draw Rocket ship Draw Male stick figure (below Rocket ship) Draw Female stick figure (below Male stick figure)

Ex #1: A Simple “Drawing” Program (2/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Ex #1: A Simple “Drawing” Program (2/4) rocket male female Design (Structure Chart): Draw 3 Figures Draw Rocket Ship Draw Triangle Draw Rectangle Draw Inverted V Draw Male Stick Figure Draw Circle Draw Female Stick Figure

Ex #1: A Simple “Drawing” Program (3/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Ex #1: A Simple “Drawing” Program (3/4) Implementation (partial program) #include <stdio.h> void draw_rocket_ship(); void draw_male_stick_figure(); void draw_circle(); void draw_rectangle(); int main(void) { draw_rocket_ship(); printf("\n\n"); draw_male_stick_figure(); return 0; } void draw_rocket_ship() { void draw_male_stick_figure() { void draw_circle() { printf(" ** \n"); printf(" * * \n"); void draw_rectangle() { printf(" ****** \n"); Unit4_DrawFiguresPartial.c What are these called? What are they for? Write a complete program Unit4_DrawFigures.c

Ex #1: A Simple “Drawing” Program (4/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Ex #1: A Simple “Drawing” Program (4/4) Identify the functions that are already coded in Unit4_DrawFiguresPartial.c and the functions that you need to write/complete. Draw 3 Figures Draw Rocket Ship Draw Triangle Draw Rectangle Draw Inverted V Draw Male Stick Figure Draw Circle Draw Female Stick Figure

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) vim Working on exercise #1, use the opportunity to practise your vim skills. See vim video clips on IVLE multimedia. Deleting lines dd: to delete current line ndd: to delete n lines starting from current line Yanking (copying) lines yy: to yank current line nyy: to yank n lines starting from current line Deleted/yanked lines are stored in buffer Pasting lines in buffer p: To paste the lines in buffer after current line P: to paste the lines in buffer before current line Auto-indent program gg=G

Lessons learned in Exercise #1 CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Lessons learned in Exercise #1 There can be a hierarchy of functions Eg: main() calls draw_rocket_ship(), which in turn calls draw_triangle() A function can be called several times, and by different functions Eg: draw_triangle() is called by call_rocket_ship() and call_female_stick_figure() A void function does work, but does not return any value to its caller

Exercise #2: Tracing Functions (1/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #2: Tracing Functions (1/3) What is the output of this program? Week3_Trace1.c #include <stdio.h> float f(int, float); int g(int); int main(void) { int a = 27; float x = 3.5F; printf("%d\n", g(2*a)); printf("%.2f\n", f(a, x)); printf("%.2f\n", f(x, a)); return 0; } float f(int a, float x) { return g(a) + x; } int g(int a) { return a%5; 4 5.50 30.00

Exercise #2: Tracing Functions (2/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #2: Tracing Functions (2/3) What is the output of this program? Week3_Trace2.c #include <stdio.h> void h(int, int); int k(int); int main(void) { int a = 26, b = 9; h(a, b); printf("%d\n", k(b)); return 0; } void h(int x, int a) { int b = x%7 + a; printf("%d\n", k(b)); } int k(int a) { return 2*a; 28 18

Exercise #2: Tracing Functions (3/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #2: Tracing Functions (3/3) What is the output of this program? Week3_Trace3.c #include <stdio.h> int m(int); int main(void) { int a; m(3); printf("%d\n", m(4)); a = m(5); printf("%d\n", a); return 0; } int m(int x) { printf("Hi!\n"); return x*(x+1)/2; } Hi! Hi! 10 This exercise is to show that a function with non-void return type can be used like a void function, but its returned value will be “lost”. You may refer to the “scanf()” function which returns an integer (number of input data read), but sometimes we use scanf() without using its returned value. Hi! 15

Exercise #3: Writing Pre-condition CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #3: Writing Pre-condition The function triangle_area() computes the area of a right-angled triangle. The two parameters are the lengths of the two perpendicular sides. How should you write the pre-condition? // Compute the area of a right-angled triangle. // side1 and side2 are the lengths of the // two perpendicular sides. // Pre-cond: double triangle_area(double side1, double side2) { return side1 * side2 / 2.0; } side1 > 0, side2 > 0

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #4: Cohesion Which of the two approaches is correct? // Compute the area of a right-angled triangle. // Pre-cond: side1 > 0, side2 > 0 double triangle_area(double side1, double side2) { return side1 * side2 / 2.0; } // Compute the area of a right-angled triangle. // Pre-cond: side1 > 0, side2 > 0 void triangle_area(double side1, double side2) { printf("Area = %.2f\n", side1 * side2 / 2.0); } In general, a function should perform either computation or I/O, not both. triangle_area() is to compute the area, so it should return the answer to the caller, which then decides whether to print the answer or use it for further computation in a bigger task.

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Pop Quiz #1 (1/2) What is the output of this code and what value does the function f() return? A Value returned = 1 #include <stdio.h> int f(); int main(void) { printf("Value returned = %d\n", f()); return 0; } int f() { printf("A\n"); return 1; printf("B\n"); return 2; printf("C\n"); return 3;

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Pop Quiz #1 (2/2) What is the output of this code? #include <stdio.h> int g(int); int main(void) { printf("Answer = %d\n", g(3 + g(7))); return 0; } int g(int n) { return n * 10; Answer = 730

Exercise #5: Magic Number CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #5: Magic Number Write a program MagicNumber.c that reads two positive integers (with at most 5 digits) and for each, adds up the digits (from right) in positions 1, 3, and 5. The right-most digit of the sum is the required answer. [Time limit: 20 min.] Eg: If input is 76524, adding up digits 4, 5 and 7, we get 16. Hence the answer is 6. You should have a function get_magic() to compute and return the answer. Decide on its parameter(s). What is the precondition of the function? This exercise is mounted on CodeCrunch The reason I want the program to read 2 integers is to show that we call the same function twice. Also to show that the name of the argument needs not be the same as the name of the parameter. Also want to check whether students know how to write the precondition. Sample run: When you learn more next time, you can remove the “at most 5 digits” restriction. Enter 1st value: 76524 Magic number = 6 Enter 2nd value: 8946 Magic number = 5

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Pop Quiz #2 (1/2) Match each condition in (A) to its equivalent condition in (B). Assume that a is an int variable. A B if (a == 0) { ... } if (a != 0) { if (a) { if (!a) { Codes in (B) are very frequently encountered in C programming. They are not considered convoluted. However, you can stick with (A) if you find it more readable.

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Pop Quiz #2 (2/2) What is the output of the following code? if (x <= y) printf("Line 1\n"); printf("Line 2\n"); printf("Line 3\n"); if (x <= y) { printf("Line 1\n"); printf("Line 2\n"); printf("Line 3\n"); } Assuming that a, b and c are int variables, the following condition is incorrect? Why? if (a > b > c) What test data could you use to expose its flaw? How can you correct it? if ((a > b) && (b > c))

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Example: Hi-Lo Game User to guess a secret jackpot number between 1 and 10 inclusive. Program responses according to whether user’s guess is smaller than, larger than, or equal to the jackpot. Analysis Inputs: Jackpot number, your guess Outputs: Appropriate messages (“too high”, “too low”, “correct!)

Example: Hi-Lo Game (version 1) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Example: Hi-Lo Game (version 1) // Hi-Lo Game version 1 #include <stdio.h> int main(void) { int guess, jackpot = 8; printf("Guess the jackpot number between 1 and 10!\n"); printf("Please type your guess: "); scanf("%d", &guess); if (guess < jackpot) printf("Sorry, your guess is too low.\n"); if (guess > jackpot) printf("Sorry, your guess is too high.\n"); if (guess == jackpot) printf("You hit the JACKPOT!\n"); return 0; } Week3_HiLo_v1.c Jackpot is fixed to 8! No fun. We need random number (you’ll learn that in discussion session.) Can we change the 3 if statements into a single nested if-else statement?

Example: Hi-Lo Game (version 2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Example: Hi-Lo Game (version 2) // Hi-Lo Game version 2 #include <stdio.h> int main(void) { int guess, jackpot = 8; printf("Guess the jackpot number between 1 and 10!\n"); printf("Please type your guess: "); scanf("%d", &guess); if (guess < jackpot) printf("Sorry, your guess is too low.\n"); else if (guess > jackpot) printf("Sorry, your guess is too high.\n"); else printf("You hit the JACKPOT!\n"); return 0; } Week3_HiLo_v2.c Is this single nested if-else statement better than 3 if statements? Why?

Exercise #6: Leap Year (1/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #6: Leap Year (1/2) Write a modular program LeapYear.c to determine whether a year is a leap year. It should have a function int isLeapYear(int) with the year as the parameter and it returns 1 (true) if it is a leap year, or 0 (false) otherwise Analysis: Input: A 4-digit positive integer Output: “xxxx is a leap year” or “xxxx is not a leap year” A year is a leap year if … It is divisible by 4 but not by 100; or It is divisible by 400

Exercise #6: Leap Year (2/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #6: Leap Year (2/2) Are these leap years? 1997 2002 1996 2000 1900 2100 2400 2300 X is a leap year if X is divisible by 4 but not by 100; or X is divisible by 400

Exercise #7: NRIC Check Code (1/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #7: NRIC Check Code (1/4) Algorithm for NRIC check code NRIC consists of 7 digits. Eg: 8730215 Step 1: Multiply the digits with corresponding weights 2,7,6,5,4,3,2 and add them up. Eg: 82 + 77 + 36 + 05 + 24 + 13 + 52 = 16+49+18+0+8+3+10 = 104 Step 2: Divide step 1 result by 11 to obtain the remainder. Eg: 104 % 11 = 5

Exercise #7: NRIC Check Code (2/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #7: NRIC Check Code (2/4) Algorithm for NRIC check code (cont…) Step 3: Subtract step 2 result from 11 Eg: 11 – 5 = 6 Step 4: Match step 3 result in this table for the check code Eg: The check code corresponding to 6 is ‘F’. Therefore, the check code for 8730215 is ‘F’. Sample run: 1 2 3 4 5 6 7 8 9 10 11 A B C D E F G H I Z J Enter 7-digit NRIC number: 8730215 Check code is F

Exercise #7: NRIC Check Code (3/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #7: NRIC Check Code (3/4) Write a program NRIC.c to generate the check code given a 7-digit NRIC number. Your program should have a function char generateCode(int) that takes in a single integer (the NRIC number) and returns a character (the check code). You need to use the char type. A character constant is enclosed in single quotes (eg: 'A', 'Z'). The format specifier for char type is %c (to be used in a printf() statement). Do not use techniques that are not covered in class, such as array. Your program may be long now; it’s ok, you can write an improved version later. This exercise is mounted on CodeCrunch.

Exercise #7: NRIC Check Code (4/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #7: NRIC Check Code (4/4) The intention of this exercise is to let you handle a single integer input (assigned to an integer variable) and then extract the 7 individual digits from it. Please do not do the following (especially for students who are more experienced in programming): use string (array of characters) and extract out the individual digit characters and convert each of them into a numeric digit; or use %1d%1d%1d%1d%1d%1d%1d in scanf() to read in 7 digits separately into 7 variables. We want to limit the technique to what we have covered in this week’s lecture, and also, we want to use an approach that is more “portable”. The %1d method may not be possible in some other programming languages.

Exercise #8: Taxi Fare (1/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #8: Taxi Fare (1/4) The taxi fare structure in Singapore must be one of the most complex in the world! See http://www.taxisingapore.com/taxi-fare/ Write a program TaxiFare.c that reads the following input data (all are of int type) from the user, and computes the taxi fare: dayType: 0 represents weekends and public holidays (PH for short); 1 represents weekdays and non-PH boardHour, boardMin: the hour and minute the passengers board the taxi (eg: 14 27 if the passengers board the taxi at 2:27 PM) distance: the distance of the journey, in metres Your program should have a function float computeFare(int dayType, int boardTime, int distance) The parameter boardTime is converted from the input data boardHour and boardMin. It is the number of minutes since 0:00hr. Eg: If boardHour and boardMin are 14 and 27 respectively, then boardTime is 867.

Exercise #8: Taxi Fare (2/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #8: Taxi Fare (2/4) To implement the actual taxi fare could be a PE question . In this exercise, we use a (grossly) simplified fare structure: Basic Fare: Surcharge (applicable at the time of boarding): Flag-down (inclusive of 1st km or less) $3.40 Every 400m thereafter or less up to 10.2km $0.22 Every 350m thereafter or less after 10.2km dayType Midnight charge (12am – 5:59am) Peak hour charge (6am – 9:29am) Peak hour charge (6pm – 11:59pm) 0: Weekends & PH 50% of metered fare None 25% of metered fare 1: Weekdays and non-PH

Exercise #8: Taxi Fare (3/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #8: Taxi Fare (3/4) You are given an incomplete program TaxiFarePartial.c. Complete the program. This exercise is mounted on CodeCrunch. Sample runs below for your checking. First 1km: $3.40 Next 9.2km: 23  $0.22 = $5.06 Next 750m: 3$0.22 = $0.66 Basic fare = $9.12 No surcharge Total fare = $9.12 Day type: 0 Boarding hour and minute: 14 27 Distance: 10950 Total taxi fare is $9.12 Day type: 1 Boarding hour and minute: 9 20 Distance: 6123 Total taxi fare is $7.83 First 1km: $3.40 Next 5123m: 13  $0.22 = $2.86 Basic fare = $6.26 Surcharge = 25%  $6.26 = $1.57 Total fare = $7.83 Day type: 1 Boarding hour and minute: 5 59 Distance: 9000 Total taxi fare is $11.70 First 1km: $3.40 Next 8km: 20  $0.22 = $4.40 Basic fare = $7.80 Surcharge = 50%  $7.80 = $3.90 Total fare = $11.70

Exercise #8: Taxi Fare (4/4) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Exercise #8: Taxi Fare (4/4) Note that due to inaccuracy of floating-point number representation, depending on how you code your formula to compute the taxi fare, the result may defer slightly from the model output CodeCrunch uses. Hence, your program may fail CodeCrunch’s tests. In this case, if the difference is very small (probably in the second decimal place), just treat your answer as correct.

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Things-To-Do (1/2) Revise Chapter 5 Functions Chapter 4 Lessons 4.1 – 4.6, Beginning Decision Making Read Application Programs 4.1 (pg 176 – 179) and 4.7 (pg 191 – 193) Preparation for next week Read Chapter 3 Lessons 4.7 – 4.11 (Repetition statements)

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Things-To-Do (2/2) Lab #1 has been released Deadline: 6 September 2014, Saturday, 9am Lab #2 will be released next week Deadline: 13 September 2014, Saturday, 9am Do practice exercises on CodeCrunch

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) End of File