Tag Archives: language

Data types in Java

A data type classifies various types of data eg. String, integer, float, boolean, the types of accepted values for that data type, operations that can be performed on the data type, the meaning of the data, and the way that data of that type can be stored.

The table below shows the most commonly used data types used in the Java programming language.

Type Description Example
int The integer (int) data type stores positive or negative whole number values. 20
float The float data type stores floating point numbers (numbers with decimal places) eg. 43.65 . Often, you will need to end a float value with an ‘f’ character eg. 43.65f 43.65f
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is always surrounded by single quotes eg. ‘a’. ‘a’
String The String data type stores letters, numbers and other characters in the form of words or sentences. A string value is always surrounded by double quotes eg. “Hello World”. “Hello world”
boolean The boolean data type stores true or false values only eg. true true

The table below shows some of the other data types used in the Java programming language.

Type Description Example
byte The byte data type stores integer numbers ranging from -128 to +127 118
short The short data type is used for integer numbers ranging from -32,768 to +32,767 -28,471
long The long data type is used for integer values exceeding 2.14 billion ‘a’
double The double data type is used for extremely long floating point numbers 1.7976931348623157 × 10^308

Sample code

The sample Java code below shows how some of the different data types can be stored in variables. Later on, we will look at how to actually work with the values of different data types (eg. math calculations with integers and floats, and decision making with booleans).

The code includes comments explaining each data type.

package myjavaproject;

public class DataTypes {
    public static void main (String[] args){
        String message = "Hello"; // variable of String data type
        char letter = 'a'; // variable of char data type
        int number = 20; // variabe of int (integer) data type
        float decimal = 43.65f; // variable of float (floating point) data type
        boolean result = true; // variable of Boolean data type
        
        // now let's output the values of the different variables
        System.out.println("Message is " + message);
        System.out.println("Letter is " + letter);
        System.out.println("Age is " + number);
        System.out.println("Score is " + decimal);
        System.out.println("The answer is " + result);
    }
}

Variables in Java

In this tutorial you will learn how to create variables in the Java programming language. Variables are used to store data in a program.  A variable is like a ‘container’ that can store a value that can be used within the program. These values can be accessed, used and modified throughout the code.

Examples of values that you might need to store in a program include the score in a game, the user’s name, a password, or numbers used in calculations. Variables can store values of different data types – we’ll look at these in the next tutorial.

Variables have three important properties:

  • Variable name (identifier) – the actual name of the variable eg. score, username, age, price. Each variable must have a unique name. Some variable names can’t be used if they are the same as a reserved word used elsewhere in the language for other things such as a function. Variable names often cannot contain spaces or start with digits (rules vary in different languages)
  • Data type – the type of data that the variable will be storing such as text or numbers. There are special names for different data types that we will look at in the next tutorial
  • Value – the actual information being stored in the variable such a “Bob” for a variable called firstName or 26 for a variable called age.

The example below shows a new variable called message being created in the Java language. The variable is of the String data type (text that can contain letters, numbers and different characters) and is given an initial value of “Hello“.

java_variables

When you create a variable in a program you declare the variable. This means you give it a name and specify the data type. You may decide to not give it a value at that point in the program and give it a value later on, or you may decide to initialise the variable with a value (that can also be changed later). In the example above, the variable is declared and given an initial value all in one line of code.

Sample code

The sample code below shows a variable called ‘message’ being declared and given a value of “Hello”. The value is displayed on the screen to the user. Then, the value is changed to “Hello there” and this is displayed as output on the screen. Lastly, the message is displayed and the text “friend.” is added on the end when displayed as output so that the message being displayed is “Hello there friend.”. This is an example of concatenation (a fancy word for joining) where two strings are joined together.

You might notice that some lines of code that begin with two // forward slashes. These are comments in the code explaining what is going on. Comments are not carried out as instructions in the code but are used to annotate your code with explanations of what the code is meant to do, or you can also use them to add information about the author of the code, the program’s purpose or when it was created/modified.

package myjavaproject;

