Beginning C for Engineers Fall 2005 Lecture 2 – Section 2 (9/7/05) Section 4 (9/8/05)

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Arithmetic in C. 2 Type Casting: STOPPED You can change the data type of the variable in an expression by: (data_Type) Variable_Name Ex: int a = 15;
Introduction to C Programming
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Flow of Control Part 1: Selection
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
COP 3275 COMPUTER PROGRAMMING USING C Instructor: Diego Rivera-Gutierrez
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
Week 8: Decisions Bryan Burlingame 21 October 2015.
Lecture 05 Functions II, Storage Class, Scope, rand() METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
COMP Loop Statements Yi Hong May 21, 2015.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
CMSC 104, Version 9/011 Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else Statement Nesting of.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
UMBC CMSC 104 – Section 01, Fall 2016
EKT120 COMPUTER PROGRAMMING
Chapter 2 - Introduction to C Programming
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Chapter 2 - Introduction to C Programming
Looping.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Relational and Logical Operators
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Relational and Logical Operators
Chapter 2 - Introduction to C Programming
More Loops Topics Relational Operators Logical Operators for Loops.
Introduction to C Programming
Programming Fundamental
Presentation transcript:

Beginning C for Engineers Fall 2005 Lecture 2 – Section 2 (9/7/05) Section 4 (9/8/05)

2 Outline Quiz 1 Hand in Academic Integrity Forms Make sure to check announcements on webpage Classroom change: (Lecture 4 and on) –Section 2 (Wednesday): starting 9/21 Sage 5101 –Section 4 (Thursday): starting 9/22 Walker 5113 Using RCS File Sharing If Statements Relational Operators Logical Operators While Loops Random Numbers

3 RCS File Sharing An icon should already be on your desktop Use your rcs username and password –Same as SecureCRT Two directories will appear: –Public (can close this) –Private (this is your personal directory) Can drag and drop files Make sure file always has a.c extension Now use SecureCRT just for compiling and running your programs –gcc –Wall filename.c –a.out or./a.out Easier to print and your programs

4 if Statements Syntax:if ( condition ) { statement1; statement 2;... } The condition is any valid expression –It evaluates to true or false (more on this later). The statements inside the IF statement can be any valid C statements including other IF statements. Meaning: condition statement1; statement2;... true false Handle one special case

5 Relational Operators operator description example result x = 10, y=2 < less than x < y false(0) > greater than x > y+5 true(1) <= less or equal x/2 <= y false >= greater or equal x/5 >= y true == equal x-1 == y false != not equal x != y true * Technically, in C, true is anything other than 0

6 Finding the minimum of two numbers /* min.c Find min of two numbers September 7, 2005 */ #include int main () { int a, b, min; /* get two inputs */ printf( "Enter the first number: ”); scanf(“%d”, &a); printf( "Enter the second number: ”); scanf(“%d”, &b); We use printf to prompt the user for two inputs –Recall that %d is used for ints in printf and scanf We use scanf to read in the numbers entered by the user

7 Finding the minimum of two numbers (cont) /* Calculate the min */ if (a <= b) { min = a; } if (b < a) { min = b; } /* Print the result */ printf (“The min is %d\n”, min); return 0; } We use an if statement to find the min. The statement min = a; only gets executed if the condition (a <= b) is true. Similarly for the statement min = b; Note that only one of the conditions will be true, so min is only assigned a value once. The brackets { } constitute a “block” - everything between them is associated with the if

8 Logical Operators ABorandnot A || BA && B!A false falsefalsefalsetrue false truetruefalsetrue true falsetruefalsefalse truetruetruetruefalse Precedence for a Boolean expression: –expressions in parentheses –arithmetic expressions –relational operators –not –and, or in order from left to right unless otherwise specified A and B are expressions which evaulate to true or false

9 Example Condition ( x = 10, y = 20) (x+1 > 0) || (y == x) && (x+y < 25) (11 > 0) (20 = = 10) (30 < 25) TRUE FALSE FALSE TRUE || FALSE TRUE TRUE && FALSE FALSE if ( )

10 Logical and Relational Operators are Binary Operators They should only be used to operate on the two values on either side. Right Wrong if ((70 <= score) && (score <= 100)) if (70 <= score <= 100) printf(“You Pass!\n”); printf(“You Pass!\n”); if (x <= y && x <= z) if (x <= y && z) printf(“x is smallest\n”); printf(“x is smallest\n”); if (y == 2 || y == 3) if (y == 2 || 3) c = 10; c = 10;

11 What can go wrong here? float average; float total; int howMany;. average = total / howMany;

12 if ( Expression ) { Statement1; Statement 2; … } else { Statement1; Statement2; … } If-Else Syntax

13 if... else provides two-way selection between executing one of 2 clauses (the if clause or the else clause) TRUE FALSE if clauseelse clause expression

14 Improved Version float average, float total; int howMany;..... if ( howMany > 0 ) { average = total / howMany; printf(“%f”, average); } else printf( “No prices were entered”);

15 Nesting IF - ELSE Statements /* Display letter grade for a given test score. */ #include int main () { float score; char grade; /* get input */ printf("Enter test score:“); scanf(“%f”, &score); … Suppose that you want a program that reads a test score and converts it to a letter grade. –90  scoreA –80  score < 90B –70  score < 80C –60  score < 70D – score < 60F rThis requires more than two cases (i.e., five cases). l multiple cases can be done with nested IF- ELSE statements l you must be careful in how you order the cases

