Chapter 2.1: Programming

Chapter 2.1: Programming · Study Questions
Compiled and interpreted languagesParadigmsError typesOperator precedenceOrder of statementsString concatenationTypesExpressions and statements
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Programming Languages

Question 1: Language and Paradigm

Which of the following language–paradigm pairs is correct?

A: Haskell treats computation as the evaluation of mathematical functions. Prolog is logic-based (facts and rules), C is imperative, and Lisp is the ancestor of functional languages.

Multiple Choice · Programming Languages

Question 2: Interpreted Language

Which statement is true of an interpreted language?

C: The interpreter reads the source code and runs the commands in order; a faulty line is noticed only when its turn comes (Python, JavaScript). A and B describe compiled languages; interpreted languages are usually slower (D).

Spot the Bug · Syntax and Semantics

Question 3: Find the Error Type

Each fragment is in a separate program. Name the kind of error (syntax, static semantic, runtime, logic) and when it is noticed.

int n = 4.5;                          // (a)
System.out.println("Merhaba";         // (b)
int[] a = new int[3];
a[3] = 1;                             // (c)
int x = 7, y = 8;
double avg = (x + y) / 2;             // (d)
Show answer
  • (a) Static semantic, at compile time: possible lossy conversion from double to int.
  • (b) Syntax, at compile time: ')' or ',' expected.
  • (c) Runtime: it compiles, and at run time it throws ArrayIndexOutOfBoundsException (valid indices are 0–2).
  • (d) Logic: it compiles and runs, but gives 7.0 for 7 and 8 (the right answer is 7.5); it is found only by testing.

Multiple Choice · Syntax and Semantics

Question 4: Error Type

In an average-computing program, the sum is mistakenly divided by 2 instead of 3. The program compiles, runs and prints a number, but the number is wrong. What kind of error is this?

C: The code obeys the language rules, so it compiles, and no operation is invalid, so no exception occurs. Logic errors are found only by comparing with the expected result, that is, by testing. Of the three error types (compile-time, runtime, logic), the exception mechanism handles only runtime errors.

Multiple Choice · Syntax and Semantics

Question 5: Dividing a Number by a String

double result = 2.3 / "abc"; — what kind of error is in this line?

B: The pattern <value> <operator> <value> fits the syntax, but dividing a number by a string has no meaning. The compiler catches it during type checking: bad operand types for binary operator '/'. It is the counterpart of the English example “I are big”.

Spot the Bug · Syntax and Semantics

Question 6: Reading an Error Message

Calc.java is compiled and the message Calc.java:7: error: cannot find symbol … symbol: variable Total appears. Where is the error, what causes it, and how is it fixed?

public class Calc {
    public static void main(String[] args) {
        int total = 0;
        for (int i = 1; i <= 3; i++) {
            total += i;
        }
        System.out.println(Total);
    }
}
Show answer

Calc.java:7: line 7; the ^ marker points at the start of Total. The declared variable is total, the one used is Total: Java is case-sensitive, so these are two different names.

It is a compile-time (static semantic) error; no .class file is produced. Fix: System.out.println(total); → prints 6.

Output Question · Expressions and Variables

Question 7: Operator Precedence

What does the program print?

System.out.println(10 - 4 - 3);
System.out.println(2 + 3 * 4 % 5);
System.out.println(20 / 3 * 3);
System.out.println(20 / 3.0 * 3);
System.out.println(-17 % 5);
System.out.println((1 + 2) * 3 / 2);
Show answer
3
4
18
20.0
-2
4

Equal precedence goes left to right: (10 − 4) − 3 = 3. * and % have equal precedence: 3 · 4 = 12, 12 % 5 = 2 → 2 + 2 = 4.

20 / 3 = 6 (integer division), 6 · 3 = 18; 20 / 3.0 is real division → 20.0. The remainder takes the sign of the dividend: −17 % 5 = −2. 9 / 2 = 4.

Step-by-Step Trace · Expressions and Variables

Question 8: Tracing Assignments

What does the program print?

a5

Space is reserved for a and 5 is stored in it.

a5b15

Right-hand side: 5 · 3 = 15 → new variable b. a does not change.

a10b15

First the right-hand side, using the old value of a: 15 − 5 = 10; then it is stored in a.

a10b1

15 / 10 = 1 (integer division, the 0.5 is dropped).

a12b1

* first: 1 · 2 = 2, then 10 + 2 = 12.

a12b1

Output 12 1. An assignment takes two steps: the right-hand side is evaluated, then the old value is overwritten.

int a = 5;
int b = a * 3;
a = b - a;
b = b / a;
a = a + b * 2;
System.out.println(a + " " + b);

Step-by-Step Trace · Strings and Types

Question 9: Concatenation Goes Left to Right

What does the program print? ('a' = 97)

Two int variables.

Left to right: 2 + 3 is two ints → 5, then 5 + "!" is concatenation → 5!.

The left operand is a string: "!" + 2 → "!2", "!2" + 3 → !23. No addition is ever done.

Parentheses bring the addition first: 2 + 3 = 5 → !5.

2 + 3 = 5, 5 + "" = "5"; from then on it is all concatenation: "52", 523.

char is a numeric code: 'a' + 3 = 97 + 3 = 100, then "c" is appended → 100c.

int a = 2, b = 3;
System.out.println(a + b + "!");
System.out.println("!" + a + b);
System.out.println("!" + (a + b));
System.out.println(a + b + "" + a + b);
System.out.println('a' + b + "c");

Spot the Bug · Strings and Types

Question 10: Comparing Different Types

Which lines do not compile? What do the compiling lines print?

int number = 5;
String text = "5";
// (1)
System.out.println(number == text);
// (2)
System.out.println(text.equals(number));
// (3)
System.out.println(
    Integer.parseInt(text) == number);
// (4)
System.out.println(3 + true);
Show answer
  • (1) does not compile: bad operand types for binary operator '==' (int and String).
  • (2) compiles, false: a String is never equal to an Integer.
  • (3) compiles, true: both sides are converted to the same type first ("5" → 5).
  • (4) does not compile: bad operand types for binary operator '+'; a boolean cannot be added to a number.

Step-by-Step Trace · Program and Algorithm

Question 11: Rotating Three Variables

What does the program print? Why is temp needed?

x1y2z3temp

The goal is to rotate the values to the left: x ← y, y ← z, z ← x.

x1y2z3temp1

The first value to be overwritten (x = 1) is saved first.

x2y2z3temp1

x = 2. The old 1 is safe in temp.

x2y3z3temp1

y = 3.

x2y3z1temp1

z takes the saved old x: 1.

x2y3z1temp1

Output 2 3 1. Without temp, the line z = x would get the new value of x (2): 2 3 2.

int x = 1, y = 2, z = 3;
int temp = x;
x = y;
y = z;
z = temp;
System.out.println(x + " " + y + " " + z);

Multiple Choice · Program and Algorithm

Question 12: Expression or Statement?

Which of the following is not a statement with an effect, but only an expression?

D: x > 3 produces a boolean value; written alone as a line it gives a not a statement error. Assignment, declaration and println have effects and are statements ending in ;.

Spot the Bug · Program and Algorithm

Question 13: Fahrenheit to Celsius

For f = 100, 37.77… is expected; what does the program print? Explain why, and fix it in two different ways.

double f = 100;
double c = 5 / 9 * (f - 32);
System.out.println(c);
Show answer
0.0

5 / 9 is a division of two ints: 0. 0 × 68.0 = 0.0. The compiler does not catch this: it is a semantic (logic) error.

Fix: 5.0 / 9 * (f - 32) or multiply first, (f - 32) * 5 / 9; both print 37.77777777777778

Coding Question · Program and Algorithm

Question 14: Body Mass Index

Write a program that reads height (m) and weight (kg) from the user as fractional numbers, then computes and prints the body mass index (BMI = weight / height²). What would happen if the formula were written as weight / height * height?

Show answer
import java.util.Scanner;

public class Bmi {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Boy (m): ");
        double height = input.nextDouble();
        System.out.print("Kilo (kg): ");
        double weight = input.nextDouble();
        double bmi = weight / (height * height);
        System.out.println("BMI: " + bmi);
    }
}
  • For height 1.75 and weight 65.2: BMI: 21.289795918367346.
  • / and * have equal precedence and are evaluated left to right: weight / height * height = (weight / height) * height = weight. The program prints 65.2; the compiler does not catch this logic error.

Multiple Choice · Program and Algorithm

Question 15: Decimal Separator in Input

The computer's locale is Turkish. The user follows the example in the prompt and types 1.75. What happens?

Scanner input = new Scanner(System.in);
System.out.print("Height (e.g. 1.75): ");
double height = input.nextDouble();

D: Scanner reads numbers using the locale's format; in Turkish the decimal separator is a comma. 1,75 is accepted, 1.75 is not recognized as a double. Constants in the source code (65.2) and println output, however, always use a dot regardless of the locale. Fix: input.useLocale(Locale.US); or change the example in the prompt to 1,75.

Multiple Choice · Popular Languages

Question 16: Kotlin

Which statement is true of Kotlin?

A: Kotlin compiles to bytecode like Java and runs on the JVM; it is widespread in Android development. B describes JavaScript, C describes Swift, D describes SQL.

The End

Chapter 2.1: Programming: Study Questions
Lecture slides: Chapter 2.1: Programming · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.