Loops CSCI 201 Principles of Software Development Jeffrey

  • Slides: 8
Download presentation
Loops CSCI 201 Principles of Software Development Jeffrey Miller, Ph. D. jeffrey. miller@usc. edu

Loops CSCI 201 Principles of Software Development Jeffrey Miller, Ph. D. jeffrey. miller@usc. edu

Outline • Loops • Program USC CSCI 201 L

Outline • Loops • Program USC CSCI 201 L

Loops Overview ▪ Loops give us a way to execute the same code multiple

Loops Overview ▪ Loops give us a way to execute the same code multiple times › Any time you find yourself copying and pasting code, you should either think “loop” or “method” ▪ There are four different ways you can loop in Java, all of which exist in C++ › › for loops while loops do. . while loops Recursion (direct or indirect) • Loops USC CSCI 201 L 3/8

for Loops 1 2 3 4 5 6 7 8 9 10 11 12

for Loops 1 2 3 4 5 6 7 8 9 10 11 12 13 for (int i=0; i < 10; i++) { System. out. print(“i=“ + i); } int num. Arr[10]; // assume populated for (int i=0; i < num; i++) { for (int j=i+1; j < num; j++) { if (num. Arr[i] > num. Arr[j]) { int temp = num. Arr[i]; num. Arr[i] = num. Arr[j]; num. Arr[j] = temp; } } } • Loops USC CSCI 201 L 4/8

while Loops 1 2 3 4 5 6 7 Scanner scan = new Scanner(System.

while Loops 1 2 3 4 5 6 7 Scanner scan = new Scanner(System. in); char ch = scan. next. Char(); while (ch != ‘q’) { System. out. println(“Not right character”); System. out. print (“Try again: “); ch = scan. next. Char(); } • Loops USC CSCI 201 L 5/8

do. . while Loops 1 2 3 4 5 6 7 8 9 Scanner

do. . while Loops 1 2 3 4 5 6 7 8 9 Scanner scan = new Scanner(System. in); System. out. print(“Enter a number: “); int val = scan. next. Int(); int remainder; do { remainder = val % 2; System. out. print(remainder); val /= 2; } while (val != 0); • Loops USC CSCI 201 L 6/8

Outline • Loops • Program USC CSCI 201 L

Outline • Loops • Program USC CSCI 201 L

Program ▪ Write a program that randomly generates dice rolls. The number of rolls

Program ▪ Write a program that randomly generates dice rolls. The number of rolls will be provided by the user. Output the number of times each number occurred followed by the percentage. Here is a sample execution with user input bolded. c: >java csci 201. Dice How many rolls? 5000 The number 1 occurred The number 2 occurred The number 3 occurred The number 4 occurred The number 5 occurred The number 6 occurred c: > • Program 800 750 825 775 800 times times (16%). (15%). (17%). (16. 5%). (15. 5%). (16%). USC CSCI 201 L 8/8