Chapter 8: Loops, Arrays, Strings - PowerPoint PPT Presentation

About This Presentation
Title:

Chapter 8: Loops, Arrays, Strings

Description:

Allocates group numbered 0 to size-1. Can be combined with declaration: ... Size of array determined by number of values. Values must be of same type ... – PowerPoint PPT presentation

Number of Views:227
Avg rating:3.0/5.0
Slides: 27
Provided by: vinod6
Learn more at: https://www.d.umn.edu
Category:

less

Transcript and Presenter's Notes

Title: Chapter 8: Loops, Arrays, Strings


1
Chapter 8 Loops, Arrays, Strings
  • Loop statements
  • do
  • while
  • for
  • Arrays
  • declaration, allocation, initialization, access
  • multi-dimensional
  • heterogeneous
  • String class

2
Loop Statements
  • Sometimes we want to execute a particular piece
    of code multiple times
  • Easy to with a loop
  • Java loops
  • do loop
  • while loop
  • for loop

3
Do Loop
  • Format
  • do
  • Stmts
  • while (Expr)
  • results in
  • Stmts
  • if Expr true done
  • Stmts
  • if Expr true done
  • Stmts
  • ...
  • Do loop repeats its statement block until the
    control expression is false
  • Always executes at least once
  • Expr must be of type boolean

4
While Loop
  • Format
  • while (Expr) Stmt
  • results in
  • if Expr false done
  • Stmt
  • if Expr false done
  • Stmt
  • if Expr false done
  • ...
  • While loop checks expression, executes statement
    if expr true
  • May not execute at all
  • Best to make Stmt a block as in
  • while (Expr)
  • Stmts

5
For Loop
  • Format
  • for (InitE TestE IncE)
  • Stmt
  • results in
  • InitE
  • if TestE false done
  • Stmt
  • IncE
  • if TestE false done
  • Stmt
  • IncE
  • For loop
  • executes InitE
  • then
  • checks TestE, if true
  • executes Stmt, IncE
  • repeats
  • Always executes InitE, may not execute Stmt or
    IncE
  • Use block for Stmt

6
Calculate sum of 1 to N
int total 0 int j 1 if (N gt 0) do
total j j while (j lt N)
int total 0 int j 1 while (j lt N)
total j j
int total 0 int j for (j 1 j lt N j)
total j
7
Tricky Aspects of Loops
  • QWhat if condition to stop loop never met?
  • A loop runs FOREVER
  • QWhats wrong with the following
  • for (j 1 j lt N j)
  • total j
  • A loop is running the empty statement () for j
    from 1 to N

8
Arrays
  • Not primitive types - no preset values
  • Not classes - cant change access methods
  • Array is a group of elements (primitive or class)
  • same type
  • index (numbered) from 0 to size-1

9
Array Declaration
  • Form
  • Type Aname
  • Type Aname
  • examples
  • int numbers
  • Button myButtons
  • Note declaration creates a pointer to an array,
    no space for array allocated

10
Array Allocation
  • Uses the new operator
  • Form
  • ArrayVarName new Typesize
  • size should be a positive integer
  • Allocates group numbered 0 to size-1
  • Can be combined with declaration
  • int numbers new int10

11
Array Initialization
  • Can be done at declaration (replaces allocation)
  • Type Name Value0, Value1,
  • Size of array determined by number of values
  • Values must be of same type
  • Elements of array set to Value0, Value1, etc. in
    order
  • double taxRates 0.0, 0.08, 0.11, 0.13, 0.28

12
Accessing Array Elements
  • Form ArrayNameExpression
  • can treat as variable of base type of array
  • e.g. in array of ints numbers, numbers0 can be
    used like any other int (written, assigned, etc.)
  • Expression should be of type int
  • Java may throw an exception if the Expression is
    not between 0 and SizeofArray-1

13
Array Processing
  • Generally done with loops
  • Process all (for loop)
  • for (j 0 j lt ArraySize j)
  • process Aj
  • total sum of elements
  • total 0
  • for (j 0 j lt N j)
  • total numbersj
  • find smallest
  • smallest 0
  • for (j 1 j lt N j)
  • if (numbersj lt numberssmallest)
  • smallest j

14
Array Processing
  • Search for element (while loop)
  • j 0
  • while ((j lt ArraySize) (Aj not what we
    want))
  • j
  • Find first non-zero element
  • j 0
  • while ((j lt N) (Aj 0))
  • j

