WizIQ helps you learn and teach online - any subject you can think of!
Join for FREE

Introduction to loops

Add to Favourites
Post to:
Comments
Presentation Transcript Presentation Transcript

Slide 1 : Programming For Artists MFA Computational Studio Arts Lesson 3

Slide 2 : Research exploration field trip Discuss dates Friday 6th Nov – reading week?

Slide 3 : SEMINAR PRESENTATIONS: Think about a computational project/artist/group or artwork you are interested in. Over the next few weeks each of you will do a ten to twelve minute presentation about the subject you have chosen, this can be presented in power point or read out from notes or whatever form is right for you and your subject. These sites are worth a visit if you aren’t sure what subject to cover: Software art repository: http://runme.org/ DAM (Digital Art Museum): http://dam.org/artists/index.htm Soundtoys : http://www.soundtoys.net/ Tom Kemp : http://tomkemp.com/particle/index.html Natalie Jeremijenko: http://www.nyu.edu/projects/xdesign/ Code : http://www.year01.com/code/html/ (online open source art) Mongrel: http://www.mongrel.org.uk/ Stanza : http://www.stanza.co.uk/ We-make-monery-not-art: http://www.we-make-money-not-art.com/ Media Art Net: http://www.medienkunstnetz.de/ Abtsraction now online project: http://www.abstraction-now.at/the-online-project/ 3 volunteers to present next week? We’ll draw up a timetable now…

seminars : seminars 20th October *3 27th (Sarah at 12) 3rd Nov – READING WEEK 10th Nov *3 17th - I’m away 24th Nov (Ricardo at 12) 1st Dec *4 8th last day of term: present mini projects Will, Hestia, Gabriel, Daniel, Ian, Ronin, Sandra, Lee, Nabil, Soyoung = 10

James Faure Walker : James Faure Walker THURSDAY 15th OCTOBERBen Pimlot seminar rooms6-8pm

Slide 6 : Recap from Lesson 2

Slide 7 : This is a UML diagram Bike Name of class colour size speed gear break() changeGear() speedUp() changeColour() State Which we can think of as attributes or qualities Behaviours These are called Methods in Java and ‘functions’ in Processing and C Object Oriented Programming

Slide 8 :

Slide 9 :

Slide 10 : You compiled and ran the Bicycle and the BicycleDemo classes in the BicycleDemo class you experimented with different values for your new bike objects. You instantiated several more Bicycle objects When you had done that you created an identical Bicycle class called Bicycle2 And instantiated several Bicycle2 objects

Slide 11 : Here you ‘instantiated’ 2 Bicycle objects – That means you created two instances of the Bicycle class… You used the methods in the Bicycle class to customise the values for new bikes We used the dot . Operator To ‘address’ or use the method we wanted

