Date post: | 18-Jan-2016 |
Category: |
Documents |
Upload: | paula-hoover |
View: | 214 times |
Download: | 0 times |
CSC 270 – Survey of Programming Languages
Loops in C
Modified from Dr. Robert Siegfried’s Presentation
Objectives• Repeating: While; Do While; Counting (for)
– Counting - # of times– While – go on a condition– Do /While – do at least once, then continue on
condition
• Condition– Switch
• Random number generation• Exit
Counting Loops (continued)
for (count = start; count <= finish; count++)
statement
variable used to counttimes through the loop
initial value of the counter
final value ofthe counter
Note: No shorthand declaration of counter so cannot do for (int count =
HelloAgain.c
#include <stdio.h>
/* * Hello again - this is a better way to write * "Hello, again" five times */int main(void){ int i; for (i = 1; i <= 5; i++) {
printf("Hello, again\n"); }
return(0);}
You try: ask how many times to repeat
The Revised HelloAgain.c#include <stdio.h>
/* * Hello again - Write "Hello, again" as many times * as the user wants */int main(void){
int i, total_times; unsigned int count;
printf("How many times do you want to ""say \"hello\" ? ");
scanf("%u", &total_times);
for (count = 0; count < total_times; count++)printf("Hello, again\n");
return(0);}
Example: Averaging n Numbers
Accumulating inside a loop
•Let's start by outlining our algorithm:
1. Find out how many values there are.
2. Add up all the values.
3. Divide by the number of values
4. Print the result
averagen.c
#include <stdio.h>/* * averagen - Find the average of n values where * the user enters n */int main(void){
float sum, average, value;int num_values, current_value;
//Find out how many values there areprintf("How many values are you going to enter ? ");scanf("%d", &num_values);
/* Read in each value and add it to the sum */sum = 0.0;for (current_value = 1;
current_value <= num_values; current_value++) {printf("What is the next value ? ");scanf("%f", &value);
sum = sum + value;}
// Calculate and print out the averageaverage = sum / num_values;printf("The average is %f\n", average);return(0);
}
averagegen.c continued
Counting loop vs Conditional Loop
• When do we end?• While loop stops at any boolean test you
choose– No automatic counter– Do /While – runs once first– While – tests the first time– Remember
• – GO condition, not STOP condition
Syntax: While and Do/While LoopsWHILE:
while(condition) {
statements
}
DO WHILE:
do {
statement(s)
} (condition)
keepasking.c While Example
#include <stdio.h>
/* A simple example of how while works */
int main(void)
{
int number;
/* Get your first number */
printf("Hi there. Pick a positive"
" integer >>");
scanf("%d", &number);
/* Keep reading number as long as
they are positive */
while (number > 0) {
printf("Pick another positive"
" integer>>");
scanf("%d", &number);
}
printf("%d is not a positive integer\n",
number);
return(0);
}
Sentinel Value
• Often conditional loops continue until some special value is encountered in the input which effectively tells the program to stop running the loop. This is called a sentinel value because it is the value for which we are watching.
• ‘X’ is the sentinel value in the GPA algorithm’s main loop
gpa.c with sentinel value
#include <stdio.h>
/*
* Calculates a grade point average assuming
* that all courses have the same point value
* and that A, B, C and D are passing grades and
* that all other grades are failing.
*/
int main(void) {
int num_courses = 0, total = 0;
char grade;
float gpa;
/*
* Print the instructions and an
* introductory message
*/
printf("This program calculates your grade"
" point average\n");
printf("assuming that all courses have "
"the same point\n");
printf("value. It also assumes that " "grades of A, B, C and D\n");
printf("are passing and that all other " "grades are failing.\n");
printf("To indicate that you are finished,"
" enter a grade of \'X\'\n\n");
/* Get the first course grade */
printf("What grade did you get in your "
"first class?");
scanf("%c", &grade);
/* Add up the numerical equivalents of
the grades */
while (grade != 'X') {
/* Convert an A to a 4, B to a 3, etc.
and add it to the total */
if (grade == 'A')
total = total + 4;
else if (grade == 'B')
total = total + 3;
else if (grade == 'C')
total = total + 2;
else if (grade == 'D')
total = total + 1;
else if (grade != 'F')
printf("A grade of %c is assumed to "
"be an F\n", grade);
num_courses++;
// Get the next course grade
printf("What grade did you get in the "
"next class?");
/*
* The \n is necessary so we can skip the
* newline we entered when we pressed
* the enter key.
*/
scanf("\n%c", &grade);
}
/*
* Divide the point total by the number of
* classes to get the grade point average
* and print it.
*/
gpa = (float) total / num_courses;
printf("Your grade point average is"
" %4.2f\n",gpa);
return(0);
}
while (grade != 'X') {
switch(grade) {
case ‘A' :
case ‘a' :
total = total + 4;
break;
….(handle b-d)
case ‘F’ :
break;
default:
printf(“%s is invalid”,grade);
printf(“enter a new grade”);
break;
}
}
GPA with Switch
switch( <variable to examine> ) {
case value to match :
case optionally another value to match :
statements to execute on either match
break;
case value to match :
case optionally another value to match :
statements to execute on either match break;
default:
statements to execute if no other match
break;
}
}
Switch
Magic Number Problem - Random
• The magic number game involves guessing a number and with each wrong guess, the player is told “too high” or “ too low”. The goal is to guess the number in the smallest number of tries.
• We need a method for having the computer pick a number at random for the player to guess.
• We will need to learn about how to use “library functions” to provide us with the magic number.
Designing the Magic Number Algorithm
Input – The player’s guess(es)
Output – A clue (“too high” or “too low”) and the number of guesses that it took.
Initial Algorithm
1. Use the random number function to pick a number
2. Let the player make a guess
3. As long as the player hasn’t guessed the number, give the appropriate clue and let him/her guess again.
4. Print the number of tries
The Magic Number Program
#include <stdio.h>#include <stdlib.h>
/* * main() - The magic number game has the user * trying to guess which number between 1 * and 100 the computer has picked */int main(void) { int magic, guess; int tries = 1;
/* * Use the random number function to pick a * number */
magic = rand() % 100 + 1;
/* Let the user make a guess */ printf("Guess ?"); scanf("%d", &guess); while (guess != magic) {
/* * Tell him whether it's too high * or too low */
if (guess > magic) printf(".. Wrong .. Too high\n\n"); else printf(".. Wrong .. Too low\n\n"); /* Let the user make another guess */ printf("Guess ?"); scanf("%d", &guess); tries++; }
/* Tell the user that (s)he won */if (guess == magic) {
printf("** Right!! ** "); printf("%d is the magic number\n", magic); } /* Tell the user how many guesses it took */ printf("You took %d guesses\n", tries); return(0);}1
Random Number not so Random?Magic number program: #include <stdio.h>#include <stdlib.h> int main(void) { int magic, guess; int tries = 1; /* * Use the random number function to pick a * number */ // srand( time( NULL)); magic = rand() % 100 + 1;
printf("%i",magic);
•Seed your random number generator using srand(seed) – time can be a good seed•For industrial strength, research your platform
Change Magic Number to Do While
• The main loop in the magic number program becomes:do{
/* Let the user make a guess */
printf("Guess: ");
scanf("%d", &guess);
/* If the user won, tell him/her */
if (guess == magic) {
printf("** Right!! ** “ << endl);
printf("%d is the magic number\n", magic);
}
Revisiting the magic number program (continued)
// Let the user make another guess
if (guess > magic)
printf(".. Wrong .. Too high\n\n");
else
printf(".. Wrong .. Too low\N\n");
tries++;
} while (guess != magic);
exit()• exit() allows the user to let a program
terminate if the program detects an unrecoverable error.
• The statement#include <stdlib.h>
has to be included to use exit.
• A non-zero status value should be returned when the program terminates abnormally.
Java Comparison Thus Far
Credit: http://introcs.cs.princeton.edu/java/faq/c2java.html
Feature C Java
type of language function oriented / imperative object orientedfile naming conventions
stack.c, stack.hStack.java - file name matches name of class
basic programming unit
function class / Abstract Data Type
portability of source code
possible with discipline yes
portability of compiled code
no, recompile for each architectureyes, bytecode is "write once, run anywhere"
compilationgcc hello.c creates machine language code
javac Hello.java creates Java virtual machine language bytecode
buffer overflowsegmentation fault, core dump, unpredicatable program
checked run-time error exception
boolean typeuse int: 0 for false, nonzero for true OR include <stdbool.h> and use bool
boolean is its own type - stores value true or false
character type char is usually 8 bit ASCII char is 16 bit UNICODE
strings '\0'-terminated character arraybuilt-in immutable String data type
accessing a library #include <stdio.h> import java.io.File;
More Java ComparisonFeature C Java
printing to standard output
printf("sum = %d", x); System.out.println("sum = " + x);
formatted printing printf("avg = %3.2f", avg);System.out.printf("avg = %3.2f", avg)
reading from stdin scanf("%d", &x); int x = StdIn.readInt();declaring constants const and #define finalfor loops for (i = 0; i < N; i++) for (int i = 0; i < N; i++)
variable auto-initialization
not guaranteed
instance variables (and array elements) initialized to 0, null, or false, compile-time error to access uninitialized variables
casting anything goeschecked exception at run-time or compile-time
demotions automatic, but might lose precisionmust explicitly cast, e.g., to convert from long to int
variable declaration at beginning of a block before you use it
variable naming conventions
sum_of_squares sumOfSquares
Credit: http://introcs.cs.princeton.edu/java/faq/c2java.html
Summary• Decisions– If / else if / else
– switch
• Loops– For counter must be created before loop starts
– While OR Do while
• Random # – rand gives # between 0 and high value
– rand() % choices and maybe add 1
– Random – seed with srand
• Exit– Requires stdlib.h; error condition should be negative
– Exits entire program