41
CSCI1226 Introduction to Computing Science and Programming Lecture 4: Looping Tami Meredith

Lecture 4: Looping Tami Meredith. Back to Basics... Programming requires: 1. Identification of the problem. 2. Solving the problem: A. Selecting the data

Embed Size (px)

DESCRIPTION

Control is Power! Control flow is actually very simple: 1. Everything is sequential, unless Something is optional (last class) Conditional Statements, i.e,. if 3. Something is repeated (this class) Looping Statements, i.e., do, for, while 4. Something complex is broken into simpler parts (last class, next class) i.e., methods, classes, objects

Citation preview

Slide 1Lecture 4: Looping
Data Management is the key here
Identifying an algorithm
Coding the solution
Control is Power!
Everything is sequential, unless ...
Conditional Statements, i.e,. if
Looping Statements, i.e., do, for, while
Something complex is broken into simpler parts (last class, next class)
i.e., methods, classes, objects
Until now all programs have been sequential
We do the instructions one after another without skipping or jumping over any
This is the default flow of execution
This is very limiting
Need ways to say:
"do this .... if .... happens and do .... otherwise"
"do this .... X times"
Execution ends normally when the end of main is reached
Execution ends any time there is a return inside main
Execution ends any time, in any method, when System.exit(n) occurs
n is the integer exit code
0 if all is OK, other values for different errors
OK for now to always use 0
Branching (Conditional Execution)
We have the "if" statement in Java to make control flow choices
if (test) true-actions else false-actions
Example:
}
Example:
result = n2 / n1;
Multiple Definitions
We can combine definitions using a comma if they have the same type
For example,
Blocks
We can group a set of statements that we wish to perform
Such a group is called a "Block"
Blocks are identified with { and }
We use blocks to put more than one statement in the "true-actions" and "false-actions" of if statements
Example
if (n1 != 0)
result = n2 / n1;
System.out.println("Quotient is " + result);
if (n1 != 0)
int n1 = 3, n2 = 4, result = 0;
// without a block
if (n1 != 0)
result = n2 / n1;
if (n1 != 0)
System.out.println("Quotient is " + result);
if (n1 != 0)
Things inside a block should be indented
Indenting indicates that something is in a block, it does not CAUSE it to be part of the block
Blocks should be used liberally
Blocks have no detrimental impacts on performance
Like parentheses, blocks add clarity and make code more understandable
Indentation can be 2, 4, or 8 spaces, but MUST be consistent for the entire program
Boolean Operators && (and) Both are true || (or) Either one or the other (or both) are true ! (not) Negation, reverses a boolean value
Operand 1
if (min <= val) {
if (val <= max) {
}
}
System.out.println("Value " + val + " is in range [min,max]");
}
// Multiple if statements, same as OR (||)
if (val < min) {
}
}
System.out.println("Value " + val + " is not in range [min,max]");
}
If val1 is less than 0 print negative the screen
If val1 is greater than 0 print positive to the screen
If val1 equals zero, print zero to the screen
Solution
public class inttest {
public static void main (String[] args) {
int val1 = 77;
if (val1 < 0) {
My solutions tend to be a little cramped
I am trying to fit things on the slide but keep the font large so you can read it
I don't have a lot of space to work with as a result
These examples are formatted OK, but could be a lot better!
Format variation is allowed ...
// stuff versus {
if (x != 0) {
if (x < 0)
if lets us chose whether to do something
We create conditions (which are often quite complex) and based on these conditions (i.e., tests) code is either executed or ignored
But, making choices is still only half the issue ...
What if we want to do something more than once?
Some Inefficient Code
int count = 0;
int stop = 8
System.out.println(count); // print 0
count = count + 1;
if (count <= stop) {
System.out.println(count); // print 1
}
// And so on, and so on ... (need a better way if stop == 100!)
// Must have enough tests to ensure we always reach stop
Our First Loop
int count = 0;
int stop = 8;
while (count <= stop) {
Loops
while a test is true
3 kinds of loops: while, do, for
All just vary only in when the test is applied
While Loops
// May do this 0 times (never!)
}
// Always does at least once
} while (test);
}
Init: Done exactly once before the loops begins, Initialisation
Test: Done before each time the body is executed
Step: Done after each time the body is executed and before the next test
Example:
System.out.println(x);
You are programmers now!
Variables/Data + If + Loops = Programs!
Just like driving a car = speeding up + slowing down + turning left or right
All the rest is the equivalent of knowing when to turn, when to speed up, what the yellow lights mean (go faster) ...
Programming is knowing when to loop, what variables you need, when to branch
You can do everything you need now
From this point onwards we learn ways to improve our programs, not do more
Infinite Loops
Many ways to create an infinite loop
Most likely we will do it by accident, but its not hard ...
int x = 0;
Loops end when we fail the test
BUT, we can "jump out" of a loop anytime we want
Use break to exit a loop
while (true) {
Loops can contain other loops!
This is confusing at first, we'll come back to it more later on
int i, j;
System.out.println((i*10) + j);
We tend to increment variables a lot when using loops
E.g., i = i + 1;
To save typing (remember, programmers are lazy) the increment operators were created:
i++ and ++i
++i; // Add 1 before using i
int i = 10, j, k;
j = i++; // j = 10, i = 11
k = ++i; // k = 12, i = 12
Decrementing
When we want to count down (instead of up) we decrement a variable
E.g., i = i - 1;
i-- and --i
++i; // Subtract 1 before using i
int i = 10, j, k;
j = i--; // j = 10, i = 9
k = --i; // k = 8, i = 8
Increment/Decrement
Expression
Alternative
i++;
j = ++i;
j = i--;
j = --i;
Exercise
Write a program that prints the numbers from 100 down to 1 using a loop
Solution 1: For
int val;
System.out.println(val);
int val = 100;
while (val > 0) {
Exercise
Write a program that prints the letters of your name, one at a time, using a loop.
Remember, charAt(i) gets the letters of a string at index i
length() returns the length of a string
Strings are indexed from 0 to length-1
Note:
You are going to need to be very comfortable with the String class (Figure 2.5, pg 86)!
Solution
public class onebyone {
String name = "Tami Meredith";
int index, len = name.length();
System.out.println(name.charAt(index));
Go to the lab and complete today's assignment
Read Chapter 5 (For next class), make notes, write down your questions and bring them next week