Schedule‎ > ‎

04A: Operators, Characters, Strings, Switch Statement

Voltage Computation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void setup() {
  Serial.begin(9600);
  cout << "Enter the current in amps" << endl;
  double amps = 0, ohms = 0;
  cin >> amps;
  
  cout << "Enter the resistance in ohms" << endl;
  cin >> ohms;
  double volts = amps * ohms;
  cout << "The voltage is " << volts << endl;
}

void loop() {
  // no code here
}


Integer Modulus

Program Testing for Even or Odd Numbers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24


void setup() {
  Serial.begin(9600);
  cout << "Enter an integer number" << endl;
}

void loop() {
  int testNum;
  cin >> testNum;
  int quotient = testNum / 2;
  int remainder = testNum % 2; //pronounced testNum "mod" two
    cout << testNum << " / 2 = " << quotient << endl;
    
    cout << "The remainder is " << remainder;

    if (0 == remainder) {
      cout << " (even)" << endl;
    } else {
      cout << " (odd)" << endl;
    }
}

^ to

^ top

Compound Assignment Operators

  • C/C++ has additional assignment operators that combine other operators with assignment
    • Known as compound assignment operators
  • The general syntax is:
    variable op= expression;
  • Where op is an operator like one of the five arithmetic operators: +, -, *, /, %
  • For example, the following two statements create the same result:
    x = x + 3;
    x += 3;
    
  • Shown below are some assignment operators with examples of how they are used

Summary of Assignment Operators Used in Arithmetic Operations

Operator Description Example Equivalent To
= Assigns the value of the expression on the right to the variable on the left x = 3  
+= Adds the expression on the right to the variable on the left x += 3 x = x + 3
-= Subtracts the expression on the right from the variable on the left x -= 3 x = x - 3
*= Multiplies the expression on the right to the variable on the left and saves the result in the variable on the left x *= 3 x = x * 3
/= Divides the variable on the left by the expression on the right and saves the result in the variable on the left x /= 3 x = x / 3
%= Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the left x %= 3 x = x % 3

Increment and Decrement Operators

  • Adding or subtracting one is a common operation in programming
  • C/C++ provides arithmetic shortcuts for these operations with the increment and decrement operators
  • The increment operator (++) adds 1 to a variable's value
  • Preincrement adds 1 before evaluating an expression
    ++sum;
  • Post-increment evaluates the expression and then adds 1
    sum++;
  • The decrement operator works like the increments operator, except it subtracts 1 from the variable:
    --sum
    sum--
    
  • Pre- and post- increment matters when the operation is part of a larger expression
  • For example, consider the code:
    int x = 5;
    int y = x++;
    cout << "x = " << x << "y = " << y << endl;
    
    
  • We may expect y to be 6 after this code executes
  • Instead, y has the value of 5
  • The reason is that ++ after a variable (post-increment) is equivalent to:
    y = x;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    y = x;
    

Check Yourself

  1. The value of counter after the following code executes is ________.
    int counter = 0;
    counter = counter + 1;
    
  2. What is an equivalent statement for each of the following shortcut assignments?
    1. a += b;
    2. a -= b;
    3. a *= b;
    4. a /= b;
    5. a %= b;
  3. List four ways to add the integer 1 to a variable named c.


switch Statements

  • The switch statement provides an alternative to an if-else-if chain
  • Executes a section of code depending on the value of a single number
  • The general syntax is:
    switch (integerExpression) {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
    }
    
  • Where:
    • integerExpression: an arithmetic expression that resolves to an integer number
    • labelx: an integer constant
    • statements: the statements to execute when the condition is met
  • Any number of case labels can be placed in any order
  • When run, the integerExpression tries to match one of the case labels
  • If a label matches then the statements after the case label start executing
  • Any value that does not match starts executing with the statement after default
  • Execution continues until the end of the switch statement or encountering a break statement
  • The break statement causes an immediate exit from the switch statement
  • Just as case identifies possible starting points, break determines end points

Example Program Using a switch Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void setup() {
Serial.begin(9600);
cout << "Enter a 1, 2 or 3: " << endl;
}

void loop() {
int num;
if (Serial.available()) {
cin >> num;
while (Serial.available()) { //put this after your cin statement
Serial.read();
}
switch (num) {
case 1:
cout << "Apple" << endl;
break;

case 2:
cout << "Banana" << endl;
break;

case 3:
cout << "Orange" << endl;
break;

default:
cout << "Invalid Entry" << endl;
}
}
}

