Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views11 pages

L07 ControlLoops

The document covers the concept of loops in programming, specifically while loops, do while loops, and for loops, along with break and continue statements. It provides examples and explanations of how these loops function, including potential pitfalls like infinite loops. Additionally, it discusses practical examples such as finding divisors and removing vowels from strings.

Uploaded by

krishddani1477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

L07 ControlLoops

The document covers the concept of loops in programming, specifically while loops, do while loops, and for loops, along with break and continue statements. It provides examples and explanations of how these loops function, including potential pitfalls like infinite loops. Additionally, it discusses practical examples such as finding divisors and removing vowels from strings.

Uploaded by

krishddani1477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Loops!

Flow of Control: Loops


(Savitch, Chapter 4)
TOPICS

• while Loops
• do while Loops
• for Loops
• break Statement
• continue Statement
CS 160, Spring Semester 2015 2

An  Example  while  Loop   Step-­‐by-­‐step  

int count = 1;
int  count  =  1;   Code begins
int sum = 0;
while (count < 5)
int  sum  =  0;  
{ while  (count  <  5)   count = 1, sum = 0
{   False,
True
true, again,
enter
exit loop
loop
sum += count;
(count
re-enter5,loop
sum 10)
count++;    sum  +=  count;  
}    count++;  
}   Bottom of loop:
What exactly does this code do?   count = 5,
2, sum = 10
3,
4, 1
3
6

CS 160, Spring Semester 2015 3 CS 160, Spring Semester 2015 4

1
More  formally: while  Loops   Echo  Example  Program  

import  java.u3l.Scanner;  
while (condition)  
body public  class  Foo  {  
• Repeatedly  executes  as  long  as  the  condition          public  sta3c  void  main(String[]  args)  {  
               Scanner  in_str  =  new  Scanner(System.in);  
evaluates  to  true
               String  user_string  =  in_str.next();  
• body  of  the  loop  is  a  single  statement or                  while  (!user_string.equals("quit"))  {  
mulIple  statements  within  {  }                            System.out.println(user_string);  
                       user_string  =  in_str.next();  
• The  condiIon  is  tested  before  the  body  is  
               }  
executed,  so  loop  may  execute  zero  Imes          }  
– This  is  called  a  pre-­‐test  loop   }  
CS 160, Spring Semester 2015 5 CS 160, Spring Semester 2015 6

Echo  Example:  Notes   Echo  Example:  QuesIons  

• “import java.util.Scanner;” is   • How  many  Imes  will  the  loop  body  


necessary  to  use  a  Scanner.   execute?  
– Problem:  Without  it,  Eclipse  will  tell  you  it  cannot  
– Undetermined:  it  will  keep  execuIng  unIl  the  
resolve  the  Scanner  class.  
user  types  “quit”  
– SoluIon:  ctrl-­‐shiT-­‐o  will  import  needed  classes.  
• Remember  that  “!”  means  “not”  in  Java.   • What  is  the  fewest  number  of  Imes  the  
• Note  the  indentaIon:  the  body  of  the  while  loop  is   loop  body  could  execute?  
indented  relaIve  to  the  surrounding  code.   – Zero  

CS 160, Spring Semester 2015 7 CS 160, Spring Semester 2015 8

2
Warning!   What  if  my  program  gets  caught  
 in  an  infinite  loop?  
• An  infinite  loop  will  occur  if  the  condiIon  never   • You  will  need  to  kill  your  program  
becomes  false.   – This  is  operaIng  system  specific  
• Example:  
• Make  your  life  easier:  run  your  program  in  
  int count = 1;
int sum = 0; count
the  debugger!  
never gets
while (count <= 5) updated –
– In  Eclipse,  select  “debug”  instead  of  “run”.  
{ always = 1 – It  will  offer  to  take  you  to  the  debug  view.  
sum += count;
– Use  the  red  buaon  to  kill  the  program.  
}
– Benefit:  Run  program  step-­‐by-­‐step  (F5).  
CS 160, Spring Semester 2015 9 CS 160, Spring Semester 2015 10

