CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

Similar documents
CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

CpSc 1111 Lab 5 Formatting and Flow Control

CpSc 1111 Lab 9 2-D Arrays

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

CpSc 1111 Lab 4 Formatting and Flow Control

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

C Functions. 5.2 Program Modules in C

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

CpSc 1111 Lab 1 Introduction to Unix Systems, Editors, and C

The C standard library

CS3157: Advanced Programming. Outline

Programming Assignment #4 Arrays and Pointers

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Computer Science & Engineering 150A Problem Solving Using Computers

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Programming for Engineers Functions

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Functions. Systems Programming Concepts

Chapter 5 C Functions

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

C Program Structures

CS 142 Style Guide Grading and Details

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Beginning C Programming for Engineers

Programming and Data Structure

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

today cs3157-fall2002-sklar-lect05 1

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Lecture 04 FUNCTIONS AND ARRAYS

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

.. Fall 2013 CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. Lab 5: Conditional Statements

3. A Periodic Alarm: intdate.c & sigsend.c

Question 2. [2 points] True False By default, structures are passed-by-reference.

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Fundamentals of Programming Session 8

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Pointers and scanf() Steven R. Bagley

CMSC 201 Fall 2018 Lab 04 While Loops

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

Compiling and Running a C Program in Unix

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

CSE 5A Introduction to Programming I (C) Homework 4

Lab Instructor : Jean Lai

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Chapter 1 Getting Started Structured Programming 1

Programming. C++ Basics

C Programs: Simple Statements and Expressions

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Program Organization and Comments

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Lecture 4. The elements of C Syntax. Daily Puzzle

WARM UP LESSONS BARE BASICS

Chapter Four: Loops II

COMP Assignment 1

CS 356, Fall 2018 Data Lab (Part 1): Manipulating Bits Due: Wednesday, Sep. 5, 11:59PM

JTSK Programming in C II C-Lab II. Lecture 3 & 4

SPRING 2017 CSCI 304 LAB1 (Due on Feb-14, 11:59:59pm)

Computer Programming: Skills & Concepts (CP) Variables and ints

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

ECE15: Lab #3. Problem 1. University of California San Diego ( 1) + x4. + x8 + (1)

Lab 1 Introduction to UNIX and C

CMSC 201 Fall 2018 Python Coding Standards

Function Call Stack and Activation Records

CS 1044 Project 1 Fall 2011

(created by professor Marina Tanasyuk) FUNCTIONS

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details.

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

King Abdulaziz University Faculty of Computing and Information Technology Computer Science Department

Section 1: Let s Shake Off the Rust!

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

بسم اهلل الرمحن الرحيم

ASSIGNMENT 2. COMP-202A, Fall 2011, All Sections. Due: Monday, October 17th, 2011 (23:30)

CSE123. Program Design and Modular Programming Functions 1-1

CS 356, Fall 2018 Data Lab (Part 2): Manipulating Bits Due: Mon, Sep. 17, 11:59PM

FALL 2017 CSCI 304 LAB1 (Due on Sep-19, 11:59:59pm)

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 1

a f b e c d Figure 1 Figure 2 Figure 3

Calling Prewritten Functions in C

Object-Based Programming. Programming with Objects

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

EL2310 Scientific Programming

Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

CS261: HOMEWORK 2 Due 04/13/2012, at 2pm

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Methods CSC 121 Fall 2016 Howard Rosenthal

Chapter 4 Functions By C.K. Liang

An Introduction to C Through Annotated Examples

Introduction to Java Applications

1. The programming language C is more than 30 years old. True or False? (Circle your choice.)

Transcription:

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point? Overview For this lab, you will use: one or more of the conditional statements explained below scanf() or fscanf() to read in integer values entered by the user (from standard input) the sqrt() function from the math library a random number generator a loop Background Information All programming languages provide constructs to execute a section of code conditionally. In this week s lab, you will implement decision making with the use of one or more of the following conditional statements. You will also learn how to use the random number generator rand() function. if Statements The simplest conditional statement is the if statement. It is used when we want the computer to maybe execute some code based on the truth value of some condition. If the condition is true, the code in the body of the if statement will execute; if it is false, the body of the if statement will be skipped and execution will continue with the code immediately after the if statement. Structure: if (condition) Example of an if statement: if (n < 2) printf( Hello\n ); The above code prints a message only if the value of n is less than two. Otherwise, it does nothing. What does the following code print if the value of n is 1? if (n < 2) printf( Hello ); printf( Tigers!!\n ); What does it print if the value of n is 2? 1

if-else Statements The previous if statement included code that executes when a condition is true. If we want certain code to execute when a condition is true and other code that executes when a condition is false, we use if-else statements. Exactly one of the two possible branches will be taken with an if-else statement. Structure: if (condition) else Example: if ((age >= 13) && (age <= 19)) printf( You are a teenager.\n ); else printf( You are not a teenager.\n ); if-else-if Statements When there are more than two options, instead of nesting if-else statements, C provides us with the if-else-if construct. Structure: if (condition) else if (condition) else if (condition) else Note: The last else is optional and works well whenever there is a fall through case when all other conditions are false. If there is no fall through option needed, then it may make sense to not have that last else at all. 2