When to Use switch Statements

  • Switch statements can only be used when
    • The are integers or chars 
    • You are looking for exact matches
  • Thus, switch statements are inherently less useful than if-else statements
  • Also, the syntax is no clearer than if-else statements
  • There is a reason for the limitations of the switch statement
    • The compiler can generate faster code for switch statements
    • Though you shouldn't count on it...
  • However, modern compilers are quite capable of optimizing if-else statements 
  • Be careful when using a switch statement
    • Every branch of the switch statement must be terminated by a break statement
    • If the break statement is missing, the program falls through and executes the next case without testing
    • There are rare uses for this fall through behavior, such as printing the words for the song, The Twelve Days of Christmas
    • However, according to a study by Peter van der Linden, reported in his book, Expert C Programming, p. 38, the falling through behavior is needed less than 3% of the time
    • Thus, the default behavior is wrong 97% of the time
  • Forgetting to type the break statement is a very common error and the source of many bugs
  • So one has to ask oneself, "Why use an inferior programming statement that causes more problems than it solves?"

Check Yourself

  1. True or false: C++ switch statements allow testing for inequalities like < and >.
  2. True or false: the default behavior of a switch statement, to continue executing past the next label, is usually correct.
  3. True or false: programmers never forget to include a break statement when needed inside a switchstatement.


^ top

Characters and Strings

Learner Outcomes

At the end of the lesson the student will be able to:

  • Identify characters and strings from their literal representation
  • Assign characters and strings to variables
  • Call commonly used String functions
  • Compare characters and strings

^ top

