Menu

[Solved]Difference Put Statement Inside Loop Outside Loop Bounds Different Version Thank Version 1 Q37292223

What is the difference when you put the if statement inside thefor-loop and outside the for-loop? Why are the bounds different foreach version. Thank you

Version 1:

public static int wordCount(String s) {

   int count = 0;

   for(int i = 0; i < s.length() – 1; i++){

       if(s.charAt(i) == ‘ ‘&& s.charAt(i+1) != ‘ ‘) {

           count++;

       }

   }

   if(s.charAt(0) != ‘ ‘) {

       count++;

   }

   return count;

}

Version 2:

public static int wordCount(String s) {

   int count = 0;

   char firstChar = s.charAt(0);

   for (int i = 1; i < s.length(); i++) {

       char nextChar =s.charAt(i);

       if (firstChar == ‘ ‘&& nextChar != ‘ ‘) {

           count++;

       }

       firstChar =nextChar;

   }

   if (s.charAt(0) != ‘ ‘) {

       count++;

   }

   return count;

}

Expert Answer


Answer to What is the difference when you put the if statement inside the for-loop and outside the for-loop? Why are the bounds di… . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *