Swift Random Numbers

Swift – Random Numbers ”; Previous Next Random Numbers are the sequence of numbers that are generated by the system without any pre-defined pattern or in an unpredictable manner. They are commonly used in chance events, produce unpredictable outcomes, etc. Random numbers are widely used in cryptography, gaming, statistical analysis, generating unique id/sessions for users, etc. In Swift, we can find random numbers using the following methods − random(in:) function random(in: using:) function randomElement() function Using random(in:) Function We can find random numbers with the help of the random(in:) function. This function returns a random number from the given range. Using this function, we can generate random numbers of Int, Double, Float and Bool types. Syntax Following is the syntax of the random(in:) function − static func random(in: inputRange) Here this function takes only one parameter which is the inputRange. The inputRange represents a range in which a random() function creates a random number. Return Value This function returns a random number from the given range. Example Swift program to generate random numbers using random(in:) function. import Foundation // Generating a random number of Int type var randomNumber1 = Int.random(in: 10…23) print(“Random Number:”, randomNumber1) // Generating a random number of Float type var randomNumber2 = Float.random(in: 10.2…23.2) print(“Random Number:”, randomNumber2) // Generating a random number of Double type var randomNumber3 = Double.random(in: 15.2..<25.2) print(“Random Number:”, randomNumber3) // Generating a random number of Bool type var randomNumber4 = Bool.random() print(“Random Number:”, randomNumber4) Output It will produce the following output − Random Number: 20 Random Number: 14.4035845 Random Number: 17.450544998301993 Random Number: true Using random(in:using:) Function To generate random numbers Swift supports a pre-defined function named random(in:using:) function. This function generates a random number within the given range with the help of a given generator. It also generates random numbers of Int, Double, Float and Bool types. Syntax Following is the syntax of the random(in:using:) function − static func random(in: inputRange, using: generator) This function takes two parameters − inputRange − It represents a range. Its value must not be empty. generator − It represents the generator using which random(in:using:) function will generate a random number. Return Value This function returns a random number within the specified range. Example Swift program to generate random numbers using random(in:using:) function. import Foundation // Specifying a generator var myGenerator = SystemRandomNumberGenerator() // Generating a random number of Int type var randomNumber1 = Int.random(in: 30…43, using: &myGenerator) print(“Random Number:”, randomNumber1) // Generating a random number of Float type var randomNumber2 = Float.random(in: 12.2…33.2, using: &myGenerator) print(“Random Number:”, randomNumber2) // Generating a random number of Double type var randomNumber3 = Double.random(in: 35.2..<45.2, using: &myGenerator) print(“Random Number:”, randomNumber3) // Generating a random number of Bool type var randomNumber4 = Bool.random(using: &myGenerator) print(“Random Number:”, randomNumber4) Output It will produce the following output − Random Number: 34 Random Number: 20.267605 Random Number: 42.47363754282583 Random Number: false Using randomElement() Function When we are working with collections such as an array and dictionary, we can use the randomElement() function. This function returns a random element from the given collection. The value returned by this function is an optional type so we must unwrap it using (!). Syntax Following is the syntax of the randomElement() function − static func randomElement() Return Value This function returns a random number from the specified collection. If the collection is empty, then it will return nil. Example Swift program to generate a random element from the given collection. import Foundation let myVeggies = [“Lemon”, “Cabbage”, “Green Chilly”, “Potato”] // Getting random element let randomVeggie = myVeggies.randomElement()! print(“Random Element: (randomVeggie)”) Output It will produce the following output − Random Element: Lemon Print Page Previous Next Advertisements ”;

Swift – Discussion

Discuss Swift ”; Previous Next Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibility. Swift 4 uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift 4 programs to run on many existing iOS 6 and OS X 10.8 platforms. Print Page Previous Next Advertisements ”;

WebAssembly – Discussion

Discuss WebAssembly ”; Previous Next WebAssembly is a new programming language for the web. WebAssembly code is low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript. Print Page Previous Next Advertisements ”;

Swift Opaque and Boxed Type

Swift – Opaque & Boxed Type ”; Previous Next Sometimes developers want to hide the details about the type. So Swift provides two special mechanisms named Opaque Types and Boxed Types. Using these two mechanisms we can manage and abstract the underlying details of types. The opaque type is used to hide the concrete type behind the protocols whereas the boxed type is used to wrap values in a container. Opaque Type The opaque type allows us to work with values of a specific type without showing the underlying concrete type. Or we can say that the opaque type is used to hide its return value type. It describes the return value in terms of the protocol it supports rather than showing the concrete type of the function’s return type. It preserves the type identity, which means the Swift compiler can access the type information but the user of the module cannot. It enhances the abstraction, encapsulation and modularity of the code by hiding the return type of the function or method and showing only the conforms to a certain protocol or structure. In Swift, we are allowed to use opaque return types with generics. Also if a function with opaque type is returned from multiple locations, then all the values returned by that function must have the same type. We can define opaque type using the some keyword along with the protocol or type. Syntax protocol ProtocolName { func methodName() -> String } func functionNAme() -> some ProtocolName { // Implementation that returns a type conforming to the given protocol} Example Swift program to demonstrate opaque type. // Function with return opaque type func randomElement() -> some Equatable{ Int.random(in: 0…14) } let elementOne = randomElement() let elementTwo = randomElement() // Now comparing the first and second elements returned by the function print(elementOne == elementTwo) Output It will produce the following output − false Example Swift program to demonstrate opaque type. // Define a protocol for shapes protocol Shape { func area() -> Double } // Implementing specific shapes struct Rectangle: Shape { let length: Double let breadth: Double func area() -> Double { return length * breadth } } struct Triangle: Shape { let length: Double let height: Double func area() -> Double { return ((length * height) / 2) } } // Function to add areas of two different shapes using opaque type func sumOfArea(rectShape: some Shape, triShape: some Shape) -> Double { return rectShape.area() + triShape.area() } let obj1 = Rectangle(length: 10.2, breadth: 11.0) let obj2 = Triangle(length: 5.1, height: 6.0) let totalArea = sumOfArea(rectShape: obj1, triShape: obj2) print(“Total Area is : (totalArea)”) Output It will produce the following output − Total Area is : 127.49999999999999 Boxed Protocol Type A boxed protocol type is used to warp a type that conforms to a protocol inside a container. It generally uses a generic type or existing type like “Any”. It allows us to work with values of different types that share a common protocol without showing the underlying types. Example Swift program to demonstrate opaque type. // Define a protocol protocol Display { func details() -> String } // Implementing for specific types struct Student: Display { var name: String func details() -> String { return “Student”s Name: (name)” } } struct Teacher: Display { var tname: String func details() -> String { return “Teacher”s Name: (tname)” } } // Wrapper type for boxed protocol struct BoxedDisplay { let x: Display init(_ x: Display) { self.x = x } } // Function that accepts a boxed protocol type func displayDetails(box: BoxedDisplay) { print(box.x.details()) } // Instances let obj1 = Student(name: “Monika”) let obj2 = Teacher(tname: “Mohit”) let box1 = BoxedDisplay(obj1) let box2 = BoxedDisplay(obj2) displayDetails(box: box1) displayDetails(box: box2) Output It will produce the following output − Student”s Name: Monika Teacher”s Name: Mohit Difference Between Opaque Type and Boxed Protocol Type Following are the major differences between opaque type and boxed protocol type − Opaque Type Boxed Protocol Type It uses some keyword to create opaque type. It uses wrapper type to create boxed protocol type. It allows function to hide its return type. It allows function to return a concrete type wrapped in a container. It provide type erasure. It may or may not have type erasure. It hides the concrete type. It warps the specific type. Print Page Previous Next Advertisements ”;

Swift – SwiftyJSON

Swift – SwiftyJSON ”; Previous Next What is JSON Data? JSON is known as JavaScript Object Notation. It is a lightweight and most commonly used data interchange format that is easy to read and write. It is generally used to transmit data between a server and an application. JSON data is generally represented in key-value pairs. For example − { “name”: “Monika”, “age”: 23, “city”: “Delhi” } Here name, age and city are the keys and Monika, 23 and Delhi are their respective values. In Swift, we can work with JSON data using the SwiftyJSON library. SwiftyJSON SwiftyJSON is a very important and powerful Swift library to handle JSON data in Swift programming language. It is commonly used to read and process JSON data returned by the APIs. It simplifies the process of parsing and working with JSON data in Swift easily by providing subscript syntax. It also provides various data types. Before SwiftyJSON the developer faced various problems while working with JSON data in Swift and the problems were − Verbose Syntax − Before the SwiftyJSON library the JSON data in Swift was handled by the JSONSerialization class which provides verbose syntaxes. Developers had to work with nested casting and a significant amount of optional unwrapping which makes code more complex and hard to read. Type Safety − While handling JSON data Swift doesn”t provide any direct way to handle optional values or nested structures in a type-safe manner. The user has to either use conditional casting or manually check the presence of keys. Readability − Reading and extracting values from the JSON was less readable. Swift doesn”t provide easy and clean syntax to work with JSON data. Error-handling − The developer had to use the do-catch block to handle errors manually because Swift does not provide any straightforward method to handle errors for JSON parsing and extracting. Lack of Convenience − Before SwiftyJSON developers had to write more boilerplate code to pars JSON data which makes the parsing more time-consuming. These issues are later solved by the SwiftJSON library. It provides more expressive and straightforward methods to deal with JSON data in Swift. How to use SwiftyJSON? To use the SwiftyJSON library in your project you have to follow the following steps − Step 1 − Install SwiftyJSON. To install SwiftyJSON you can use either CocoaPods or Swift Package Manager. Here we will use Swift Package Manager. So Open Xcode project → go to File → Swift Packages → Add Package Dependency and then enter the following SwiftyJSON GitHub repository URL − https://github.com/SwiftyJSON/SwiftyJSON.git Now follow the prompts to add the package. Step 2 − Now to use SwiftyJSON import the library at the top of the code using the import keyword. import SwiftyJSON Creating JSON Object: To create a JSON object SwiftyJSON provides the following initialiser. let object = JSON(data: dataObject) Or let obj = JSON(jsonObj) Accessing data − You can use subscripts to access JSON data. // Getting string from JSON dictionary let stdName = json[“name”].stringValue // Getting int from JSON array let value = json[1].int= Iterating over an array or dictionary − SwiftyJSON supports a for-in loop to iterate over the elements of an array or dictionary. // For array for(index, element):(String, JSON) in json{ Write something } // For dictionary for(key, element):(String, JSON) in json{ Write something } Example import SwiftyJSON // JSON string let inputJsonString = “”” { “name”: “Mohan”, “age”: 40, “branch”: “CSE” }””” if let jsonObj = inputJsonString.data(using: .utf8) { let x = try? JSON(data: jsonObj) // Accessing values using SwiftyJSON subscript syntax let name = x?[“name”].stringValue let age = x?[“age”].intValue let branch = x?[“branch”].stringValue // Perform operations print(“Name: (name ?? “N/A”)”) print(“Age: (age ?? 0)”) print(“Branch: (branch ?? “N/A”)”) } Output This code will work on Xcode. It will not work on an online Swift compiler. − Name: Mohan Age: 40 Branch: CSE Print Page Previous Next Advertisements ”;

Swift – for in loop

Swift – for-in Loop ”; Previous Next Swift for-in Loop The for-in loop iterates over collections of elements, such as ranges arrays, sets, dictionaries, etc. It iterates through each element of the specified collection without any explicit index manipulation. It is the most commonly used control flow statement because it expresses logic in a very clean and readable way. It is also compatible with functional programming, which means you can easily use high-order functions like filter(), map(), reduce, etc with a for-in loop. Syntax Following is the syntax of the for-in loop − for index in var{ Statement(s) } Flow Diagram The following flow diagram will show how the for-in loop works − Example Swift program to demonstrate the use of for-in loop. import Foundation var someInts:[Int] = [10, 20, 30] for index in someInts { print( “Value of index is (index)”) } Output It will produce the following output − Value of index is 10 Value of index is 20 Value of index is 30 Swift for-in Loop with Underscore “_” In a for-in loop, we can also ignore values from the given collection with the help of underscore “_”. Here we use underscore “_” in place of variable Name in the for-in loop. It will ignore the current value while iterating. It is commonly used when we only want to iterate a given number of times and does not require the value from the collection. Syntax Following is the syntax of the for-in loop with underscore − for _ in var{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with underscore. import Foundation let numbers = [3, 5, 76, 12, 4] // Using the underscore to ignore the values for _ in numbers { // Following code will execute in each iteration print(“Hello!! for-in loop!”) } Output It will produce the following output − Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Swift for-in Loop with Ranges We can also use range with a for-in loop. A range is the easiest way to represent a range of values in the for-in loop, it can be open, closed or half-open. The for-in loop iterates over each value in the given range and in each iteration, the loop variable takes the value of the current element in the range. Syntax Following is the syntax of the for-in loop with range − // With a closed range for variableName in start…end{ Statement(s) } // With half-open range for variableName in start..<end{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with range. import Foundation // Using closed Range print(“Loop 1:”) for x in 1…6 { print(x) } // Using half-open Range print(“Loop 2:”) for y in 1..<6 { print(y) } Output It will produce the following output − Loop 1: 1 2 3 4 5 6 Loop 2: 1 2 3 4 5 Swift for-in Loop with stride() Function We can use the stride() function with a for-in loop. The stride() function iterates over a range of values with a specific step between them. It is generally used to achieve more complex iteration patterns or can create a loop with a customized iteration pattern. Syntax Following is the syntax of the for-in loop with stride() function − for variableName in stride(from: value, to: value, by: value){ statement(s) } Parameters The stride() function takes three parameters − from − It contains the starting value of the range. to − It contains the end value of the range. Its value does not include. by − It contains the number of steps or strides between the values. If its value is positive, then the stride iterates in an upward direction or if the value is negative, then the stride iterates in the downward direction. Example Swift program to demonstrate how to use for-in loop with stride() function. import Foundation // The stride() function moves in upward direction print(“Loop 1:”) for x in stride(from: 1, to: 7, by: 2) { print(x) } // The stride() function moves in downward direction print(“nLoop 2:”) for y in stride(from: 7, to: 1, by: -2) { print(y) } Output It will produce the following output − Loop 1: 1 3 5 Loop 2: 7 5 3 Swift for-in Loop with where Clause Swift also provides a where clause which we can use with a for-in loop. A where clause is used to filter out only those elements that satisfy the condition specified in the where clause from the given collection. It can work with all iterable collections such as arrays, sets, and dictionaries. Syntax Following is the syntax of the for-in loop with where clause − for variableName in collectionName where condition{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with where clause. import Foundation let nums = [43, 23, 66, 12, 2, 45, 33] // Using the where clause to filter out only even elements from the array for n in nums where n % 2 == 0 { print(“Even number is (n)”) } Output It will produce the following output − Even number is 66 Even number is 12 Even number is 2 Print Page Previous Next Advertisements ”;

WebAssembly – Examples

WebAssembly – Examples ”; Previous Next The chapter discusses the examples with regards to WebAssembly. Example 1 Following is the example of C Program to get the max Element − void displaylog(int n); /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; displaylog(result); return result; } Compile the code in wasm fiddle and download the .wasm and .wat code. Wat code The Wat code is as follows − (module (type $FUNCSIG$vi (func (param i32))) (import “env” “displaylog” (func $displaylog (param i32))) (table 0 anyfunc) (memory $0 1) (export “memory” (memory $0)) (export “max” (func $max)) (func $max (; 1 😉 (param $0 i32) (param $1 i32) (result i32) (call $displaylog (tee_local $0 (select (get_local $0) (get_local $1) (i32.gt_s (get_local $0) (get_local $1)) ) ) ) (get_local $0) ) ) Download .wasm code and let us use in the .html file as shown below − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″> </head> <body> <script> const importObj = { env: { displaylog: n => alert(“The max of (400, 130) is ” +n) } }; fetch(“testmax.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.max(400,130)); }); </script> </body> </html> Output The output is as follows − Example 2 Following is the C++ code to get the fibonacci series of given number. #include <iostream>> void displaylog(int n); int fibonacciSeries(int number) { int n1=0,n2=1,n3,i; for(i=2;i<number;++i) { n3=n1+n2; displaylog(n); n1=n2; n2=n3; } return 0; } I am using wasm explorer to compile the code. Download Wat and Wasm and test the same in the browser. You can use the below mentioned code − <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″> </head> <body> <script> const importObj = { env: { _Z10displaylogi: n => console.log(n) } }; fetch(“fib.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports._Z15fibonacciSeriesi(10)); }); </script> </body> </html> Output The output is as follows − Example 3 Following is the Rust code to add elements in a given array. fn add_array(x: i32) -> i32 { let mut sum = 0; let mut numbers = [10,20,30]; for i in 0..3 { sum += numbers[i]; } sum } We are going to make use of WebAssembly Studio to compile RUST to wasm. Build the code and download the wasm file and execute the same in the browser. <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″> </head> <body> <script> const importObj = { env: { } }; fetch(“add_array.wasm”) .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.add_array()); }); &lt/script> </body> </html> Output The output will be as given below − Print Page Previous Next Advertisements ”;

Swift – if statement

Swift – If Statement ”; Previous Next An if statement consists of a Boolean expression followed by a block of statements. When the boolean expression is true, then only the block of statements will execute. Otherwise, the controls move to the next statement present just after the if statement block. They are also known as branch statements because they allow the program to take different paths according to the given condition. For example, a teacher says to its students that “they are only allowed to write with a black pencil”. So here the conditional statement is “black pencil”. Hence If the “black pencil = true”, then only students are allowed to write. Syntax Following is the syntax of the if statement − if boolean_expression{ /* statement(s) will execute if the boolean expression is true */ } If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. Flow Diagram The following flow diagram will show how if-statement works − Example Swift program to check if the given number is less than 20 or not using the if statement. import Foundation var varA:Int = 10; /* Check the boolean condition using the if statement */ if varA < 20 { /* If the condition is true then print the following */ print(“varA is less than 20”); } print(“Value of variable varA is (varA)”); Output It will produce the following output − varA is less than 20 The value of variable varA is 10 Example Swift program to find the age for voting using if statement. import Foundation var age : Int = 19; /* Checking the age for voting */ if age >= 18 { /* If the condition is true */ print(“Eligible for voting”); } print(“A Candidate whose age is 18+ is eligible for voting “) Output It will produce the following output − Eligible for voting A candidate whose age is 18+ is eligible for voting Example Swift program to check the entered username is equal to the stored username using if statement. import Foundation let username = “input231″ let inputUsername = “input231″ // Checking for equality if username == inputUsername{ print(“Login successful”) } var result = 32 + 23 print(result) Output It will produce the following output − Login successful 55 Print Page Previous Next Advertisements ”;