Another  example:  find  divisors   Notes  on  divisor  example  (1)  


public  class  foo  {  
     public  sta3c  void  main(String[]  args)  {  
• The  main  method  takes  an  array  of  strings  
           int  number  =  Integer.parseInt(args[0]);   (called  arguments  or  args).  
           int  divisor  =  2;   – args[0]  is  the  first  string  passed  to  the  method  
           while  (divisor  <  number  )  {  
                 if  ((number  %  divisor)  ==  0)  {   – args[1]  would  be  the  second  string  
                       System.out.print(divisor  +  "  ");   – args.length  tells  you  how  many  strings  there  are  
                 }   – More  about  arrays  later…    
                 divisor  =  divisor  +  1;  
           }  
     }  
}  
 
CS 160, Spring Semester 2015 11 CS 160, Spring Semester 2015 12

3
Notes  on  divisor  example  (2)   Divisor  example  quesIons  

• Integer  is  an  object  class  in  Java.  It  has  a  


method  that  reads  a  string  and  returns  the   • If  the  argument  is  ’32’,  how  many  Imes  
integer  it  contains.  Hence   will  the  loop  body  be  executed?  
Integer.parseInt(args[0]); – 30  
• We  append  a  space  to  the  number  when   • If  the  argument  is  ‘2’,  how  many  Imes  will  
the  loop  body  be  executed?  
prinIng,  so  that  the  numbers  are  separated  
– 0  
in  the  output.  
• If  the  argument  is  ‘-­‐5’,  what  will  happen?  
– The  loop  body  will  run  0  Imes  
CS 160, Spring Semester 2015 13 CS 160, Spring Semester 2015 14

Example  Program  to   Remove  Vowels:  Notes  


