1. Home
  2. /
  3. Zig
  4. /
  5. Shopping Cart

Shopping Cart - Zig Typing CST Test

Loading…

Shopping Cart — Zig Code

Adds and removes items in a shopping cart with total cost.

const std = @import("std");
var items: [5]?[]const u8 = [_]?[]const u8{null} ** 5;
var prices: [5]f64 = [_]f64{0} ** 5;
var count: usize = 0;
var total: f64 = 0;

fn addItem(item: []const u8, price: f64) void {
	if (count < items.len) {
		items[count] = item;
		prices[count] = price;
		total += price;
		count += 1;
	}
}

fn removeItem(index: usize) void {
	if (index < count) {
		total -= prices[index];
		for (index..count-1) |i| {
		items[i] = items[i+1];
		prices[i] = prices[i+1];
		}
		count -= 1;
	}
}

fn printCart() void {
	for (0..count) |i| {
		std.debug.print("{s}: ${f}\n", .{items[i], prices[i]});
	}
	std.debug.print("Total: ${f}\n----------------\n", .{total});
}

pub fn main() void {
	addItem("Apple", 2.0);
	addItem("Banana", 3.0);
	printCart();
	removeItem(0);
	printCart();
}

Zig Language Guide

Zig is a general-purpose, statically typed, compiled programming language designed for robustness, optimal performance, and simplicity. It emphasizes manual memory management, safety features, cross-compilation, and direct interoperability with C, making it ideal for system programming, embedded development, and high-performance applications.

Primary Use Cases

  • ▸System programming and OS development
  • ▸Embedded and bare-metal applications
  • ▸High-performance libraries and tools
  • ▸Cross-platform and cross-compiler projects
  • ▸Interfacing with C libraries and APIs

Notable Features

  • ▸Manual memory management with safety
  • ▸Comptime (compile-time) execution
  • ▸Direct C interoperability
  • ▸Error unions and optional types
  • ▸Cross-compilation built-in

Origin & Creator

Created by Andrew Kelley in 2015 with the goal of replacing C while providing safer and more readable system programming constructs.

Industrial Note

Zig is gaining traction in system-level programming, embedded device firmware, WebAssembly development, game engine tooling, and low-level networking applications.

More Zig Typing Exercises

Zig Counter and Theme ToggleZig Random Number GeneratorZig Todo ListZig Dice RollerZig Countdown TimerZig Prime CheckerZig Temperature ConverterZig Name GreetingZig Stopwatch

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher