AP CSA Unit 1 Day 18: Multi Concept Cast Div Mod

Unit 1 Advanced (Cycle 2) Day 18 of 28 Advanced

Multi-Concept: Casting, Division, Modulo

Section Mixed — Review: Casting and Arithmetic

Key Concept

Multi-concept problems combine casting, integer division, and modulo in a single expression. The key is to evaluate each operator at its position using the types of its specific operands. In (double)(17 % 5) + 17 / 5, the modulo produces 2 (cast to 2.0), and the integer division produces 3 (promoted to 3.0 for the addition), giving 5.0. The AP exam uses parentheses and casts to change the evaluation order in ways that produce different results than students expect.

Consider the following code segment.

int n = 12345; int d1 = n % 10; int d2 = (n / 10) % 10; int d3 = (n / 100) % 10; System.out.println(d1 + "" + d2 + "" + d3);

What is printed as a result of executing the code segment?

Answer: (B) 543

This code extracts individual digits using division and modulo:

d1: 12345 % 10 = 5 (last digit).

d2: 12345 / 10 = 1234. Then 1234 % 10 = 4 (second-to-last digit).

d3: 12345 / 100 = 123. Then 123 % 10 = 3 (third-to-last digit).

Output: 5 + "" + 4 + "" + 3 = "543" (digits in reverse order).

Why Not the Others?

(A) The digits are extracted from right to left (ones, tens, hundreds), so they print as 543, not 345.

(C) This would be the first three digits in order. But % 10 extracts from the right side of the number, not the left.

(D) 321 would be the first three digits reversed. But the code extracts the last three digits: 5, 4, 3.

Common Mistake

The % 10 operator extracts the ones digit. Dividing by 10 first shifts the number right, making the tens digit into the ones position. Dividing by 100 shifts two places. The extracted digits come out in reverse order.

AP Exam Tip

Digit extraction is a classic AP exam pattern. n % 10 = last digit, (n / 10) % 10 = second-to-last, (n / 100) % 10 = third-to-last. The digits come out right-to-left.

Review this topic: Section Mixed — Review: Casting and Arithmetic • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.