public class CreatingVariables {
    public static void main (String[] args){
        String message = "Hello"; // create and initialise String variable
        System.out.println(message);  // output variable value
        message = "Hello there"; // modify variable value
        System.out.println(message); // output modified variable value
        System.out.println(message + " friend.");  // concatenate strings
    }
}

Introduction to programming in Java

Welcome to the Java programming tutorial series. In this tutorial, I will show you how to download the Java SDK and Netbeans IDE so you can begin coding in Java. You will also learn how to write your very first program in Java – a ‘Hello world’ program.

Watch the video below and then scroll down for the links to the Java SDK and Netbeans IDE downloads and to view the sample code for the example shown in the video.

Downloads

All downloads are available for Windows, Mac and Linux

Sample code

Here is the sample Java code for this tutorial. Keep in mind that the project name in the video example was HelloWorld and so the package in the sample code is also called helloworld.

package helloworld;
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
    
}

Building a 4WD Autonomous Car with Arduino

In this tutorial you will learn to make a 4WD robotic car with built-in obstacle avoidance. This project involves building a 4WD car with an ultrasonic sensor that can detect nearby objects and change its direction to avoid these objects. The ultrasonic sensor will be attached to a servo motor which is constantly scanning left and right looking for objects in its way.

4WD autonomous robotic car
4WD autonomous robotic car

You can extend this project by adding more sensors such as ultrasonic sensor to the rear so that the car doesn’t reverse into objects, speed detection sensors to determine speed, line following sensors, and LED brake lights. You could even add light sensors and LEDs to turn headlights on in low-light conditions or a Bluetooth connection to control the car through a mobile app.

Parts required

Here is what you will need:

  • 1x Arduino Uno board
  • 1x 4WD Robotic Car kit (4 wheels, 4 motors, chassis, AA battery enclosure, screws)
  • 6x AA batteries
  • 1x 9V battery
  • 1x 9V battery power cable barrel jack connector
  • 1x L298N Motor Module
  • 1x Arduino Sensor Shield v5.0
  • 1x HC-SR04 Ultrasonic Sensor
  • 1x Servo motor (any small servo motor will do but if you don’t have one you can leave it out)
  • Assorted colour wires:
    • 4x female-to-female wires for Ultrasonic Sensor
    • 8x female-to-female wires for the Motor Module to Sensor Shield
    • 8x bare-ended wires to go from the four motors to the Motor Module
    • 2x bare-ended wires to go from the Motor Module to Sensor Shield
    • 3x wires for the servo motor with female end attaching to Sensor Shield (should already be included with the servo motor)
    • 2x bare-ended wires to go from AA Battery enclosure to the motor Module (should already be included with the battery enclosure)
  • Arduino IDE software – free at http://www.arduino.cc
  • 1x USB cable (A male plug to B male plug)
  • A computer to program with

Note: Make sure you get a range of different colours for the wires (eg. red for voltage, black for ground, etc.). Some items such as the battery enclosure, motors and servo motor may come with wires so you may not need to purchase these separately. Some motor modules or sensor shields may use different pins (eg. male or female or just bare-ended wires).

Below are images of the main components you need (apart from the wiring and batteries) – the different robot parts, shields, modules and sensors.

Click for larger image
Click for larger image

Assembling the robotic car

The first thing to do is to assemble all the car chassis parts and attach the motors to the wheels. This is explained in detail in the video below.

Wiring it up

Now that the chassis is assembled and the wheels and motors are attached, you will need to wire up all of the components. You can watch the video below or scroll down for the step-by-step instructions and wiring diagram.

  1. Connect the red wire (voltage) from the battery enclosure to VCC on the L298N Motor Module.
  2. Connect the black wire (ground) from the battery enclosure to GND on the Motor Module.
  3. Connect the red wire from Motor A1 (rear left) and the red wire from Motor A2 (front left) to OUT1 on the Motor Module (both wires can be twisted together and will go into OUT1 – the wiring diagram further down this page shows how to do this).
  4. Connect the black wire from Motor A1 (rear left) and the black wire from Motor A2 (front left) to OUT2 on the Motor Module.
  5. Connect the red wire from Motor B1 (rear right) and the red wire from Motor B2 (front right) to OUT3 on the Motor Module.
  6. Connect the black wire from Motor B1 (rear right) and the black wire from Motor B2 (front right) to OUT4 on the Motor Module.
  7. Connect a female-to-female end wire from ENA (Engine A) on the Motor Module to signal pin 1 on the Sensor Shield (the #2 pin in the S row. There are three rows – S stands for Signal, V for Voltage and G for Ground).
  8. Connect a female-to-female end wire from 5V (next to ENA) on the Motor Module to voltage pin 1 on the Sensor Shield (it doesn’t really matter which pin for voltage as long as it is in the V row).
  9. Connect a female-to-female end wire from IN1 on the Motor Module to signal pin 2 on the Sensor Shield.
  10. Connect a female-to-female end wire from IN2 on the Motor Module to signal pin 3 on the Sensor Shield.
  11. Connect a female-to-female end wire from IN3 on the Motor Module to signal pin 4 on the Sensor Shield.
  12. Connect a female-to-female end wire from IN4 on the Motor Module to signal pin 5 on the Sensor Shield.
  13. Connect a female-to-female end wire from 5V (next to ENB) on the Motor Module to voltage pin 6 on the Sensor Shield (it doesn’t really matter which pin for voltage as long as it is in the V row).
  14. Connect a female-to-female end wire from ENB (Engine B) on the Motor Module to signal pin 6 on the Sensor Shield.
  15. Connect the signal wire from the servo motor to signal (S) pin 7 on the Sensor Shield, the voltage wire from the servo motor to the voltage (V) pin 7 on the Sensor Shield, and the ground wire from the servo motor to the GND (G) pin 7 on the Sensor Shield.
  16. Attach the Ultrasonic Sensor to the servo motor and then attach the servo motor to the front of the car so that it can scan left and right looking for objects in its path.
    You can use sticky tape, blu-tack, glue or a 3D printed/laser cut mount or whatever you like to attach everything, as long as everything is firmly mounted.
  17. Use female-to-female end plugs to connect the Ultrasonic sensor to the Sensor Shield. Firstly, attach the TRIG pin from the Ultrasonic sensor to signal (S) pin 8 on the Sensor Shield. Attach the ECHO pin from the ultrasonic sensor to signal (S) pin 9 on the Sensor Shield. Attach the VCC pin from the Ultrasonic Sensor to the voltage (V) pin 10 on the Sensor Shield. Lastly, attach the GND pin from the Ultrasonic Sensor to the GND (G) pin 11 on the Sensor Shield.
  18. Now attach the Sensor Shield on top of the Arduino Uno board making sure to not bend any pins. Connect a 9V Battery Barrel Jack Connector to a 9V battery and then plug this in to the Arduino’s barrel jack (see diagram below).
  19. That’s it! Now all you need is batteries and the code!

Please note: There are several variations of the sensors and modules and several different ways to wire this up. For example, you can add a charging component to charge batteries and you can also add different switches. There may be other better methods to use, but I have gone for the simplest way I know of to set this up.

Wiring diagram

Click for larger image
Click for larger image

Writing the code

Here is the code to get your robot moving. The code is written in C language and is written in the Arduino IDE software. The code for a robot with a servo motor and the code for a robot without a servo motor is shown below. If you don’t have an ultrasonic sensor and just want to use Bluetooth control via a phone app, then you can just extract the parts of the code that you need and then add the Bluetooth code.

Code to use with a servo motor

// Setup the servo motor
#include <Servo.h>
Servo myservo;
int servposnum = 0;
int servpos = 0;

// Setup Motor A (front and rear) pins
int enableA = 1;
int pinA1 = 3;
int pinA2 = 2;

// Setup Motor B (front and rear) pins
int enableB = 6;
int pinB1 = 5;
int pinB2 = 4;

// Setup Ultrasonic Sensor pins
#define trigPin 8
#define echoPin 9


void setup() {
  // The setup code goes here and runs once only
  // Configure the pin modes for each drive motor
   pinMode (enableA, OUTPUT);
   pinMode (pinA1, OUTPUT);
   pinMode (pinA2, OUTPUT);

   pinMode (enableB, OUTPUT);
   pinMode (pinB1, OUTPUT);
   pinMode (pinB2, OUTPUT); 

   // Configure the pin modes for the Ultrasonic Sensor
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);

   // Turn pin into servo driver. Calls pinMode. Returns 0 on failure.
   myservo.attach(7);
}

