Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 270 – Survey of Programming Languages Loops in C Modified from Dr. Robert Siegfried’s Presentation.

Similar presentations


Presentation on theme: "CSC 270 – Survey of Programming Languages Loops in C Modified from Dr. Robert Siegfried’s Presentation."— Presentation transcript:

1 CSC 270 – Survey of Programming Languages Loops in C Modified from Dr. Robert Siegfried’s Presentation

2 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

3 Counting Loops (continued) for (count = start; count <= finish; count++) statement variable used to count times through the loop initial value of the counter final value of the counter Note: No shorthand declaration of counter so cannot do for (int count =

4 HelloAgain.c #include /* * Hello again -this is a better way to write *"Hello, again" five times */ intmain(void) {inti; for (i = 1; i <= 5; i++) { printf("Hello, again\n"); } return(0); } You try: ask how many times to repeat

5 The Revised HelloAgain.c #include /* * Hello again -Write "Hello, again" as many times *as the user wants */ intmain(void) { inti, 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); }

6 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

7 averagen.c #include /* * averagen - Find the average of n values where *the user enters n */ intmain(void) { floatsum, average, value; intnum_values, current_value; //Find out how many values there are printf("How many values are you going to enter ? "); scanf("%d", &num_values);

8 /* 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 average average = sum / num_values; printf("The average is %f\n", average); return(0); } averagegen.c continued

9 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

10 Syntax: While and Do/While Loops WHILE: while(condition){ statements } DO WHILE: do { statement(s) } (condition)

11 keepasking.c While Example #include /* A simple example of how while works */ intmain(void) { intnumber; /* Get your first number */ printf("Hi there. Pick a positive" " integer >>"); scanf("%d", &number);

12 /* 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); }

13 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

14 gpa.c with sentinel value #include /* * 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;

15 /* * 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");

16 /* 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 */

17 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++;

18 // 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); }

19 /* * 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); }

20 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

21 switch( ) { 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

22 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.

23 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

24 The Magic Number Program #include /* * 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;

25 /* 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++; }

26 /* 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

27 Random Number not so Random? Magic number program: #include 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

28 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); }

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

30 exit() exit() allows the user to let a program terminate if the program detects an unrecoverable error. The statement #include has to be included to use exit. A non-zero status value should be returned when the program terminates abnormally.

31 Java Comparison Thus Far Credit: http://introcs.cs.princeton.edu/java/faq/c2java.html FeatureCJava type of languagefunction oriented / imperativeobject oriented file naming conventions stack.c, stack.h Stack.java - file name matches name of class basic programming unit functionclass / Abstract Data Type portability of source code possible with disciplineyes portability of compiled code no, recompile for each architecture yes, bytecode is "write once, run anywhere" compilation gcc hello.c creates machine language code javac Hello.java creates Java virtual machine language bytecode buffer overflow segmentation fault, core dump, unpredicatable program checked run-time error exception boolean type use int: 0 for false, nonzero for true OR include and use bool boolean is its own type - stores value true or false character typechar is usually 8 bit ASCIIchar is 16 bit UNICODE strings'\0'-terminated character array built-in immutable String data type accessing a library#include import java.io.File;

32 More Java Comparison Feature CJava printing to standard output printf("sum = %d", x);System.out.println("sum = " + x); formatted printingprintf("avg = %3.2f", avg); System.out.printf("avg = %3.2f", avg) reading from stdinscanf("%d", &x);int x = StdIn.readInt(); declaring constantsconst and #definefinal for loopsfor (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 castinganything goes checked exception at run-time or compile-time demotionsautomatic, but might lose precision must explicitly cast, e.g., to convert from long to int variable declarationat beginning of a blockbefore you use it variable naming conventions sum_of_squaressumOfSquares Credit: http://introcs.cs.princeton.edu/java/faq/c2java.html

33 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


Download ppt "CSC 270 – Survey of Programming Languages Loops in C Modified from Dr. Robert Siegfried’s Presentation."

Similar presentations


Ads by Google