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

Similar documents
CpSc 1111 Lab 5 Formatting and Flow Control

CpSc 1111 Lab 4 Formatting and Flow Control

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

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

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

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

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

CpSc 1111 Lab 9 2-D Arrays

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

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

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Use of scanf. scanf("%d", &number);

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

DECISION CONTROL AND LOOPING STATEMENTS

Flow Control. CSC215 Lecture

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

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

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

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

Informatica e Sistemi in Tempo Reale

Fundamentals of Programming

Fundamental of Programming (C)

Lecture 3. More About C

Variables and literals

EL2310 Scientific Programming

Introduction. C provides two styles of flow control:

printf( Please enter another number: ); scanf( %d, &num2);

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

Formatting & Style Examples

Reserved Words and Identifiers

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

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

Repetition Structures

CpSc 101, Fall 2015 Lab7: Image File Creation

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Fundamentals of Programming Session 8

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

8. Control statements

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

Topic 6: A Quick Intro To C

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Stream Model of I/O. Basic I/O in C

CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014)

Module 4: Decision-making and forming loops

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Programming for Electrical and Computer Engineers. Loops

The Design of C: A Rational Reconstruction (cont.)

LECTURE 5 Control Structures Part 2

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Course Outline Introduction to C-Programming

Introduction to Programming

(Refer Slide Time: 00:26)

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

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

Lecture 6. Statements

EL2310 Scientific Programming

C: How to Program. Week /Mar/05

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Dept. of CSE, IIT KGP

Continued from previous lecture

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structure: Selection

Variables and Functions. ROBOTC Software

CS : Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September

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

Chapter 3: Arrays and More C Functionality

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

C introduction: part 1

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CSI33 Data Structures

Lecture 03 Bits, Bytes and Data Types

Technical Questions. Q 1) What are the key features in C programming language?

CS50 Supersection (for those less comfortable)

The Design of C: A Rational Reconstruction: Part 2

Lecture 10. Daily Puzzle

University of Maryland College Park Dept of Computer Science CMSC106 Fall 2013 Midterm I Key

3 The L oop Control Structure

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

C and Programming Basics

Should you know scanf and printf?

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Physics 2660: Fundamentals of Scientific Computing. Lecture 5 Instructor: Prof. Chris Neu

9/10/2016. Time for Some Detailed Examples. ECE 120: Introduction to Computing. Let s See How This Loop Works. One Statement/Step at a Time

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

SU 2017 May 11/16 LAB 2: Character and integer literals, number systems, character arrays manipulation, relational operator

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Transcription:

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting Your factors.c and multtable.c files are due by Wednesday, 11:59 pm, to be submitted on the SoC handin page at 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. Thursday in lab, you will get the instructions for Part b. The final program after Thursday s lab will be due by Friday, 11:59 pm, to be submitted on the SoC handin page at 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. Overview By the end of the lab, you will be able to: use fscanf() to accept an integer input from the user execute a basic block iteratively using loops and conditional statements to produce a table that a table of factors and multiples of the numbers from 1 to the number entered by the user Background Information The following will review the three different types of loops that you learned about in lecture as well as if statements. Loops Remember lab 1 where you were supposed to print Hello World! 20 times? What if you were supposed to print that message 1000 times? Would you really copy and paste it 1000 times in your program? Sometimes it is necessary to repetitively execute a statement, or block of statements, while some condition remains true, or until some condition becomes false. Because of all the possible formulations of conditions, it is the case that there are multiple correct ways to construct such iterations. And, alas, there are even more incorrect ways to construct them. There are three different iteration constructs in C: 1. while loop 2. do-while loop 3. for loop 1. while Loop The while loop allows us to write a segment of code that repeats while some condition remains true. // loop index variable used in condition declared and // initialized somewhere above the while loop while (condition) { loop_expression; // expression that changes the condition, // updates the loop index variable 1