16 Nesting IF - ELSE Statements (cont.) /* calculate the letter grade */ if (score < 60) { grade = ‘F’; } else if (score < 70) { grade = ‘D’ } else if (score < 80) { grade = ‘C’; } else if (score < 90) { grade = ‘B’; } else { grade = ‘A’; } printf(“Letter grade is %c\n”, grade); return 0; } Each case assumes the previous cases are not true. If multiple cases are true, only the first true case is executed. The last case is usually written with “else” rather than “else if ” to serve as a default case. –catch situations where the other cases don’t apply Each case can have multiple statements to execute. –in this example there is only one statement in each case

17 Use of blocks is recommended if ( Expression ) { } else { } int x = 5; if ( x == 1 ) printf( “one\n” ); else printf( “two\n” ); “if clause” “else clause” * Braces can only be omitted when each clause is a single statement Be careful with this however! If you add another statement and forget about the missing { }’s then the added statement will be outside the if or else clause and will be executed no matter what.

18 What output? and Why? int age; age = 30; if ( age < 18 ) printf( “Do you drive?” ); printf( “You’re too young to vote”);

19 What output? and Why? int age; … age = 20; … if ( age = 16 ) { printf( “Did you get your driver’s license?\n”); } You need to be extra careful with testing for equality. Here you need two =‘s otherwise it is an assignment statement and passes as true!!

20 While Loops l Loops are used to execute a block of code repeatedly until a certain condition is true SYNTAX: while ( Expression ) {.. /* loop body */. } NOTE: Loop body can be a single statement, a null statement, or a block. If statements execute a block of code when a certain condition is true

21 WHILE LOOP When the expression is tested and found to be false, the loop is exited and control passes to the statement which follows the loop body. FALSE TRUE body statement Expression

22 #include int main() { int total = 0, num; printf( “Enter a number (-1 to stop ) ”); scanf(“%d”, &num); while (num != -1) { total = total + num; printf( “Enter a number (-1 to stop ) ”); scanf(“%d”, &num); } printf( “Total = %d”, total); return 0; }

23 Example from HW 1 printf("Enter the radius of the first circle: "); scanf("%f", &radius1); aCircle1 = PI * radius1 * radius1; circ1 = PI * 2 * radius1; printf("The circumference of the first circle is %f\n", circ1); printf("The area of the first circle is %f\n", aCircle1); printf("Enter the radius of the second circle: "); scanf("%f", &radius2); aCircle2 = PI * radius2 * radius2; circ2 = PI * 2 * radius2; printf("The circumference of the second circle is %f\n", circ2); printf("The area of the second circle is %f\n", aCircle2);

24 HW1 using one while loop numCircles = 1; while(numCircles < 3) { printf(“Enter radius for circle %d: ”, numCircles); scanf(“%f”, &radius); aCircle = radius * radius * PI; c = radius * PI * 2; printf(“The circumference for circle %d is: %f\n”, numCircles, c); printf(“The area for circle %d is: %f\n”, numCircles, aCircle); numCircles = numCircles + 1; }

25 Random Numbers Random numbers use the rand() function, defined in the header file. In general, rand() produces a random integer between 0 and 32,767. However, it is usually more useful to restrict the range it produces Ex: /* random int between 1 and 20 */ int randint = 1 + rand () % 20; Remember the % operator returns the remainder of the division. Here it would return a number between 0 and 19, so that is why we add 1 to it so that randint is a number from 1 to 20.

26 Rand() /* random float between 0 and 1 */ float randfloat = 1.0 * rand () / RAND_MAX ; RAND_MAX is the maximum int rand() would return, so above rand() / RAND_MAX is by itself is integer division and would therefore not return the correct result. This is why you must multiply rand() by 1.0 first! To get unpredictably random numbers, the random seed can be set using srand. A good seed is the time function, defined in the time.h header file. srand ( time ( NULL ) );

27 Example with Random Numbers # include int main ( ) { int cointoss, guess ; srand ( time ( NULL )); /* seeds the random number generator */ cointoss = rand () % 2; /* cointoss is either 0 or 1 */ printf (" Guess (0: Heads, 1: Tails ): " ); scanf ( " %d", & guess ); if ( cointoss == guess ) printf ("You got it !\n"); else printf(“Sorry!\n”); return 0; }

28 Example with Random Numbers # include int main ( ) { int cointoss, guess ; cointoss = 0; srand ( time ( NULL )); /* seeds the random number generator */ while ( cointoss != -1) { /* continue until user stops */ cointoss = rand () % 2; /* cointoss is either 0 or 1 */ printf (" Guess ( 0: Heads, 1: Tails, -1: Stop ): " ); scanf ( " %d", & guess ); if ( cointoss == guess ) printf ("You got it !\n"); else if ( cointoss != -1 ) printf(“Sorry!\n”); } return 0; }

29 Homework HW 2 is due next week. –Submission instructions are the same as before. Read Chapter 3 You can spend the rest of class on the Lab 2 –Take your time and read the entire lab before coding! –If you don’t finish in class, it to me or put in my mailbox in Amos Eaton by tomorrow evening.