void loop() {
  // Main code goes here and will run repeatedly:

     car(); // function keeps moving car forward while distance > 15cm
     avoid(); // function makes car go back, turn slightly right to move forward in new direction
     
}

// Create motor functions
void motorAforward() {
 digitalWrite (pinA1, HIGH);
 digitalWrite (pinA2, LOW);
}
void motorBforward() {
 digitalWrite (pinB1, LOW);
 digitalWrite (pinB2, HIGH);
}
void motorAbackward() {
 digitalWrite (pinA1, LOW);
 digitalWrite (pinA2, HIGH);
}
void motorBbackward() {
 digitalWrite (pinB1, HIGH);
 digitalWrite (pinB2, LOW);
}
void motorAstop() {
 digitalWrite (pinA1, HIGH);
 digitalWrite (pinA2, HIGH);
}
void motorBstop() {
 digitalWrite (pinB1, HIGH);
 digitalWrite (pinB2, HIGH);
}
void motorAcoast() {
 digitalWrite (pinA1, LOW);
 digitalWrite (pinA2, LOW);
}
void motorBcoast() {
 digitalWrite (pinB1, LOW);
 digitalWrite (pinB2, LOW);
}
void motorAon() {
 digitalWrite (enableA, HIGH);
}
void motorBon() {
 digitalWrite (enableB, HIGH);
}
void motorAoff() {
 digitalWrite (enableA, LOW);
}
void motorBoff() {
 digitalWrite (enableB, LOW);
}

// Setup movement functions
void forward (int duration) {
 motorAforward();
 motorBforward();
 delay (duration);
}
void backward (int duration) {
 motorAbackward();
 motorBbackward();
 delay (duration);
}
void right (int duration) {
 motorAbackward();
 motorBforward();
 delay (duration);
}
void left (int duration) {
 motorAforward();
 motorBbackward();
 delay (duration);
}
void coast (int duration) {
 motorAcoast();
 motorBcoast();
 delay (duration);
}
void breakRobot (int duration) {
 motorAstop();
 motorBstop();
 delay (duration);
}
void disableMotors() {
 motorAoff();
 motorBoff();
}
void enableMotors() {
 motorAon();
 motorBon();
}

// Setup Ultrasonic Sensor distance measuring
int distance() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  return distance;
}

// Setup the main car function
void car() {
int distance_0;
distance_0 = distance();
  // Keep moving forward in a straight line while distance of objects > 15cm
  while(distance_0 > 15)
  {
     // Keep moving servo motor back and forth to scan surroundings
     // This allows the ultrasonic sensor to see more to its left and right
     if(servposnum == 0)
     {
      myservo.writeMicroseconds (1900);
      servposnum = 1;
      delay(100);     
     }
     else if(servposnum == 1)
     {
      myservo.writeMicroseconds (2200);
      servposnum = 2;
     delay(100);
     }
     else if(servposnum  == 2)
     {
      myservo.writeMicroseconds (1900);
      servposnum = 3;
      delay(100);
     }
     else if(servposnum == 3)
     {
      myservo.writeMicroseconds (1600);
      servposnum = 1;
      delay(100);
     }
     motorAon();
     motorBon();
     forward(1);    
     distance_0 = distance();
     
  }
  breakRobot(0);

}
void avoid()
{
    // Go back and turn slightly right to move car in new direction if object detected < 15cm away
    backward(500);
    right(360);
}

Code to use without a servo motor

// Setup Motor A (front and rear) pins
int enableA = 1;
int pinA1 = 3;
int pinA2 = 2;

// Setup Motor B (front and rear) pins
int enableB = 6;
int pinB1 = 5;
int pinB2 = 4;

// Setup Ultrasonic Sensor pins
#define trigPin 8
#define echoPin 9

void setup() {
  // The setup code goes here and runs once only
  // Configure the pin modes for each drive motor
   pinMode (enableA, OUTPUT);
   pinMode (pinA1, OUTPUT);
   pinMode (pinA2, OUTPUT);

   pinMode (enableB, OUTPUT);
   pinMode (pinB1, OUTPUT);
   pinMode (pinB2, OUTPUT);

   // Configure the pin modes for the Ultrasonic Sensor
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
}

void loop() {
  // Main code goes here and will run repeatedly:
  car(); // function keeps moving car forward while distance of objects in front are > 15cm away
  avoid(); // function makes car go back, turn slightly right to move forward in new direction
}

// Create motor functions
void motorAforward() {
 digitalWrite (pinA1, HIGH);
 digitalWrite (pinA2, LOW);
}
void motorBforward() {
 digitalWrite (pinB1, LOW);
 digitalWrite (pinB2, HIGH);
}
void motorAbackward() {
 digitalWrite (pinA1, LOW);
 digitalWrite (pinA2, HIGH);
}
void motorBbackward() {
 digitalWrite (pinB1, HIGH);
 digitalWrite (pinB2, LOW);
}
void motorAstop() {
 digitalWrite (pinA1, HIGH);
 digitalWrite (pinA2, HIGH);
}
void motorBstop() {
 digitalWrite (pinB1, HIGH);
 digitalWrite (pinB2, HIGH);
}
void motorAcoast() {
 digitalWrite (pinA1, LOW);
 digitalWrite (pinA2, LOW);
}
void motorBcoast() {
 digitalWrite (pinB1, LOW);
 digitalWrite (pinB2, LOW);
}
void motorAon() {
 digitalWrite (enableA, HIGH);
}
void motorBon() {
 digitalWrite (enableB, HIGH);
}
void motorAoff() {
 digitalWrite (enableA, LOW);
}
void motorBoff() {
 digitalWrite (enableB, LOW);
}

// Setup movement functions
void forward (int duration) {
 motorAforward();
 motorBforward();
 delay (duration);
}
void backward (int duration) {
 motorAbackward();
 motorBbackward();
 delay (duration);
}
void right (int duration) {
 motorAbackward();
 motorBforward();
 delay (duration);
}
void left (int duration) {
 motorAforward();
 motorBbackward();
 delay (duration);
}
void coast (int duration) {
 motorAcoast();
 motorBcoast();
 delay (duration);
}
void breakRobot (int duration) {
 motorAstop();
 motorBstop();
 delay (duration);
}
void disableMotors() {
 motorAoff();
 motorBoff();
}
void enableMotors() {
 motorAon();
 motorBon();
}

// Setup Ultrasonic Sensor distance measuring
int distance() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  return distance;
}

// Setup the main car function
void car() {
int distance_0;
distance_0 = distance();
  // Keep moving forward in a straight line while distance of objects in front > 15cm away
  while(distance_0 > 15)
  {
     motorAon();
     motorBon();
     forward(1);
     distance_0 = distance();
  }
  breakRobot(0);

}

// Go back and turn slightly right to move car in new direction
// This function only runs if an obstacle within 15cm is detected
void avoid()
{
    backward(500);
    right(360);
}

Finishing up

Once you have the code you will need to verify it and then upload it to your Arduino Uno board. Make sure you have either the Arduino disconnected from the Sensor Shield or all batteries disconnected when uploading the code to prevent any errors while uploading. Make sure to also arrange the different components carefully in the chassis to prevent any short circuits.

