// This program checks whether a user-input value // is between 0 and 1, non-inclusive. #include <stdio.h>

Similar documents
Sources: On the Web: Slides will be available on:

arrays C Programming Language - Arrays

C Programming. Charudatt Kadolkar. IIT Guwahati. C Programming p.1/34

CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan 20 July 2015

Informatica e Sistemi in Tempo Reale

Java Basics: Data Types, Variables, and Loops

The C Programming Language

Passing 1D arrays to functions.

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

J a v a Quiz (Unit 3, Test 0 Practice)

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Chapter 5. Selection 5-1

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

FEEG Applied Programming 5 - Tutorial Session

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Introduction to Programming II Winter, 2014 Assignment 2

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

1 Description of The Simpletron

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Lab Experience 17. Programming Language Translation

Module 816. File Management in C. M. Campbell 1993 Deakin University

The programming language C. sws1 1

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Computer Science 2nd Year Solved Exercise. Programs 3/4/2013. Aumir Shabbir Pakistan School & College Muscat. Important. Chapter # 3.

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Chapter 8 Selection 8-1

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Introduction to Java

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Education: P.h.D. Candidate (Santa Clara University, California) M.S. in Computer Engineering (Santa Clara University, California)

CS 241 Data Organization Coding Standards

Senem Kumova Metin & Ilker Korkmaz 1

University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. CSC467 Compilers and Interpreters Fall Semester, 2005

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

MAT 2170: Laboratory 3

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Body Mass Index and Calorie Intake

10CS35: Data Structures Using C

Chapter 2: Elements of Java

5 Arrays and Pointers

Solving Rational Equations

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

(hours worked,rateofpay, and regular and over time pay) for a list of employees. We have

Introduction to Python

Statements and Control Flow

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Computer Programming I

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

CS 106 Introduction to Computer Science I

C A R I B B E A N E X A M I N A T I O N S REPORT ON CANDIDATES S WORK IN THE CARIBBEAN SECONDARY EDUCATION CERTIFICATE EXAMINATION MAY/JUNE 2012

CSI 333 Lecture 1 Number Systems

Part I. Multiple Choice Questions (2 points each):

Excel: Introduction to Formulas

Chapter 1: Key Concepts of Programming and Software Engineering

CS 1361-D10: Computer Science I

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8

CP Lab 2: Writing programs for simple arithmetic problems

C++FA 5.1 PRACTICE MID-TERM EXAM

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Chapter 5 Functions. Introducing Functions

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

B.Sc.(Computer Science) and. B.Sc.(IT) Effective From July 2011

C Programming Structure of a C18 Program

Answers to Review Questions Chapter 7

Conditionals (with solutions)

13 Classes & Objects with Constructors/Destructors

Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm

The C Programming Language course syllabus associate level

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Introduction to Visual C++.NET Programming. Using.NET Environment

JavaScript: Control Statements I

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

While Loop. 6. Iteration

Java Types and Enums. Nathaniel Osgood MIT April 25, 2012

Example of a Java program

Chapter One Introduction to Programming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Iteration CHAPTER 6. Topic Summary

Visual Logic Instructions and Assignments

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Stacks. Linear data structures

Chapter 3. Input and output. 3.1 The System class

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Transcription:

CS1010 Programming Methodology Week 5: Selection Statements and Repetition Statements Learn as much as you can while you are young, since life becomes too busy later. ~ Dana Stewart Scott To students: Some of the programs shown here are available on the CS1010 website, CA Discussion : http://www.comp.nus.edu.sg/~cs1010/3_ca/discussion.html Please be reminded that the deadline for Lab #2 is 12 Feb (Fri) 10pm! Please be reminded that your Practical Exam 1 (PE1) is on 17 Feb (Wed)! Please look up the CS1010 website, PE page for more information. I. Syntax and Good Programming Habits 1. The following programs either do not work or work but are very badly written. Explain why and how would you correct/improve them? (a) bad_prog1.c: The gcc compiler issues a warning for this program. Why? If you ignore the warning and go ahead to run it, and enter 0.5 as the input, what result do you get? Why? (Hint: if you add this printf() statement just before the if statement, printf("%d\n", 0 < value); what output does it give?) (Always compile your programs with the Wall option, and do not ignore warnings. The compiler must have some good reason to alert you through its warnings.) // This program checks whether a user-input value // is between 0 and 1, non-inclusive. float value; printf("enter value: "); scanf("%f", &value); if (0 < value < 1) printf("%f is between 0 and 1\n", value); printf("%f is not between 0 and 1\n", value); (b) Suppose you correct the program in (a), but remove the ampersand (&) in the scanf statement. You ignore the compiler s warnings and go ahead to run the program. What will happen? CS1010 AY2015/6 Semester 2 (Week 5) Page 1 of 12

