In the previous 2 articles we learned some of the foundational concepts and skills used in zig language. In this article we'll cover control of flow statements necessary to make decisions based on conditions. We'll also learn more operators, play with boolean values, and play with "while loops" for repition control. Let's get started.
Control Statements
There are three categories of control statements:
- Sequential (default)
- Selection
- Repetition
Relational Operators
Operators are use to perform comparisons and return true or false results.
Operator | Description |
---|---|
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
== | Equal to |
!= | Not equal to |
touch relational.zig
const std = @import("std");
pub fn main() !void {
const a: i32 = 10;
const b: i32 = 20;
const stdout = std.io.getStdOut().writer();
stdout.print("a == b : {}\n", .{a == b}) catch {};
stdout.print("a != b : {}\n", .{a == b}) catch {};
stdout.print("a < b : {}\n", .{a == b}) catch {};
stdout.print("a > b : {}\n", .{a == b}) catch {};
stdout.print("a >= b : {}\n", .{a == b}) catch {};
stdout.print("a <= b : {}\n", .{a == b}) catch {};
}
> zig run relational.zig
a == b : false
a != b : false
a < b : false
a > b : false
a >= b : false
a <= b : false
The value of operators returns a boolean not an i32 like mathematical operators.
Let's talk about logical operators
Logical Operators
AND Operator (p AND q
)
p | q | p AND q |
---|---|---|
T | T | T |
T | F | F |
F | T | F |
F | F | F |
OR Operator (p OR q
)
p | q | p OR q |
---|---|---|
T | T | T |
T | F | T |
F | T | T |
F | F | F |
NOT Operator (NOT p
)
p | NOT p |
---|---|
T | F |
F | T |
This table may seem confusing, let's look at it with code:
touch logical.zig
const std = @import("std");
pub fn main() void {
const stdout = std.io.getStdOut().writer();
const a = true;
const b = false;
const andResult = a and b;
stdout.print("a and b : {}\n", .{andResult}) catch {};
const orResult = a or b;
stdout.print("a or b : {}\n", .{orResult}) catch {};
const notResultA = !a;
const notResultB = !b;
stdout.print("!a : {}\n", .{notResultA}) catch {};
stdout.print("!b : {}\n", .{notResultB}) catch {};
//combination
const comboResult = (a and b) or (!a and !b);
stdout.print("(a and b) or (!a and !b): {}\n", .{comboResult}) catch {};
}
> zig run logical.zig
a and b : false
a or b : true
!a : false
!b : true
(a and b) or (!a and !b): false
If and If-Else
If statements allow us to choose to do something or not whereas if-else statments allow us to choose between doing on thing or another thing and can be chained to simulate multiple selections.
touch if-statement.zig
const std = @import("std");
pub fn main() void {
const age1: u32 = 22;
const age2: u32 = 40;
if (age2 > age1) {
std.debug.print("Person 2 is older\n", .{});
}
if (age1 > age2) {
std.debug.print("Person 1 is older\n", .{});
} else {
std.debug.print("Person 1 is younger\n", .{});
}
if (age1 >= 21) {
std.debug.print("Here, have a beer!\n", .{});
} else if (age1 >= 18) {
std.debug.print("You can vote\n", .{});
}
}
> zig run if-statement.zig
Person 2 is older
Person 1 is younger
Here, have a beer!
While Loops or "Repetition Control Statements"
Also called "loops", allow us to perform iteration with a block of code. The while loop is a fundamental repetition control statement. It keeps looping/iterating as long as the loop continuation condition remains true. These are useful when we may not know the number of iterations ahead of time or there are dynamic conditions. We will look at for loops in a later article.
touch while.zig
const std = @import("std");
pub fn main() void {
var counter: usize = 1;
while (counter <= 5) {
std.debug.print("Counter is : {}\n", .{counter});
counter += 1;
}
}
> zig run while.zig
Counter is : 1
Counter is : 2
Counter is : 3
Counter is : 4
Counter is : 5
Challenge: Power of three
Create a new file called power-3.zig.
Find the first power of 3 greater than or equal to 30
Don't look at the code below, cheater!
const std = @import("std"); pub fn main() void { const N: usize = 30; var power: usize = 1; while (power < N) { power *= 3; } std.debug.print("The first power of 3 greater than or equal to {} is : {}\n", .{ N, power }); }
zig run power-3.zig
The first power of 3 greater than or equal to 30 is : 81
Conclusion of Drew Learns Zig (Part 3)
In this third installment of the "Drew Learns Zig" series, we have delved deeper into the practical aspects of the Zig programming language, focusing on flow control and logical reasoning. From relational and logical operators to control structures like if
, if-else
, and while
loops, this article has covered the foundational elements that enable complex decision-making and repetitive tasks within a program.
Understanding these control statements and operators is crucial for any developer aiming to build efficient and dynamic software. By applying the learned concepts to real-world coding challenges, such as the "Power of three" exercise, you not only reinforce your understanding but also improve your problem-solving skills in Zig.
As you continue to explore Zig, remember that the simplicity and clarity of your code matter. Each concept learned today serves as a stepping stone to more advanced topics we will cover in future articles, including for
loops and concurrency. Keep practicing, keep challenging yourself, and stay tuned for more insights into this powerful programming language.
Drew is a seasoned DevOps Engineer with a rich background that spans multiple industries and technologies. With foundational training as a Nuclear Engineer in the US Navy, Drew brings a meticulous approach to operational efficiency and reliability. His expertise lies in cloud migration strategies, CI/CD automation, and Kubernetes orchestration. Known for a keen focus on facts and correctness, Drew is proficient in a range of programming languages including Bash and JavaScript. His diverse experiences, from serving in the military to working in the corporate world, have equipped him with a comprehensive worldview and a knack for creative problem-solving. Drew advocates for streamlined, fact-based approaches in both code and business, making him a reliable authority in the tech industry.