And that’s it! There is so much more that can be done with this project. Try extending your project by adding the following features:

  • Line following
  • Low-light activated headlights (using light sensors and LEDs)
  • Brake lights
  • Speed measuring
  • Bluetooth/mobile app control
  • More ultrasonic sensors to avoid reversing into objects or falling off edges

The video below shows a demo of the 4WD autonomous car using an Arduino and the ultrasonic sensor attache to a servo motor. Six AA batteries power the motors while the Arduino board is powered using a separate 9V battery.

More photos

While loops in C#

While loops are used to repeat a section of code while a specified condition evaluates to true. For example, a user could keep being asked to enter a password while the password they are providing is incorrect. When the password they provide is correct, the loop will end.

The video below explains how to use while loops in C#. You can also scroll down to see the sample code.

Sample code

The sample C# code for a solution and project called MyApp is shown below. In this program, a variable called myNumber is created which is initially given an integer value of 1.

A while loop is created which checks if the value of myNumber is less than 10. While the value of myNumber is less than 10, the value is displayed to the user and then increased by 1, each time the loop repeats. Each repetition of a loop is called an iteration. Try the code below in your own program.

using System;

namespace MyApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Hello World!");
      int myNumber = 1;
      while(myNumber < 10)
      {
        Console.WriteLine(x);
        myNumber++;
      }
      Console.ReadLine ();
    }
  }
}

Next tutorial: For loops

Conditional programming in C#

Conditional statements are used so that your program can make decisions based on different conditions. For example, a game might display a message to the player if their score is higher than a certain number. Or an app might provide different content based on its user’s age. When your program has a range of conditions, you can build powerful algorithms.

Watch the video below and then scroll down to view the sample code.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
   Console.WriteLine("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if statements allow you to specify what action will occur when a condition is met and else statements can be used to run another piece of code if the condition is not met. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else
{
   Console.WriteLine("You are not old enough to vote");
}

else if statement

The limitation of using just if and else statements is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the else if statement comes in.

Using else if statements allows you to test multiple conditions. You can have several else if statements that each test a different condition. The else part is optional when using if and else if statements but is handy if you want something to happen if none of the specified conditions are met.

Here is some sample code for the ifelse if and else statements:

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else if(age==17)
{
   Console.WriteLine("You can vote after your next birthday");
}
else
{
   Console.Writeline("You are not old enough to vote");
}

Sample C# code

Here is the sample C# code used in the video. Comments have been added to the code to explain each part of the code.

using System;

namespace MyCSharpApp
{
  class MainClass

  {
    public static void Main (string[] args)
    {
      // Ask the user to select an option (type of calculation)
      // \n will create a new line
      Console.WriteLine ("Select from one of the following options: \n1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");

      // Store the selected option in a variable as an integer value (1, 2, 3, or 4)
      int option = int.Parse (Console.ReadLine ());

      // Ask the user to enter two numbers
      Console.WriteLine ("Enter two numbers...");

      // Store the first number in a variable as a float value
      float num1 = float.Parse(Console.ReadLine ());

      // Ask the user to enter the first of the two numbers
      Console.WriteLine ("Enter the first number:");

      // Ask the user to enter the second of the two numbers
      Console.WriteLine ("Enter the second number:");

      // Store the second number in a variable as a float value
      float num2 = float.Parse(Console.ReadLine ());

      // check the option selected and display the result of the relevant calculation

      // if option 1 (add) was selected...
      if (option == 1) {
        Console.WriteLine ("The answer is: " + (num1 + num2));
      }

      // if option 2 (subtract) was selected...
      else if (option == 2) {
        Console.WriteLine ("The answer is: " + (num1 - num2));
      }

      // if option 3 (multiply) was selected...
      else if (option == 3) {
        Console.WriteLine ("The answer is: " + (num1 * num2));
      }

      // if option 4 (divide) was selected...
      else if (option == 4) {
        Console.WriteLine ("The answer is: " + (num1 / num2));
      } 

      // if no option was selected...
      else {
        Console.WriteLine ("Option is not recognised");
      }
    }
  }
}

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Logical operators

Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s firstname is “Joe” AND their last name is also “Bloggs”.

if (first_name == "Joe" && last_name == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Next tutorial: While loops in C#

Integers and floats in C#

In the previous tutorial we looked at how to create variables and work with the string data type in C#. In this tutorial we will look at how to work with the integer and float data types in C# and also how to convert strings to integers or floats using the int.Parse() and float.Parse() methods. You will also learn how to manipulate numbers using arithmetic operators.

Watch the video below or scroll down to see the sample code.

Sample C# code

using System;

namespace MyCSharpApp
{
  class MainClass

  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Enter two numbers...");
      float num1 = float.Parse(Console.ReadLine ());
      float num2 = float.Parse(Console.ReadLine ());
      Console.WriteLine (num1 + num2);
    }
  }
}

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used number variables (although they can be used for other things too).

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5;

