Skip to content

Turing Assignment Statement Visual Basic

In the programs that we have examined to this point, each of the statements is executed once, in the order given. Most programs are more complicated because the sequence of statements and the number of times each is executed can vary. We use the term control flow to refer to statement sequencing in a program.

  • Write a program RollDie.java that generates the result of rolling a fair six-sided die (an integer between 1 and 6).
  • Write a program that takes three integer command-line arguments a, b, and c and print the number of distinct values (1, 2, or 3) among a, b, and c.
  • Write a program that takes five integer command-line arguments and prints the median (the third largest one).
  • (hard) Now, try to compute the median of 5 elements such that when executed, it never makes more than 6 total comparisons.
  • How can I create in an infinite loop with a for loop?

    Solution: is the same as .

  • What's wrong with the following loop?
    boolean done = false; while (done = false) { ... }
    The while loop condition uses instead of so it is an assignment statement (which makes always and the body of the loop will never be executed). It's better to style to avoid using .
    boolean done = false; while (!done) { ... }
  • What's wrong with the following loop that is intended to compute the sum of the integers 1 through 100?
    for (int i = 1; i <= N; i++) { int sum = 0; sum = sum + i; } System.out.println(sum);
    The variable should be defined outside the loop. By defining it inside the loop, a new variable is initialized to 0 each time through the loop; also it is not even accessible outside the loop.
  • Write a program Hurricane.java that that takes the wind speed (in miles per hour) as an integer command-line argument and prints whether it qualifies as a hurricane, and if so, whether it is a Category 1, 2, 3, 4, or 5 hurricane. Below is a table of the wind speeds according to the Saffir-Simpson scale.
    CategoryWind Speed (mph)
    174 - 95
    296 - 110
    3111 - 130
    4131 - 155
    5155 and above
  • What is wrong with the following code fragment?
    double x = -32.2; boolean isPositive = (x > 0); if (isPositive = true) System.out.println(x + " is positive"); else System.out.println(x + " is not positive");

    Solution: It uses the assignment operator instead of the equality operator . A better solution is to write .

  • Change/add one character so that the following program prints 20 xs. There are two different solutions.
    int i = 0, n = 20; for (i = 0; i < n; i--) System.out.print("x");
    Solution: Replace the i < n condition with -i < n. Replace the i-- with n--. ( In C, there is a third: replace the < with a +.)
  • What does the following code fragment do?
    if (x > 0); System.out.println("positive");

    Solution: always prints regardless of the value of because of the extra semicolon after the statement.

  • RGB to HSB converter. Write a program that takes an RGB color (three integers between 0 and 255) and transforms it to an HSB color (three different integers between 0 and 255). Write a program that applies the inverse transformation.
  • Boys and girls. A couple beginning a family decides to keep having children until they have at least one of either sex. Estimate the average number of children they will have via simulation. Also estimate the most common outcome (record the frequency counts for 2, 3, and 4 children, and also for 5 and above). Assume that the probability p of having a boy or girl is 1/2.
  • What does the following program do?
    public static void main(String[] args) { int N = Integer.parseInt(args[0]); int x = 1; while (N >= 1) { System.out.println(x); x = 2 * x; N = N / 2; } }
    Solution: Prints all of the powers of 2 less than or equal to n.
  • Boys and girls. Repeat the previous question, but assume the couple keeps having children until they have another child which is of the same sex as the first child. How does your answer change if p is different from 1/2?

    Surprisingly, the average number of children is 2 if p = 0 or 1, and 3 for all other values of p. But the most likely value is 2 for all values of p.

  • Given two positive integers and , what result does the following code fragment leave in
    c = 0; while (b > 0) { if (b % 2 == 1) c = c + a; b = b / 2; a = a + a; }

    Solution: a * b.

  • Write a program using a loop and four conditionals to print
    12 midnight 1am 2am ... 12 noon 1pm ... 11pm
  • What does the following program print?
    public class Test { public static void main(String[] args) { if (10 > 5); else; { System.out.println("Here"); }; } }
  • Alice tosses a fair coin until she sees two consecutive heads. Bob tosses another fair coin until he sees a head followed by a tail. Write a program to estimate the probability that Alice will make fewer tosses than Bob? Solution: 39/121.
  • Rewrite DayOfWeek.java from Exercise 1.2.29 so that it prints the day of the week as Sunday, Monday, and so forth instead of an integer between 0 and 6. Use a statement.
  • Number-to-English. Write a program to read in a command line integer between -999,999,999 and 999,999,999 and print the English equivalent. Here is an exhaustive list of words that your program should use: negative, zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety, hundred, thousand, million . Don't use hundred, when you can use thousand, e.g., use one thousand five hundred instead of fifteen hundred. Reference.
  • Gymnastics judging. A gymnast's score is determined by a panel of 6 judges who each decide a score between 0.0 and 10.0. The final score is determined by discarding the high and low scores, and averaging the remaining 4. Write a program that takes 6 real command line inputs representing the 6 scores and prints their average, after throwing out the high and low scores.
  • Quarterback rating. To compare NFL quarterbacks, the NFL devised a the quarterback rating formula based on the quarterbacks number of completed passes (A), pass attempts (B), passing yards (C), touchdown passes (D), and interception (E) as follows:
    1. Completion ratio: W = 250/3 * ((A / B) - 0.3).
    2. Yards per pass: X = 25/6 * ((C / B) - 3).
    3. Touchdown ratio: Y = 1000/3 * (D / B)
    4. Interception ratio: Z = 1250/3 * (0.095 - (E / B))
    The quarterback rating is computed by summing up the above four quantities, but rounding up or down each value so that it is at least 0 and and at most 475/12. Write a program that takes five command line inputs A, B, C, D, and E, and prints the quarterback rating. Use your program to compute Steve Young's 1994 record-setting season (112.8) in which he completed 324 of 461 passes for 3,969 yards, and threw 35 touchdowns and 10 interceptions. As of 2014, the all-time single-season record is 122.5 by Aaron Rodgers in 2011.
  • Decimal expansion of rational numbers. Given two integers p and q, the decimal expansion of p/q has an infinitely repeating cycle. For example, 1/33 = 0.03030303.... We use the notation 0.(03) to denote that 03 repeats indefinitely. As another example, 8639/70000 = 0.1234(142857). Write a program that reads in two command line integers p and q and prints the decimal expansion of p/q using the above notation. Hint: use Floyd's rule.
  • Friday the 13th. What is the maximum number of consecutive days in which no Friday the 13th occurs? Hint: The Gregorian calendar repeats itself every 400 years (146097 days) so you only need to worry about a 400 year interval.

    Solution: 426 (e.g., from 8/13/1999 to 10/13/2000).

  • January 1. Is January 1 more likely to fall on a Saturday or Sunday? Write a program to determine the number of times each occurs in a 400 year interval.

    Solution: Sunday (58 times) is more likely than Saturday (56 times).

  • What do the following two code fragments do?
    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (i != j) System.out.println(i + ", " + j); for (int i = 0; i < N; i++) for (int j = 0; (i != j) && (j < N); j++) System.out.println(i + ", " + j);
  • Determine what value gets printed out without using a computer. Choose the correct answer from 0, 100, 101, 517, or 1000.
    int cnt = 0; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) for (int k = 0; k < 10; k++) if (2*i + j >= 3*k) cnt++; System.out.println(cnt);
  • Rewrite CarLoan.java from Creative Exercise XYZ so that it properly handles an interest rate of 0% and avoids dividing by 0.
  • Write the shortest Java program you can that takes an integer command-line argument n and prints if (1 + 2 + ... + n) 2 is equal to (13 + 23 + ... + n3).

    Solution: Always print .

  • Modify Sqrt.java so that it reports an error if the user enters a negative number and works properly if the user enters zero.
  • What happens if we initialize to instead of in program Sqrt.java?
  • Sample standard deviation of uniform distribution. Modify Exercise 8 so that it prints the sample standard deviation in addition to the average.
  • Sample standard deviation of normal distribution. that takes an integer N as a command-line argument and uses Web Exercise 1 from Section 1.2 to print N standard normal random variables, and their average value, and sample standard deviation.
  • Loaded dice. [Stephen Rudich] Suppose you have three, three sided dice. A: {2, 6, 7}, B: { 1, 5, 9}, and C: {3, 4, 8}. Two players roll a die and the one with the highest value wins. Which die would you choose? Solution: A beats B with probability 5/9, B beats C with probability 5/9 and C beats A with probability 5/9. Be sure to choose second!
  • Thue–Morse sequence. Write a program ThueMorse.java that reads in a command line integer n and prints the Thue–Morse sequence of order n. The first few strings are 0, 01, 0110, 01101001. Each successive string is obtained by flipping all of the bits of the previous string and concatenating the result to the end of the previous string. The sequence has many amazing properties. For example, it is a binary sequence that is cube-free: it does not contain 000, 111, 010101, or where is any string. It is self-similar: if you delete every other bit, you get another Thue–Morse sequence. It arises in diverse areas of mathematics as well as chess, graphic design, weaving patterns, and music composition.
  • Program Binary.java prints the binary representation of a decimal number n by casting out powers of 2. Write an alternate version Program Binary2.java that is based on the following method: Write 1 if n is odd, 0 if n is even. Divide n by 2, throwing away the remainder. Repeat until n = 0 and read the answer backwards. Use to determine whether n is even, and use string concatenation to form the answer in reverse order.
  • What does the following code fragment do?
    int digits = 0; do { digits++; n = n / 10; } while (n > 0);

    Solution: The number of bits in the binary representation of a natural number n. We use a loop so that code output 1 if n = 0.

  • Write a program that takes an integer command-line argument and prints the integers from 10 to 99 with integers per line.
  • Modify so that it prints the integers from 1 to 1000 with integers per line. Make the integers line up by printing the right number of spaces before an integer (e.g., three for 1-9, two for 10-99, and one for 100-999).
  • Suppose a, b, and c are random number uniformly distributed between 0 and 1. What is the probability that a, b, and c form the side length of some triangle? Hint: they will form a triangle if and only if the sum of every two values is larger than the third.
  • Repeat the previous question, but calculate the probability that the resulting triangle is obtuse, given that the three numbers for a triangle. Hint: the three lengths will form an obtuse triangle if and only if (i) the sum of every two values is larger than the third and (ii) the sum of the squares of every two side lengths is greater than or equal to the square of the third.

    Answer.

  • What is the value of after executing the following code?
    int M = 987654321; String s = ""; while (M != 0) { int digit = M % 10; s = s + digit; M = M / 10; }
  • What is the value of i after the following confusing code is executed?
    int i = 10; i = i++; i = ++i; i = i++ + ++i;

    Moral: don't write code like this.

  • Formatted ISBN number. Write a program ISBN2.java that reads in a 9 digit integer from a command-line argument, computes the check digit, and prints the fully formatted ISBN number, e.g, 0-201-31452-5.
  • UPC codes. The Universal Product Code (UPC) is a 12 digit code that uniquely specifies a product. The least significant digit d1(rightmost one) is a check digit which is the uniquely determined by making the following expression a multiple of 10:
    (d1 + d3 + d5 + d7 + d9 + d11) + 3 (d2 + d4 + d6 + d8 + d10 + d12)

    As an example, the check digit corresponding to 0-48500-00102 (Tropicana Pure Premium Orange Juice) is 8 since

    (8 + 0 + 0 + 0 + 5 + 4) + 3 (2 + 1 + 0 + 0 + 8 + 0) = 50

    and 50 is a multiple of 10. Write a program that reads in a 11 digit integer from a command line parameter, computes the check digit, and prints the the full UPC. Hint: use a variable of type to store the 11 digit number.

  • Write a program that reads in the wind speed (in knots) as a command line argument and prints its force according to the Beaufort scale. Use a statement.
  • Making change. Write a program that reads in a command line integer N (number of pennies) and prints the best way (fewest number of coins) to make change using US coins (quarters, dimes, nickels, and pennies only). For example, if N = 73 then print
    2 quarters 2 dimes 3 pennies

    Hint: use the greedy algorithm. That is, dispense as many quarters as possible, then dimes, then nickels, and finally pennies.

  • Write a program Triangle.java that takes a command-line argument N and prints an N-by-N triangular pattern like the one below.
    * * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *
  • Write a program Ex.java that takes a command-line argument N and prints a (2N + 1)-by-(2N + 1) ex like the one below. Use two loops and one statement.
    * . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *
  • Write a program BowTie.java that takes a command-line argument N and prints a (2N + 1)-by-(2N + 1) bowtie like the one below. Use two loops and one statement.
    * . . . . . * * * . . . * * * * * . * * * * * * * * * * * * * . * * * * * . . . * * * . . . . . *
  • Write a program Diamond.java that takes a command-line argument N and prints a (2N + 1)-by-(2N + 1) diamond like the one below.
    % java Diamond 4 . . . . * . . . . . . . * * * . . . . . * * * * * . . . * * * * * * * . * * * * * * * * * . * * * * * * * . . . * * * * * . . . . . * * * . . . . . . . * . . . .
  • Write a program Heart.java that takes a command-line argument N and prints a heart.
  • What does the program Circle.java print out when N = 5?
    for (int i = -N; i <= N; i++) { for (int j = -N; j <= N; j++) { if (i*i + j*j <= N*N) System.out.print("* "); else System.out.print(". "); } System.out.println(); }
  • Seasons. Write a program that takes two command line integers M and D and prints the season corresponding to month M (1 = January, 12 = December) and day D in the northern hemisphere. Use the following table
    SEASONFROMTO
    SpringMarch 21June 20
    SummerJune 21September 22
    FallSeptember 23December 21
    WinterDecember 21March 20
  • Zodiac signs. Write a program that takes two command line integers M and D and prints the Zodiac sign corresponding to month M (1 = January, 12 = December) and day D. Use the following table
    SIGNFROMTO
    CapricornDecember 22January 19
    AquariusJanuary 20February 17
    PiscesFebruary 18March 19
    AriesMarch 20April 19
    TaurusApril 20May 20
    GeminiMay 21June 20
    CancerJune 21July 22
    LeoJuly 23August 22
    VirgoAugust 23September 22
    LibraSeptember 23October 22
    ScorpioOctober 23November 21
    SagittariusNovember 22December 21
  • Muay Thai kickboxing. Write a program that reads in the weight of a Muay Thai kickboxer (in pounds) as a command-line argument and prints their weight class. Use a statement.
    CLASSFROMTO
    Flyweight0112
    Super flyweight112115
    Bantamweight115118
    Super bantamweight118122
    Featherweight122126
    Super featherweight126130
    Lightweight130135
    Super lightweight135140
    Welterweight140147
    Super welterweight147154
    Middleweight154160
    Super middleweight160167
    Light heavyweight167175
    Super light heavyweight175183
    Cruiserweight183190
    Heavyweight190220
    Super heavyweight220-
  • Euler's sum of powers conjecture. In 1769 Euler generalized Fermat's Last Theorem and conjectured that it is impossible to find three 4th powers whose sum is a 4th power, or four 5th powers whose sum is a 5th power, etc. The conjecture was disproved in 1966 by exhaustive computer search. Disprove the conjecture by finding positive integers a, b, c, d, and e such that a5 + b5 + c5 + d5= e5. Write a program Euler.java that reads in a command line parameter N and exhaustively searches for all such solutions with a, b, c, d, and e less than or equal to N. No counterexamples are known for powers greater than 5, but you can join EulerNet, a distributed computing effort to find a counterexample for sixth powers.
  • Blackjack. Write a program that takes three command line integers x, y, and z representing your two blackjack cards x and y, and the dealers face-up card z, and prints the "standard strategy" for a 6 card deck in Atlantic city. Assume that x, y, and z are integers between 1 and 10, representing an ace through a face card. Report whether the player should hit, stand, or split according to these strategy tables. (When you learn about arrays, you will encounter an alternate strategy that does not involve as many if-else statements).
  • Blackjack with doubling. Modify the previous exercise to allow doubling.
  • Projectile motion. The following equation gives the trajectory of a ballistic missile as a function of the initial angle theta and windspeed: xxxx. Write a java program to print the (x, y) position of the missile at each time step t. Use trial and error to determine at what angle you should aim the missile if you hope to incinerate a target located 100 miles due east of your current location and at the same elevation. Assume the windspeed is 20 mph due east.
  • World series. The baseball world series is a best of 7 competition, where the first team to win four games wins the World Series. Suppose the stronger team has probability p > 1/2 of winning each game. Write a program to estimate the chance that the weaker teams wins the World Series and to estimate how many games on average it will take.
  • Consider the equation (9/4)^x = x^(9/4). One solution is 9/4. Can you find another one using Newton's method?
  • Sorting networks. Write a program Sort3.java with three statements (and no loops) that reads in three integers a, b, and c from the command line and prints them out in ascending order.
    if (a > b) swap a and b if (a > c) swap a and c if (b > c) swap b and c
  • Oblivious sorting network. Convince yourself that the following code fragment rearranges the integers stored in the variables A, B, C, and D so that A <= B <= C <= D.
    if (A > B) { t = A; A = B; B = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (D > E) { t = D; D = E; E = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; }
    Devise a sequence of statements that would sort 5 integers. How many statements does your program use?
  • Optimal oblivious sorting networks. Create a program that sorts four integers using only 5 statements, and one that sorts five integers using only 9 statements of the type above? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can you check that your program works for all inputs?

    Solution: Sort4.java sorts 4 elements using 5 compare-exchanges. Sort5.java sorts 5 elements using 9 compare-exchanges.

    The 0-1 principle asserts that you can verify the correctness of a (deterministic) sorting algorithm by checking whether it correctly sorts an input that is a sequence of 0s and 1s. Thus, to check that works, you only need to test it on the 2^5 = 32 possible inputs of 0s and 1s.

  • Optimal oblivious sorting (challenging). Find an optimal sorting network for 6, 7, and 8 inputs, using 12, 16, and 19 statements of the form in the previous problem, respectively.

    Solution: Sort6.java is the solution for sorting 6 elements.

  • Optimal non-oblivious sorting. Write a program that sorts 5 inputs using only 7 comparisons. Hint: First compare the first two numbers, the second two numbers, and the larger of the two groups, and label them so that a < b < d and c < d. Second, insert the remaining element e into its proper place in the chain a < b < d by first comparing against b, then either a or d depending on the outcome. Third, insert c into the proper place in the chain involving a, b, d, and e in the same manner that you inserted e (with the knowledge that c < d). This uses 3 (first step) + 2 (second step) + 2 (third step) = 7 comparisons. This method was first discovered by H. B. Demuth in 1956.
  • Weather balloon. (Etter and Ingber, p. 123) Suppose that h(t) = 0.12t4 + 12t3 - 380t2 + 4100t + 220 represents the height of a weather balloon at time t (measured in hours) for the first 48 hours after its launch. Create a table of the height at time t for t = 0 to 48. What is its maximum height? Solution: t = 5.
  • Will the following code fragment compile? If so, what will it do?
    int a = 10, b = 18; if (a = b) System.out.println("equal"); else System.out.println("not equal");

    Solution: It uses the assignment operator instead of the equality operator in the conditional. In Java, the result of this statement is an integer, but the compiler expects a boolean. As a result, the program will not compile. In some languages (notably C and C++), this code fragment will set the variable a to 18 and print without an error.

  • Gotcha 1. What does the following code fragment do?
    boolean a = false; if (a = true) System.out.println("yes"); else System.out.println("no");
    Solution: it prints . Note that the conditional uses = instead of ==. This means that is assigned the value As a result, the conditional expression evaluates to . Java is not immune to the = vs. == error described in the previous exercise. For this reason, it is much better style to use or when testing booleans.
  • Gotcha 2. What does the following code fragment do?
    int a = 17, x = 5, y = 12; if (x > y); { a = 13; x = 23; } System.out.println(a);
    Solution: Always prints 13 since there is a spurious semicolon after the statement. Thus, the assignment statement will be executed even though It is legal (but uncommon) to have a block that does not belong to a conditional statement, loop, or method.
  • Gotcha 3. What does the following code fragment do?
    for (int x = 0; x < 100; x += 0.5) { System.out.println(x); }
    Solution: It goes into an infinite loop printing . The compound assignment statement is equivalent to .
  • What does the following code fragment do?
    int income = Integer.parseInt(args[0]); if (income >= 311950) rate = .35; if (income >= 174700) rate = .33; if (income >= 114650) rate = .28; if (income >= 47450) rate = .25; if (income >= 0) rate = .22; System.out.println(rate);
    It does not compile because the compile cannot guarantee that is initialized. Use instead.
  • Application of Newton's method. Write a program that finds the radii where the probability of finding the electron in the 4s excited state of hydrogen is zero. The probability is given by: (1 - 3r/4 + r2/8 - r3/192)2 e-r/2, where r is the radius in units of the Bohr radius (0.529173E-8 cm). Use Newton's method. By starting Newton's method at different values of r, you can discover all three roots. Hint: use initial values of r= 0, 5, and 13. Challenge: explain what happens if you use an initial value of r = 4 or 12.
  • Pepys problem. In 1693, Samuel Pepys asked Isaac Newton which was more likely: getting at least one 1 when rolling a fair die 6 times or getting at least two 1's when rolling a fair die 12 times. Write a program Pepys.java that uses simulation to determine the correct answer.
  • What is the value of the variable s after running the following loop when N = 1, 2, 3, 4, and 5.
    String s = ""; for (int i = 1; i <= N; i++) { if (i % 2 == 0) s = s + i + s; else s = i + s + i; }

    Solution: Palindrome.java.

  • Body mass index. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program that takes two command-line arguments, and , computes the BMI, and prints the corresponding BMI category:
    • Starvation: less than 15
    • Anorexic: less than 17.5
    • Underweight: less than 18.5
    • Ideal: greater than or equal to 18.5 but less than 25
    • Overweight: greater than or equal to 25 but less than 30
    • Obese: greater than or equal to 30 but less than 40
    • Morbidly Obese: greater than or equal to 40
  • Reynolds number. The Reynolds number is the ratio if inertial forces to viscous forces and is an important quantity in fluid dynamics. Write a program that takes in 4 command-line arguments, the diameter d, the velocity v, the density rho, and the viscosity mu, and prints the Reynold's number d * v * rho / mu (assuming all arguments are in SI units). If the Reynold's number is less than 2000, print , if it's between 2000 and 4000, print , and if it's more than 4000, print .
  • Wind chill revisited. The wind chill formula from Exercise 1.2.14 is only valid if the wind speed is above 3MPH and below 110MPH and the temperature is below 50 degrees Fahrenheit and above -50 degrees. Modify your solution to print an error message if the user types in a value outside the allowable range.
  • Point on a sphere. Write a program to print the (x, y, z) coordinates of a random point on the surface of a sphere. Use Marsaglia' method: pick a random point (a, b) in the unit circle as in the example. Then, set x = 2a sqrt(1 - a^2 - b^2), y = 2b sqrt(1 - a^2 - b^2), z = 1 - 2(a^2 + b^2).
  • Powers of k. Write a program that takes an integer as command-line argument and prints all the positive powers of in the Java data type. Note: the constant is the value of the largest integer in .
  • Square root, revisited. Why not use the loop-continuation condition in Sqrt.java instead of ?

    Solution: Surprisingly, it can lead to inaccurate results or worse. For example, if you supply SqrtBug.java with the command-line argument , you get as the answer (instead of ); if you supply , you get an infinite loop!

  • What happens when you try to compile the following code fragment?
    double x; if (a >= 0) x = 3.14; if (a < 0) x = 2.71; System.out.println(x);

    Solution: It complains that the variable x might not have been initialized (even though we can clearly see that x will be initialized by one of the two if statements). You can avoid this problem here by using if-else.

  •  The Start: Introduction, Comments, Output, Variables, Input
    AuthorMessage
    Cervantes




    Posted: Thu Aug 18, 2005 11:24 am   Post subject: The Start: Introduction, Comments, Output, Variables, Input




    Introduction to Programming

      Programming may seem scary at first, but hold fast! It is elegantly simple. Here's why: Programming languages are not computer languages. They are human languages that computers can translate into their own language (binary). They have been successfully designed by humans for use by humans, despite the restrictions placed on programming languages because they must be understood by computers as well. Writing in a programming language is strikingly similar to writing in a language in the traditional sense of the word: there are syntax rules to follow, there are objects that analogous to nouns, and methods that are analogous to verbs. There are no adjectives, mind you, because computers understand quantity, not quality.

      That said, let's delve in and learn just how computer languages work. The only thing you need to know right now is that the computer executes the code sequentially--line by line. The first line of a program is completely executed before execution of the next line has begun.




    Comments

      Some code is difficult to understand, even if you understand the language it is written in. To that end, the designers of programming languages have allowed us to comment our code. In Turing, this is done by placing the percent sign (%) before a comment.
    Turing:

    % This is a comment.  Everything after the % on this line is ignored by the computer.

    Another way of commenting code is by using matching sets of "/*" and "*/"
    Turing:

    /*
    This is a comment.  Everything after the forward-slash-asterisk but before the matching asterisk-forward-slash is ignored by the computer.
    */

    Commenting makes your code more understandable to yourself (you may think you know what your code is doing, but you probably won't know when you return to it a month later) and to others who read your code. If your code is more understandable, you will be more productive in writing it and others will spend less time understanding it and more time helping/learning from you.




    Output

      There are several ways that our computers can communicate to us. The first and most obvious is visually, through the monitor. The second is audibly, through the speakers. The last is much more tangible: the printer. We will begin by learning how to output text to the monitor, and save the speakers and printer for later lessons.

      We want to put some text on the screen, to prove that the link between us and the computer does in fact exist. Let me repeat that again: We want to put some text on the screen. In Turing, we do this by using the put command, followed by the text, contained in double quotes, that we want to output, like this:
    Turing:

    Type this code into your Turing window and click the Run button (or hit F1). You should see a Turing Run Window pop up with some buttons across the top and text that says "Hello World". If you see this, the first task is complete. If not, go update your version of Turing.

    Now, a bit of explanation is due. The put command takes whatever is after it and puts it at the cursor location in the Run Window. You don't see the cursor, mind you, because we never asked for input; only output. The cursor begins in the upper left corner, and with each time you put text on the screen, the cursor moves down one line.

    What comes after the put command determines what you will see on the screen. In the case of our "Hello World" program, we put a string on the screen. "What's a string?" you ask. Let us examine.




    Variable Types

      Strings:

        We have already encountered the string. Now let us answer the unrelenting question, "What is a string?" A string is a sequence of characters. The characters can be ordinary things such as letters and numbers, or they can be wacky things found in the ASCII chart such as the plus-minus sign (±). A string is bounded by quotation marks, as in "Yarr! I caught me aye fish!" A string can contain a maximum of 255 characters.

      Characters:

        A character is a single letter, number, or any wacky symbol that you can find in the ASCII chart. Characters are bound by quotation marks, as in 'Q'. Generally, strings use double quotes and characters use single quotes, though either type can use either style of quotation mark.

      Integers:

        We should all know what an integer is, given some fundamental math. Just to make sure, an integer is a whole number; it has no decimals; it is a fraction whose denominator is 1; it can be negative, zero, or positive.

      Real Numbers:

        Real numbers can contain decimal places. Turing supports up to 16 decimal places for real numbers. Real numbers contain the realms of the positive, the negative, and zero.

      Boolean:

        The boolean (named after George Boole) variable type contains only two alternatives: true or false. We will look into these in greater depth later, particularly when learning about conditions or if statements.





    Returning to Output

      Now that we know our Hello World program output a string on the screen, let's experiment with the other variable types. Let's try outputting an integer, then a real number.
    Turing:

    put7                               % Outputs 7
    put8.19538032154                 % Outputs 8.19538

    Notice how the real number was rounded.
    Now I know everyone loves arithmetic, so it's about time we did some. Quickly now, (4 + 8) / 2 * (3 - 5) equals what?

    Turing:

    put(4 + 8) / 2*(3 - 5)       % Outputs -12

    Turing does the math following the precedence rules, BEDMAS (Brackets, Exponents, Division and Multiplication, Addition and Subtraction). Now let's output the question and the answer:
    Turing:

    put"(4 + 8) / 2 * (3 - 5) = ",(4 + 8) / 2*(3 - 5)
    % Output: (4 + 8) / 2 * (3 - 5) = -12

    Notice the use of the comma (,). The comma separates one section from the next. The first section is a string, which shows us the question. The next section is an integer, which is the answer.
    Strings can be added together, a process called concatenation: we are taking one value and placing another value directly after it.
    Turing:

    put"Hello " + "Alan Turing."      % Outputs "Hello Alan Turing."

    "Alan Turing" is placed directly after "Hello ", to produce a quaint greeting to the legendary mathematician, cryptographer, logician, philosopher, biologist, and computer scientist, Alan Turing (1912 - 1954).




    Constants and Variables

      We use constants and variables in mathematics all the time. Consider the following equation:
    Volume_of_a_Sphere:

    Volume equals four-thirds pi times the radius cubed.
    There are two variables in the above equation: V and r. V represents volume. r represents the radius of the sphere. V and r have values that can change. They are probably real numbers.
    There is only one constant in the above equation, pi. It's value is constant, unchanging, no matter when or where you are in the universe. It is always (approximately) 3.14159265358979323846.

    In programming, a variable represents a location in the memory where a value is stored.

    Declaring Constants and Variables

      The general syntax (read: grammar) for creating a constant in Turing looks like this:
    Turing:

    const variableName : typeSpec

    Declaring a variable is the same, except the keyword const is replaced with var.
    Turing:

    var variableName : typeSpec

    variableName is the name of your variable. It can contain letters (upper case and lower case), numbers (though it cannot start with a number), and underscores.
    typeSpec is the variable type: a string, integer, real number, or a boolean value. Let's create one variable of each type:
    Turing:

    var customerName :string          % A variable to store the name of your customer
    var numberOfPassengers :int        % A variable to store the number of passengers (in your private jet, nonetheless)
    var priceOfASausage :real         % A variable to store the cost of a sausage at the local supermarket
    var tastyToblerone :boolean        % A variable to store whether a toblerone bar is tasty or not



    Assigning Values to Variables

      The thing is, none of these variables have been assigned any values. To assign a value to a variable, we use the colon-equals (:=).
      The general syntax (read: grammar) for creating a variable in Turing looks like this:
    Turing:

    customerName :="Wolfgang Mozart"
    numberOfPassengers :=645
    priceOfASausage :=2.55
    tastyToblerone :=true

    The variable on the left side of the assignment (:=) is given the value on the right side of the assignment (:=).
    You can assign more complex things to variables, as well. You can assign entire expressions, variables, or mixtures of both to variables. Watch:
    Turing:

    var priceOfChocolateBar :real
    var priceOfTeddyBear :real
    var priceOfBicycle :real
    var numOfChocolateBars :int
    var numOfTeddyBears :int
    var numOfBicycles :int
    var total :real

    priceOfChocolateBar :=1.49
    priceOfTeddyBear :=6.99
    priceOfBicycle :=349.99
    numOfChocolateBars :=2
    numOfTeddyBears :=4
    numOfBicycles :=1
    total := priceOfChocolateBar * numOfChocolateBars + priceOfTeddyBear * numOfTeddyBears + priceOfBicycle * numOfBicycles

    put"The cost of ", numOfChocolateBars, " chocolate bars, ", numOfTeddyBears, " teddy bears, and ", numOfBicycles, " bicycles comes to $", total, "."

    You can even use the value of the variable you are assigning to on the right side of the assignment (:=). Say we want to buy another chocolate bar:
    Turing:

    % Add the current total and the cost of  another chocolate bar,
    % and assign the sum to the variable, total
    total := total + priceOfChocolateBar



    Three Examples to Digest

      If you haven't opened Turing (the programming language, not the person) already, do so. Copy and paste the following code into the typing area and run the program.
      Example 1: Various Facts
    Turing:

    var customerName :string         % A variable to store the name of your customer
    var numberOfPassengers :int       % A variable to store the number of passengers (in your private jet, nonetheless)
    var priceOfASausage :real        % A variable to store the cost of a sausage at the local supermarket
    var tastyToblerone :boolean       % A variable to store whether a toblerone bar is tasty or not

    customerName :="Wolfgang Mozart"
    numberOfPassengers :=645
    priceOfASausage :=2.55
    tastyToblerone :=true

    put"A wispy, frail man named ", customerName, " has entered your store."
    put"Despite the occupant limit of 200 people, you have managed to fit ", numberOfPassengers, " people into your private jet!"
    put"Due to inflation, the price of a single, moderately spicy, Italian sausage has risen to $", priceOfASausage, "."
    put"True or False: Toblerone's are tasty: ", tastyToblerone

    The program should execute successfully. The output should look like this:

    A wispy, frail man named Wolfgang Mozart has entered your store.
    Despite the occupant limit of 200 people, you have managed to fit 645 people into your private jet!
    Due to inflation, the price of a single, moderately spicy, Italian sausage has risen to $2.55.
    True or False: Toblerone's are tasty: true


    Example 2: Volume of a Sphere
    Turing:

    var V :real
    var r :real
    /*
    Because pi is declared as a constant, we must give it a value immediately.  We cannot wait a line or two, because then we are changing the value of pi from nothing (nil) to 3.1415...
    */
    const pi :real:=3.14159265358979323846

    r :=10
    V :=4 / 3* pi * r ** 3       
    % Usually we use the carat (^) for exponents, but Turing uses a double-asterisk (**). 
    % The base is immediately before the double-asterisk.
    % The exponent is immediately after the double-asterisk.

    put"The volume of a sphere with radius ", r, " units is ", V, " cubic units."

    Here's the output:

    The volume of a sphere with radius 10 units is 4188.790205 cubic units.


    Example 3: Quadratic Formula
    If you don't know anything about the quadratic formula, don't worry. Just look at the programming, and don't worry about the math.
    Turing:

    % We can declare variables of the same variable type on the same line,
    % by separating them with commas.
    var a, b, c, x1, x2 :real
    a :=5
    b :=8
    c := -3
    x1 :=(-b + (b**2 - 4*a*c)** 0.5) / (2* a)
    x2 :=(-b - (b**2 - 4*a*c)** 0.5) / (2* a)
    /*
    Raising something to the power of one-half is the same as taking the square root of it.
    for curiosity, these lines could also be written like this:
    x1 := (-b + sqrt (b**2 - 4*a*c)) / (2 * a)
    x2 := (-b - sqrt (b**2 - 4*a*c)) / (2 * a)
    */

    put"The roots of the parabola 'y = ", a, "x**2 + ", b, "x + ", c, "' are ", x1, " and ", x2, "."

    Here's the output:

    The roots of the parabola 'y = 5x**2 + 8x + -3' are 0.313553 and -1.913553.




    Problems with Assignability

      If you've been tinkering around with Turing as you're reading this, you may have already discovered this. Say you have a integer variable. You are not allowed to assign it a value such as "Fred" or 4.684. This is a syntax error.
      That's understandable, but what about this next scenario? You've got an integer variable and you want to assign it a value of "7". That's 7, in double-quotes. We can't even do this. The reason is "7", the string, is stored in memory differently than is 7, the integer. (Integers can be stored using simple binary. 7, for example, is 111 in binary. Strings, however, are actually a collection of characters, and the characters are defined by their ASCII value. 7 has an ASCII value of 55, which in binary is 110111. A conversion must take place in order to allow things to operate smoothly. I discuss this in my String Manipulation tutorial, but don't go there. This is all just to peak your unbridled and ever-lusting curiosity. Is it satisfied now?)

      For now, accept the rules of assignability. Don't go trying to assign a value of "Jared Diamond" to your boolean variable.





    Getting Information From The User

      Now comes the fun part. We're going to learn how to get input from the user of your program. The most basic way of doing this is using the get command. It's rather simple:
    Turing:

    var name :string
    put"What is your name?"
    get name
    put"Hello ", name, "!"

    First, we must declare our variable. Then we get the variable name, which will get input from the user. Try running this program.
    Question 1:
      Try to crash the above program.

    Hint 1:
      Look above, where we first introduced the variable types.

    When you're done crashing that delicious program, try running the following, very similar program:
    Turing:

    var age :int
    put"How old are you?"
    get age
    put"Wow! ", age, " sure is old, especially for you mortals! *cackle*"

    This program is much easier to crash. Entering a string such as "Insolent fool! I'm immortal!" or entering a real number such as 9e5 (this means 9 * 10^5, which is nine hundred thousand [900 000], and is in fact a valid real number).

    Question 2:
      Write a program to output the kinetic energy of an object given its mass its velocity (that is, the user inputs the mass and the velocity) according to the following formula:
      Ek = 1/2 * m * v^2
      where Ek is the kinetic energy of the object,
      m is the mass of the object,
      and v is the velocity of the object.





    Conclusion

      If you've made it this far, kudos to you! You've mastered the fundamentals of Turing and of any programming language. You can now interact with the computer through Turing, and you're program can interact with the user through the put and get commands.

      Now take your mind off these things. Spin an album-side (or have you been multitasking this whole time?), go for a run, talk to your family/friends, or, in the spirit of getting into the CompSci.ca community, download and watch some anime / play DDR.
      The Beatles - Tomorrow Never Knows wrote:

      Turn off your mind, relax, and float downstream.
      It is not dieing. It is not dieing.
      Lay down all thoughts, surrender to the void.
      It is shining. It is shining.
      That you may see the meaning of within.
      It is being. It is being.

      When you're ready, learn how to test certain conditions using if statements.


    Answers

      Answer 1
        Input a string longer than 255 characters. 3.5 lines of characters using the standard run window size should do it.


      Answer 2
    Turing:

    var kineticEnergy, mass, velocity :real
    put"Please enter the mass of an object, in kilograms: " ..
    % The .. makes the cursor follow this line,
    % rather than jumping down to the next line.
    % Thus, the text the user types will appear
    % immediately after the request.
    get mass
    put"Please enter the velocity of the same object, in metres per second: "..
    get velocity
    kineticEnergy :=0.5* mass * velocity ** 2
    put"The kinetic energy of your object is ", kineticEnergy, " Joules."

    Sponsor
    Sponsor

    [Gandalf]




    Posted: Thu Aug 18, 2005 12:34 pm   Post subject: (No subject)

    Wow, that's pretty detailed and well presented. Read that once or twice and you're set from knowing no programming to being on a path to making some amazing programs .

    Good job!
    theguru




    Posted: Fri Oct 07, 2005 9:55 pm   Post subject: (No subject)

    great tutorial. lot's of details and examples. i think you should put something about escape characters. i don't know if turing has any but it should. for example how would you put a "quotes" in the put command. if turing is like c++ and other languages it should be \" but correct me if I'm wrong.
    [Gandalf]




    Posted: Fri Oct 07, 2005 10:25 pm   Post subject: (No subject)

    Indeed... The \ is the escape character in Turing as well.

    \n - newline
    \t - tab
    \" - quote
    \' - single quote (for chars)
    \b - backspace
    \\ - backslash
    and the whole lot of them...
    theguru




    Posted: Fri Oct 07, 2005 11:16 pm   Post subject: (No subject)

    ok, thanks a lot for the help. but shouldn't they put that in the tutorial too? and what's the function for square roots?
    Cervantes




    Posted: Thu Oct 13, 2005 3:28 pm   Post subject: (No subject)

    ok, thanks a lot for the help. but shouldn't they put that in the tutorial too? and what's the function for square roots?

    sqrt() or raise the number to the exponent of (1/2)

    Please don't flood the tutorial with questions. There's an entire forum for that.

    I could add that to the tutorial, yes. But then that's more to digest, and not necessary at this level.
    FakeSound




    Posted: Sat Apr 22, 2006 9:23 am   Post subject: (No subject)

    Hey, I'm new to programming and I just wanted to say that this site is really helpful .. thanks guys
    jamonathin




    Posted: Sun Apr 23, 2006 5:02 pm   Post subject: (No subject)

    - Im just amazed at the length and detail of these tutorials you produce. No it's not hard to remeber all of these things when you need them, but to spit them all out off the top of your head? - crazy.

    You need to start writing books Cervantes .
    Jessica43999




    Posted: Tue Jun 06, 2006 11:17 am   Post subject: Putting On Same Line

    Does anybody know how to make something put on the same row over and over again? Like, a score in a loop?
    Delos




    Posted: Tue Jun 06, 2006 12:16 pm   Post subject: (No subject)

    Sounds like you'll want to look into locate(). If this does not suit your needs, then please post a question in [Turing Help]. Make sure to include a clear description of your problem, some sample code illustrating what you've done so far, and your thoughts on where you think the problem may lie.
    [Gandalf]




    Posted: Tue Jun 06, 2006 6:22 pm   Post subject: (No subject)

    Use .. after your put statement, for example:
    code:
    for i : 1 .. 10
        put i ..
    end for

    Will put the numbers from 1 to 10 right beside each other. If you had read Cervantes' tutorial thoroughly then you would have found the answer to your question.
    Foundation




    Posted: Tue Sep 12, 2006 5:09 pm   Post subject: Thanks!

    I'm just learning about Turing, and this really helps! I appreciate this very much. Thanks.
    Andr3iB




    Posted: Mon Feb 12, 2007 9:51 am   Post subject: Re: The Start: Introduction, Comments, Output, Variables, Input

    WOW Cervantes, your tutorials are really really helpful! Thnx for all the hard work!
    Cervantes




    Posted: Mon Feb 12, 2007 2:01 pm   Post subject: RE:The Start: Introduction, Comments, Output, Variables, Input

    You're most welcome.
    TuringError




    Posted: Wed Nov 14, 2007 6:01 pm   Post subject: Re: The Start: Introduction, Comments, Output, Variables, Input

    Awesome,thank u so muchhh