Type char

  • In addition to numbers, computers can manipulate text and other non-numerical types
  • Values of type char (short for character) are a single letter, number or special symbol
  • We specify a character by enclosing it in single quotes (")
    • The quote marks are not part of the data
  • For example:
    'a'   'b'   'Z'   '3'   'q'   '$'   '*'

ASCII Code

  • When we use a char data type, we store the character using a code known as ASCII
  • ASCII, which is an acronym for American Standard Code for Information Interchange, assigns a number to every character
  • Remember that computers store only numbers
  • So to handle text, each character is assigned a number as shown below
  • Each character requires 7-bits, which means it fits within one byte
  • ASCII was the first standardized code but is limited to English
  • However, ASCII has been extended to include all languages
  • The extended ASCII code is called Unicode

Table of ASCII Codes

ASCII table

Source: imageKB.com

Declaring and Assigning char Variables

  • As with other data types, we must declare char variables before use:
    char letterA;
  • We assign values to a char variable using the equals sign:
    letterA = 'A';
  • Just like numerical types, we can combine declaration and assignment into one statement:
    char letterB = 'B';
  • C++ allows us to assign ASCII code numbers to char variables as well
    char letterC = 67;
    char letterD = letterC + 1;
    

Example Code with char Variables

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void setup() {
Serial.begin(9600);
char letterA;
letterA = 'A';
cout << letterA << " ";

char letterB = 'B';
cout << letterB << " ";
char letterC = 67;
cout << letterC << " ";
char letterD = letterC + 1;
cout << letterD << " " << endl;
cout << "Enter some characters: ";
}

void loop() {
if (Serial.available()) {
char code;
cin >> code;

if (10 == code) {
cout << "Line feed";
} else if (13 == code) {
cout << "carriage return";
} else {
cout << "you entered: " << code << endl;
}
}
}

Serial I/O with Type char

  • Like numbers, we can output type char using cout
    char letter = 'A';
     cout << letter; 
  • Also, we can input type char using cin
    char letter; cin >> letter;
     cout << letter;

Check Yourself

  1. The type of delimiter used to enclose single characters of type char is the ________.
  2. The correct data type for a single character is ________.
    1. character
    2. char
    3. text
    4. string
  3. Which of the following correctly declares a variable for a single character and assigns it a value?
    1. char var = 'z';
    2. char var = 122;
    3. char var = "z";
    4. char var = 'a' + 25;
  4. True or false: we can display a single ASCII character with cout.

More Information

  • ASCII: Video introduction from Harvard CS50.tv on YouTube

^ top

Introduction to Strings

  • In addition to single characters, computers can work with text strings
  • For example, in the following the characters between the double quotes are displayed as text:
    cout << "Hello World" << endl;
    
  • Programmers refer to text like this as a string because it is composed of a sequence of characters that we string together
  • Strings are enclosed in double quotes, which are not part of the string
  • For example:
    "Hello"  "b"  "3.14159"  "$3.95"  "My name is Ed"
  • Notice that the string "3.14159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently and we must use them in different ways
  • For instance, we cannot multiply the "3.14159" by 2, but we can when it is expressed as a double:
    cout << "3.14159" * 2; // NO!
    cout << 3.14159 * 2; // allowed
    

String Variables and Serial I/O

  • We declare and assign values to String variables like numeric and character types
  • For example:
    String firstName;             // declaration
    firstName = "Sharon";         // assignment
    String lastName = "Strelitz";  // declaration + assignment
    Serial.print(firstName); 
     Serial.print(" "); 
Serial.println(lastName);

Serial I/O with Strings

  • Like numbers and characters, we can output type String using Serial.print() and Serial.println()
  • Also, we can input a string by calling Serial.readString() as shown below

Example of Serial I/O with Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void setup() {
  Serial.begin(9600);
  cout << "Enter your name." << endl;
}

void loop() {
  if (Serial.available()) {
    String name = Serial.readString();
    Serial.print("You entered: ");
    Serial.println(name);
  }
}

Check Yourself

  1. True or false: use a String variable rather than a char variable when you need to store more than one character.
  2. The type of delimiters used to enclose strings is the ________
  3. True or false: "A" and 'A' are the same.
  4. True or false: we can perform arithmetic operations on strings.
  5. Which of the following is the correct way to declare a string variable named myString and assign it the text "Hi Mom!"?
    1. string myString = Hi Mom!;
    2. string myString = "Hi Mom!";
    3. String myString = "Hi Mom!";
    4. String myString = "Hi Mom"!
  6. Which of the following is the correct way to input text from the serial port and store it in a previously declared variable named myWord?
    1. myWord = serial.readString();
    2. myWord = Serial.read();
    3. myWord = Serial.readString();
    4. myWord = Serial.parseInt();

More Information

^ top

Output of Hard-to-Print Characters

  • We have been using Serial.print() and Serial.println() to output strings
  • However, some strings are more difficult to output than others
  • For example, what if we wanted to output : Say, "Hey!"
  • We could write a statement like:
    Serial.println("Say, "Hey!"");
    
  • How would the compiler treat the double-quote marks (") in the statement?
  • Some characters cannot be output directly in a string
  • Also, the first 32 ASCII characters are old Teleprinter control characters
  • Some control characters are still used today such as newline characters
  • We need some way to output characters like control codes and double quotes (")

Escape Sequences

  • C++ can print control codes and some hard-to-print characters using escape sequences
  • A backslash (\) directly in front of some characters tell the compiler to escape from the normal interpretation
  • The following table lists some common nonprinting and hard-to-print characters supported by the Serial Monitor
Sequence Meaning
\n New line
\t Horizontal tab
\\ Backslash
\' Single quote
\" Double quote
\ooo ASCII character in octal notation
\xhhh ASCII character in hexadecimal notation

Examples of Escape Sequences Supported by the Serial Monitor

1
2
3
4
5
6
7
8
9
10
11
12
13
void setup() {
  Serial.begin(9600);
  Serial.println("Say, \"Hey!\"");
  Serial.println("one\ntwo\x00Athree");  //x00A is 10 which is line feed or newline
  Serial.println("Left\tRight");
}

void loop() {
}

Check Yourself

  1. True or false: an escape sequence is a series of characters that does not represent itself but is translated into a character code.
  2. Which of the following is an escape sequence?
    1. "/n"
    2. "/t/n/t"
    3. "\n\t\""
    4. "/\n"
  3. Which of the following is a correct way to print: Say, "Hey"!?
    1. Serial.println("Say, "Hey!"");
    2. Serial.println(\"Say, "Hey!"\");
    3. Serial.println("Say, \"Hey!\"");
    4. Serial.println("Say, \"Hey!"\");

^ top

Joining Strings (Concatenation)

  • We can join strings together in a variety of ways
  • The join operation is called concatenation
  • We join two strings together using the '+' operator
  • We can concatenate a String variable with:
    • Another String variable
    • A literal string in double quotes like "abc"
    • A literal char like 'a' or a char variable
    • An literal integer like 123 or an integer variable

Examples of Concatenation

  • We can join a String variable with another, like:
    String s1 = "Hello", s2 = "World!";
    String s3 = s1 + s2;
    Serial.println(s3);
    
  • The String s3 now has the contents of both s1 and s2
  • We can also mix String variables and literal strings:
    String s1 = "Hello", s2 = "World!";
    String s4 = s1 + ", " + s2;
    Serial.println(s4);
    
  • One or both strings surrounding the + must be a String variable
  • For instance, the following will NOT work:
    String greeting = "Hello" + " " + "World!"; // No!
    
  • However, this is not usually a problem because we can just make one long literal string:
    String greeting = "Hello World!";
    
  • In addition, we can concatenate strings and characters:
    char letter = 'A';
    String s5 = "BC";
    s5 = letter + s5 + 'D';
    Serial.println(s5);
    
  • Arduino C++ also lets us join a string with an integer, like:
    String s6 = s5 + 123;
    Serial.println(s6);
    
  • Notice that we can concatenate a string with a floating-point number
    String s7 = s5 + 123.4567; // 2 decimal places
    
  • To control the number of decimal places we use a String constructor function to convert the number to a String like:
    String s8 = s5 + String(123.4567, 3);
    Serial.println(s8);
    
  • The first constructor function argument is the floating-point number and the second is the number of decimal places
  • We will discuss constructor functions in more detail later in the course

Example Code Showing Concatenation of Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void setup() {
  Serial.begin(9600);
  String s1 = "Hello", s2 = "World!";
  String s3 = s1 + s2;
  Serial.println(s3);
  String s4 = s1 + ", " + s2;
  Serial.println(s4);
  //String greeting = "Hello" + " " + "World!"; // No!
  char letter = 'A';
  String s5 = "BC";
  s5 = letter + s5 + 'D';
  Serial.println(s5);
  String s6 = s5 + 123;
  Serial.println(s6);
  String s7 = s5 + 123.4567; // 2 decimal places
  Serial.println(s7);
  String s8 = s5 + String(123.4567, 3); // 3 DP
  Serial.println(s8);
}

void loop() {
}

Appending Strings

  • Notice that we can append a string to a String variable
  • For example, we can add one string to the end of another using +=:
    String s9 = "Hello";
    s9 += " World";
    Serial.println(s7);
    
  • Appending can be useful when building up strings containing text and numbers from various sources

You can combine cout with Serial.print

int a = 10;

double b = 2.34;

String userName = Serial.readString();

Serial.print(userName);

cout << “ has “ << a << “ hats and “ << b << “ dollars” << endl; 

Check Yourself

  1. The operator used to join two strings is ________.
  2. The value of s3 after the following code executes is ________.
    String s1 = "Hi ", s2 = "Mom!";
    String s3 = s1 + s2;
    
  3. The result of trying to compile and run the following code is ________.
    String s1 = "Hi", s2 = "Mom!";
    String s3 = s1 + " " + s2;
    
  4. The result of trying to compile and run the following code is ________.
    String s1 = "Hi " + " " + "Mom!";
    

^ top

String Functions

  • Strings are a special type of variable called objects, which we will study in more detail later in the course
  • An object is a data type that can have functions associated with it
  • These functions are called member functions and are called using dot notation
  • The syntax for calling a member function of a string object is:
    stringName.functionName(arguments)
    
  • Where:
    • stringName: the name of the string variable
    • functionName: the name of the member function
    • arguments: the input values, if any
  • Once we create a String variable, we call (invoke) its member functions

Some Commonly-Used String Functions

  • Arduino C/C++ supports many String functions (see documentation)
  • We cover a few commonly used String functions in this section
  • length(): Returns the number of characters in a string
    String greeting = "Hello, World!";
    String msg = "The number of characters is ";
    msg += greeting.length();
    Serial.println(msg);
    
  • substring(from, to): Returns a substring starting at index from and ending just before to
  • For example, we extract the first 4 letters of a string:
    String greeting = "Hello, World!\n";
    String sub = greeting.substring(0, 4);
    
  • Similarly, we extract characters 7 to 12, but not including 12:
    sub += greeting.substring(7, 12);
    
    H e l l o ,
    W o r l d ! \n
    0 1 2 3 4 5 6 7 8 9 10 11 12 13
  • When finished, we print the message we extracted with substring():
    Serial.println(sub);
    
  • trim(): Removes any leading and trailing whitespace.
    String padding = "  text  \n";
    Serial.println("For the string \"" + padding + "\"");
    String msg = "the number of characters is ";
    Serial.println("Before trim() " + msg + padding.length());
    padding.trim();
    Serial.println("After trim() " + msg + padding.length());
    
  • The trim() function is useful for removing line endings when reading strings from the serial port
    String inStr = Serial.readString();
    inStr.trim();
    Serial.println(inStr);
    

Example Code Calling String Member Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <ArduinoSTL.h>
using namespace std;

void setup() {
  Serial.begin(9600);
  Serial.println("Enter a string");
}

void loop() {
  if (Serial.available()) {
    // Demonstrate input
    String inStr = Serial.readString();
    Serial.println("For the string \"" + inStr + "\"");
    String msg = "the number of characters is ";
    Serial.println("Before trim() " + msg + inStr.length());
    inStr.trim();
    Serial.println("After trim() " + msg + inStr.length());
    // Demonstrate substring()
    String greeting = "Hello, World!";
    Serial.println("For the greeting: " + greeting);
    String sub = greeting.substring(0, 4);
    sub += greeting.substring(6, 12);
    Serial.println("The substring greeting is: " + sub);
  }
}

Check Yourself

  1. True or false: an object is a data type that can have functions associated with it.
  2. To call a function that is part of an object, between the object name and the function name we code a ________.
  3. The following code displays ________.
    String message = "Hi mom!";
    Serial.println(message.length());
    
    1. 2
    2. 6
    3. 7
    4. "Hi mom!"
  4. For the following string variable, the function call that extracts "mom" is ________.
    String message = "Hi mom!";
    
    1. message.substring(3, 6)
    2. message.substring(2, 6)
    3. message.substring(3, 5)
    4. message.substring(2, 5)

^ top

Comparing Characters and Strings

  • Character data can be evaluated using relational operators
  • Relational operators are useful for making alphabetic comparison between characters, like:
    if ('A' < 'B')
    
  • Since C++ stores characters as numbers using ASCII codes, the computer is actually comparing numbers
  • Remember that letters nearer to the start of the alphabet have lower numerical values than later letters
  • Thus a numerical comparison can decide the alphabetical order of characters

Example Program Comparing Characters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void setup() {
  Serial.begin(9600);
  char chOne = 'A';
  char chTwo = 'B';
  String sp = "'"; // to start print statements
  if (chOne == chTwo) {
    Serial.println(sp + chOne + "' == '" + chTwo + "'");
  }
  if (chOne != chTwo) {
    Serial.println(sp + chOne + "' != '" + chTwo + "'");
  }
  if (chOne < chTwo) {
    Serial.println(sp + chOne + "' < '" + chTwo + "'");
  }
  if (chOne <= chTwo) {
    Serial.println(sp + chOne + "' <= '" + chTwo + "'");
  }
  if (chOne > chTwo) {
    Serial.println(sp + chOne + "' > '" + chTwo + "'");
  }
  if (chOne >= chTwo) {
    Serial.println(sp + chOne + "' >= '" + chTwo + "'");
  }
}

void loop() {
}

Comparing Strings

  • We can compare strings using relational operators as well
  • C++ compares two strings using lexicographical order (a.k.a. alphabetical order)
  • Lexicographical order means the comparison is based on the alphabetical order of component letters
  • For example, "car" is less than "cat":
    c a r
    c a t
  • Also, "car" is less than "card"
    c a r
    c a r d
  • We can test string comparisons in the following example program

Example Program Comparing Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void setup() {
  Serial.begin(9600);
  String strOne = "car";
  String strTwo = "cat";
  if (strOne == strTwo) {
    Serial.println(strOne + " == " + strTwo);
  }
  if (strOne != strTwo) {
    Serial.println(strOne + " != " + strTwo);
  }
  if (strOne < strTwo) {
    Serial.println(strOne + " < " + strTwo);
  }
  if (strOne <= strTwo) {
    Serial.println(strOne + " <= " + strTwo);
  }
  if (strOne > strTwo) {
    Serial.println(strOne + " >= " + strTwo);
  }
  if (strOne >= strTwo) {
    Serial.println(strOne + " >= " + strTwo);
  }
}

void loop() {
}

Check Yourself

  1. The result of evaluating the following relational expression is ________.
    'A' < 'B'
  2. The result of evaluating the following relational expression is ________.
    "A" < "B"
  3. Of the following pairs of strings, which comes first in lexicographic order for each of them?
    1. "Harry", "Potter"
    2. "Harry", "Hairy"
    3. "car", "C++"
    4. "car model", "carburetor"

More Information

^ top

Exercise 1: Initials (10m)

In this exercise we write an interactive program using strings that runs like this:

Enter your first name: Sharon
Enter your last name: Strelitz
Welcome "Sharon Strelitz"!
Your initials: SS
Enter your first name: (so you can start over)

Note that the underlined font shows what is typed by the user in the text field at the top of the window. As you work through the exercise, I suggest that you compile after each step so you know where an error is located if you make a mistake. Also, if you get stuck then ask a classmate or the instructor for help.

Parts

  • Arduino board
  • USB cable

Starter Code

// Must remember names across loop() calls
String firstName = "";
String lastName = "";

void setup() {
  Serial.begin(9600);
  Serial.println("Enter your first name:");
}


void loop() {
  if (Serial.available()) {
    // put your code here
  }
}

Specifications

  1. Start the Arduino IDE, copy the starter code above and paste it into the main IDE window.
  2. Save the project using the name initials (File > Save As...) to a convenient location like the Desktop or the Arduino projects folder.
  3. Compile the sketch to verify you copied the starter code correctly.

    When compiling is successful, you will see a message at the bottom of the source code window saying, "Done compiling."

  4. Where shown by the comment, add a statement to read a string from the serial port and save it in a String variable named inStr, like:
    String inStr = Serial.readString();
    inStr.trim(); //trims off any leading or trailing newlines
  5. Next, add an if-else statement to test if the firstName variable is empty, like:
    if (firstName == "") {
      // add code to store inStr in firstName
    } else {
      // add code to store inStr in lastName and make initials
    }
    
  6. Inside the if-clause, assign inStr to firstName and then add a second statement prompting the user to enter their last name.
  7. Inside the else-clause, assign inStr to lastName and then add a series of statements that extract the first letter of the first and last names using substring() like:
    String initials = firstName.substring(0, 1);
    initials += lastName.substring(0, 1);
    
  8. Next inside the else-clause, print the welcome message followed by printing the initials, like:
    String sp = "Welcome \"";
    Serial.println(sp + firstName + " " + lastName + "\"!");
    Serial.print("Your initials are: ");
    Serial.println(initials);
  9.  Print out the length of the lastName in a nice format like "The length of your last name is: "
  10. After the above statements, assign an empty string to both firstName and lastName and then print a message to enter the first name.
  11. Compile and upload your code to verify it works correctly.

    You should now be able to see it work like the example shown at the start. If you have problems, ask a classmate or the instructor for help.

  12. Save your initials.ino file to submit to Canvas with the next homework.

When finished, please help those around you.


^ top

Summary

  • A character is a letter, number or special symbol
  • We make character literals by enclosing a single character in single quotes
  • We declare character variables using char as the data type:
    char letter = 'A';
    
  • Each character is stored as a number, using its ASCII code
  • We can input and output char data to the Serial Monitor like:
    char letter = Serial.read(); // input
    Serial.println(letter); // output
    
  • We make string literals by enclosing characters in double quotes
  • We declare string variables using String as the data type:
    String s1 = "Hello Mom!";
  • To concatenate two strings, use the "+" operator:
    String s2 = s1 + " suffix";
  • Type String can be input and output with the Serial Monitor
  • We use functions of the String object for some operations
  • We looked at the member functions:
    • length(): Returns the number of characters in a string
      String s = "Hello";
      Serial.println(s.length());
      
    • substring(from, to): Returns a substring starting at index from and ending just before to
    • String greeting = "Hello, World!\n";
      String sub = greeting.substring(0, 4);
      
    • trim(): Removes any leading and trailing whitespace, which is useful for removing line endings when reading strings from the serial port
      String inStr = Serial.readString();
      inStr.trim();
      Serial.println(inStr);
      
  • We can use these relational operators with characters and strings
  • Relational operators are useful for making alphabetic comparisons

^ top

Wrap Up and Reminders

  • For the next homework, see the schedule
  • When class is over, please shut down your computer.
  • Complete unfinished exercises from today before the next class meeting

^ top

Subpages (2): calculator initials