Slide 12 : class Variables { public static void main (String[] args) { // declare & initialize each variable type char chr = 'M'; String str = "Java for artists"; int num = 12345; float dec = 7f; boolean flg = false;   // display value stored in each variable System.out.println("Character is " + chr); System.out.println("Text string is " + str); System.out.println("Integer number is " + num); System.out.println("Decimal number is " + dec); System.out.println("Boolean flag is " + flg); } } You declared and initialised these different types of variables:

Slide 13 : // this is a comment, anything written behind the //double forward slashes will be ignored by the //compiler, it is really useful to write notes like //this.

Slide 14 : Lesson 3 A three part lesson: arithmetic, control structures and loops….

Slide 15 : I ARITHMETIC + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator (or Modulus) ++ Increment -- Decrement += add assign -+ subtract assign *= multiply assign /= divide assign - negation operator (int x = 5; x = -x; this will make x have a value of –5)

Slide 16 : Compile and run this program in BlueJ class Arithmetic { public static void main (String[] args) { // create variables, initialize & operate int gr = (int) (Math.random() * 250); int minute = 59; double pi = 3.14159; int addNum = 20 + 30; String addStr = "I love " + "Java"; float subtracted = 35.75f - 28.25f; int multiplied = 8 * 50; int modulo = 65 % 2; int increased = 5 ; increased = ++increased; int decreased = 5 ; decreased = --decreased; double i = 12.00; int x = 4; // display results System.out.println ("The square root of " + i + " is " + Math.sqrt(i)); System.out.println ("Today's random number is "+ gr); System.out.println (minute/60); System.out.println (pi); System.out.println("Added numbers total " +addNum); System.out.println("Concatenated string is " +addStr); System.out.println("Subtraction result : " +subtracted); System.out.println("Multiplication result: " +multiplied); System.out.println("Modulus result:" +modulo); System.out.println("Increment result: " +increased); System.out.println("Decrement result: " +decreased); System.out.println(x); //will print 4 x += 4; //this is the same as saying x = x+4 System.out.println("add assign operator working on x = " + x); //will now print 8; x -= 4; //this is the same as saying x = x - 4 System.out.println("subtract assign operator working on x = " + x ); } }

Slide 17 : If you are unfamiliar with some of the operators used a few of the results may seem strange. System.out.println (minute/60); will produce the answer 0. The value of the variable minute is 59, and 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Java is performing integer division. (its disregarding the numbers after the point); When both of the operands are integers (operands are the things operators operate on), the result must also be an integer, and by convention integer division always rounds down, even in cases like this where the next integer is so close. A possible alternative in this case is to calculate a percentage rather than a fraction: System.out.print ("Percentage of the hour that has passed: ");     System.out.println (minute*100/60); This will result in: Percentage of the hour that has passed: 98 Again the result is rounded down, but at least now the answer is approximately correct If you needed a more precise answer it would be better to use floats or doubles instead of ints: float prec = 59f; float prec2 = 60f; System.out.println (prec/prec2); //Result = 0.98333335

Slide 18 : The Increment and decrement (++ & - - ) operators alter the value by one and return the new value, hence ‘int increased = 5 ; increased = ++increased;‘ returns the value 6. This is often used to count iterations in a loop. //uses increment operator to count class Count { public static void main (String[] args) { int num = 12; int count = 0 ; while ( count < num )// < means less than // > means greater than. we will cover relational expressions another day { count++ ; //keep counting while count is less than 12 System.out.println("COUNT IS:" +count);//add one to count with every iteration while it is less than 12 } } } The modulo or remainder operator % divides the first number given by the second number and returns the remainder; you can use this operator to find out if a number is odd or even.   That is why in the following example   int modulo = 65 % 2; comes out as 1, which is the remainder of the division. If the answer is zero the number is even. We’ll go back to the Count class later on in the lesson

Slide 19 : //class to find if number is odd or even in Java class Evens { public static void main (String[] args) { //could be any number we want to test: int x = 101; if(x%2 == 0) System.out.println("is even"); else System.out.println("is odd"); } } Compile and run this Java code , experiment with different values for int x to test the program

Slide 20 : The modulo operator is also commonly used to keep numbers within a range, for example I might want to keep an ellipse moving between a certain range of points, or within the boundaries of the window Remember: The modulo operator calculates the remainder when one number is divided by another. Try this in Processing: float a = 0.0; void draw() { background(204); a = (a + 0.5)%width; line(a, 0, a, height); } Moves the line and returns it to zero when it reaches the extent of width, ie 100, the modulo Will divide a by 100 and return 0, cleverly returning the line to 0 on the x axis 100 on x axis

Slide 21 : /* This is another example of using the modulo operator to obtain A desired range, in this case the boundary of the window */ float a = 0.0; void setup() { size(200, 200); //size of window } void draw() { background(153, 234, 255); //background colour a = (a + 0.5)%width; //width = width of window, add 0.5 to float a //the modulo expression returns the ellipse to the other side of the screen //when it reaches the extreme right hand side ie when remainder is 0 fill(0, 0, 255); //colour of ellipse is blue ellipse(a, 150, 35, 35); //try these for fun : fill(0, 0, 255, a); ellipse(a, height/2, a, a); ellipse(12, a, 20, 20); ellipse(a, a, 20, 20); } This ellipse is moving across the screen, when the modulo operator returns a remainder of 0 the ellipse will go back to the other side instead of disappearing off the edge of the screen forever For fun I’ve put the variable ‘a’ into other parameters such as the width and height of an ellipse and the alpha channel of the fill Crazy eh?

Other ways of moving shapes, and changing polarity : Other ways of moving shapes, and changing polarity

Slide 23 : Clever bit

Slide 24 : //move ellipse across screen when mouse is clicked int a; int b; void setup(){ size(200, 200); noLoop(); } void draw(){ background(234, 34, 0); makeBox(); } void mousePressed(){ b += 1; redraw();/* Executes the code within draw() one time. This functions allows the program to update the display window only when necessary, for example when an event registered by mousePressed() or keyPressed() occurs. In structuring a program, it only makes sense to call redraw() within events such as mousePressed(). This is because redraw() does not run draw() immediately (it only sets a flag that indicates an update is needed). Calling redraw() within draw() has no effect because draw() is continuously called anyway. */ } void makeBox(){ a = (int)random(255); //a random colour for the ellipse fill(a, a/2, a); ellipse(45, b, 6+b, 6+b); }

Slide 25 : RUN YOUR OWN LOTTERY! if you want to easily generate random integers try this in java: int rando = (int) (Math.random() * 250); System.out.println ("Today's random number is "+ rando); This will generate a pseudo random number between 0 and 250 (P.S Rando is just a name I chose..well, randomly. In processing you would write int rando = (int)random(250); P.P.S As usual there are other more sophisticated ways of doing this

Slide 26 : Assignment and equality   == is an equality operator, it is used to compare two operands, to test if one thing is equal to another, for example: if (num == 2) do something; != means NOT equal to.   = is an assignment operator, as you have seen we use it to assign values, as in int x = 10; Ball b = new Ball(); It’s important not to get = and == mixed up.

Slide 27 : When you start using more complex expressions you should also be aware of rules about the order of precedence, int x = 3 + 4 * 5 the answer is 23 int y = (3 + 4) * 5 the answer is 35 Order of precedence: Multiplicative * / % Additive +- Assignment = In other words division will happen before subtraction And addition before assignment, you can check this out on The web, it just might explain any odd results you get!

Slide 28 : II Control structures     If /if-else /switch [selection]   In class Evens I used an if/else statement, or conditional branching to find out if the int x was even or not.   An if/else statement takes the form of: If (test expression) do-this; else do-this instead; Using ‘if’, ‘if else’ and ‘switch’ statements allows us to control the flow of our programs, to define the order in which our code is executed. The program can make choices; it can behave differently every time it is executed .

Slide 29 : In Evens.java I could have used an if statement on its own, just to find out if the number was even, without the else part, it would have looked like this:   if(x%2 == 0) System.out.println("is even"); If (test expression) execute this code if true;   If multiple instructions are to be carried out conditional to the test expression, we must put braces around those instructions, for example: IF

Slide 30 : //Java public class ifOnly { public static void main(String[] args) { int circle = 120; int value = 4; if(circle >100) { System.out.println(“that’s a pretty big circle”); value = value * 20; System.out.println(“there are a lot of instructions here, your circle has a value of “ + value); } } } Brackets to contain multiple statements Note semi colons at end of each statement In programming a‘statement’ means an instruction you give the computer. An ‘expression’ is a statement involving mathematical operations.

Slide 31 : // Processing:The test expressions are "x > 100" and "x < 100" // Because x is 150, the code inside the first block // runs and the ellipse draws, but the code in the second // block is not run and the rectangle is not drawn int x = 150; if (x > 100) { // If x is greater than 100, ellipse(50, 50, 36, 36); // draw this ellipse } if (x < 100) { // If x is less than 100 rect(35, 35, 30, 30); // draw this rectangle } line(20, 20, 80, 80); //will be drawn whatever //happens as its outside of conditional code

Slide 32 : If else allows us to add more conditional branches to our code. We can have a block of code to execute if something is true and another block if something is false:

// Processing: Because x is 90, only the rectangle drawsint x = 90;if (x > 100) { // If x is greater than 100, ellipse(50, 50, 36, 36); // draw this ellipse.} else { // Otherwise, rect(33, 33, 34, 34); // draw this rectangle}line(20, 20, 80, 80); //this line is outside of the conditional statements, it will run whatever //the result : // Processing: Because x is 90, only the rectangle drawsint x = 90;if (x > 100) { // If x is greater than 100, ellipse(50, 50, 36, 36); // draw this ellipse.} else { // Otherwise, rect(33, 33, 34, 34); // draw this rectangle}line(20, 20, 80, 80); //this line is outside of the conditional statements, it will run whatever //the result What if we want to do this and test another condition?

Slide 34 : // If x is less than or equal to 100, then draw // the rectangle. Otherwise, if x is greater than // or equal to 300, draw the line. If x is between // 100 and 300, draw the ellipse. Because x is 101, // only the ellipse draws. int x = 101; if (x <= 100) { rect(33, 33, 34, 34); } else if (x >= 300) { line(50, 0, 50, 100); } else { ellipse(50, 50, 36, 36); } Combine if and else to make multiple tests: Another test expression No test expression just do this if the previous two are false Test expression

Slide 35 : Switch The switch statement is an efficient and neater alternative to using a large numbers of if statements   Consider this program that uses multiple if statements:

Slide 36 : import java.util.*;   public class Timetable { public static void main(String[]args) { char group; Scanner sc = new Scanner(System.in); System.out.println("****Lab Times******"); System.out.println("enter your group(A, B, C)"); group = sc.next().charAt(0); if(group == 'A') {System.out.print("10.00 a.m"); } else { if (group == 'B') { System.out.print("10.00 a.m"); } else { if (group =='C') { System.out.print("11.00 a.m"); } else { System.out.print("No such group"); }}}}} I’ll run this in BlueJ and show you what ‘Scanner’ is

Slide 37 : It gets tedious and untidy writing all those if statements, a better way is to use the switch statement: import java.util.*; public class TimetableWithSwitch { public static void main(String[]args) { char group; Scanner sc = new Scanner(System.in); System.out.println("****Lab Times******"); System.out.println("enter your group(A, B, C)"); group = sc.next().charAt(0); switch(group) //NOW WE START THE SWITCH { case 'A' : System.out.print("10.00 a.m"); break; //break statement that ends switch if this case is selected case 'B' : System.out.print("1.00 p.m"); break; case 'C' : System.out.print("11.00 pm"); break; default: System.out.print("NO SUCH GROUP");   }//END SWITCH } }

Slide 38 : import java.awt.Graphics; import javax.swing.*; public class SwitchTest extends JApplet { int choice; public void init() { String input; input = JOptionPane.showInputDialog( "Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" + "Enter 3 to draw ovals\n" ); choice = Integer.parseInt( input ); } public void paint( Graphics g ) { for ( int i = 0; i < 10; i++ ) { switch( choice ) { case 1: g.drawLine( 10, 10, 250, 10 + i * 10 ); break; case 2: g.drawRect( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 ); break; case 3: g.drawOval( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 ); break; default: JOptionPane.showMessageDialog( null, "Invalid value entered" ); } // end switch } // end for } // end paint() } // end class SwitchTest * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. COMPILE AND RUN THIS CODE IN BlueJ,

Slide 39 : Run this code without the break statements, what happens? You can just comment them out like this //break;

Slide 40 : Iteration/repetition Otherwise known as LOOPS

Slide 41 : If I wanted to print the same line ten times I could write this: class Tired { public static void main(String[]args) { System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); System.out.println("***I am tired*****"); } } As you can imagine this is a rather tedious way of doing things, it would make more sense to use some sort of code that made the computer repeat the procedure for us. Using a loop or iteration, is the standard form of program control for this sort of repetition,

Slide 42 : Java has three kinds of loops, a for loop, a while loop and a do..while loop. The code above would look like this if I used a for loop:

Slide 43 : class notTired { //first class bracket public static void main(String[]args) { //'main' method beginning bracket for(int i = 1; i<=10; i++) // as long as ‘i’ is less than or equal to 10 keep looping { //bracket containing things I want to happen while loop is looping System.out.println(i); System.out.println("***I am not tired now*****"); } //end looping stuff } //end main method } //last class bracket COMPILE AND RUN THIS CODE IN BlueJ We’ll cover logical operators in detail during the next lesson For Loop If the number of repetitions can be determined prior to entering the loop, use a for loop, for example I know I want to print something ten times or draw 22 circles etc

Slide 44 : FOR LOOPS   The general form of the for statement can be expressed as follows: for (initialization; termination; increment) { statement(s) } It’s crucial to have a terminating expression in the code or there is the danger of creating an infinite loop. This can damage the very fabric of the universe and you don’t want to do that do you? for(int i = 1; i<=10; i++) { Stuff you want to happen goes in here }

Slide 45 : //guess what this does?   class NASA { public static void main(String[]args){     System.out.println("This is not part of a loop"); //it happens before the loop starts   for(int i = 10; i>=1; i- -) //as long as ‘i’ is equal to or greater than 1 keep looping and decrementing ‘i’ by 1 { //in the loop System.out.println(i); //for each loop print the value of ‘i’ }   System.out.println("***WE HAVE LIFT OFF!!*****"); //this is outside of the loop //it gets executed when the loop has finished } }

Slide 46 : Loops allow us to make the computer carry out tasks over and over again. We’ve already seen a while loop in the Count class: class Count { public static void main (String[] args) { int num = 12; int count = 0 ; while ( count < num ) //while count is still less than 12, (or whatever num is) keep adding 1 to count { count++ ; System.out.println("COUNT IS:" + count); //when count is 12 it will stop looping } } // this program evaluates the test expression ‘count < num ‘ //while it is still true it keeps looping } While loop If the number of repetitions required cannot be determined prior to entering the loop and you wish to allow for the possibility of zero repetitions – use a while loop. ‘num’ might be an unpredictable variable, a variable coming from another part of our class, it might be: a user entry, a random number, etc, the while loop will not loop if num is 0

Slide 47 : When the evaluation returns as false, ie the count has reached 11, the loop will stop.

Slide 48 : strokeWeight(2);//thickness of line stroke(234, 23, 123); //nice colour for (int i = 20; i < 80; i += 5) { line(20, i, 80, i + 15); } Run this Processing example:

Slide 49 : This is point 20 0n x axis strokeWeight(2);//thickness of line stroke(234, 23, 123); //nice colour for (int i = 20; i < 80; i += 5) { line(20, i, 80, i + 15); //draw a line 20 on x axis //to i on Y axis, (i goes up by 5 with each loop ) // to 80 on x axis and i on y axis + 15 // 5 creates spacing, + 15 creates the slant or //offset at other end } A line has four coordinates, 2 for its beginning coordinates and two for its end ones Beginning points End points Point 80 on X axis

Slide 50 : for (int d = 100; d > 0; d -= 10) { ellipse(width/2, height/2, d, d); } //incredibly simple Processing program using a for loop Considering its simplicity it returns a tricky looking result..

Slide 51 : void setup() { size(200, 200); //size of window } void draw() { strokeWeight(2);//thickness of line //nice colour for (int d = 150; d > 0; d -= 10) { stroke(255, d*2, d); ellipse(width/2, height/2, d, d); } } Variation on previous code:

Slide 52 : do….while Loops class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } } Unlike our other loops the do..while loop has its test condition at the end of the loop; This means the loop will iterate at least once regardless of the condition. This could be suitable in a situation where you want something to repeat until the user chooses to quit.

Slide 53 : import java.util.*; //the Scanner object belongs to the ‘util’ class so we must write an import java.util statement //this will keep going until the user terminates the loop with a ‘n’ response public class Whiler { public static void main(String[] args) { char response; Scanner sc = new Scanner(System.in); System.out.println("Welcome to this do while loop, would you like to loop again?((y/n)?"); do { System.out.println("another go?((y/n)?"); response = sc.next().charAt(0); } while (response == 'y'); } }

Slide 54 : So the Scanner class is a handy part of the java util package, it allows us to get keyboard input very easily. Our scanner sc is an object of the scanner class, System.in refers to the keyboard, System.out refers to the screen.

Slide 55 : WHICH LOOP FOR WHICH SITUATION?   ·       If the number of repetitions can be determined prior to entering the loop, use a for loop   ·       If the number of repetitions required cannot be determined prior to entering the loop and you wish to allow for the possibility of zero repetitions – use a while loop.   ·       If the number of repetitions required cannot be determined before the loop and you require at least one repetition of the loop, use a do..while loop       (From ‘Java In Two Semesters’ (an excellent book) )

Slide 56 : 1) Make your own patterns using some of the looping structures we learnt about today. Make sure you comment your code: //explaining what you have done and why If you can include arithmetic and conditional branching that would be excellent. Can you make patterns with your OO creatures? You should be able to. 2) Make your OO creature move across the screen and back. Lab 3

Slide 57 : Export your work as an applet, upload it to your site and send me a link to it. If you do this every week I can give you feedback. Each lab contributes to your final mark for this module, which is 30 credits (over 2 terms) towards your MFA. Submitting work

Slide 58 : noStroke(); for (int y=0; y<100; y+=10) { for (int x=0; x<100; x+=10) { fill((x+y) * 1.4); rect(x, y, 10, 10); } } fill(0, 76); noStroke(); smooth(); for (int y = -10; y <= 100; y += 10) { for (int x = -10; x <= 100; x += 10) { ellipse(x + y/8.0, y + x/8.0, 15 + x/2, 10); } } for (int x = 20; x <= 80; x += 5) { line(x, 20, x, 80); } for (int x = 20; x <= 80; x += 5) { if((x % 10) ==0) { line(20, x, 50, x); }else { line(50, x, 80, x); } } Processing examples, there are lots more in the sketch examples This is embedded iteration, a loop within a loop for each iteration this inner loop is executed

Slide 59 : Java examples – the previous Processing code can easily be adapted for Java Where loops work in exactly the same way public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; //graphics object I need for setStroke() method setSize(200, 300); int width3 = 5; Color oran = new Color(232, 111, 0);//orange g.setColor(oran);//background g.fillRect(0, 0, getWidth(), getHeight()); //background rectangle g2.setStroke(new BasicStroke(width3)); //loop more or less lifted from my Processing example for (int y=0; y<300; y+=10) { for (int x=0; x<200; x+=10) { g2.setStroke(new BasicStroke(width3)); g.setColor(Color.red); g.fillOval( x, y, 5, 5); // g.drawLine( x, 0, getHeight(), getWidth()); } }} public Dimension getPreferredSize() { return new Dimension(200, 300); } public Dimension getMinimumSize() { return getPreferredSize(); } public static void main(String args[]) { JFrame mainFrame = new JFrame("Patterns"); mainFrame.getContentPane().add(new simplePattern()); mainFrame.pack(); mainFrame.setVisible(true); } }

Slide 60 : import java.awt.*; import javax.swing.*; public class simplePattern3 extends JComponent { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; //graphics object I need for setStroke() method setSize(300, 300); g.fillRect(0, 0, getWidth(), getHeight()); //background rectangle, size of window int rings = 10; //change number of rings int SIZE = 300; int x = SIZE/2; // x,y of top left corner for drawing circles int y = SIZE/2; for (int i=rings; i>0; i--) { if (i%2 == 0) { g.setColor(Color.red); } else { g.setColor(Color.blue); } int radius = i * 150/rings; //experiment with different radii - compute radius of this ring i * 100/radius g.fillOval(x-radius, y-radius, radius*2, radius*2); } } public Dimension getPreferredSize() { return new Dimension(300, 300); } public Dimension getMinimumSize() { return getPreferredSize(); } public static void main(String args[]) { JFrame mainFrame = new JFrame("Patterns"); mainFrame.getContentPane().add(new simplePattern3()); mainFrame.pack(); mainFrame.setVisible(true); } } JAVA EXAMPLE:

Slide 61 : Java example: //example of embedded iteration: import java.awt.*; import javax.swing.*; public class circRows extends JComponent { int box_space = 22; int margin = 2; public void paintComponent(Graphics g) { super.paintComponent(g); // draw entire component white g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); // red circle for(int i = margin; i < 400-margin; i += box_space) { for(int j = margin; j < 400-margin; j += box_space) { g.setColor(Color.red); g.fillOval(j, i, 22, 22); } } } public Dimension getPreferredSize() { //size of window return new Dimension(400, 400); } public Dimension getMinimumSize() { return getPreferredSize(); } public static void main(String args[]) { JFrame mainFrame = new JFrame("Embedded iteration"); mainFrame.getContentPane().add(new circRows()); mainFrame.pack(); mainFrame.setVisible(true); } }

Slide 62 :

Slide 63 : Use modulo operator To make blue circle if uneven Red if even

Slide 64 : //JAVA EXAMPLE draw circles in a ring with alternate colours import javax.swing.*; import java.awt.*; import java.awt.geom.*; public class ringCircles extends JFrame { public static void main(String[] args) { ringCircles eg = new ringCircles(); } public ringCircles() { super("Draw Ellipse Demo"); setSize(400, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); Container contentArea = getContentPane(); contentArea.setBackground(Color.white); PaintedPanel graphicsPanel = new PaintedPanel(); contentArea.add(graphicsPanel); setContentPane(contentArea); } class PaintedPanel extends JPanel { public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; Continued on next slide

Slide 65 : g.setColor(Color.red); g2d.translate(185.0, 185.0);// // Move the origin to the center of the circle. for (int i=0; i<32; i++) { // Rotate the coordinate system around current // origin, which is at the center of the circle g2d.rotate(Math.PI/16.0); g.fillOval(120, 0, 23, 23); if(i % 2 == 1) { g.setColor(Color.blue);} else { g.setColor(Color.red); } }}}}

Binary numbers : Binary numbers The binary numeral system, or base-2 number system represents numeric values using two symbols, 0 and 1. Owing to its straightforward implementation in digital electronic circuitry using logic gates, the binary system is used internally by all modern computers. History A full set of eight trigrams and 64 hexagrams, was known to the ancient Chinese through the classic text I Ching. An arrangement of the hexagrams of the I Ching, ordered according to the values of the corresponding binary numbers (from 0 to 63), and a method for generating them, was developed by the Chinese scholar and philosopher Shao Yong in the 11th century. The Indian writer Pingala (c. 200 BC) developed advanced mathematical concepts for describing prosody, and in doing so presented the first known description of a binary numeral system. Similar sets of binary combinations have also been used in traditional African divination systems such as Ifá as well as in medieval Western geomancy. The base-2 system utilized in geomancy had long been widely applied in sub-Saharan Africa.

Binary Numbers : Binary Numbers Binary Numbers Overview Binary is a number system used by digital devices like computers, cd players, etc. Binary is Base 2 unlike our counting system decimal which is Base 10 (denary). In other words, Binary has only 2 different numerals (0 and 1), unlike Decimal which has 10 numerals (0,1,2,3,4,5,6,7,8 and 9). Here is an example of a binary number: 10011100 As you can see it is simply a bunch of zeroes and ones, there are 8 numerals in all which make this an 8 bit binary number, bit is short for Binary Digit, and each numeral is classed as a bit. The bit on the far right (in this case a zero) is known as the Least significant bit (LSB), and the bit on the far left (in this case a 1) is known as the Most significant bit (MSB) notations used in digital systems: 4 bits = Nibble8 bits = Byte16 bits = Word32 bits = Double word64 bits = Quad Word (or paragraph)

Slide 68 : Electronically binary numbers are stored/processed using off or on electrical pulses, a digital system will interpret these off and on states as 0 and 1. In other words if the voltage is low then it would represent 0 (off state), and if the voltage is high then it would represent a 1 (on state).

Converting binary to decimal To convert binary into decimal is very simple and can be done as shown below:Say we want to convert the 8 bit value 10011101 into a decimal value, we can use a formula like that below:so 11111111= 255, a familiar number to us nowAs you can see we have placed the numbers 1, 2, 4, 8, 16, 32, 64, 128 (powers of two) in reverse numerical order and then written the binary value below. To convert you simply take a value from the top row wherever there is a 1 below and add the values together, for instance in our example we would have 128 + 16 + 8 + 4 + 1 = 157. For a 16 bit value you would use the decimal values 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 for the conversion. : Converting binary to decimal To convert binary into decimal is very simple and can be done as shown below:Say we want to convert the 8 bit value 10011101 into a decimal value, we can use a formula like that below:so 11111111= 255, a familiar number to us nowAs you can see we have placed the numbers 1, 2, 4, 8, 16, 32, 64, 128 (powers of two) in reverse numerical order and then written the binary value below. To convert you simply take a value from the top row wherever there is a 1 below and add the values together, for instance in our example we would have 128 + 16 + 8 + 4 + 1 = 157. For a 16 bit value you would use the decimal values 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 for the conversion.

Slide 70 : Converting decimal to binary To convert decimal to binary is also very simple, you simply divide the decimal value by 2 and then write down the remainder, repeat this process until you cannot divide by 2 anymore, for example let's take the decimal value 157: Next write down the value of the remainders from bottom to top (in other words write down the bottom remainder first and work your way up the list) which gives: 10011101 = 157

Slide 71 : In 1605 Francis Bacon discussed a system by which letters of the alphabet could be reduced to sequences of binary digits, which could then be encoded as scarcely visible variations in the font in any random text. Importantly for the general theory of binary encoding, he added that this method could be used with any objects at all: "provided those objects be capable of a twofold difference only; as by Bells, by Trumpets, by Lights and Torches, by the report of Muskets, and any instruments of like nature".[3] The modern binary number system was fully documented by Gottfried Leibniz in the 17th century in his article Explication de l'Arithmétique Binaire. Leibniz's system uses 0 and 1, like the modern binary numeral system. As a Sinophile, Leibniz was aware of the I Ching and noted with fascination how its hexagrams correspond to the binary numbers from 0 to 111111, and concluded that this mapping was evidence of major Chinese accomplishments in the sort of philosophical mathematics he admired. In 1854, British mathematician George Boole published a landmark paper detailing an algebraic system of logic that would become known as Boolean algebra. His logical calculus was to become instrumental in the design of digital electronic circuitry. In 1937, Claude Shannon produced his master's thesis at MIT that implemented Boolean algebra and binary arithmetic using electronic relays and switches for the first time in history. Entitled A Symbolic Analysis of Relay and Switching Circuits, Shannon's thesis essentially founded practical digital circuit design.

Slide 72 : In November 1937, George Stibitz, then working at Bell Labs, completed a relay-based computer he dubbed the "Model K" (for "Kitchen", where he had assembled it), which calculated using binary addition. Bell Labs thus authorized a full research programme in late 1938 with Stibitz at the helm. Their Complex Number Computer, completed January 8, 1940, was able to calculate complex numbers. In a demonstration to the American Mathematical Society conference at Dartmouth College on September 11, 1940, Stibitz was able to send the Complex Number Calculator remote commands over telephone lines by a teletype. It was the first computing machine ever used remotely over a phone line. Some participants of the conference who witnessed the demonstration were John Von Neumann, John Mauchly and Norbert Wiener, who wrote about it in his memoirs.

Slide 73 : The other major numbering system used by computers is hexadecimal, or Base 16. In this system, the numbers are counted from 0 to 9, then letters A to F before adding another digit. The letter A through F represent decimal numbers 10 through 15, respectively. The chart overleaf indicates the values of the hexadecimal position compared to 16 raised to a power and decimal values. It is much easier to work with large numbers using hexadecimal values than decimal. An entire RGB colour can be represented by six hexadecimal digits. #FFFFFF = 255, 255, 255 or white  #000000 = 000, 000, 000 or black Two Hexadecimal digits together (called a "byte" in computer terminology) can represent 16×16=256 different levels of color. 16 Million Colors Because each of the three colors can have values from 0 to 255 (256 possible values), there are 256×256×256 = 2563 = 16,777,216 possible color combinations (and this is why you see claims of "16 Million Colors" on computer equipment) Conversion page: http://www.mathsisfun.com/hexadecimal-decimal-colors.html

Slide 74 :

Slide 75 : Systems of counting on (digits) have been devised for both binary and hexadecimal. Arthur C. Clarke suggested using each finger as an on/off bit, allowing finger counting from zero to 1023 on ten fingers. Another system for counting up to FF (255) is illustrated on the right; it seems to be an extension of an existing system for counting in twelves (dozens and grosses), that is common in South Asia and elsewhere.

Slide 76 : How to use Processing in Java, not something I am necessarily here to encourage! First you have to import the processing.core jar into BlueJ Options>Preferences>libraries You’ll find the jar in the bowels of Processing lib > core.jar

Slide 77 : import processing.core.*; import java.applet.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.zip.*; public class CubicGrid extends PApplet { float boxSize; float margin = boxSize*2; float depth = 400; int boxFill; int bcol; public void setup(){ size(400, 400, P3D); //200, 200 noStroke(); } public void draw(){ background(255); boxSize = 45; // center and spin grid translate(width/2, height/2, -depth/2); rotateY(frameCount*PI/300); rotateX(frameCount*PI/300); float conv = boxSize; int bcol = (int)conv; // build grid using multiple translations for (float i=-depth/2+margin; i<=depth/2-margin; i+=boxSize){ pushMatrix(); for (float j=-height+margin; j<=height-margin; j+=boxSize){ pushMatrix(); for (float k=-width+margin; k<=width-margin; k+=boxSize){ // base fill color on counter values, abs function // ensures values stay within legal range //bcol is coming from eliza boxFill = color(20, 0, abs(k), 30); //boxFill = color(abs(i), abs(j), abs(k), 50); //continued overleaf

Slide 78 : pushMatrix(); translate(k, j, i); fill(boxFill); box(boxSize, boxSize, boxSize); popMatrix(); } popMatrix(); } popMatrix(); } } static public void main(String args[]) { PApplet.main(new String[] { "CubicGrid" }); }}

Slide 79 : Some interesting projects:

Slide 80 : http://www.tmema.org/messa/messa.html#background

Slide 81 : http://softcinema.net/?reload

Slide 82 : http://www.textarc.org/

CodeProfiles W.Bradford Paley 2002 : CodeProfiles W.Bradford Paley 2002

Slide 84 : http://artport.whitney.org/commissions/codedoc/Paley/CodeProfiles_800x600.html

W. Bradford Paley, Code Profiles, 2002Touchscreen; software commissioned by the Whitney Museum of American Arthttp://artport.whitney.org/commissions/codedoc/Paley/CodeProfiles_800x600.htmlCode Profiles is a software that displays its underlying code and comments on itself. The code reads in its own source and displays it in a tiny font. As users move their finger over the touch screen, each line of the code becomes legible. The software moves three points in "code space": the white line traces the code in the order it was written by the artist; the amber line traces the code word by word as someone might read it; the green line shows a sample of how the computer reads the code. The code lines themselves gradually get brighter as they execute more. In a self-reflexive way, Code Profiles unveils a "virtual object" as the algorithms constructing this very object. : W. Bradford Paley, Code Profiles, 2002Touchscreen; software commissioned by the Whitney Museum of American Arthttp://artport.whitney.org/commissions/codedoc/Paley/CodeProfiles_800x600.htmlCode Profiles is a software that displays its underlying code and comments on itself. The code reads in its own source and displays it in a tiny font. As users move their finger over the touch screen, each line of the code becomes legible. The software moves three points in "code space": the white line traces the code in the order it was written by the artist; the amber line traces the code word by word as someone might read it; the green line shows a sample of how the computer reads the code. The code lines themselves gradually get brighter as they execute more. In a self-reflexive way, Code Profiles unveils a "virtual object" as the algorithms constructing this very object.

Slide 86 : EunJoo  talk at 12

Slide 87 : ma501ed@gold.ac.uk Programming For Artists website: http://www.doc.gold.ac.uk/~ma501ed/pfa.html These lessons: http://www.doc.gold.ac.uk/~ma501ed/resources.html My email address (Eleanor Dare):

Want to learn?

Sign up and browse through relevant courses.

Name:
Your Email:
Password:
Country:
Contact no.:


Area code Number
Subject you are interested in:
Word verification: (Enter the text as in image)


Sign Up Already a member? Sign In
I agree to WizIQ's User Agreement & Privacy Policy
St.Peter's School
The Oldest & best Boys residential School
User

Your Facebook Friends on WizIQ

Explore Similar Courses