Transcript ppt
Beginning C for Engineers
Fall 2005
Lecture 2 –
Section 2 (9/7/05)
Section 4 (9/8/05)
Outline
•
•
•
•
Quiz 1
Hand in Academic Integrity Forms
Make sure to check announcements on webpage
Classroom change: (Lecture 4 and on)
•
•
•
•
•
•
Using RCS File Sharing
If Statements
Relational Operators
Logical Operators
While Loops
Random Numbers
– Section 2 (Wednesday): starting 9/21 Sage 5101
– Section 4 (Thursday): starting 9/22 Walker 5113
2
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
3
if Statements
• Syntax:
if ( condition )
{
statement1;
statement 2;
...
}
Handle one special case
• 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
true
statement1;
statement2;
...
false
4
Relational Operators
operator
description
<
>
<=
>=
==
!=
less than
greater than
less or equal
greater or equal
equal
not equal
example
x = 10, y=2
x<y
x > y+5
x/2 <= y
x/5 >= y
x-1 == y
x != y
result
false(0)
true(1)
false
true
false
true
* Technically, in C, true is anything other than 0
5
Finding the minimum of two numbers
/*
*/
min.c
Find 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
6
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
7
Logical Operators
A and B are expressions which evaulate to true or false
A
B
or
A || B
and
A && B
not
!A
false
false
true
true
false
true
false
true
false
true
true
true
false
false
false
true
true
true
false
false
Precedence for a Boolean expression:
–
–
–
–
–
expressions in parentheses
arithmetic expressions
relational operators
not
and, or
in order from left to right
unless otherwise specified
8
Example Condition ( x = 10, y = 20)
if ( (x+1 > 0) || (y == x) && (x+y < 25) )
(11 > 0)
(20 = = 10)
(30 < 25)
TRUE
FALSE
FALSE
TRUE || FALSE
TRUE
TRUE && FALSE
FALSE
9
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))
printf(“You Pass!\n”);
if (70 <= score <= 100)
printf(“You Pass!\n”);
if (x <= y && x <= z)
printf(“x is smallest\n”);
if (x <= y && z)
printf(“x is smallest\n”);
if (y == 2 || y == 3)
c = 10;
if (y == 2 || 3)
c = 10;
10
What can go wrong here?
float average;
float total;
int
howMany;
.
.
.
average = total / howMany;
11
If-Else Syntax
if ( Expression )
{
Statement1;
Statement 2;
…
}
else
{
Statement1;
Statement2;
…
}
12
if ... else provides two-way selection
between executing one of 2 clauses
(the if clause or the else clause)
TRUE
if clause
expression
FALSE
else clause
13
Improved Version
float average,
float total;
int
howMany;
. . . . .
if ( howMany > 0 )
{
average = total / howMany;
printf(“%f”, average);
}
else
printf( “No prices were entered”);
14
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
–70 score < 80
–60 score < 70
–
score < 60
B
C
D
F
This requires more than two
cases (i.e., five cases).
multiple cases can be
done with nested IFELSE statements
you must be careful in
how you order the cases
15
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
16
Use of blocks is recommended
if ( Expression )
{
}
else
{
}
“if clause”
“else clause”
* Braces can only be omitted when each clause is a single statement
int x = 5;
if ( x == 1 )
printf( “one\n” );
else
printf( “two\n” );
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.
17
What output? and Why?
int age;
age = 30;
if ( age < 18 )
printf( “Do you drive?” );
printf( “You’re too young to vote”);
18
What output? and Why?
int age;
…
You need to be extra careful
with testing for equality.
age = 20;
Here you need two =‘s
otherwise it is an
…
assignment statement and
if ( age = 16 )
passes as true!!
{
printf( “Did you get your driver’s license?\n”);
}
19
While Loops
Loops are used to execute a block of code
repeatedly until a certain condition is true
SYNTAX:
If statements execute a block of code
when a certain condition is true
while ( Expression )
{
.
.
/* loop body */
.
}
NOTE: Loop body can be a single
statement, a null statement, or a block.
20
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
Expression
TRUE
body
statement
21
#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;
}
22
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);
23
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;
}
24
Random Numbers
Random 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.
25
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 ) );
26
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");
else
printf(“Sorry!\n”);
return 0;
}
27
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;
}
28
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.
29