beginning c for engineers fall 2005 lecture 2 – section 2 (9/7/05) section 4 (9/8/05)

Post on 28-Dec-2015

221 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Beginning C for EngineersFall 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 email 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:

conditionstatement1;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.cFind min of two numbers September 7, 2005

*/

#include <stdio.h>

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

A B or and notA || B A && B !A

false falsefalsefalse truefalse true true false truetrue false true false falsetrue true true true false

Precedence for a Boolean expression:– expressions in parentheses– arithmetic expressions– relational operators– not– and, or

in order from left to rightunless 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 clause else clause

expression

14

Improved Version

float average,float total;int howMany;

. . . . .

if ( howMany > 0 ){

average = total / howMany;

printf(“%f”, average);}

elseprintf( “No prices were entered”);

15

Nesting IF - ELSE Statements/* Display letter grade for a given test score.*/

#include <stdio.h>

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 score A–80 score < 90 B–70 score < 80 C–60 score < 70 D– score < 60 F

This requires more than two cases (i.e., five cases).

multiple cases can be done with nested IF-ELSE statements

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

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

bodystatement

Expression

22

#include <stdio.h>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 NumbersRandom numbers use the rand() function,

defined in the <stdlib.h> 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 <stdio.h># include <stdlib.h># include <time.h>

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");

elseprintf(“Sorry!\n”);

return 0;}

28

Example with Random Numbers

# include <stdio.h># include <stdlib.h># include <time.h>

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, email it to

me or put in my mailbox in Amos Eaton by tomorrow evening.

top related