(c) bad_prog2.c A list is in non-decreasing order if any value in the list is never smaller than its preceding value. For example: (-5, 6, 9, 12), and (2, 8, 8, 15, 15). (If any value must be larger than its preceding value, the list is said to be strictly increasing or monotonically increasing.) Comment on the program below and improve it. // This program checks whether 3 input values // are in non-decreasing order. int a, b, c; printf("enter 3 integers: "); scanf("%d %d %d", &a, &b, &c); if (a <= b) { if (b <= c) printf("the values are in non-decreasing order.\n"); printf("the values are not in non-decreasing order.\n"); if (a > b) { if (b <= c) printf("the values are not in non-decreasing order.\n"); printf("the values are not in non-decreasing order.\n"); printf("the values are not in non-decreasing order.\n"); CS1010 AY2015/6 Semester 2 (Week 5) Page 2 of 12

(d) bad_prog3.c Improve the following program. To avoid re-computation and to aid checking, what variable do you think you may introduce and how are you going to make use of it? // declare the first input and second input double the_first_input, the_second_input; // ask user to enter two values printf("enter two values: "); scanf("%lf %lf", &the_first_input, &the_second_input); if (the_first_input/the_second_input < 90.2) { if (the_first_input/the_second_input < 32.5) printf("paper\n"); if (the_first_input/the_second_input >= 45.8) printf("ruler\n"); printf("pencil\n"); { if (the_first_input/the_second_input >= 100.0) printf("unknown\n"); if (the_first_input/the_second_input < 100.0) printf("eraser\n"); printf("clip\n"); CS1010 AY2015/6 Semester 2 (Week 5) Page 3 of 12

(e) bad_prog4.c In Unit 2 slides 24 26, we discussed the GCD algorithm. The program below includes the GCD function. Trace the code to verify that it is correct. You should discover that the assumption of A > B in the Euclidean algorithm (slide 24) is not necessary. // This program computes the GCD of two non-negative integers, // not both zeroes. void GCD(int, int); // prototype for GCD function int num1, num2; printf("enter two non-negative integers, not both zeroes: "); scanf("%d %d", &num1, &num2); GCD(num1, num2); // This function computes the GCD of a and b // Pre-cond: a and b are both >= 0, and not both = 0 void GCD(int a, int b) { int r; // r is the remainder of a/b while (b > 0) { r = a%b; a = b; b = r; printf("the GCD is %d\n", a); However, the function is considered not well written, although it is correct, as it violates some principle of programming. Do you know why? CS1010 AY2015/6 Semester 2 (Week 5) Page 4 of 12

II. Exploration 2. Conditional operator? : (a) There is a conditional operator? : which is commonly used in place of the if statement wherever appropriate. Study the program cond_op1.c below, run it and test it with several inputs. // Illustrating the conditional operator? : int n, p; printf("enter an integer: "); scanf("%d", &n); p = ((n > 5) && (n < 20))? 33 : -77; printf("p = %d\n", p); (b) Do you know how to use the conditional operator? : now? Try to replace the if statement in the following program cond_op2.c with the conditional operator. int a, b, max; printf("enter 2 integers: "); scanf("%d %d", &a, &b); if (a > b) max = a; max = b; Replace the if statement in the box with the conditional operator. printf("max = %d\n", max); CS1010 AY2015/6 Semester 2 (Week 5) Page 5 of 12