The table below shows the different assignment operators available in C#.

Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Next tutorial: Conditional programming in C#

Variables and strings in C#

This tutorial explains how to create variables and use strings in the C# programming language. Variables are used to store data that can be used throughout a program.

Variables can store data of different types. One data type is the string. Strings can contain characters such as letters, numbers or symbols. Strings can be a single character, a bunch of mixed characters, words, or sentences.

Other data types include integers (whole numbers eg. 4), floats, (numbers with decimal place eg. 3.56), and Booleans (true or false values). There are other data types that exist but these are the main ones we will start with. In this tutorial we will focus on strings and how they can be used in variables and statements.

When you create a variable you must declare its data type (eg. string), give it a name (eg. age, score, name), and then you can assign it a value. For example,  look at the following statement:

string firstName = "Joe";

The statement above would create a new variable called firstName of the string data type containing the value Joe. Strings are always contained inside single or double quotes.

Watch the video below and then scroll down to see the sample code.

Sample C# code

The code below contains comments to explain each statement.

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("What is your name?"); // this displays a message in console
      string message = "Hello there, "; // creates a string variable that contains a message
      string name = Console.ReadLine (); // creates a string that stores the user's name from input
      Console.WriteLine (message + name); // writes the message and name to the console
    }
  }
}

Next tutorial: Integers and floats in C#

Hello world (in C#)

This tutorial is an introduction to Xamarin Studio and the C# programming language. In this video I explain how to create a new solution in Xamarin Studio and cover some of the basics of the C# language. We will create our first program in C# and develop skills in the language before moving on to creating mobile apps.

Watch the video below and then scroll down to see the sample code. Make sure you check out the C# code reference here.

Sample C# code

This code is used in a solution and project both called MyCSharpApp created in Xamarin Studio. If you use this code, make sure your solution, project and namespace are called MyCSharpApp. The code also contains comments (after the double forward slashes) to explain what each statement in the code does.

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Hello, this is my first C# app"); // this displays a message in console
      Console.ReadLine (); // this waits until the user enters something
    }
  }
}

Next tutorial: Variables and strings in C#

Blinking LED Arduino project

This video tutorial has been designed for those just starting out with Arduino. For this beginner project you will need an Arduino Uno board (or compatible board), an LED of any colour, a 470-Ohm resistor, two jumper wires, a breadboard, a male A-B USB cable, and a computer (Mac/Windows) with the Arduino IDE software installed.

This project involves programming your Arduino Uno to make an LED light blink on and off. To get started, watch the video below or click here to view it on YouTube. Access the links below to get a copy of the code, printed instructions, schematic, and a guide to resistors.

Downloads:

The source code is also available here:

/*
 Blink
 Turns on an LED on for one second, then off for one second, repeatedly.
*/
 
// Give the LED a name - it will be connected on PIN 13
int led = 13;
 
// the setup routine runs once when you press reset:
void setup() { 
 // initialize the digital pin as an output.
 pinMode(led, OUTPUT); 
}
 
// the loop routine runs over and over again forever:
void loop() {
 digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
 delay(1000); // wait for a second (1000 = 1 sec.)
 digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
 delay(1000); // wait for a second
}

Photos

1 2 3 4