15
Multi-Dimensional Arrays
  • Forms (2-dimensional)
  • Type Name new TypeSize1Size2
  • Type Name new TypeSize1Size2
  • Example int twodnums new int43

16
Non-Rectangular Arrays
  • Need not allocate subarrays of same size
  • int nonrect new int4
  • nonrect0 new int1
  • nonrect1 new int2
  • nonrect2 new int3
  • nonrect3 new int4

17
Heterogeneous Arrays
  • Arrays may be of class parent type, can hold
    different types of elements (as long as parent is
    a superclass of type)
  • Example
  • array of Employees
  • Employees may be Salaried or Hourly

18
public abstract class Employee public float
get2WeekSal() public class SalariedEmployee
extends Employee private float
YearlySalary public float get2WeekSal()
return YearlySalary / 26.0 public class
HourlyEmployee extends Employee private
float HoursPerWeek private float PayPerHour
public float get2WeekSal() return
HoursPerWeek PayPerHour 2
Employee bees new Employee20 totalSal
0.0 for (j 0 j lt 20 j) totalSal
beesj.get2WeekSal()
19
Sorting
  • Take an array of elements and order them by some
    index
  • array of integers - order from smallest to
    largest
  • array of employees - order alphabetically
  • Some methods
  • selection sort
  • insertion sort
  • shell sort
  • quick sort

20
Selection Sort
Find smallest element, put at position 0 Find
next smallest element, put at position 1 (neednt
look at 0) Find next smallest element, put at
position 2 (ignore 0 and 1) etc. for (j 0 j lt
ArraySize-1 j) smallest j for (k
j1 k lt ArraySize k) if (Arrayk lt
Arraysmallest) smallest k
swap(Arrayj,Arraysmallest)
21
Insertion Sort
Like sorting a deck of cards Start with empty
sorted hand Add 1 card in the right place
(sorted hand of 1 card) Add 1 card in the right
place (sorted hand of 2 cards) etc. for (j 1
j lt ArraySize j) k j while ((k gt 0)
(Arrayk lt Arrayk-1))
swap(Arrayk,Arrayk-1) k--
22
String Class
  • String is a group of characters viewed as a
    single entity
  • A String, lvljsjlfl, (empty string)
  • Constructors
  • YourString - converts things between to
    string
  • String(char c) - array of chars to string
  • String(String s) - makes copy of String s
  • Special Method (append)
  • abc 123 produces abc123

23
String Methods
  • boolean equals(Object obj) - true if strings same
  • boolean equalsIgnoreCase(Object obj) - same as
    equals but upper and lower case chars match (a
    equals A)
  • int compareTo(String s) - compares
    alphabetically, -1 if this string less, 0 if
    same, 1 if greater
  • boolean endsWith(String s) - true if string ends
    with s
  • boolean startsWith(String s) - true if string
    starts with s
  • int length() - number of chars in string

24
String Methods (cont)
  • char charAt(int index) - returns char at position
    index
  • int indexOf(char c) - location of first
    occurrence of c
  • int indexOf(char c, int s) - first occurrence
    after loc s
  • int indexOf(String s) - first occurrence of
    string s
  • int indexOf(String s, int st) - first occurrence
    of s after st
  • these routines return -1 if not found
  • there are four similar lastIndexOf routines that
    find the last occurrence of the given char or
    string
  • char toCharArray() - returns chars of string as
    array
  • void getChars(int s, int e, char c, int cst) -
    returns chars of string from s to e in array c
    starting at cst

25
String Methods (cont)
  • static String valueOf(boolean b) - returns string
    corresponding to boolean value
  • similar versions for char, int, long, float,
    double
  • String substring(int s) - new string using chars
    from s on
  • String substring(int s, int e) - new string,
    chars from s to e
  • String concat(String s) - equivalent to
  • String toLowerCase() - new string, all lower case
  • String toUpperCase() - new string, all upper case
  • String trim() - new string, all leading white
    space gone
  • String replace(char old, char newc) - string with
    old replaced by newc

26
Related Methods
  • static Boolean valueOf(String s) - examines s,
    returns the boolean value that can be read from s
  • similar methods for char, int, long, float double
  • error occurs if the string can not be matched to
    type
Write a Comment
User Comments (0)
About PowerShow.com