1 / 33

CSC 270 – Survey of Programming Languages

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

sefren
Télécharger la présentation

CSC 270 – Survey of Programming Languages

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 final value of the counter initial value of the counter variable used to count times through the loop Note: No shorthand declaration of counter so cannot do for (int count =

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

  5. 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); }

  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 <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 are printf("How many values are you going to enter ? "); scanf("%d", &num_values);

  8. averagegen.c continued /* 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); }

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

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

  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. GPA with Switch 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; } }

  21. 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; } }

  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 • Let the player make a guess • As long as the player hasn’t guessed the number, give the appropriate clue and let him/her guess again. • Print the number of tries

  24. 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;

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

  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 <stdlib.h> 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

  32. More Java Comparison 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

More Related