<< Chapter < Page Chapter >> Page >

Some important things to notice about this algorithm:

  • The empty case must be checked explicitly — no polymorphism to help you out here!
  • The desired result index cannot be declared inside the for loop because otherwise it won't be visible to the outside world.
  • Be careful about using the minIdx value if the array was indeed empty--it's an invalid value! It can't be set to a valid value because otherwise you can't tell the difference between a value that was never set and one that was.
  • The for loop has two initialization statements separated by a comma.
  • The loop does work correctly if the array only has one element, but only because the termination check is done before the loop body.
  • Notice that to prove that this algorithm works properly, one must make separate arguments about the empty case, the one element case and the n-element case. Contrast this to the much simpler list algorithm that only needs an empty and non-empty cases.

For convenience, Java 5.0 now offers a compact syntax used for traversing all the elements of an array or of anything that subclasses type Iterable :

MyType[] myArray; // array is initialized with data somewherefor(MyType x: myArray){ // code involving x, i.e. each element in the array}

It is important to remember that this syntax is used when one wants to process every element in an array (or an Iterable object) independent of order of processing because Java does not guarantee a traversal order.

Let's look at an algorithm where we might not want to process the entire array:

// Find the first index of a given value in an array int idx = -1; // initialize the index to an invalid value.for(int j=0; j<myArray.length; j++) { //no initialization ; end index at length-1; //increment index every time the loop is processed.if(desiredValue == myArray[j]) { // found match!idx = j; // save the index. break; // break out of the loop.} }

Notes:

  • The only way you can tell if the desired value was actually found or not is if the value of idx is -1 or not. Thus the value of idx must be checked before it is ever used.
  • The resultant idx variable cannot be used as the index inside the loop because one would not be able to tell if the desired value was found or not unless one also checked the length of the array. This is because if the desired value was never found, idx at the end of the loop would equal the length of the array, which is only an invalid value if you already know the length of the array.
  • The break statement stops the loop right away and execution resumes at the point right after end of the loop.

There is a counterpart to break called continue that causes the loop to immediately progress to the beginning of the next iteration. It is used much more rarely than break , usually in situations where there are convoluted and deeply nested if - else statements.

Can you see that the price of the compact syntax of for loops is a clear understandability of the process?

While loops

for loops are actually a specialized version of while loops. while loops have no special provisions for initialization or loop incrementing, just the termination condition.

Questions & Answers

what does preconceived mean
sammie Reply
physiological Psychology
Nwosu Reply
How can I develope my cognitive domain
Amanyire Reply
why is communication effective
Dakolo Reply
Communication is effective because it allows individuals to share ideas, thoughts, and information with others.
effective communication can lead to improved outcomes in various settings, including personal relationships, business environments, and educational settings. By communicating effectively, individuals can negotiate effectively, solve problems collaboratively, and work towards common goals.
it starts up serve and return practice/assessments.it helps find voice talking therapy also assessments through relaxed conversation.
miss
Every time someone flushes a toilet in the apartment building, the person begins to jumb back automatically after hearing the flush, before the water temperature changes. Identify the types of learning, if it is classical conditioning identify the NS, UCS, CS and CR. If it is operant conditioning, identify the type of consequence positive reinforcement, negative reinforcement or punishment
Wekolamo Reply
please i need answer
Wekolamo
because it helps many people around the world to understand how to interact with other people and understand them well, for example at work (job).
Manix Reply
Agreed 👍 There are many parts of our brains and behaviors, we really need to get to know. Blessings for everyone and happy Sunday!
ARC
A child is a member of community not society elucidate ?
JESSY Reply
Isn't practices worldwide, be it psychology, be it science. isn't much just a false belief of control over something the mind cannot truly comprehend?
Simon Reply
compare and contrast skinner's perspective on personality development on freud
namakula Reply
Skinner skipped the whole unconscious phenomenon and rather emphasized on classical conditioning
war
explain how nature and nurture affect the development and later the productivity of an individual.
Amesalu Reply
nature is an hereditary factor while nurture is an environmental factor which constitute an individual personality. so if an individual's parent has a deviant behavior and was also brought up in an deviant environment, observation of the behavior and the inborn trait we make the individual deviant.
Samuel
I am taking this course because I am hoping that I could somehow learn more about my chosen field of interest and due to the fact that being a PsyD really ignites my passion as an individual the more I hope to learn about developing and literally explore the complexity of my critical thinking skills
Zyryn Reply
good👍
Jonathan
and having a good philosophy of the world is like a sandwich and a peanut butter 👍
Jonathan
generally amnesi how long yrs memory loss
Kelu Reply
interpersonal relationships
Abdulfatai Reply
What would be the best educational aid(s) for gifted kids/savants?
Heidi Reply
treat them normal, if they want help then give them. that will make everyone happy
Saurabh
What are the treatment for autism?
Magret Reply
hello. autism is a umbrella term. autistic kids have different disorder overlapping. for example. a kid may show symptoms of ADHD and also learning disabilities. before treatment please make sure the kid doesn't have physical disabilities like hearing..vision..speech problem. sometimes these
Jharna
continue.. sometimes due to these physical problems..the diagnosis may be misdiagnosed. treatment for autism. well it depends on the severity. since autistic kids have problems in communicating and adopting to the environment.. it's best to expose the child in situations where the child
Jharna
child interact with other kids under doc supervision. play therapy. speech therapy. Engaging in different activities that activate most parts of the brain.. like drawing..painting. matching color board game. string and beads game. the more you interact with the child the more effective
Jharna
results you'll get.. please consult a therapist to know what suits best on your child. and last as a parent. I know sometimes it's overwhelming to guide a special kid. but trust the process and be strong and patient as a parent.
Jharna
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Principles of object-oriented programming. OpenStax CNX. May 10, 2013 Download for free at http://legacy.cnx.org/content/col10213/1.37
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?

Ask