print and println@printftry-catch for Exception HandlingfinallyImplementing decision-making logic and looping mechanisms are primary aspects of programming in Julia. Hands-on examples help solidify the understanding of these concepts. By working through practical exercises, you will become more comfortable constructing programs that can react to different conditions and automate repetitive tasks.
if-elseif-else Ladder - Checking Number SignDecision-making is fundamental in programming. The if-elseif-else structure allows your program to execute different blocks of code based on specific conditions. Let's create a simple program to determine if a number is positive, negative, or zero.
Objective:
To use if-elseif-else statements to categorize a number.
Scenario:
Given a variable number, we want to print whether it's positive, negative, or zero.
The Code:
function check_number_sign(number)
if number > 0
println("$number is positive.")
elseif number < 0
println("$number is negative.")
else
println("$number is zero.")
end
end
# Test cases
check_number_sign(10)
check_number_sign(-5)
check_number_sign(0)
How It Works:
check_number_sign function takes one argument, number.if number > 0 condition is checked first. If true, "is positive." is printed, and the rest of the elseif and else blocks are skipped.false, the elseif number < 0 condition is evaluated. If true, "is negative." is printed, and the else block is skipped.if and elseif conditions are false, the code inside the else block is executed, printing "is zero.".
This demonstrates how Julia evaluates conditions sequentially.Expected Output:
10 is positive.
-5 is negative.
0 is zero.
for Loop - Summing a Seriesfor loops are ideal for when you know how many times you want to repeat an action, such as iterating over a collection of items or a range of numbers.
Objective:
To use a for loop to calculate the sum of numbers in a given range.
Scenario: Calculate the sum of all integers from 1 to 10.
The Code:
function sum_series(n)
total_sum = 0 # Initialize an accumulator variable
for i in 1:n
total_sum = total_sum + i # Add the current number to the sum
end
println("The sum of numbers from 1 to $n is $total_sum.")
end
# Calculate sum up to 10
sum_series(10)
# Calculate sum up to 5
sum_series(5)
How It Works:
sum_series function takes an integer n as input.total_sum = 0 initializes a variable to store the cumulative sum. This is often called an accumulator.for i in 1:n starts a loop. The variable i will take on each value in the range from 1 to n, one at a time (e.g., 1, 2, 3, ..., n).total_sum = total_sum + i updates the total_sum by adding the current value of i. The += operator (total_sum += i) is a shorthand for this.total_sum is printed.Expected Output:
The sum of numbers from 1 to 10 is 55.
The sum of numbers from 1 to 5 is 15.
while Loop - Countdownwhile loops are used when you want to repeat a block of code as long as a certain condition remains true. The number of iterations might not be known beforehand.
Objective:
To use a while loop to perform a countdown.
Scenario: Create a program that counts down from a given number to 1.
The Code:
function countdown(start_value)
println("Starting countdown from $start_value...")
current_value = start_value
while current_value > 0
println(current_value)
current_value = current_value - 1 # Decrement the counter
end
println("Blast off!")
end
# Perform a countdown from 3
countdown(3)
How It Works:
countdown function takes start_value as input.current_value = start_value initializes a variable that will change with each iteration.while current_value > 0 sets the condition for the loop. The code inside the loop will execute as long as current_value is greater than 0.println(current_value) prints the current number.current_value = current_value - 1 (or current_value -= 1) decreases current_value by 1. This step is significant; without it, the condition current_value > 0 would always be true, leading to an infinite loop.current_value becomes 0, the condition current_value > 0 becomes false, and the loop terminates. The "Blast off!" message is then printed.Expected Output:
Starting countdown from 3...
3
2
1
Blast off!
break, continue, and Logical OperatorsSometimes, you need finer control over loop execution. continue skips the rest of the current iteration and proceeds to the next, while break exits the loop entirely. Logical operators like && (AND) allow you to combine conditions.
Objective:
To demonstrate break, continue, and the use of logical operators (&&) within a loop.
Scenario: Iterate through a list of numbers. We want to print a special message for positive even numbers. Negative numbers should be skipped. If a zero is encountered, processing should stop, as it might signify an end-of-data marker.
The Code:
function process_numbers(data)
println("Processing data: $data")
for num in data
if num == 0
println("Zero encountered, stopping processing.")
break # Exit the loop immediately
end
if num < 0
println("Skipping negative number: $num")
continue # Skip to the next iteration
end
# Check if the number is positive and even
if num > 0 && num % 2 == 0 # num % 2 == 0 checks for evenness
println("Found positive even number: $num")
elseif num > 0 # It's positive but odd
println("Found positive odd number: $num")
end
# Implicitly, we do nothing more for numbers not caught by these conditions
# if they weren't negative (skipped) or zero (stopped).
end
println("Finished processing.")
end
# Test data
my_data = [2, 5, -3, 8, 0, 12, -1]
process_numbers(my_data)
How It Works:
process_numbers function iterates through each num in the data array.if num == 0: If the current number is zero, a message is printed, and break causes the for loop to terminate immediately. Any remaining numbers in my_data after the zero will not be processed.if num < 0: If the number is negative, a message is printed, and continue skips the rest of the code inside the loop for the current num, moving directly to the next number in my_data.if num > 0 && num % 2 == 0: This condition uses the logical AND operator &&. It checks if num is greater than 0 AND if num divided by 2 has a remainder of 0 (i.e., num is even). If both are true, the corresponding message is printed. The modulo operator % gives the remainder of a division.elseif num > 0: If the number is positive but not even (meaning it's odd), this block catches it.break statement is executed.Expected Output:
Processing data: [2, 5, -3, 8, 0, 12, -1]
Found positive even number: 2
Found positive odd number: 5
Skipping negative number: -3
Found positive even number: 8
Zero encountered, stopping processing.
Finished processing.
The ternary operator provides a compact way to write simple if-else statements, especially useful for assignments. Its syntax is condition ? value_if_true : value_if_false.
Objective: To use the ternary operator for concise conditional assignment.
Scenario: Assign a status ("Approved" or "Pending Review") to an application based on a score. If the score is 70 or above, it's "Approved"; otherwise, it's "Pending Review".
The Code:
function get_application_status(score)
status = score >= 70 ? "Approved" : "Pending Review"
println("Score: $score, Status: $status")
end
# Test cases
get_application_status(85)
get_application_status(60)
How It Works:
get_application_status function takes a score.status = score >= 70 ? "Approved" : "Pending Review":
score >= 70 is the condition.true, status is assigned the value "Approved".false, status is assigned the value "Pending Review".if-else block:
# if score >= 70
# status = "Approved"
# else
# status = "Pending Review"
# end
Expected Output:
Score: 85, Status: Approved
Score: 60, Status: Pending Review
The FizzBuzz problem is a classic programming task often used in interviews. It combines loops and conditional logic.
The Challenge: Write a Julia program that prints numbers from 1 to 30 (inclusive). However, for multiples of three, print "Fizz" instead of the number. For multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
Hints:
for loop to iterate from 1 to 30.if-elseif-else statements.% is your friend here (e.g., number % 3 == 0 checks if number is a multiple of 3).Solution:
function fizzbuzz(limit)
for i in 1:limit
if i % 3 == 0 && i % 5 == 0 # or i % 15 == 0
println("FizzBuzz")
elseif i % 3 == 0
println("Fizz")
elseif i % 5 == 0
println("Buzz")
else
println(i)
end
end
end
# Run FizzBuzz up to 30
println("Running FizzBuzz up to 30:")
fizzbuzz(30)
How It Works:
fizzbuzz function iterates from 1 to limit.if i % 3 == 0 && i % 5 == 0: This condition checks if i is a multiple of both 3 and 5. This is equivalent to checking i % 15 == 0. It's important to check this first, because if we checked for multiples of 3 first, then a number like 15 would print "Fizz" and the "FizzBuzz" condition would never be met for it.elseif i % 3 == 0: If the first condition is false, this checks if i is a multiple of 3.elseif i % 5 == 0: If the first two conditions are false, this checks if i is a multiple of 5.else: If none of the above conditions are true, the number i itself is printed.Expected Output (Partial):
Running FizzBuzz up to 30:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
...
29
FizzBuzz
To continue strengthening your skills with control flow structures:
check_number_sign function: Add a check for whether a positive number is even or odd.sum_series function: Calculate the sum of only even numbers or only odd numbers within the range.while loop that asks for user input: Keep asking until the user types "quit". (You might need to peek ahead at Chapter 7 for readline() or simplify this to a non-interactive condition for now).for loop to find the largest number in an array: Initialize a variable to the first element (or a very small number) and update it if you find a larger element.By actively coding and experimenting with these fundamental control flow structures, you are building a solid foundation for writing more complex and intelligent Julia programs. These tools are essential for guiding the logic and behavior of your applications.
Was this section helpful?
© 2026 ApX Machine LearningEngineered with