Remove  Vowels  
public  class  Foo  {  
     public  sta3c  void  main(String[]  args)  {  
           String  str  =  args[0];   • The  charAt(i)  method  of  String  returns  the  
           int  ctr  =  0;   ith  character.  
           while  (ctr  <  str.length())  {  
                 switch(str.charAt(ctr))  {   – Zero-­‐based:  0,  1,  2,  …  
                       case  'a'  :    
                       case  'e'  :   •  The  length()  method  of  String  returns  the  
                       case  'i'  :  
                       case  'o'  :  
number  of  characters  in  the  string.  
                       case  'u'  :  break;  
                       default  :  System.out.print(str.charAt(ctr));  
                 }  
                 ctr  =  ctr  +  1;  
           }  
     …   CS 160, Spring Semester 2015 15 CS 160, Spring Semester 2015 16

4
 Remove  Vowels:  QuesIons    for  Loop  

• If  the  input  is  “Programming”:   • It  is  common  to  iterate  counter  number  of  
– How  many  Imes  will  the  loop  body  execute?   Imes.  
• 11   – counter  might  be  a  numeric  bound  
– What  will  the  output  be?  
• As  in  the  divisor  example  
• Prgrmmng  
• If  the  input  is  “Java”:   – counter  might  be  the  length  of  a  string  or  array  
– How  many  Imes  will  the  loop  body  execute?   • As  in  the  remove  vowels  example  
• Exercise   • A  for  loop  gives  you  a  mechanism  to  specify  
– What  will  the  output  be?  
• Exercise   this  explicitly  
CS 160, Spring Semester 2015 17 CS 160, Spring Semester 2015 18

 for  Loop:  Syntax    for  Loop:  Order  


for (initialization; condition; update)
body
 
• A  pre-­‐test  loop  that:  
– IniIalizes  a  loop  variable  
– Executes  body  of  loop  zero  or  more  Imes  
for(  iniIalizaIon  ;  booleanExpression  ;  incrementer  )  
– Repeatedly:   {  
• Tests  the  condiIon      statements;  
• Executes  the  body  if  condiIon  is  true,  else  exits  loop  
• Updates  the  loop  variable   }  

CS 160, Spring Semester 2015 19 CS 160, Spring Semester 2015 20

5
Example   Mapping  between  
 for  and  while  
• while  loop  version  
int sum = 0;
initialization;
for(int count=1; count <= 5; count++) while (condition)
sum +=count; {
statement;
update;
}
• for  loop  version  
for (initialization; condition; update )
statement;

CS 160, Spring Semester 2015 21 CS 160, Spring Semester 2015 22

Temperature  Conversion   Example:  Reversing  a  String  


   Program   Why the -1?
System.out.println(“\tDEGREES C\tDEGREES F”); String s = “nice string”;
for (int i=s.length()-1; i>= 0; i--)
{
for (int cent = 50; cent <= 100; cent++)
{ System.out.print(s.charAt(i));
double fahr = (9.0 / 5.0) * cent + 32.0; }
System.out.print(“\t” + cent);
System.out.println(“\t” + fahr);
} What happens if
we use println
instead of print?

CS 160, Spring Semester 2015 23 CS 160, Spring Semester 2015 24

6
Variants  on  the  for  Loop   do while  Statement  
1
2
• MulIple  variables  in  for  loop   3
4
do
 int  x  =  1;   5 {
 for(  int  lo  =  0,  hi  =  10;  lo  <  hi;  lo++,  hi-­‐-­‐)   body
   System.out.println(  x++  );   } while (condition);  
 
• Not  all  parts  to  the  for  loop   • post-­‐test  loop:  always  executes  the  loop  body  at  least  
once  
 String  s  =  “Javarules”;   • Executes  again  as  long  as  its  condiIon  is  true  
       int  i  =  s.length(  )  –  1;   seluravaJ • {  }  are  required  
 for ( ; i>=0; ) • ;  required  aTer  while  
System.out.print( s.charAt(i--) );
CS 160, Spring Semester 2015 25 CS 160, Spring Semester 2015 26

Example   Mapping  between    


do while  and  while  

int count = 1; • do  while  version   • while  version  


int sum = 0;    
do do statement;
{ statement; while (condition)
sum += count; while (condition); statement;
count++;                  
} while (count <= 5);

How  does  this  differ  from  the  previous?  


CS 160, Spring Semester 2015 27 CS 160, Spring Semester 2015 28

7
Which  loop  to  use?   Problem  Solving  and    
FormulaIng  Loops  
• Stepwise  Development:  
if  (  you  know  the  #  of  iteraIons  )  
– Break  problem  into  subparts  
– use  a      for    loop  
– IdenIfy  repeaIng  paaern  in  problem  formulaIon  
else  if  (  statements  should  be  done  at  least  once  )   – Put  paaern  into  body  of  loop  
– use  a    do…while  loop   – IdenIfy  a  conInuing  condiIon  (or  terminaIon  condiIon)  
else   – Make  separate  loops  when  mulIple  paaerns  are  found  
– use  a    while    loop   – Make  nested  loops  when  one  paaern  fits  within  another  

CS 160, Spring Semester 2015 29 CS 160, Spring Semester 2015 30

Example:     Reading  Input  Using  a  Loop  


Reading  Input  from  User  
• Strategy:   Scanner in = new Scanner( System.in );
– Ask  user  for  input   int score = 0, sumOfScores = 0; sentinel
do {
– Do  something  with  the  input   sumOfScores += score;
– Ask  user  for  input   pattern System.out.println("Enter score [or -1 for end of input]: ");
score = in.nextInt( );
– Do  something  with  the  input   } while( score != -1 );
– …   System.out.println("Sum of scores was " + sumOfScores);

– UnIl  user  no  longer  has  input  to  enter  


• QuesIons:  
– How  does  user  indicate  no  more  input?   When the user is entering a set of data, you need some
way for them to say “no more” -- called a sentinel.
– What  is  the  paaern?  
– What  is  terminaIng  condiIon?  

CS 160, Spring Semester 2015 31 CS 160, Spring Semester 2015 32

8
In  other  words  …   Nested  Loops  

• Stepwise  refinement   • Write  the  code  to  print  out  the  following:  
– don’t  do  everything  at  once   *
** ALGORITHM
– idenIfy  sub-­‐tasks  and  work  on  one  at  the  Ime  
*** OUTER LOOP: 10 times (10 rows)
• IdenIfy  loop  paaerns   **** INNER LOOP: 1 to outer loop counter
– the  repeated  behavior   ***** print *
****** go to next line
– what  is  to  be  done  before  the  loop   *******
•  e.g.,  iniIalizaIon   ********
– how  is  loop  terminaIon  decided   *********
– what  needs  to  be  done  aTer  the  loop     **********
•  e.g.,  store  or  print  results  
CS 160, Spring Semester 2015 33 CS 160, Spring Semester 2015 34

Nested  Loops   CauIons  about  Loops  

public class Stars • Ensure  that  the  required  precision  of  your  condiIon  matches  
{ that  of  the  type  
public static void main(String[] args) • Recall  that  two  doubles  may  be  mathema5cally  equal  but  not  
{ in  the  computer!  
for( int c = 1; c <= 10; c++ ) • Use  {  }    for  mulIple  statements  
{
for( int i = 0; i < c; i++ ) • Check  for  off-­‐by-­‐1  errors,  most  importantly  make  sure  that  
{ loop  ends  at  the  right  Ime)  
System.out.print( '*' ); • Do  NOT  put  a  ‘;’  at  the  end  of  a  for(  )  or  while(  )  statement!!!  
}
System.out.println( ); • In  a  while  loop,  the  condiIon  must  be  testable  prior  to  
} execuIng  the  body  
} Why do we have • In  any  loop,  ensure  that  the  update  will  eventually  cause  
} an empty println ? cause  the  condiIon  to  become  false  
CS 160, Spring Semester 2015 35 CS 160, Spring Semester 2015 36

9
CauIons  about  Loops   CauIons  about  Loops  

• Check  for  off-­‐by-­‐1  errors  (make  sure  that  it  is  ending  at  the   • Do  NOT  put  a  ;  at  the  end  of  a  for(  )  or  while(  )  !!!    
right  Ime)   Declares  an  empty  body  for  the  loop.    Therefore  the  
  statements  you  think  are  in  the  body  of  the  loop  actually  
aren’t  
 for ( int i=1; i<100; i++ )
 
{
 for ( int i=0; i<100; i++ );
System.out.print( “*” );
{
}
System.out.print( “*” );
Prints 99 stars. }
Why? Prints ONE star!
Why?
CS 160, Spring Semester 2015 37 CS 160, Spring Semester 2015 38

Infinite  Loop   Programming  PracIce  

• Infinite  Loops:  loop  with  a  condiIonal  that   • Run  your  loops  by  hand  (pencil  and  paper)  
never  becomes  false:   – Write  out  expectaIons,  check  them  if  need  be  
• Don’t  use  break  and  continue  in  loops  
– They  get  very  confusing  very  fast  
while(       true  )       for  (int  i=1;  i>0;  i++  )  
       computeSquares();          processOutput(  );   • Echo  values  of  variables  
            System.out.println(“Str: “ + Str);
    • Use  useful  idenIfiers    
    – no  one-­‐leaer  idenIfiers,  except  for  loop  indices  
x  =  1;   y  =  1;   • Declare  variables  in  the  right  scope  
while(  x  <  10  );   while(  y  <  10  )     – OTen  at  top  of  scope  is  good  
       x  =  x  +  5;          System.out.print(  y  );   • Give  yourself  a  chance  to  succeed  
         y++;   – Don’t  start  your  project  on  day  before  the  deadline  

CS 160, Spring Semester 2015 39 CS 160, Spring Semester 2015 40

10
Loop  PracIce  Problems  

• Find  the  minimum  integer  in  a  sequence  of  integers  


• Find  the  maximum  in  a  sequence  of  integers  
• Find  the  longest  word  in  a  sequence  of  words  
• Determine  if  a  word  is  a  palindrome  

CS 160, Spring Semester 2015 41

11

You might also like