Example: if ( (day > 2) && (day <= 6) ) printf( weekday\n ); else if (day == 7) printf( Saturday\n ); else printf( Sunday\n ); Dangling else Problem The compiler associates an else- part with the closest if. The following code illustrates this point. What does it print? (Remember that the compiler ignores formatting.) int n = 5; printf( hello\n ); if (n < 4) if (n > 0) printf( good\n ); else printf( bye\n ); Random Number Generators rand() and srand() The function rand() will generate a (pseudo) random number from 0 to RAND_MAX, which is a constant defined in <stdlib.h> with a value of 32,767. You use the rand() function to return a value in a range by using modulo of the returned value by the range span + initial value of the range: rand() % range_span + initial value where range_span = (high low + 1) For example, if you wanted 100 numbers from 0 to 99: (rand() % 100) If you wanted 100 numbers from 1 to 100: (rand() % 100) + 1 1985 2016 (inclusive): (rand() % 32) + 1985 10 30 (inclusive): (rand() % 21) + 10 But, using rand() as explained above will produce the same set of random values every time you run it because it automatically seeds the random number generator with 1. You can seed the random number generator with the srand() function using something other than 1. The most common way to seed the random number generator is to use the time function, which is in the <time.h> library file. This will seed the random number generator with the current time, which will be different every time you run the program, thus producing different sets of random values every time you run the program. The way to do this is by including the following line of code in your program, somewhere above the rand() function call: srand( (int)time(0) ); Typically, you would only seed the random number generator once per every set of calls to rand(). Don t forget to #include both <stdlib.h> and <time.h> at the top of your file. 3

The math.h Library (same as in the Lab 4 write-up) Another library provided by C is the math.h library. This library provides math functions that you can use, such as pow(), sqrt(), abs(), cos(), sin(), tan(), log(), among many others. Pages 485-492 of the Programming in C book list many of the functions in this library. You can also learn about the math library functions by typing man at the Unix command prompt, a space, the function name, and then pressing Enter. For example, to learn about sqrt you would enter: man sqrt To get some experience using the math library, for this lab assignment, you will be using the sqrt() function. One last thing for you to know - you will need to compile your program with an option (l for library, m for math), for example: gcc -Wall lab6.c lm Lab Assignment Reminder About Style, Formatting, and Commenting Requirements The top of your file should have a header comment, which should contain: o Your name o Date o Lab section o Lab number o Brief description about what the program does o Any other helpful information that you think would be good to have. Variables should be declared at the top of the main function, and should have meaningful names. One exception to the rule of using meaningful names for variables is to use i or j or n or some other single letter as a loop index variable name; this is a common, acceptable practice. Always indent your code in a readable way. Some formatting examples may be found here: https://people.cs.clemson.edu/~chochri/assignments/formatting_examples.pdf Write a program called lab6.c which will prompt the user to enter a three digit number on the keyboard. Your program will find the square root of the number using the sqrt() function from the math library (make it also an integer value). You can print that value to the screen so that you check to make sure it compiles and works; then remove or comment out that print statement and continue to the next step. That square root value will be used as the radius of a circle. Your program will use a random number generator (RNG) to check if a randomly generated point falls within the circle with that radius and center at (0,0). Both values of the point (x,y) will be randomly generated. Don t forget to seed the random number generator first. Both times that rand() is called, the general formula will be: (rand() % (total number of values within the range)) + (beginning value of the range) The range of values should be within (radius + 5) and +(radius + 5). The total number of values within the range will be an expression based on that range. Put this much into a loop that goes 10 times (except for seeding the RNG this only needs to be done once before the loop) and show the (x,y) values each time. Compile and run, and verify by inspection that both the x and y values of each of the 10 points fall within the correct range. Run it several times and you will see a different set of random (x,y) values each time it is run. Once you feel confident that your random (x,y) values are within the correct range, comment out the line of code where it is seeded, and then recompile and run again. The output on the following page shows what you should get when entering 100 as your 3-digit input number with an un-seeded RNG. 4

Enter a 3 digit number: 100 ( -2, 1) ( 12, 10) ( 8, 10) ( 1, -3) ( -6, -14) (-13, -8) ( 5, 4) ( 8, 1) (-15, -9) ( 7, 1) If your output matches what is shown above, you can continue with the rest of the program. You ll need the formula for determining if a point falls within a circle you can Google this if you need to. Using an if-else statement inside that loop that goes 10 times, print to the user whether that point lies inside, on the circumference of, or outside the circle. Your finished output should look like the following: Enter a 3 digit number: 100 ( -2, 1) is inside the circle with radius 10 ( 12, 10) is outside the circle with radius 10 ( 8, 10) is outside the circle with radius 10 ( 1, -3) is inside the circle with radius 10 ( -6,-14) is outside the circle with radius 10 (-13, -8) is outside the circle with radius 10 ( 5, 4) is inside the circle with radius 10 ( 8, 1) is inside the circle with radius 10 (-15, -9) is outside the circle with radius 10 ( 7, 1) is inside the circle with radius 10 Turn In Work 1. Before turning in your assignment, make sure you have followed all of the instructions stated in this assignment and any additional instructions given by your lab instructor(s). Always test, test, and retest that your program compiles and runs successfully on our Unix machines before submitting it. 2. Show your TA that you completed the assignment. Then submit your lab6.c program using the handin page: http://handin.cs.clemson.edu. Don t forget to always check on the handin page that your submission worked. You can go to your bucket to see what is there. Grading Rubric If your program does not compile on our Unix machines or your assignment was not submitted on time, then you will receive a grade of zero for this assignment. Otherwise, points for this lab assignment will be earned based on the following criteria: Functionality 60 Style, Formatting, & Commenting 10 Use of conditional statement 10 Use of loop 10 Use of sqrt() from math.h 5 Use of rand() from stdlib.h 5 Penalty for not following this lab s instructions (incorrect I/O, etc.) -5 if warnings when compile, and other point deductions decided by grader 5

6