Important Notes: The statement or statements controlled by the while loop are called the body of the loop and are enclosed by curly braces. It is necessary that the body of the loop modify the value of the condition. Why? Proper use of indentation is critical for human readability. But, indentation is completely irrelevant to the C compiler. Print the integer values between 10 and 1 in decreasing order. (Note: This is not a complete C program; it needs to include stdio.h and it needs a proper main() function header. Also, it is not indented properly see how hard it is to read and make sense of the code?) int value; value = 10; fprintf(stdout, " Table Of Values \n"); while (value > 0) { fprintf (stdout, "%3d\n", value); value = value - 1; In the above code, we only want the heading to be printed one time, so the first fprintf() is placed outside the loop. Example of while loop (with proper formatting and good use of comments): // addition.c // 08/31/15 // Print the sum of positive integers provided by the user. #include <stdio.h> int main(void) { int input; // to hold user input int sum = 0; // sum of all input values // prompt user and get input printf("enter a positive integer, or a negative integer when done: "); scanf("%d", &input); // loop to add each input to sum, and get another integer from user while (input >= 0) { sum = sum + input; printf("enter a positive integer, or a negative integer when done: "); scanf("%d", &input); // display the sum printf("the sum is %d\n", sum); return 0; Notice that we prompt the user for the first input before the loop. Inside the loop, we do the math and prompt the user for the next number. 2

2. do-while Loop The do-while loop allows us to write a segment of code that also repeats while some condition remains true. // loop index variable used in condition declared and // initialized somewhere above do-while loop do { loop_expression; // expression that changes the condition, or updates // the loop index variable while (condition); Important Notes: The above loop is guaranteed to execute the statement(s) at least once. Do you see why? As with the while() loop, it is necessary that the body of the loop modify the value of the condition so that it is not an infinite loop. Don t forget the semi-colon after the while condition. The other loops do not have a semi-colon at the end of the loop. 3. for Loop The third loop structure is the for loop. // loop index variable declared somewhere above for loop for (init_expression; loop_condition; loop_expression) { Important Notes: The statement or statements controlled by the for loop are called the body of the loop and are enclosed in curly braces. The init_expression gives the starting value for the control variable (loop index variable) being used by the loop. The control variable needs to be declared somewhere above the for loop, probably at the top of the program where the other variables are declared. int i; for (i = 0; loop_condition; loop_expression) The loop_condition will be evaluated before each iteration of the loop; if it evaluates to true, an iteration of the loop body will occur; if it evaluates to false, no code inside the body of the loop will execute. int i; for (i = 0; i <= 3; loop_expression) o In this code above, as long as the value of i is less than or equal to 3, the statements inside the body of the loop will be executed. 3

The loop_expression will change the value of the loop control variable so that a stopping point may be reached in the loop_condition. int i; for (i = 0; i <= 3; i++) o In the code above, i will increment by 1 each time immediately after an iteration of the loop, allowing for the loop_condition to eventually evaluate to false (assuming a proper condition exists), thereby ending the loop. (i++ is the same as i = i + 1 and the same as i += 1 and with loops, the same as ++i ) for (value = 10; value > 0; value--) { fprintf(stdout, "%3d\n", value); Note: value-- is the same as value = value 1 Also, the starting value for the control variable called value in this case is 10, and it decrements by 1 after each iteration of the loop. The loop will continue to iterate as long as the value of the control variable is greater than 0. So, how many iterations will occur? Review of 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. 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? 4

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. if (condition) { else { 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. 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. if ( (day > 2) && (day <= 6) ) { printf( weekday\n ); else if (day == 7) { printf( Saturday\n ); 5

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 ); Review of scanf() and characters By now, you know to use scanf() or fscanf() to get input from the user. For example, if you were asking the user to enter an integer, and storing their input into a variable called input, your code might look like the following: int input; fprintf(stdout, Enter an integer: ); fscanf(stdin, %d, &input); If the user were to enter a character, your code would change this way: char inputchar; fprintf(stdout, Enter a character: ); fscanf(stdin, %c, &inputchar); Remember that characters are char type, which is really a specialized type of int. If the user entered a lower case t as their character which was stored in the variable called inputchar, to print the value of that variable, you would use %c as the format string, just like above in the fscanf(), such as: fprintf(stdout, %c, inputchar); Which would print the letter t to the screen. If you instead typed the following, what would be printed? fprintf(stdout, %d, inputchar); If you refer to an ASCII table, such as this one: http://www.asciitable.com, you will see that the decimal (integer) value for the lower case t is 116. You will also see that the octal value of that letter is 164, and the hexadecimal value is 74. That same ASCII table is also in section 3.7 of the the Chapter 3 notes posted on Canvas, as well as a direct link on the Chapter 3 page on Canvas. Formatting Output To print an octal value to the screen, you would use %o or %#o in the print statement. Using the second one: %#o prints a leading 0. int x = 42; fprintf(stdout, %o, x); 6

fprintf(stdout, %#o, x); produces the following output: 52 052 because 42 in decimal has an octal value of 52. To print hex values to the screen, you could use %x or %X or %#x or %#X. You should create a test.c file (not to be handed in) to play around with these different types of formatting to get a feel for how they work. You already know that to limit the precision of a floating-point value printed out to the screen to three decimal places, you might do something like the following: fprintf(stdout, %.3f, var1); There are other flags and modifiers that can be included in a print statement to format the output: %[flags][width][.precision][length]type where flags include: - left-justify + generate a plus sign for positive values # put a leading 0 (zero) on an octal value and 0x (zero-x) on a hex value 0 (zero, not the letter O ) pad a number with leading zeros and the width modifier: is the minimum number of characters to generate numbers are padded with leading spaces unless the width has a leading zero flag specifying leading zeros if the number is larger than the number of digits specified, the number will be printed with the wider width For example, using the - as a flag, left justifies the values in a column that is width wide. fprintf(stdout, %-6d%-6d, 12, 43); fprintf(stdout, %-6d%-6d, 324, 72); produces the following output with the values in columns that are 6 characters wide and are left-justified: 12 43 324 72 The C programming language does not have a type called string but rather uses an array of characters to represent a string. We have not gotten to this in lecture yet, so it s ok if you do not understand what an array is. For now, just know that you can print a string in a printf() statement by using the format specifier %s and then using a string literal in double quotes after the comma, as in the following example: fprintf(stdout, %s, Hello World! ); which would produce the following output to the screen: Hello World! Formatted output using width values can be used for strings as well. For example: fprintf(stdout, %8s%10s\n%8s%10s, apple, orange, banana, grape ); would produce the following output to the screen: apple orange banana grape 7

You can add additional code like the above example into your test.c file to play around with formatting output into columns, left justified or not, using a plus sign for positive values, etc. 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 Don t forget to use the Wall flag when compiling, for example: gcc Wall factors.c You will be creating two files today, one called multtable.c and factors.c. In multtable.c, provide a C program that will do the following: 1. Prompt the user to enter an integer. Note: Use fprintf() and fscanf () functions throughout your program. 2. Using loops, print out to the user a multiplication table from 1 to the number entered by the user. SAMPLE OUTPUT Multiplication Table from 1 to? (enter an integer): - - > 10 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 3. The numbers in the first column should be in a field of width 6 with 2 spaces after the number; and each number in the remaining columns should be in a field of width 4. 8

In factors.c, provide a C program that will do the following: 1. Prompt the user to enter an integer. Note: Use fprintf() and fscanf () functions throughout your program. 2. Using loops, print out to the user the factors for each number from 1 to the number entered by the user. SAMPLE OUTPUT Factors from 1 to? (enter an integer): - - > 10 1 1 2 1 2 3 1 3 4 1 2 4 5 1 5 6 1 2 3 6 7 1 7 8 1 2 4 8 9 1 3 9 10 1 2 5 10 3. The numbers in the first column should be in a field of width 4 with 2 spaces after the number; and each number in the remaining columns should be just simply %d with 1 space after the d. 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 both of your files: multtable.c and factors.c 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 (correct output on various test cases) 65 Output Formatting (as per lab specs) 10 Code Style: Formatting & Commenting 10 Proper use of loops and Conditional Statements 10 Use of fprintf() and fscanf() 5 Miscellaneous point deductions as decided by grader for things like: compilation warnings use of break not in switch statements naming files incorrectly missing return statement at bottom of main() function 9

etc. 10