WebAssembly – Working with C

WebAssembly – Working with C ”; Previous Next In this chapter, we are going to compile a simple C program to javascript and execute the same in the browser. For Example − C Program #include<stdio.h> int square(int n) { return n*n; } We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as square.c. We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code. Compile test.c in your command prompt as shown below − emcc square.c -s STANDALONE_WASM –o findsquare.wasm emcc command takes care of compiling the code as well as give you the .wasm code. We have used STANDALONE_WASM option that will give only the .wasm file. Example − findsquare.html <!doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Square function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id=”textcontent”></div> <script> let square; fetch(“findsquare.wasm”).then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { square = instance.exports.square(13); console.log(“The square of 13 = ” +square); document.getElementById(“textcontent”).innerHTML = “The square of 13 = ” +square; }); </script> </body> </html> Output The output is as mentioned below − Print Page Previous Next Advertisements ”;

Tcl/Tk – Quick Guide

Tcl-Tk – Quick Guide ”; Previous Next Tcl – Overview Tcl is shortened form of Tool Command Language. John Ousterhout of the University of California, Berkeley, designed it. It is a combination of a scripting language and its own interpreter that gets embedded to the application, we develop with it. Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac OSX. Tcl is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell (csh), the Korn Shell (sh), and Perl. It aims at providing ability for programs to interact with other programs and also for acting as an embeddable interpreter. Even though, the original aim was to enable programs to interact, you can find full-fledged applications written in Tcl/Tk. Features of Tcl The features of Tcl are as follows − Reduced development time. Powerful and simple user interface kit with integration of TK. Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform. Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days. You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C, C&plus;&plus;, or Java to Tcl or vice versa. Have a powerful set of networking functions. Finally, it”s an open source, free, and can be used for commercial applications without any limit. Applications Tcl is a general-purpose language and you can find Tcl everywhere. It includes, Scalable websites that are often backed by databases. High performance web servers build with TclHttpd. Tcl with CGI based websites. Desktop GUI applications. Embedded applications. Tcl – Environment Setup Local Environment Setup If you are willing to set up your environment for Tcl, you need the following two software applications available on your computer − Text Editor Tcl Interpreter. Text Editor This will be used to type your program. Examples of a few text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of a text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your text editor are called source files and contain program source code. The source files for Tcl programs are named with the extension “.tcl”. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it, and finally execute it. The Tcl Interpreter It is just a small program that enables you to type Tcl commands and have them executed line by line. It stops execution of a tcl file, in case, it encounters an error unlike a compiler that executes fully. Let”s have a helloWorld.tcl file as follows. We will use this as a first program, we run on a platform you choose. #!/usr/bin/tclsh puts “Hello World!” Installation on Windows Download the latest version for windows installer from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use. Run the downloaded executable to install the Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” command and then execute the program using the following steps C:Tcl> tclsh helloWorld.tcl We can see the following output. C:Tcl> helloWorld C:Tcl is the folder, I am using to save my samples. You can change it to the folder in which you have saved Tcl programs. Installation on Linux Most of the Linux operating systems come with Tcl inbuilt and you can get started right away in those systems. In case, it”s not available, you can use the following command to download and install Tcl-Tk. $ yum install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” command and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world Installation on Debian based Systems In case, it”s not available in your OS, you can use the following command to download and install Tcl-Tk − $ sudo apt-get install tcl tk Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” command and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world Installation on Mac OS X Download the latest version for Mac OS X package from the list of Active Tcl binaries available. The active Tcl community edition is free for personal use. Run the downloaded executable to install the Active Tcl, which can be done by following the on screen instructions. Now, we can build and run a Tcl file say helloWorld.tcl by switching to folder containing the file using ”cd” and then execute the program using the following steps − $ tclsh helloWorld.tcl We can see the following output − $ hello world Installation from Source Files You can use the option of installing from source files when a binary package is not available. It is generally preferred to use Tcl binaries for Windows and Mac OS X, so only compilation of sources on unix based system is shown below. Download the source files. Now, use the following commands to extract, compile, and build after switching to the downloaded folder. $ tar zxf tcl8.6.1-src.tar.gz $ cd tcl8.6.1 $ cd unix $ ./configure —prefix=/opt —enable-gcc $ make $ sudo make install Note − Make sure, you change the file name to the version you downloaded on commands 1 and 2 given above. Tcl – Special Variables In Tcl, we