(c) Exploration: You have used format specifiers in a printf() statement, such as %d for integers, and %f for float and double values. There are others, such as %c for characters, and %s for strings. We will explore %s here. The following two printf() statements are equivalent: printf("good morning, David!\n"); printf("good %s, %s!\n", "morning", "David"); Here we use string literals such as "morning" and "David" in the print list (see lecture notes: Unit #3 slide 20) of the second statement, but in general you can use string variables here. We will discuss string variables another time. Can you modify the program cond_op3.c below by using the %s format specifier and the conditional operator? int n; printf("enter a non-negative integer: "); scanf("%d", &n); if (n < 2) printf("there is %d person.\n", n); printf("there are %d persons.\n", n); CS1010 AY2015/6 Semester 2 (Week 5) Page 6 of 12

3. Study the following program switch_to_if.c. You see a new data type here: the char type, which stands for character. Character constants are enclosed in single quotes, for example, 'A', 'w', '+'. The format specifier for character in a printf() statement is %c. What is the output if the user enters 12? Replace the switch statement with an equivalent if statement. // To convert switch statement into if statement. int score; char grade; printf("enter score: "); scanf("%d", &score); switch (score) { case 10: case 9: case 8: grade = 'A'; break; case 7: case 6: grade = 'B'; break; case 5: grade = 'C'; break; default: grade = 'F'; printf("grade is %c.\n", grade); CS1010 AY2015/6 Semester 2 (Week 5) Page 7 of 12

III. Problem Solving with Selection Statements 4. Study the following program if_to_switch.c. This program differs from the one in question 3 above in that the input is a real number from 0.0 to 100.0. You may assume that the user always enters a non-negative score that is at most 100.0. // To convert if statement into switch statement. float score; char grade; // You may assume score entered is >= 0.0 and <= 100.0 printf("enter score: "); scanf("%f", &score); if (score >= 80.0) grade = 'A'; if (score >= 60.0) grade = 'B'; if (score >= 50.0) grade = 'C'; grade = 'F'; printf("grade is %c.\n", grade); Convert the if statement into a switch statement. The challenge here is that the input score is a real number. Think about it. If you need help, post on IVLE, in the Discussion sessions forum. CS1010 AY2015/6 Semester 2 (Week 5) Page 8 of 12

5. Modularise the switch_to_if.c program given in question 3, that is, write a function compute_grade(int mark) to take in the mark (an integer) and return the corresponding grade (a character). This function is to be called in the main() function. 6. Given a person s weight in kilograms and height in metres, his/her BMI (Body Mass Index) is calculated based on this formula: BMI = Weight / Height 2 The following table shows the body types according to a person s gender and BMI: Female Male Underweight BMI 19 BMI 20 Acceptable BMI > 19 and 24 BMI > 20 and 25 Overweight BMI > 24 BMI > 25 Write a program bmi.c to do the following: 1. Read the user s gender (type int), weight (type double) and height (type double). 2. Call a function body_type() that takes in the above values, and returns the body type which is an integer. You need to find out what are the parameters for this function. 3. Upon obtaining the body type, display a suitable advice for the user. The gender is encoded using the following integers: 0 to represent female 1 to represent male The body type is encoded using the following integers: -1 to represent underweight 0 to represent acceptable 1 to represent overweight You are to define constants for the above integers, and use the switch statement wherever possible. Sample runs are shown below: Enter your gender (0 for female, 1 for male): 0 Enter your weight (kg) and height (m): 62 1.6 Time to join the gym! Enter your gender (0 for female, 1 for male): 1 Enter your weight (kg) and height (m): 62 1.6 Great! Maintain it! CS1010 AY2015/6 Semester 2 (Week 5) Page 9 of 12

Enter your gender (0 for female, 1 for male): 1 Enter your weight (kg) and height (m): 61.5 1.8 Stuff yourself with more food! IV. Repetition Statements I 7. Conversion of loop construct. You have learned 3 loop constructs: for, while and do-while. For each of the following parts, a particular loop construct is used. Rewrite the loop construct using the other 2 loop constructs (without adding any if statement), and indicate if there is any limitation on the new codes. You may assume that all variables are of type int. (a) sum = 0; i = -5; do { sum += i; i += 5; while (i < 100); printf("sum = %d\n", sum); (b) This for loop may look strange, but after converting it into the other 2 loop constructs you should understand what it does. Can you describe what the code does in words? printf("enter n: "); for (scanf("%d", &n); n < 0; scanf("%d", &n)) printf("enter n: "); printf("n = %d\n", n); Suppose the valid range of values for score in question 3 should be 0 to 10 inclusive. Would you now be able to write a code to check that the user s input is valid (and keep asking if it is invalid) before going on to the switch statement? (c) printf("enter n: "); scanf("%d", &n); i = 0; while (i < n) { printf("*"); i += 3; printf("\n"); CS1010 AY2015/6 Semester 2 (Week 5) Page 10 of 12

8. Manual tracing. (a) Spot an error in this program and correct it. Then manually trace the program and write out its output. int i, sum; for (i = 1; i < 1000; i*=2) sum += i; printf("sum = %d\n", sum); (b) Manually trace the program and write out its output. int a = 10, b = 200; while ((a*a) < (a+b)) { printf("a = %d, b = %d\n", a, b); a++; b+=10; (c) Manually trace the program and write out its output. int x, y, count = 0; for (x = 1; x <= 6; x++) for (y = x + 1; y <= 6; y++) count++; printf("count = %d\n", count); (d) Suppose we have a function draw_line(int a, int b) which draws a horizontal line segment from a to b. If you replace the statement count++; in part (c) above with the statement draw_line(x, y);, how would the line segments be drawn? The diagram below shows the first two line segments drawn (a new line segment is drawn above an old one). Complete the diagram. [You may look up the CS1010 website ( CA Discussion ) after 12 th September for the answer, but only after you attempt the question.] 1 2 3 4 5 6 CS1010 AY2015/6 Semester 2 (Week 5) Page 11 of 12

(e) Manually trace the program and write out its output. int x, y, z, count = 0; for (x = 1; x <= 5; x++) for (y = x; y <= 5; y++) for (z = x; z <= y; z++) count++; printf("count = %d\n", count); CS1010 AY2015/6 Semester 2 (Week 5) Page 12 of 12