Pnge 200 Homework 3-4

This chapter explains the basic syntaxes of the Java programming language. I shall assume that you could write some simple Java programs. (Otherwise, read "Introduction To Java Programming for First-time Programmers".)

To be a proficient programmer, you need to master two things: (1) the syntax of the programming language, and (2) the libraries associated with the language.

You may also try the "Exercises on Java Basics".

Basic Syntaxes

Revision

The steps in writing a Java program is illustrated as follows:

Step 1: Write the source codes () using a programming text editor (such as Notepad++, Textpad, gEdit) or an (such as Eclipse or NetBeans).

Step 2: Compile the source codes () into Java portable bytecode () using the JDK compiler ("").

Step 3: Run the compiled bytecode () with the input to produce the desired output, using the Java Runtime ("").

Below is a simple Java program that demonstrates the three basic programming constructs: sequential, loop, and conditional. Read "Introduction To Java Programming for First-time Programmers" if you need help in understanding this program.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class OddEvenSum { public static void main(String[] args) { int lowerbound = 1, upperbound = 1000; int sumOdd = 0; int sumEven = 0; int number = lowerbound; while (number <= upperbound) { if (number % 2 == 0) { sumEven += number; } else { sumOdd += number; } ++number; } System.out.println("The sum of odd numbers from " + lowerbound + " to " + upperbound + " is " + sumOdd); System.out.println("The sum of even numbers from " + lowerbound + " to " + upperbound + " is " + sumEven); System.out.println("The difference between the two sums is " + (sumOdd - sumEven)); } }

The expected outputs are:

The sum of odd numbers from 1 to 1000 is 250000 The sum of even numbers from 1 to 1000 is 250500 The difference between the two sums is -500

Comments

Comments are used to document and explain your codes and your program logic. Comments are not programming statements. They are ignored by the compiler and have no consequences to the program execution. Nevertheless, comments are VERY IMPORTANT for providing documentation and explanation for others to understand your programs (and also for yourself three days later).

There are two kinds of comments in Java:

  1. Multi-Line Comment: begins with a and ends with a , and can span multiple lines.
  2. End-of-Line (Single-Line) Comment: begins with and lasts till the end of the current line.

I recommend that you use comments liberally to explain and document your codes. During program development, instead of deleting a chunk of statements irrevocably, you could comment-out these statements so that you could get them back later, if needed.

Statements and Blocks

Statement: A programming statement is the smallest independent unit in a program, just like a sentence in the English language. It performs a piece of programming action. A programming statement must be terminated by a semi-colon (), just like an English sentence ends with a period. (Why not ends with a period like an English sentence? This is because period crashes with decimal point - it is hard for the dumb computer to differentiate between period and decimal point in the early days of computing!)

For examples,

int number1 = 10; int number2, number3=99; int product; product = number1 * number2 * number3; System.out.println("Hello");

Block: A block is a group of statements surrounded by a pair of curly braces . All the statements inside the block is treated as one single unit. Blocks are used as the body in constructs like class, method, if-else and for-loop, which may contain multiple statements but are treated as one unit (one body). There is no need to put a semi-colon after the closing brace to end a compound statement. Empty block (i.e., no statement inside the braces) is permitted. For examples,

if (mark >= 50) { System.out.println("PASS"); System.out.println("Well Done!"); System.out.println("Keep it Up!"); } if (number == 88) { System.out.println("Got it!"); } else { System.out.println("Try Again!"); } i = 1; while (i < 8) { System.out.print(i + " "); ++i; } public static void main(String[] args) { ...statements... }

White Spaces and Formatting Source Codes

White Spaces: Blank, tab and newline are collectively called white spaces. Java, like most of the computing languages, ignores extra white spaces. That is, multiple contiguous white spaces are treated as a single white space.

You need to use a white space to separate two keywords or tokens to avoid ambiguity, e.g.,

int sum=0; double average;

Additional white spaces and extra lines are, however, ignored, e.g.,

int sum = 0 ; double average ;

Formatting Source Codes: As mentioned, extra white spaces are ignored and have no computational significance. However, proper indentation (with tabs and blanks) and extra empty lines greatly improves the readability of the program. This is extremely important for others (and yourself three days later) to understand your programs.

For example, the following one-line hello-world program works. But can you read and understand the program?

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

Braces: Java's convention is to place the beginning brace at the end of the line, and align the ending brace with the start of the statement.

Indentation: Indent each level of the body of a block by an extra 3 (or 4) spaces.

public class ClassName { public static void main(String[] args) { statement; statement; if (test) { statements; } else { statements; } init; while (test) { statements; update; } } }

Variables and Types

Variables

Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.

More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a name, a type and stores a value.

  • A variable has a name (aka identifier), e.g., , , , and . The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., ), as well as to retrieve the value stored (e.g., ).
  • A variable has a type. Examples of Java type are:
    • : meant for integers (whole numbers) such as and .
    • : meant for floating-point (real numbers), such as , , , , having a optional decimal point and fractional part.
    • : meant for texts such as , . Strings are enclosed within a pair of double quotes.
    • : meant for a single character, such as , . A char is enclosed by a pair of single quotes.
  • A variable can store a value of that particular data type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a variable can store an integer value such as , but NOT real number such as , nor string such as .
  • The concept of type was introduced in the early programming languages to simplify interpretation of data made up of binary numbers ('s and 's). The type determines the size and layout of the data, the range of its values, and the set of operations that can be applied.

The following diagram illustrates three types of variables: , and . An variable stores an integer (or whole number or fixed-point number); a variable stores a floating-point number or real number; a variable stores texts.

Identifiers (or Names)

An identifier is needed to name a variable (or any other entity such as a method or a class). Java imposes the following rules on identifiers:

  • An identifier is a sequence of characters, of any length, comprising uppercase and lowercase letters , digits , underscore , and dollar sign .
  • White space (blank, tab, newline) and other special characters (such as , , , , , , commas, etc.) are not allowed. Take note that blank and dash () are not allowed, i.e., "" and "" are not valid names. (This is because blank creates two tokens and dash crashes with minus sign!)
  • An identifier must begin with a letter or underscore (). It cannot begin with a digit (because that could confuse with a number). Identifiers begin with dollar sign () are reserved for system-generated entities.
  • An identifier cannot be a reserved keyword or a reserved literal (e.g., , , , , , , , , ).
  • Identifiers are case-sensitive. A is NOT a , and is NOT a .

Caution: Programmers don't use blank character in names. It is either not supported (e.g., in Java and C/C++), or will pose you many more challenges.

Variable Naming Convention

A variable name is a noun, or a noun phrase made up of several words with no spaces between words. The first word is in lowercase, while the remaining words are initial-capitalized. For example, , , , , and . This convention is also known as camel-case.

Recommendations
  1. It is important to choose a name that is self-descriptive and closely reflects the meaning of the variable, e.g., or , but not or , to store the number of students. It is okay to use long names!
  2. Do not use meaningless names like , , , , , , , , .
  3. Avoid single-letter names like , , , , , , which is easier to type but often meaningless. Exception are common names like , , for coordinates, for index. Long names are harder to type, but self-document your program. (I suggest you spend sometimes practicing your typing.)
  4. Use singular and plural nouns prudently to differentiate between singular and plural variables.  For example, you may use the variable to refer to a single row number and the variable to refer to many rows (such as an array of rows - to be discussed later).

Variable Declaration

To use a variable in your program, you need to first "introduce" it by declaring its name and type, in one of the following syntaxes. The act of declaring a variable allocates a storage (of size capable of holding a value of the type).

SyntaxExample
type identifier;type identifier1,identifier2, ...,identifierN;type identifier=initialValue;type identifier1=initValue1, ...,identifierN=initValueN;  int option;   double sum, difference, product, quotient;   int magicNumber = 88;   String greetingMsg = "Hi!", quitMsg = "Bye!";

Take note that:

  • Java is a "strongly type" language. A variable is declared with a type. Once the type of a variable is declared, it can only store a value belonging to this particular type. For example, an variable can hold only integer such as , and NOT floating-point number such as or text string such as .
  • Each variable can only be declared once.
  • You can declare a variable anywhere inside the program, as long as it is declared before used.
  • The type of a variable cannot be changed inside the program, after it is declared.
  • A variable declaration statement begins with a type, and works for only that type. In other words, you cannot declare variables of two different type in a single declaration statement.

Constants (final Variables)

Constants are non-modifiable variables, declared with keyword . Their values cannot be changed during program execution. Also, constants must be initialized during declaration. For examples:

final double PI = 3.1415926;

Constant Naming Convention: Use uppercase words, joined with underscore. For example, , .

Expressions

An expression is a combination of operators (such as addition , subtraction , multiplication , division ) and operands (variables or literals), that can be evaluated to yield a single value of a certain type. For example,

1 + 2 * 3 int sum, number; sum + number double principal, interestRate; principal * (1 + interestRate)

Assignment

An assignment statement:

  1. assigns a literal value (of the ) to a variable (of the ), e.g., ; or
  2. evaluates an expression (of the RHS) and assign the resultant value to a variable (of the LHS), e.g., .

The syntax for assignment statement is:

SyntaxExample
variable=literalValue;variable=expression;  number = 88;   sum = sum + number;

The assignment statement should be interpreted this way: The expression on the right-hand-side (RHS) is first evaluated to produce a resultant value (called r-value or right-value). The r-value is then assigned to the variable on the left-hand-side (LHS) or l-value. Take note that you have to first evaluate the RHS, before assigning the resultant value to the LHS. For examples,

number = 8; number = number + 1; 8 = number; // INVALID number + 1 = sum; // INVALID

In Java, the equal symbol is known as the assignment operator. The meaning of in programming is different from Mathematics. It denotes assignment of the LHS value to the RHS variable, instead of equality of the RHS and LHS. The RHS shall be a literal value or an expression that evaluates to a value; while the LHS must be a variable.

Note that is valid (and often used) in programming. It evaluates and assign the resultant value to the variable . illegal in Mathematics.

While is allowed in Mathematics, it is invalid in programming (because the LHS of an assignment statement must be a variable).

Some programming languages use symbol "", "" or "" as the assignment operator to avoid confusion with equality.

Primitive Types

In Java, there are two broad categories of types: primitive types (e.g., , ) and reference types (e.g., objects and arrays). We shall describe the primitive types here and the reference types (classes and objects) in the later chapters on "Object-Oriented Programming".

TYPEDESCRIPTION
byteInteger8-bit signed integer
The range is
short16-bit signed integer
The range is
int32-bit signed integer
The range is (≈9 digits)
long64-bit signed integer
The range is (≈19 digits)
floatFloating-Point
Number
32-bit single precision floating-point number
(6-7 significant decimal digits, in the range of )
double64-bit double precision floating-point number
(14-15 significant decimal digits, in the range of )
charCharacter
Represented in 16-bit Unicode to .
Can be treated as 16-bit unsigned integers in the range of in arithmetic operations.
booleanBinary
Takes a value of either or .
The size of is not defined in the Java specification, but requires at least one bit.
Built-in Primitive Types

Primitive type are built-in to the languages. Java has eight primitive types, as listed in the above table:

  • There are four integer types: 8-bit , 16-bit , 32-bit and 64-bit . They are signed integers in 2's complement representation, and can hold an integer value of the various ranges as shown in the table.
  • There are two floating-point types: 32-bit single-precision and 64-bit double-precision , represented as specified by IEEE 754 standard. A can represent a number between and , approximated. A can represented a number between and , approximated. Take note that not all real numbers can be represented by and . This is because there are infinite real numbers even in a small range of say , but there is a finite number of patterns in a n-bit representation. Most of the floating-point values are approximated to their nearest representation.
  • The type represents a single character, such as , , . In Java, char is represented using 16-bit Unicode (in UCS-2 format) to support internationalization (i18n). A can be treated as a 16-bit unsigned integer (in the range of ) in arithmetic operations. For example, character is (decimal) or (hexadecimal); character is (decimal) or (hexadecimal); character is (decimal) or (hexadecimal).
  • Java introduces a new binary type called "", which takes a value of either or .

Example: The following program can be used to print the maximum, minimum and bit-length of the primitive types. The maximum, minimum and bit-size of are kept in constants , , .

public class PrimitiveTypesMinMax { public static void main(String[] args) { System.out.println("int(min) = " + Integer.MIN_VALUE); System.out.println("int(max) = " + Integer.MAX_VALUE); System.out.println("int(bit-length) = " + Integer.SIZE); System.out.println("byte(min) = " + Byte.MIN_VALUE); System.out.println("byte(max) = " + Byte.MAX_VALUE); System.out.println("byte(bit-length)=" + Byte.SIZE); System.out.println("short(min) = " + Short.MIN_VALUE); System.out.println("short(max) = " + Short.MAX_VALUE); System.out.println("short(bit-length) = " + Short.SIZE); System.out.println("long(min) = " + Long.MIN_VALUE); System.out.println("long(max) = " + Long.MAX_VALUE); System.out.println("long(bit-length) = " + Long.SIZE); System.out.println("char(min) = " + (int)Character.MIN_VALUE); System.out.println("char(max) = " + (int)Character.MAX_VALUE); System.out.println("char(bit-length) = " + Character.SIZE); System.out.println("float(min) = " + Float.MIN_VALUE); System.out.println("float(max) = " + Float.MAX_VALUE); System.out.println("float(bit-length) = " + Float.SIZE); System.out.println("double(min) = " + Double.MIN_VALUE); System.out.println("double(max) = " + Double.MAX_VALUE); System.out.println("double(bit-length) = " + Double.SIZE); } }

The expected outputs are:

int(min) = -2147483648 int(max) = 2147483647 int(bit-length) = 32 byte(min) = -128 byte(max) = 127 byte(bit-length)=8 short(min) = -32768 short(max) = 32767 short(bit-length) = 16 long(min) = -9223372036854775808 long(max) = 9223372036854775807 long(bit-length) = 64 char(min) = 0 char(max) = 65535 char(bit-length) = 16 float(min) = 1.4E-45 float(max) = 3.4028235E38 float(bit-length) = 32 double(min) = 4.9E-324 double(max) = 1.7976931348623157E308 double(bit-length) = 64
String

Another commonly-used type is , which represents texts (a sequence of characters) such as . is not a primitive type, and will be further elaborated later. In Java, a is enclosed by single quotes (e.g., , ), while a is enclosed by double quotes (e.g., ). For example,

String message = "Hello, world!"; char gender = 'm';
Choice of Data Types for Variables

As a programmer, you need to choose variables and decide on the type of the variables to be used in your programs. Most of the times, the decision is intuitive. For example, use an integer type for counting and whole number; a floating-point type for number with fractional part, for text message, for a single character, and for binary outcomes.

Rules of Thumb
  • Use for integer and for floating point numbers. Use , , and only if you have a good reason to choose that specific precision.
  • Use for counting and indexing, NOT floating-point type ( or ). This is because integer type are precise and more efficient in operations.
  • Use an integer type if possible. Use a floating-point type only if the number contains a fractional part.
Data Representation

Read "Data Representation" if you wish to understand how the numbers and characters are represented inside the computer memory. In brief, It is important to take note that char is different from , , , , , and . They are represented differently in the computer memory, with different precision and interpretation. For example, is , is , is , is , is , is , is , and is a complex object.

There is a subtle difference between and .

Furthermore, you MUST know the type of a value before you can interpret a value. For example, this value cannot be interpreted unless you know its type (or its representation).

Example (Variable Names and Types): Paul has bought a new notebook of "abc" brand, with a processor speed of 3.2GHz, 4 GB of RAM, 500GB hard disk, with a 15-inch monitor, for $1650.45. He has chosen service plan 'B' among plans 'A', 'B' and 'C', plus on-site servicing. Identify the data types and name the variables.

The possible variable names and types are:

String name = "Paul"; String brand = "abc"; double processorSpeedInGHz = 3.2; double ramSizeInGB = 4; int harddiskSizeInGB = 500; int monitorInInch = 15; double price = 1650.45; char servicePlan = 'B'; boolean onSiteService = true;

Exercise (Variable Names and Types): You are asked to develop a software for a college. The system shall maintain information about students. This includes name, address, phone number, gender, date of birth, height, weight, degree pursued (e.g., B.Sc., B.A.), year of study, average GPA, with/without tuition grant, is/is not a scholar. Each student is assigned a unique 8-digit number as id. Identify the variables. Assign a suitable name to each variable and choose an appropriate type. Write the variable declaration statements.

Literals for Primitive Types and String

A literal, or literal constant, is a specific constant value, such as , , , , , , that is used in the program source. It can be assigned directly to a variable; or used as part of an expression. They are called literals because they literally and explicitly identify their values. We call it literal to distinguish it from a variable.

Integer (, , , ) literals

A whole number, such as and , is treated as an by default. In Java, the range of 32-bit literals is () to (). For example,

int number = -123; int sum = 1234567890; int bigSum = 8234567890;

An literal may precede with a plus () or minus () sign, followed by digits. No commas or special symbols (e.g., or space) is allowed (e.g., and are invalid). No preceding is allowed too (e.g., is invalid).

You can use a prefix (zero) to denote a value in octal, and prefix (or ) for a value in hexadecimal, e.g.,

int number = 1234; int number = 01234; int number = 0x1abc;

(JDK 1.7) From JDK 7, you can use prefix '' or '' to specify a value in binary. You are also permitted to use underscore () to break the digits into groups to improve the readability. But you must start and end the literal with a digit. For example,

int number1 = 0b01010000101000101101000010100010; int number2 = 0b0101_0000_1010_0010_1101_0000_1010_0010; int number3 = 2_123_456;

A literal above the range requires a suffix or (avoid lowercase, which confuses with the number one), e.g., , . In Java, the range of 64-bit literals is () to (). For example,

long bigNumber = 1234567890123L; long sum = 123;

No suffix is needed for and literals. But you can only use integer values in the permitted range. For example,

byte smallNumber = 12345; byte smallNumber = 123; short midSizeNumber = -12345;
Floating-point (, ) literals

A number with a decimal point, such as and , is treated as a by default. You can also express them in scientific notation, e.g., , , where or denotes the exponent in base of 10. You could precede the fractional part or exponent with a plus () or minus () sign. Exponent values are restricted to integer. There should be no space or other characters in the number.

You can optionally use suffix or to denote literals.

You MUST use a suffix of or for literals, e.g., . For example,

float average = 55.66; float average = 55.66f;
Character () Literals and Escape Sequences

A printable literal is written by enclosing the character with a pair of single quotes, e.g., , , and . In Java, characters are represented using 16-bit Unicode, and can be treated as a 16-bit unsigned integers in arithmetic operations. In other words, and 16-bit unsigned integer are interchangeable. You can also assign an integer in the range of to a variable.

For example,

char letter = 'a'; char anotherLetter = 98; System.out.println(letter); System.out.println(anotherLetter); anotherLetter += 2; System.out.println(anotherLetter);

Non-printable and control characters can be represented by a so-called escape sequence, which begins with a back-slash () followed by a pattern. The commonly-used escape sequences are:

Escape SequenceDescriptionUnicode in Hex (Decimal)
\nNewline (or Line-feed)000AH (10D)
\rCarriage-return000DH (13D)
\tTab0009H (9D)
\"Double-quote0022H (34D)
\'Single-quote0027H (39D)
\\Back-slash005CH (92D)
\uhhhhUnicode number hhhh (in hex),
e.g., \u000a is newline, \u60a8 is 您, \u597d is 好
hhhhH

Notes:

  • Newline () and Carriage-Return (), represented by the escape sequence , and respectively, are used as line delimiter (or end-of-line, or EOL). Take note that Unixes and Mac use () as EOL, while Windows use ().
  • Horizontal Tab () is represented as .
  • To resolve ambiguity, characters back-slash (), single-quote () and double-quote () are represented using escape sequences , and , respectively. E.g.,
    • To represent a back-slash , you need to write , instead of , as a back-slash begins an escape sequence. Similarly, to include a back-slash in a double-quoted string, you need to write .
    • To represent a single-quote , you need to write to distinguish it from the closing single-quote. But you can write double-quote directly, i.e., .
    • To place a double-quote in a double-quoted string, you need to use to distinguish it from the closing double-quote, e.g., . But you can write single-quote directly, e,g, .
  • Other less commonly-used escape sequences are: for alert or bell, for backspace, for form-feed, for vertical tab. These may not be supported in some consoles.
String Literals

A literal is composed of zero of more characters surrounded by a pair of double quotes, e.g., , . For example,

String directionMsg = "Turn Right"; String greetingMsg = "Hello"; String statusMsg = "";

String literals may contains escape sequences. Inside a , you need to use for double-quote to distinguish it from the ending double-quote, e.g. . Single-quote inside a does not require escape sequence. For example,

System.out.println("Use \\\" to place\n a \" within\ta\tstring"); Use \" to place a " within a string

Exercise: Write a program to print the following animal picture using multiple . Take note that you need to use escape sequences to print special characters.

'__' (oo) +========\/ / || %%% || * ||-----|| "" ""
boolean Literals

There are only two literals, i.e., and . For example,

boolean done = true; boolean gameOver = false;
Example on Literals
public class LiteralTest { public static void main(String[] args) { String name = "Tan Ah Teck"; char gender = 'm'; boolean isMarried = true; byte numChildren = 8; short yearOfBirth = 1945; int salary = 88000; long netAsset = 8234567890L; double weight = 88.88; float gpa = 3.88f; System.out.println("Name is " + name); System.out.println("Gender is " + gender); System.out.println("Is married is " + isMarried); System.out.println("Number of children is " + numChildren); System.out.println("Year of birth is " + yearOfBirth); System.out.println("Salary is " + salary); System.out.println("Net Asset is " + netAsset); System.out.println("Weight is " + weight); System.out.println("GPA is " + gpa); } }

The expected outputs are:

Name is Tan Ah Teck
Gender is m
Is married is true
Number of children is 8
Year of birth is 1945
Salary is 88000
Net Asset is 8234567890
Weight is 88.88
GPA is 3.88

Operations

Arithmetic Operators

Java supports the following arithmetic operators:

OperatorDescriptionUsageExamples
*Multiplicationexpr1 * expr22 * 3 → 6
3.3 * 1.0 → 3.3
/Divisionexpr1 / expr21 / 2 → 0
1.0 / 2.0 → 0.5
%Remainder (Modulus)expr1 % expr25 % 2 → 1
-5 % 2 → -1
5.5 % 2.2 → 1.1
+Addition
(or unary positive)
expr1 + expr2
+expr
1 + 2 → 3
1.1 + 2.2 → 3.3
-Subtraction
(or unary negate)
expr1 - expr2
-expr
1 - 2 → -1
1.1 - 2.2 → -1.1

All these operators are binary operators, i.e., they take two operands. However, '+' and '-' can also be interpreted as unary "positive" and "negative" operators. For example,

int number = -88; int x = +5;

Arithmetic Expressions

In programming, the following arithmetic expression:

must be written as . You cannot omit the multiplication symbol (), as in Mathematics.

Rules on Precedence

Like Mathematics:

  1. The multiplication (), division () and remainder () take precedence over addition () and subtraction (). For example, is interpreted as .
  2. Unary (positive) and (negate) have higher precedence.
  3. Parentheses have the highest precedence and can be used to change the order of evaluation.
  4. Within the same precedence level (e.g., addition and subtraction), the expression is evaluated from left to right (called left-associative). For example, is evaluated as and is .

Mixed-Type Operations

The arithmetic operators are only applicable to primitive numeric types: , , , , , , and .These operators do not apply to .

If both operands are , , or , the arithmetic operations are carried in that type, and evaluated to a value of that type, i.e., ; .

It is important to take note division produces an , i.e., , with the result truncated, e.g., , instead of ?!

If both operand are , or , the operations are carried out in , and evaluated to a value of . A is treated as a 16-bit unsigned integer in the range of . For example, .

If the two operands belong to different types, the value of the smaller type is promoted automatically to the larger type (known as implicit type-casting). The operation is then carried out in the larger type, and evaluated to a value in the larger type.

  • , or is first promoted to before comparing with the type of the other operand.
  • The order of promotion is: .

For examples,

  1. . Hence, .
  2. .
  3. (You probably don't expect this answer!)
  4. (The result is an , NOT !) byte b1 = 1, b2 = 2; byte b3 = b1 + b2;

The type-promotion rules for binary operations can be summarized as follows:

  1. If one of the operand is , the other operand is promoted to ;
  2. Else If one of the operand is , the other operand is promoted to ;
  3. Else If one of the operand is , the other operand is promoted to ;
  4. Else both operands are promoted to .

The type-promotion rules for unary operations (e.g., negate ) can be summarized as follows:

  1. If the operand is , , or , there is no promotion.
  2. Else (the operand is , , ), the operand is promoted to .

For example,

byte b1 = 1; byte b2 = -b1;
Remainder (Modulus) Operator

To evaluate the remainder (for negative and floating-point operands), perform repeated subtraction until the absolute value of the remainder is less than the absolute value of the second operand.

For example,

    Exponent?

    Java does not have an exponent operator. (The operator is for exclusive-or, NOT exponent). You need to use method to evaluate raises to power .

    Overflow/Underflow

    Study the output of the following program:

    public class OverflowTest { public static void main(String[] args) { int i1 = 2147483647; System.out.println(i1 + 1); System.out.println(i1 + 2); System.out.println(i1 * i1); int i2 = -2147483648; System.out.println(i2 - 1); System.out.println(i2 - 2); System.out.println(i2 * i2); } }

    In arithmetic operations, the resultant value wraps around if it exceeds its range (i.e., overflow). Java runtime does NOT issue an error/warning message but produces an incorrect result.

    On the other hand, integer division produces an truncated integer and results in so-called underflow. For example, gives , instead of . Again, Java runtime does NOT issue an error/warning message, but produces an imprecise result.

    It is important to take note that checking of overflow/underflow is the programmer's responsibility. i.e., your job!!!

    Why computer does not flag overflow/underflow as an error? This is due to the legacy design when the processors were very slow. Checking for overflow/underflow consumes computation power. Today, processors are fast. It is better to ask the computer to check for overflow/underflow (if you design a new language), because few humans expect such results.

    To check for arithmetic overflow (known as secure coding) is tedious. Google for "INT32-C. Ensure that operations on signed integers do not result in overflow" @ www.securecoding.cert.org.

    Type-Casting

    In Java, you will get a compilation error if you try to assign a or value of to an variable. This is because the fractional part would be lost. The compiler issues an error "possible loss in precision". For example,

    double d = 3.5; int i; i = d;int sum = 55.66f;
    Explicit Type-Casting and Type-Casting Operator

    To assign the a value to an variable, you need toinvoke the so-called type-casting operator - in the form of - to operate on the operand and return a truncated value in . In other words, you tell the compiler you concisely perform the truncation and you are aware of the possible loss of precision. You can then assign the truncated value to the variable. For example,

    double d = 3.5; int i; i = (int) d;

    Type-casting is an operation which takes one operand. It operates on its operand, and returns an equivalent value in the specified type.

    There are two kinds of type-casting in Java:

    1. Explicit type-casting via a type-casting operator in the prefix form of , as described above, and
    2. Implicit type-casting performed by the compiler automatically, if there is no loss of precision.
    Implicit Type-Casting in Assignment

    Explicit type-casting is not required if you assign an value to a variable, because there is no loss of precision. The compiler will perform the type-casting automatically (i.e., implicit type-casting). For example,,

    int i = 3; double d; d = i; d = (double) i; double aDouble = 55; double nought = 0;

    The following diagram shows the order of implicit type-casting performed by compiler. The rule is to promote the smaller type to a bigger type to prevent loss of precision, known as widening conversion. Narrowing conversion requires explicit type-cast to inform the compiler that you are aware of the possible loss of precision. Take note that is treated as an 16-bit unsigned integer in the range of . value cannot be type-casted (i.e., converted to non-).

    Example: Suppose that you want to find the average (in ) of the integers between and . Study the following codes:

    1 2 3 4 5 6 7 8 9 10 11 12 13 public class Sum1To100 { public static void main(String[] args) { int sum = 0; double average; int number = 1; while (number <= 100) { sum += number; ++number; } average = sum / 100; System.out.println("Average is " + average); } }

    This is because both the and are . The result of division is an , which is then implicitly casted to and assign to the variable . To get the correct answer, you can do either:

    average = (double)sum / 100; average = sum / (double)100; average = sum / 100.0; average = (double)(sum / 100);

    Compound Assignment Operators

    Besides the usual simple assignment operator () described earlier, Java also provides the so-called compound assignment operators as listed:

    OperationDescriptionUsageExample
    =Assignment
    Assign the value of the LHS to the variable at the RHS
    var = exprx = 5;
    +=Compound addition and assignmentvar += expr
    same asvar = var + expr
    x += 5;
    same as x = x + 5
    -=Compound subtraction and assignmentvar -= expr
    same asvar = var - expr
    x -= 5;
    same as x = x - 5
    *=Compound multiplication and assignmentvar *= expr
    same asvar = var * expr
    x *= 5;
    same as x = x * 5
    /=Compound division and assignmentvar /= expr
    same asvar = var / expr
    x /= 5;
    same as x = x / 5
    %=Compound remainder (modulus) and assignmentvar %= expr
    same asvar = var % expr
    x %= 5;
    same as x = x % 5

    Increment/Decrement

    Java supports these unary arithmetic operators: increment () and decrement () for all numeric primitive types (, , , , , and , except ).

    OperatorDescriptionExample
    ++Increment the value of the variable by 1.
    x++ or ++x is the same as x += 1 or x = x + 1
    int x = 5;
    x++;
    ++x;
    --Decrement the value of the variable by 1.
    x-- or --x is the same as x -= 1 or x = x - 1
    int y = 6;
    y--;
    --y;

    The increment () and decrement () operate on its operand and store the result back to its operand. For example, retrieves x, increment and stores the result back to x. Writing is a logical error!!!

    Unlike other unary operator (such as negate ()) which promotes , and to , the increment and decrement do not promote its operand (because there is no such need).

    The increment/decrement unary operator can be placed before the operand (prefix), or after the operands (postfix), which affects its resultant value.

    • If these operators are used by themselves (e.g., or ), the outcomes are the same for pre- and post-operators, because the resultant values are discarded.
    • If '++' or '--' involves another operation (e.g., or ), then pre- or post-order is important to specify the order of the two operations:
    OperatorDescriptionExample
    ++varPre-Increment
    Increment var, then use the new value of var
    y = ++x;
    same as x=x+1; y=x;
    var++Post-Increment
    Use the old value of var, then increment var
    y = x++;
    same as oldX=x; x=x+1; y=oldX;
    --varPre-Decrementy = --x;
    same as x=x-1; y=x;
    var--Post-Decrementy = x--;
    same as oldX=x; x=x-1; y=oldX;

    For examples,

    x = 5; System.out.println(x++); x = 5; System.out.println(++x);

    Prefix operator (e.g, ) could be more efficient than postfix operator (e.g., )?!

    Relational and Logical Operators

    Very often, you need to compare two values before deciding on the action to be taken, e.g. if mark is more than or equals to 50, print "PASS!".

    Java provides six comparison operators (or relational operators):

    OperatorDescriptionUsageExample (x=5, y=8)
    ==Equal toexpr1 == expr2(x == y) → false
    !=Not Equal toexpr1 != expr2(x != y) → true
    >Greater thanexpr1 > expr2(x > y) → false
    >=Greater than or equal toexpr1 >= expr2(x >= 5) → true
    <Less thanexpr1 < expr2(y < 8) → false
    <=Less than or equal toexpr1 >= expr2(y <= 8) → true

    In Java, these comparison operations returns a value of either or .

    Each comparison operation involves two operands, e.g., . It is invalid to write in programming. Instead, you need to break out the two comparison operations , , and join with with a logical AND operator, i.e., , where denotes AND operator.

    Java provides four logical operators, which operate on operands only, in descending order of precedences, as follows:

    OperatorDescriptionUsage
    !Logical NOT!booleanExpr
    ^Logical XORbooleanExpr1 ^ booleanExpr2
    &&Logical ANDbooleanExpr1 && booleanExpr2
    ||Logical ORbooleanExpr1 || booleanExpr2

    The truth tables are as follows:

    AND (&&)truefalse
    truetruefalse
    falsefalsefalse

    OR (||)truefalse
    truetruetrue
    falsetruefalse

    NOT (!)truefalse
    Resultfalsetrue

    XOR (^)truefalse
    truefalsetrue
    falsetruefalse

    Example:

    (x >= 0) && (x <= 100)   (x < 0) || (x > 100) !((x >= 0) && (x <= 100))   ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

    Exercise: Study the following program, and explain its output.

    public class RelationalLogicalOpTest { public static void main(String[] args) { int age = 18; double weight = 71.23; int height = 191; boolean married = false; boolean attached = false; char gender = 'm'; System.out.println(!married && !attached && (gender == 'm')); System.out.println(married && (gender == 'f')); System.out.println((height >= 180) && (weight >= 65) && (weight <= 80)); System.out.println((height >= 180) || (weight >= 90)); } }

    Write an expression for all unmarried male, age between 21 and 35, with height above 180, and weight between 70 and 80.

    Exercise: Given the year, month (1-12), and day (1-31), write a boolean expression which returns true for dates before October 15, 1582 (Gregorian calendar cut over date).

    Ans:

    Operator Precedence

    The precedence from highest to lowest is: (unary), , , '. But when in doubt, use parentheses!

    System.out.println(true || true && false); System.out.println(true || (true && false)); System.out.println((true || true) && false); System.out.println(false && true ^ true); System.out.println(false && (true ^ true)); System.out.println((false && true) ^ true);
    Short-Circuit Operation

    The logical AND () and OR () operators are known as short-circuit operators, meaning that the right operand will not be evaluated if the result can be determined by the left operand. For example, gives ; give without evaluating the right operand. This may have adverse consequences if you rely on the right operand to perform certain operations, e.g. but will not be evaluated.

    Strings

    A is a sequence of characters. A string literal is surrounded by a pair of double quotes, e.g.,

    String s1 = "Hi, This is a string!" String s2 = ""

    You need to use an escape sequence for special control characters (such as newline and tab ), double-quote and backslash (due to conflict) and Unicode character (if your editor does not support Unicode input), e.g.,

    String s3 = "A \"string\" nested \\inside\\ a string" String s4 = "Hello, \u60a8\u597d!"

    Single-quote () does not require an escape sign.

    String s5 = "Hi, I'm a string!"

    String and '+' Operator

    In Java, is a special operator. It is overloaded. Overloading means that it carries out different operations depending on the types of its two operands.

    • If both operands are numbers (, , , , , , ), performs the usual addition, e.g., 1 + 2 → 3 1.2 + 2.2 → 3.4 1 + 2.2 → 1.0 + 2.2 → 3.2
    • If both operands are s, concatenates the two Strings and returns the concatenated . E.g., "Hello" + "world" → "Helloworld" "Hi" + ", " + "world" + "!" → "Hi, world!"
    • If one of the operand is a and the other is numeric, the numeric operand will be converted to and the two s concatenated, e.g., "The number is " + 5 → "The number is " + "5" → "The number is 5" "The average is " + average + "!" (suppose average=5.5) → "The average is " + "5.5" + "!" → "The average is 5.5!" "How about " + a + b (suppose a=1, b=1) → "How about 11"

    String Operations

    The most commonly-used methods are:

    • : return the length of the string.
    • : return the at the position (index begins at to ).
    • : for comparing the contents of two strings. Take note that you cannot use to compare two strings.

    For examples,

    String str = "Java is cool!"; System.out.println(str.length()); System.out.println(str.charAt(2)); System.out.println(str.charAt(5));   String anotherStr = "Java is COOL!"; System.out.println(str.equals(anotherStr)); System.out.println(str.equalsIgnoreCase(anotherStr)); System.out.println(anotherStr.equals(str)); System.out.println(anotherStr.equalsIgnoreCase(str));

    To check all the available methods for , open JDK API documentation ⇒ select package "" ⇒ select class "" ⇒ choose method. For examples,

    String str = "Java is cool!"; System.out.println(str.length()); System.out.println(str.charAt(2)); System.out.println(str.substring(0, 3)); System.out.println(str.indexOf('a')); System.out.println(str.lastIndexOf('a')); System.out.println(str.endsWith("cool!")); System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase());

    String/Primitive Conversion

    "String" to "int/byte/short/long": You could use the JDK built-in methods to convert a containing a valid integer literal (e.g., "") into an (e.g., ). The runtime triggers a if the input string does not contain a valid integer literal (e.g., ""). For example,

    String inStr = "5566"; int number = Integer.parseInt(inStr); number = Integer.parseInt("abc");

    Similarly, you could use methods , , to convert a string containing a valid , or literal to the primitive type.

    "String" to "double/float": You could use or to convert a (containing a floating-point literal) into a or , e.g.

    String inStr = "55.66"; float aFloat = Float.parseFloat(inStr); double aDouble = Double.parseDouble("1.2345"); aDouble = Double.parseDouble("abc");

    "String" to "char": You can use to extract individual character from a , e.g.,

    String msg = "101100111001!"; int pos = 0; while (pos < msg.length()) { char binChar = msg.charAt(pos); ....... ++pos; }

    "String" to "boolean": You can use method to convert string of "" or "" to or , e.g.,

    String boolStr = "true"; boolean done = Boolean.parseBoolean(boolStr); boolean valid = Boolean.parseBoolean("false");

    Primitive (int/double/float/byte/short/long/char/boolean) to "String": To convert a primitive to a , you can use the '+' operator to concatenate the primitive with an empty, or use the JDK built-in methods , , , , , etc. For example,

    String s1 = 123 + ""; String s2 = 12.34 + ""; String s3 = 'c' + ""; String s4 = true + ""; String s1 = String.valueOf(12345); String s2 = String.valueof(true); double d = 55.66; String s3 = String.valueOf(d); String s4 = Integer.toString(1234); String s5 = Double.toString(1.23); char c1 = Character.toString('z'); char c = 'a'; String s5 = c; String s6 = c + ""; boolean done = false; String s7 = done + ""; String s8 = Boolean.toString(done); String s9 = String.valueOf(done);

    "char" to "int": You can convert char to to to by subtracting the with (e.g., ).

    Flow Control

    There are three basic flow control constructs - sequential, conditional (or decision), and loop (or iteration), as illustrated below.

    Sequential Flow Control

    A program is a sequence of instructions executing one after another in a predictable manner. Sequential flow is the most common and straight-forward, where programming statements are executed in the order that they are written - from top to bottom in a sequential manner.

    Conditional Flow Control

    There are a few types of conditionals, if-then, if-then-else, nested-if (if-elseif-elseif-...-else), switch-case, and conditional expression.

    Braces: You could omit the braces , if there is only one statement inside the block. However, I recommend that you keep the braces to improve the readability of your program. For example,

    if (mark >= 50) System.out.println("PASS"); else { System.out.println("FAIL"); System.out.println("Try Harder!"); }
    "switch-case-default"

    "switch-case" is an alternative to the "nested-if". In a switch-case statement, a statement is needed for each of the cases. If is missing, execution will flow through the following case. You can use an , , , or variable as the case-selector, but NOT , , and . (JDK 1.7 supports as the case-selector).

    Conditional Operator (? :)

    A conditional operator is a ternary (3-operand) operator, in the form of . Depending on the , it evaluates and returns the value of or .

    SyntaxExample
    booleanExpr?trueExpr:falseExprSystem.out.println((mark >= 50) ? "PASS" : "FAIL"); max = (a > b) ? a : b; abs = (a > 0) ? a : -a;

    Exercises on Conditional

    LINK TO EXERCISES ON CONDITIONAL FLOW CONTROL

    Loop Flow Control

    Again, there are a few types of loops: for, while-do, and do-while.

    SyntaxExampleFlowchart
    for (initialization;test;post-processing) {body;}   int sum = 0; for (int number = 1; number <= 1000; ++number) { sum += number; }
    while (test) {body; }  

    This chapter explains the features, technical details and syntaxes of the C++ programming language. I assume that you could write some simple programs. Otherwise, read "Introduction To C++ Programming for Novices and First-time Programmers".

    To be a proficient programmer, you need to master two things: (1) the syntax of the programming language, and (2) the core libraries (i.e., ) associated with the language.

    Introduction to C++

    C++ Standards

    C++ is standardized as ISO/IEC 14882. Currently, there are two versions:

    1. C++98 (ISO/IEC 14882:1998): 1st standard version of C++.
    2. C++03 (ISO/IEC 14882:2003): minor "bug-fix" to C++98 with no change to the language. Commonly refer to as C++98/C++03 or First C++ standard.
    3. C++11 (ISO/IEC 14882:2011): 2nd standard version of C++. Formerly called C++0x, as it was expected to finalize in 200x. It adds some new features to the language; more significantly, it greatly extends the C++ standard library and standard template library (STL).
    C++ Features
    1. C++ is C. C++ supports (almost) all the features of C. Like C, C++ allows programmers to manage the memory directly, so as to develop efficient programs.
    2. C++ is OO. C++ enhances the procedural-oriented C language with the object-oriented extension. The OO extension facilitates design, reuse and maintenance for complex software.
    3. Template C++. C++ introduces generic programming, via the so-called template. You can apply the same algorithm to different data types.
    4. STL. C++ provides a huge set of reusable standard libraries, in particular, the Standard Template Library (STL).
    C++ Strength and Pitfall

    C++ is a powerful language for high-performance applications, including writing operating systems and their subsystems, games and animation. C++ is also a complex and difficult programming language, which is really not meant for dummies. For example, to effectively use the C++ Standard Template Library (STL), you need to understand these difficult concepts: pointers, references, operator overloading and template, on top of the object-oriented programming concepts such as classes and objects, inheritance and polymorphism; and the traditional constructs such as decision and loop. C++ is performance centric. The C++ compiler does not issue warning/error message for many obvious programming mistakes, undefined and unspecified behaviors, such as array index out of range, using an uninitialized variable, etc, due to the focus on performance and efficiency rather than the ease of use - it assumes that those who choose to program in C++ are not dummies.

    Basic Syntaxes

    Revision

    Below is a simple C++ program that illustrates the important programming constructs (sequential flow, while-loop, and if-else) and input/output. Read "Introduction To C++ Programming for Novices and First-time Programmers" if you need help in understanding this program.

    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 32 33 34 35 36 37 38 39 40 41 42 43 #include <iostream> using namespace std; int main() { int sumOdd = 0; int sumEven = 0; int upperbound; int absDiff; cout << "Enter the upperbound: "; cin >> upperbound; int number = 1; while (number <= upperbound) { if (number % 2 == 0) { sumEven += number; } else { sumOdd += number; } ++number; } if (sumOdd > sumEven) { absDiff = sumOdd - sumEven; } else { absDiff = sumEven - sumOdd; } cout << "The sum of odd numbers is " << sumOdd << endl; cout << "The sum of even numbers is " << sumEven << endl; cout << "The absolute difference is " << absDiff << endl; return 0; }
    Enter the upperbound: 1000 The sum of odd numbers is 250000 The sum of even numbers is 250500 The absolute difference is 500
    Program Notes

    using namespace std;
    The names and belong to the namespace. They can be referenced via fully qualified name and , or simply as and with a " statement. For simplicity, I shall use the latter approach in this section. I will discuss the significance later.

    return 0;
    The return value of 0 indicates normal termination; while non-zero (typically 1) indicates abnormal termination. C++ compiler will automatically insert a "" at the end of the the function, thus, it statement can be omitted.

    Instead of using numeric value of zero and non-zero, you can also use or , which is defined in the header (i.e., you need to "".

    Comments

    Comments are used to document and explain your codes and program logic. Comments are not programming statements and are ignored by the compiler, but they VERY IMPORTANT for providing documentation and explanation for others to understand your program (and also for yourself three days later).

    There are two kinds of comments in C/C++:

    1. Multi-line Comment: begins with a and ends with a , and can span several lines.
    2. End-of-line Comment: begins with and lasts till the end of the current line.

    You should use comments liberally to explain and document your codes. During program development, instead of deleting a chunk of statements permanently, you could comment-out these statements so that you could get them back later, if needed.

    Statements and Blocks

    Statement: A programming statement is the smallest independent unit in a program, just like a sentence in the English language. It performs a piece of programming action. A programming statement must be terminated by a semi-colon (), just like an English sentence ends with a period. (Why not ends with a period like an english sentence? This is because period crashes with decimal point - it is hard for the dumb computer to differentiate between period and decimal point!)

    For examples,

    int number1 = 10; int number2, number3 = 99; int product; product = number1 * number2 * number3; cout << "Hello" << endl;

    Block: A block (or a compound statement) is a group of statements surrounded by braces . All the statements inside the block is treated as one unit. Blocks are used as the body in constructs like function, if-else and loop, which may contain multiple statements but are treated as one unit. There is no need to put a semi-colon after the closing brace to end a complex statement. Empty block (without any statement) is permitted. For examples,

    if (mark >= 50) { cout << "PASS" << endl; cout << "Well Done!" << endl; cout << "Keep it Up!" << endl; } if (number == 88) { cout << "Got it" << endl; } else { cout << "Try Again" << endl; } i = 1; while (i < 8) { cout << i << endl; ++i; } int main() { ...statements... }

    White Spaces and Formatting Source Codes

    White Spaces: Blank, tab and new-line are collectively called white spaces. C++, like most of the computing languages, ignores extra white spaces. That is, multiple contiguous white spaces are treated as a single white space.

    You need to use a white space to separate two keywords or tokens, e.g.,

    int sum=0; double average; average=sum/100.0;

    Additional white spaces and extra lines are, however, ignored, e.g.,

    int sum = 0 ; double average ; average = sum / 100.0;

    Formatting Source Codes: As mentioned, extra white spaces are ignored and have no computational significance. However, proper indentation (with tabs and blanks) and extra empty lines greatly improves the readability of the program, which is extremely important for others (and yourself three days later) to understand your programs. For example, the following hello-world works, but can you understand the program?

    #include <iostream> using namespace std;int main(){cout<<"Hello, world!"<<endl;return 0;}

    Braces: Place the beginning brace at the end of the line, and align the ending brace with the start of the statement.

    Indentation: Indent the body of a block by an extra 3 (or 4 spaces), according to its level.

    For example,

    #include <iostream> using namespace std; int main() { int mark = 70; if (mark >= 50) { cout << "You Pass!" << endl; } else { cout << "You Fail!" << endl; } return 0; }

    Most IDEs (such as CodeBlocks, Eclipse and NetBeans) have a command to re-format your source code automatically.

    Note: Traditional C-style formatting places the beginning and ending braces on the same column. For example,

    #include <iostream> using namespace std; int main() { if (mark >= 50) { cout << "You Pass!" << endl; } else { cout << "You Fail!" << endl; }}

    Preprocessor Directives

    C++ source code is pre-processed before it is compiled into object code (as illustrated).

    A preprocessor directive, which begins with a sign (such as , ), tells the preprocessor to perform a certain action (such as including a header file, or performing text replacement), before compiling the source code into object code. Preprocessor directives are not programming statements, and therefore should NOT be terminated with a semi-colon. For example,

    #include <iostream> #include <cmath> #define PI 3.14159265 // DO NOT terminate preprocessor directive with a semi-colon

    In almost all of the C++ programs, we use to include the input/output stream library header into our program, so as to use the IO library function to carry out input/output operations (such as and ).

    More on preprocessor directives later.

    Variables and Types

    Variables

    Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.

    More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a name, a type and stores a value.

    • A variable has a name (or identifier), e.g., , , , . The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., ), and retrieve the value stored (e.g., ).
    • A variable has a type. Examples of type are,
      • : for integers (whole numbers) such as and ;
      • : for floating-point or real numbers such as , , having a decimal point and fractional part.
    • A variable can store a value of that particular type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a variable can store an integer value such as , but NOT real number such as , nor texts such as .
    • The concept of type was introduced into the early programming languages to simplify interpretation of data made up of 0s and 1s. The type determines the size and layout of the data, the range of its values, and the set of operations that can be applied.

    The following diagram illustrates two types of variables: and . An variable stores an integer (whole number). A variable stores a real number.

    Identifiers

    An identifier is needed to name a variable (or any other entity such as a function or a class). C++ imposes the following rules on identifiers:

    • An identifier is a sequence of characters, of up to a certain length (compiler-dependent, typically 255 characters), comprising uppercase and lowercase letters , digits , and underscore .
    • White space (blank, tab, new-line) and other special characters (such as , , , , , , commas, etc.) are not allowed.
    • An identifier must begin with a letter or underscore. It cannot begin with a digit. Identifiers beginning with an underscore are typically reserved for system use.
    • An identifier cannot be a reserved keyword or a reserved literal (e.g.,, , , , ).
    • Identifiers are case-sensitive. A is NOT a , and is NOT a .

    Caution: Programmers don't use blank character in names. It is either not supported, or will pose you more challenges.

    Variable Naming Convention

    A variable name is a noun, or a noun phrase made up of several words. The first word is in lowercase, while the remaining words are initial-capitalized, with no spaces between words. For example, , , , , and . This convention is also known as camel-case.

    Recommendations
    1. It is important to choose a name that is self-descriptive and closely reflects the meaning of the variable, e.g., or .
    2. Do not use meaningless names like , , , , , , , , .
    3. Avoid single-alphabet names, which is easier to type but often meaningless, unless they are common names like , , for coordinates, for index.
    4. It is perfectly okay to use long names of says 30 characters to make sure that the name accurately reflects its meaning!
    5. Use singular and plural nouns prudently to differentiate between singular and plural variables.  For example, you may use the variable to refer to a single row number and the variable to refer to many rows (such as an array of rows - to be discussed later).

    Variable Declaration

    To use a variable in your program, you need to first "introduce" it by declaring its name and type, in one of the following syntaxes:

    SyntaxExample
    type identifier;type identifier-1,identifier-2, ...,identifier-n;type identifier=value;type identifier-1=value-1, ...,identifier-n=value-n;  int option;   double sum, difference, product, quotient;   int magicNumber = 88;   double sum = 0.0, product = 1.0;

    Example,

    int mark1; mark1 = 76; int mark2; mark2 = mark1 + 10; double average; average = (mark1 + mark2) / 2.0; int mark1;mark2 = "Hello";

    Take note that:

    • In C++, you need to declare the name of a variable before it can be used.
    • C++ is a "strongly-type" language. A variable takes on a type. Once the type of a variable is declared, it can only store a value belonging to this particular type. For example, an variable can hold only integer such as , and NOT floating-point number such as or text string such as . The concept of type was introduced into the early programming languages to simplify interpretation of data made up of 0s and 1s. Knowing the type of a piece of data greatly simplifies its interpretation and processing.
    • Each variable can only be declared once.
    • In C++, you can declare a variable anywhere inside the program, as long as it is declared before used. (In C prior to C99, all the variables must be declared at the beginning of functions.) It is recommended that your declare a variable just before it is first used.
    • The type of a variable cannot be changed inside the program.
    CAUTION: Uninitialized Variables

    When a variable is declared, it contains garbage until you assign an initial value. It is important to take note that C/C++ does not issue any warning/error if you use a variable before initialize it - which certainly leads to some unexpected results. For example,

    1 2 3 4 5 6 7 8 9 #include <iostream> using namespace std; int main() { int number; cout << number << endl; return 0; }

    Constants (const)

    Constants are non-modifiable variables, declared with keyword . Their values cannot be changed during program execution. Also, must be initialized during declaration. For examples:

    const double PI = 3.1415926;

    Constant Naming Convention: Use uppercase words, joined with underscore. For example, , .

    Expressions

    An expression is a combination of operators (such as addition , subtraction , multiplication , division ) and operands (variables or literal values), that can be evaluated to yield a single value of a certain type. For example,

    1 + 2 * 3 int sum, number; sum + number double principal, interestRate; principal * (1 + interestRate)

    Assignment (=)

    An assignment statement:

    1. assigns a literal value (of the RHS) to a variable (of the LHS); or
    2. evaluates an expression (of the RHS) and assign the resultant value to a variable (of the LHS).

    The RHS shall be a value; and the LHS shall be a variable (or memory address).

    The syntax for assignment statement is:

    SyntaxExample
    variable=literal-value;variable=expression;  number = 88;   sum = sum + number;

    The assignment statement should be interpreted this way: The expression on the right-hand-side (RHS) is first evaluated to produce a resultant value (called rvalue or right-value). The rvalue is then assigned to the variable on the left-hand-side (LHS) (or lvalue, which is a location that can hold a rvalue). Take note that you have to first evaluate the RHS, before assigning the resultant value to the LHS. For examples,

    number = 8; number = number + 1;

    The symbol "" is known as the assignment operator. The meaning of "" in programming is different from Mathematics. It denotes assignment instead of equality. The RHS is a literal value; or an expression that evaluates to a value; while the LHS must be a variable. Note that is valid (and often used) in programming. It evaluates and assign the resultant value to the variable . illegal in Mathematics. While is allowed in Mathematics, it is invalid in programming (because the LHS of an assignment statement must be a variable). Some programming languages use symbol "", "←", "->", or "→" as the assignment operator to avoid confusion with equality.

    Fundamental Types

    Integers: C++ supports these integer types: , , , , (in C++11) in a non-decreasing order of size. The actual size depends on the implementation. The integers (except ) are signed number (which can hold zero, positive and negative numbers). You could use the keyword to declare an unsigned integers (which can hold zero and positive numbers). There are a total 10 types of integers - combined with .

    Characters: Characters (e.g., , , , ) are encoded in ASCII into integers, and kept in type . For example, character is (decimal) or (hexadecimal); character is (decimal) or (hexadecimal); character is (decimal) or (hexadecimal). Take note that the type can be interpreted as character in ASCII code, or an 8-bit integer. Unlike or , which is , could be or , depending on the implementation. You can use or to explicitly declare or .

    Floating-point Numbers: There are 3 floating point types: , and , for single, double and long double precision floating point numbers. and are represented as specified by IEEE 754 standard. A can represent a number between and , approximated. A can represented a number between and , approximated. Take note that not all real numbers can be represented by and , because there are infinite real numbers. Most of the values are approximated.

    Boolean Numbers: A special type called (for boolean), which takes a value of either or .

    The table below shows the typical size, minimum, maximum for the primitive types. Again, take note that the sizes are implementation dependent.

    CategoryTypeDescriptionBytes
    (Typical)
    Minimum
    (Typical)
    Maximum
    (Typical)
    Integersint
    (or signed int)
    Signed integer (of at least 16 bits)4 (2)-21474836482147483647
    unsigned intUnsigned integer (of at least 16 bits)4 (2)04294967295
    charCharacter
    (can be either signed or unsigned depends on implementation)
    1  
    signed charCharacter or signed tiny integer
    (guarantee to be signed)
    1-128127
    unsigned charCharacter or unsigned tiny integer
    (guarantee to be unsigned)
    10255
    short
    (or short int)
    (or signed short)
    (or signed short int)
    Short signed integer (of at least 16 bits)2-3276832767
    unsigned short
    (or unsigned shot int)
    Unsigned short integer (of at least 16 bits)2065535
    long
    (or long int)
    (or signed long)
    (or signed long int)
    Long signed integer (of at least 32 bits)4 (8)-21474836482147483647
    unsigned long
    (or unsigned long int)
    Unsigned long integer (of at least 32 bits)4 (8)0same as above
    long long
    (or long long int)
    (or signed long long)
    (or signed long long int) (C++11)
    Very long signed integer (of at least 64 bits)8-263263-1
    unsigned long long
    (or unsigned long long int) (C++11)
    Unsigned very long integer (of at least 64 bits)80264-1
    Real NumbersfloatFloating-point number, ≈7 digits
    (IEEE 754 single-precision floating point format)
    43.4e383.4e-38
    doubleDouble precision floating-point number, ≈15 digits
    (IEEE 754 double-precision floating point format)
    81.7e3081.7e-308
    long doubleLong double precision floating-point number, ≈19 digits
    (IEEE 754 quadruple-precision floating point format)
    12 (8)  
    Boolean
    Numbers
    boolBoolean value of either or 1false (0)true (1 or non-zero)
    Wide
    Characters
    wchar_t
    char16_t (C++11)
    char32_t (C++11)
    Wide (double-byte) character2 (4)  

    In addition, many C++ library functions use a type called , which is equivalent () to a , meant for counting, size or length, with 0 and positive integers.

    *The sizeof Operator

    C/C++ provides an unary operator to get the size of the operand (in bytes). The following program uses operator to print the size of the fundamental types.

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <iostream> using namespace std; int main() { cout << "sizeof(char) is " << sizeof(char) << " bytes " << endl; cout << "sizeof(short) is " << sizeof(short) << " bytes " << endl; cout << "sizeof(int) is " << sizeof(int) << " bytes " << endl; cout << "sizeof(long) is " << sizeof(long) << " bytes " << endl; cout << "sizeof(long long) is " << sizeof(long long) << " bytes " << endl; cout << "sizeof(float) is " << sizeof(float) << " bytes " << endl; cout << "sizeof(double) is " << sizeof(double) << " bytes " << endl; cout << "sizeof(long double) is " << sizeof(long double) << " bytes " << endl; cout << "sizeof(bool) is " << sizeof(bool) << " bytes " << endl; return 0; }
    sizeof(char) is 1 bytes sizeof(short) is 2 bytes sizeof(int) is 4 bytes sizeof(long) is 4 bytes sizeof(long long) is 8 bytes sizeof(float) is 4 bytes sizeof(double) is 8 bytes sizeof(long double) is 12 bytes sizeof(bool) is 1 bytes

    The results may vary among different systems.

    *Header <climits>

    The header (ported to C++ from C's ) contains information about limits of integer type. For example,

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <iostream> #include <climits> using namespace std; int main() { cout << "int max = " << INT_MAX << endl; cout << "int min = " << INT_MIN << endl; cout << "unsigned int max = " << UINT_MAX << endl; cout << "long long max = " << LLONG_MAX << endl; cout << "long long min = " << LLONG_MIN << endl; cout << "unsigned long long max = " << ULLONG_MAX << endl; cout << "Bits in char = " << CHAR_BIT << endl; cout << "char max = " << CHAR_MAX << endl; cout << "char min = " << CHAR_MIN << endl; cout << "signed char max = " << SCHAR_MAX << endl; cout << "signed char min = " << SCHAR_MIN << endl; cout << "unsigned char max = " << UCHAR_MAX << endl; return 0; }
    int max = 2147483647 int min = -2147483648 unsigned int max = 4294967295 long long max = 9223372036854775807 long long min = -9223372036854775808 unsigned long long max = 18446744073709551615 Bits in char = 8 char max = 127 char min = -128 signed char max = 127 signed char min = -128 unsigned char max = 255

    Again, the outputs depend on the system.

    The minimum of unsigned integer is always 0. The other constants are , , , , , . Try inspecting this header (search for under your compiler).

    *Header <cfloat>

    Similarly, the header (ported from C's ) contain information on limits for floating point numbers, such as minimum number of significant digits (, , for , and ), number of bits for mantissa (, , ), maximum and minimum exponent values, etc. Try inspecting this header (search for under your compiler).

    *Header <limits>

    The and headers are ported over from C's and . C++ added a new header called .

    [TODO]

    Choosing Types

    As a programmer, you need to choose variables and decide on the type of the variables to be used in your programs. Most of the times, the decision is intuitive. For example, use an integer type for counting and whole number; a floating-point type for number with fractional part, for a single character, and for binary outcome.

    Rule of Thumb
    • Use for integer and for floating point numbers. Use , , and only if you have a good reason to choose that specific precision.
    • Use (or ) for counting and indexing, NOT floating-point type ( or ). This is because integer type are precise and more efficient in operations.
    • Use an integer type if possible. Use a floating-point type only if the number contains a fractional part.

    Read my article on "Data Representation" if you wish to understand how the numbers and characters are represented inside the computer memory. In brief, It is important to take note that is different from , , , , and . They are represented differently in the computer memory, with different precision and interpretation. For example, is , is , is , is , is , is .

    There is a subtle difference between and .

    Furthermore, you MUST know the type of a value before you can interpret a value. For example, this value cannot be interpreted unless you know the type.

    *The typedef Statement

    Typing "" many time can get annoying. The statement can be used to create a new name for an existing type. For example, you can create a new type called "" for "" as follow. You should place the immediately after . Use with care because it makes the program hard to read and understand.

    typedef unsigned int uint;

    Many C/C++ compilers define a type called , which is a of .

    typedef unsigned int size_t;

    Literals for Fundamental Types and String

    A literal is a specific constant value, such as , , , , , that can be assigned directly to a variable; or used as part of an expression. They are called literals because they literally and explicitly identify their values.

    Integer Literals

    A whole number, such as and , is treated as an , by default. For example,

    int number = -123; int sum = 4567; int bigSum = 8234567890;

    An literal may precede with a plus () or minus () sign, followed by digits. No commas or special symbols (e.g., or space) is allowed (e.g., and are invalid). No preceding is allowed too (e.g., is invalid).

    Besides the default base 10 integers, you can use a prefix (zero) to denote a value in octal, prefix for a value in hexadecimal, and prefix '' for binary value (in some compilers), e.g.,

    int number1 = 1234; int number2 = 01234; int number3 = 0x1abc; int number4 = 0b10001001;

    A literal is identified by a suffix or (avoid lowercase, which can be confused with the number one). A is identified by a suffix . You can also use suffix for , for , and for . For example,

    long number = 12345678L; long sum = 123; long long bigNumber = 987654321LL;

    No suffix is needed for literals. But you can only use integer values in the permitted range. For example,

    short smallNumber = 1234567890; short midSizeNumber = -12345;
    Floating-point Literals

    A number with a decimal point, such as and , is treated as a , by default. You can also express them in scientific notation, e.g., , , where or denotes the exponent in power of 10. You could precede the fractional part or exponent with a plus () or minus () sign. Exponent shall be an integer. There should be no space or other characters (e.g., space) in the number.

    You MUST use a suffix of or for literals, e.g., . For example,

    float average = 55.66; float average = 55.66f;

    Use suffix (or ) for .

    Character Literals and Escape Sequences

    A printable literal is written by enclosing the character with a pair of single quotes, e.g., , , and . In C++, characters are represented using 8-bit ASCII code, and can be treated as a 8-bit signed integers in arithmetic operations. In other words, and 8-bit signed integer are interchangeable. You can also assign an integer in the range of to a variable; and to an .

    You can find the ASCII code table HERE.

    For example,

    char letter = 'a'; char anotherLetter = 98; cout << letter << endl; cout << anotherLetter << endl; anotherLetter += 2; cout << anotherLetter << endl; cout << (int)anotherLetter << endl;

    Non-printable and control characters can be represented by a so-called escape sequence, which begins with a back-slash (). The commonly-used escape sequences are:

    Escape SequenceDescriptionHex (Decimal)
    \nNew-line (or Line-feed)0AH (10D)
    \rCarriage-return0DH (13D)
    \tTab09H (9D)
    \"Double-quote (needed to include " in double-quoted string)22H (34D)
    \'Single-quote27H (39D)
    \\Back-slash (to resolve ambiguity)5CH (92D)

    Notes:

    • New-line () and carriage return (), represented by , and respectively, are used as line delimiter (or end-of-line, or EOL). However, take note that Unixes/Mac use as EOL, Windows use .
    • Horizontal Tab () is represented as .
    • To resolve ambiguity, characters back-slash (), single-quote () and double-quote () are represented using escape sequences , and , respectively. This is because a single back-slash begins an escape sequence, while single-quotes and double-quotes are used to enclose character and string.
    • Other less commonly-used escape sequences are: or , for alert or bell, for backspace, for form-feed, for vertical tab. These may not be supported in some consoles.
    The <cctype> Header

    The header (ported from C's ) provides functions such as , , , , , , to determine the type of character; and , for case conversion.

    String Literals

    A literal is composed of zero of more characters surrounded by a pair of double quotes, e.g., , , . For example,

    String directionMsg = "Turn Right"; String greetingMsg = "Hello"; String statusMsg = "";

    String literals may contains escape sequences. Inside a , you need to use for double-quote to distinguish it from the ending double-quote, e.g. . Single quote inside a does not require escape sequence. For example,

    cout << "Use \\\" to place\n a \" within\ta\tstring" << endl; Use \" to place a " within a string

    TRY: Write a program to print the following picture. Take note that you need to use escape sequences to print special characters.

    '__' (oo) +========\/ / || %%% || * ||-----|| "" ""
    bool Literals

    There are only two literals, i.e., and . For example,

    bool done = true; bool gameOver = false; int i; if (i == 9) { ...... }

    In an expression, values and literals are converted to 0 for and 1 (or a non-zero value) for .

    Example (Literals)
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include <iostream> using namespace std; int main() { char gender = 'm'; bool isMarried = true; unsigned short numChildren = 8; short yearOfBirth = 1945; unsigned int salary = 88000; double weight = 88.88; float gpa = 3.88f; cout << "Gender is " << gender << endl; cout << "Is married is " << isMarried << endl; cout << "Number of children is " << numChildren << endl; cout << "Year of birth is " << yearOfBirth << endl; cout << "Salary is " << salary << endl; cout << "Weight is " << weight << endl; cout << "GPA is " << gpa << endl; return 0; }
    Gender is m Is married is 1 Number of children is 8 Year of birth is 1945 Salary is 88000 Weight is 88.88 GPA is 3.88

    Operations

    Arithmetic Operators

    C++ supports the following arithmetic operators for numbers: , , , , (treated as 8-bit signed integer), , , , , , , and .

    OperatorDescriptionUsageExamples
    *Multiplicationexpr1 * expr22 * 3 → 6; 3.3 * 1.0 → 3.3
    /Divisionexpr1 / expr21 / 2 → 0; 1.0 / 2.0 → 0.5
    %Remainder (Modulus)expr1 % expr25 % 2 → 1; -5 % 2 → -1
    +Additionexpr1 + expr21 + 2 → 3; 1.1 + 2.2 → 3.3
    -Subtractionexpr1 - expr21 - 2 → -1; 1.1 - 2.2 → -1.1

    All the above operators are binary operators, i.e., they take two operands. The multiplication, division and remainder take precedence over addition and subtraction. Within the same precedence level (e.g., addition and subtraction), the expression is evaluated from left to right. For example, is evaluated as .

    It is important to take note that produces an , with the result truncated, e.g.,(instead of ).

    Take note that C/C++ does not have an exponent (power) operator ( is exclusive-or, not exponent).

    Arithmetic Expressions

    In programming, the following arithmetic expression:

    must be written as . You cannot omit the multiplication symbol (as in Mathematics).

    Like Mathematics, the multiplication and division take precedence over addition and subtraction . Parentheses have higher precedence. The operators , , , and are left-associative. That is, is treated as .

    Mixed-Type Operations

    If both the operands of an arithmetic operation belong to the same type, the operation is carried out in that type, and the result belongs to that type. For example, .

    However, if the two operands belong to different types, the compiler promotes the value of the smaller type to the larger type (known as implicit type-casting). The operation is then carried out in the larger type. For example, . Hence, .

    For example,

    TypeExampleOperation
    int2 + 3int 2 + int 3 → int 5
    double2.2 + 3.3double 2.2 + double 3.3 → double 5.5
    mix2 + 3.3int 2 + double 3.3 → double 2.0 + double 3.3 → double 5.3
    int1 / 2int 1 / int 2 → int 0
    double1.0 / 2.0double 1.0 / double 2.0 → double 0.5
    mix1 / 2.0int 1 / double 2.0 → double 1.0 + double 2.0 → double 0.5
    Example
    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 #include <iostream> #include <iomanip> using namespace std; int main() { int i1 = 2, i2 = 4; double d1 = 2.5, d2 = 5.0; cout << fixed << setprecision(1); cout << i1 << " + " << i2 << " = " << i1+i2 << endl; cout << d1 << " + " << d2 << " = " << d1+d2 << endl; cout << i1 << " + " << d2 << " = " << i1+d2 << endl; cout << i1 << " - " << i2 << " = " << i1-i2 << endl; cout << d1 << " - " << d2 << " = " << d1-d2 << endl; cout << i1 << " - " << d2 << " = " << i1-d2 << endl; cout << i1 << " * " << i2 << " = " << i1*i2 << endl; cout << d1 << " * " << d2 << " = " << d1*d2 << endl; cout << i1 << " * " << d2 << " = " << i1*d2 << endl; cout << i1 << " / " << i2 << " = " << i1/i2 << endl; cout << d1 << " / " << d2 << " = " << d1/d2 << endl; cout << i1 << " / " << d2 << " = " << i1/d2 << endl; return 0; }

    Overflow/UnderFlow

    Study the output of the following program:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <iostream> using namespace std; int main() { int i1 = 2147483647; cout << i1 + 1 << endl; cout << i1 + 2 << endl; cout << i1 * i1 << endl; int i2 = -2147483648; cout << i2 - 1 << endl; cout << i2 - 2 << endl; cout << i2 * i2 << endl; return 0; }

    In arithmetic operations, the resultant value wraps around if it exceeds its range (i.e., overflow or underflow). C++ runtime does not issue an error/warning message but produces incorrect result.

    It is important to take note that checking of overflow/underflow is the programmer's responsibility, i.e., your job!

    This feature is an legacy design, where processors were slow. Checking for overflow/underflow consumes computation power and reduces performance.

    To check for arithmetic overflow (known as secure coding) is tedious. Google for "INT32-C. Ensure that operations on signed integers do not result in overflow" @ www.securecoding.cert.org.

    Compound Assignment Operators

    Besides the usual simple assignment operator described earlier, C++ also provides the so-called compound assignment operators as listed:

    OperatorUsageDescriptionExample
    =var = exprAssign the value of the LHS to the variable at the RHSx = 5;
    +=var += exprsame as var = var + exprx += 5; same as x = x + 5
    -=var -= exprsame as var = var - exprx -= 5; same as x = x - 5
    *=var *= exprsame as var = var * exprx *= 5; same as x = x * 5
    /=var /= exprsame as var = var / exprx /= 5; same as x = x / 5
    %=var %= exprsame as var = var % exprx %= 5; same as x = x % 5

    Increment/Decrement Operators

    C++ supports these unary arithmetic operators: increment and decrement .

    OperatorExampleResult
    ++x++; ++xIncrement by 1, same as x += 1
    --x--; --xDecrement by 1, same as x -= 1

    For example,

    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 #include <iostream> using namespace std; int main() { int mark = 76; cout << mark << endl; mark++; cout << mark << endl; ++mark; cout << mark << endl; mark = mark + 1; cout << mark << endl; mark--; cout << mark << endl; --mark; cout << mark << endl; mark = mark - 1; cout << mark << endl; return 0; }

    The increment/decrement unary operator can be placed before the operand (prefix operator), or after the operands (postfix operator). They takes on different meaning in operations.

    OperatorDescriptionExampleResult
    ++varPre-Increment
    Increment var, then use the new value of var
    y = ++x;same as x=x+1; y=x;
    var++Post-Increment
    Use the old value of var, then increment var
    y = x++;same as oldX=x; x=x+1; y=oldX;
    --varPre-Decrementy = --x;same as x=x-1; y=x;
    var--Post-Decrementy = x--;same as oldX=x; x=x-1; y=oldX;

    If '++' or '--' involves another operation, then pre- or post-order is important to specify the order of the two operations. For examples,

    x = 5; cout << x++ << endl; x = 5; cout << ++x << endl;

    Prefix operator (e.g, ) could be more efficient than postfix operator (e.g., ) in some situations.

    Implicit Type-Conversion vs. Explicit Type-Casting

    Converting a value from one type to another type is called type casting (or type conversion). There are two kinds of type casting:

    1. Implicit type-conversion performed by the compiler automatically, and
    2. Explicit type-casting via an unary type-casting operator in the form of or .
    Implicit (Automatic) Type Conversion

    When you assign a value of a fundamental (built-in) type to a variable of another fundamental type, C++ automatically converts the value to the receiving type, if the two types are compatible. For examples,

    • If you assign an value to a variable, the compiler automatically casts the value to a double (e.g., from 1 to 1.0) and assigns it to the variable.
    • if you assign a value of to an variable, the compiler automatically casts the value to an value (e.g., from 1.2 to 1) and assigns it to the variable. The fractional part would be truncated and lost. Some compilers issue a warning/error "possible loss in precision"; others do not.
    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 #include <iostream> #include <iomanip> using namespace std; int main() { int i; double d; cout << fixed << setprecision(1); i = 3; d = i; cout << "d = " << d << endl; d = 5.5; i = d; cout << "i = " << i << endl; i = 6.6; cout << "i = " << i << endl; }

    C++ will not perform automatic type conversion, if the two types are not compatible.

    Explicit Type-Casting

    You can explicitly perform type-casting via the so-called unary type-casting operator in the form of or . The type-casting operator takes one operand in the particular type, and returns an equivalent value in the new type. Take note that it is an operation that yields a resultant value, similar to an addition operation although addition involves two operands. For example,

    cout << fixed << setprecision(1); cout << (double)5 << endl; cout << (int)5.5 << endl; double aDouble = 5.6; int anInt = (int)aDouble; cout << double(5) << endl; cout << int(5.5) << endl; cout << int(aDouble) << endl;

    Example: Suppose that you want to find the average (in ) of the integers between and . Study the following codes:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <iostream> #include <iomanip> using namespace std; int main() { int sum = 0; double average; for (int number = 1; number <= 100; ++number) { sum += number; } average = sum / 100; cout << fixed << setprecision(1); cout << "Average is " << average << endl; return 0; }

    You don't get the fractional part although the is a . This is because both the and are . The result of division is an , which is then implicitly casted to and assign to the variable . To get the correct answer, you can do either:

    average = (double)sum / 100; average = sum / (double)100; average = sum / 100.0; average = (double)(sum / 100); average = double(sum) / 100;

    Example:

    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 <iostream> #include <iomanip> using namespace std; int main() { cout << fixed << setprecision(1); int i1 = 4, i2 = 8; cout << i1 / i2 << endl; cout << (double)i1 / i2 << endl; cout << i1 / (double)i2 << endl; cout << (double)(i1 / i2) << endl; double d1 = 5.5, d2 = 6.6; cout << (int)d1 / i2 << endl; cout << (int)(d1 / i2) << endl; d1 = i1; cout << d1 << endl; i2 = d2; cout << i2 << endl; }

    Example:

    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 #include <iostream> #include <iomanip> using namespace std; int main() { double celsius, fahrenheit; cout << fixed << setprecision(2); cout << "Enter the temperature in celsius: "; cin >> celsius; fahrenheit = celsius*9/5 + 32; cout << celsius << "C is " << fahrenheit << "F" << endl; cout << "Enter the temperature in fahrenheit: "; cin >> fahrenheit; celsius = (fahrenheit - 32)*5/9; cout << fahrenheit << "F is " << celsius << "C" << endl; return 0; }
    *Operator static-cast<type>

    C++ introduces a new operator called to perform type conversion (because the regular cast mentioned earlier is too lax and could produce expected results). signal an error if conversion fails. For example,

    double d = 5.5; int i = static_cast<int>(d); float f = static_cast<float>(i); long l = static_cast<logn>(d);

    Relational and Logical Operators

    Very often, you need to compare two values before deciding on the action to be taken, e.g., if mark is more than or equal to 50, print "PASS".

    C++ provides six comparison operators (or relational operators):

    OperatorDescriptionUsageExample (x=5, y=8)
    ==Equal toexpr1 == expr2(x == y) → false
    !=Not Equal toexpr1 != expr2(x != y) → true
    >Greater thanexpr1 > expr2(x > y) → false
    >=Greater than or equal toexpr1 >= expr2(x >= 5) → true
    <Less thanexpr1 < expr2(y < 8) → false
    <=Less than or equal toexpr1 >= expr2(y <= 8) → true

    In C++, these comparison operations returns a value of either (0) or (1 or a non-zero value).

    Each comparison operation involves two operands, e.g., . It is invalid to write in programming. Instead, you need to break out the two comparison operations , , and join with with a logical AND operator, i.e., , where denotes AND operator.

    C++ provides four logical operators (which operate on operands only):

    OperatorDescriptionUsage
    &&Logical ANDexpr1 && expr2
    ||Logical ORexpr1 || expr2
    !Logical NOT!expr
    ^Logical XORexpr1 ^ expr2

    The truth tables are as follows:

    AND (&&)truefalse
    true
    false
    OR (||)truefalse
    true
    false
    XOR (^)truefalse
    true
    false

    Example:

    (x >= 0) && (x <= 100)   (x < 0) || (x > 100) !((x >= 0) && (x <= 100))   ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

    Exercise: Given the year, month (1-12), and day (1-31), write a boolean expression which returns true for dates before October 15, 1582 (Gregorian calendar cut over date).

    Ans:

    Flow Control

    There are three basic flow control constructs - sequential, conditional (or decision), and loop (or iteration), as illustrated below.

    Sequential Flow Control

    A program is a sequence of instructions. Sequential flow is the most common and straight-forward, where programming statements are executed in the order that they are written - from top to bottom in a sequential manner.

    Conditional (Decision) Flow Control

    There are a few types of conditionals, if-then, if-then-else, nested-if (if-elseif-elseif-...-else), switch-case, and conditional expression.

    "switch-case" is an alternative to the "nested-if". In a switch-case statement, a statement is needed for each of the cases. If is missing, execution will flow through the following case. You can use either an or variable as the case-selector.

    Conditional Operator: A conditional operator is a ternary (3-operand) operator, in the form of . Depending on the , it evaluates and returns the value of or .

    SyntaxExample
    booleanExpr?trueExpr:falseExprcout << (mark >= 50) ? "PASS" : "FAIL" << endl; max = (a > b) ? a : b; abs = (a > 0) ? a : -a;

    Braces: You could omit the braces , if there is only one statement inside the block. For example,

    if (mark >= 50) cout << "PASS" << endl; else { cout << "FAIL" << endl; cout << "Try Harder!" << endl; }

    However, I recommend that you keep the braces, even though there is only one statement in the block, to improve the readability of your program.

    Exercises

    [TODO]

    Loop Flow Control

    Again, there are a few types of loops: for-loop, while-do, and do-while.

    SyntaxExampleFlowchart
    for (init;test;post-proc) {body;} int sum = 0; for (int number = 1; number <= 1000; ++number) { sum += number; }
    while (condition) {body; }  int sum = 0, number = 1; while (number <= 1000) { sum += number; ++number; }
    do {body; } while (condition) ;int sum = 0, number = 1; do { sum += number; ++number; } while (number <= 1000);

    The difference between while-do and do-while lies in the order of the body and condition. In while-do, the condition is tested first. The body will be executed if the condition is true and the process repeats. In do-while, the body is executed and then the condition is tested. Take note that the body of do-while will be executed at least once (vs. possibly zero for while-do).

    Suppose that your program prompts user for a number between to , and checks for valid input, do-while with a boolean flag could be more appropriate.

    bool valid = false; int number; do { ...... if (number >=1 && number <= 10) { valid = true; } } while (!valid);

    Below is an example of using while-do:

    bool gameOver = false; while (!gameOver) { ...... ...... }

    Example (Counter-Controlled Loop): Prompt user for an upperbound. Sum the integers from 1 to a given upperbound and compute its average.

    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 #include <iostream> using namespace std; int main() { int sum = 0; int upperbound; cout << "Enter the upperbound: "; cin >> upperbound; for (int number = 1; number <= upperbound; ++number) { sum += number; } cout << "Sum is " << sum << endl; cout << "Average is " << (double)sum / upperbound << endl; int count = 0; sum = 0; for (int number=1; number <= upperbound; number=number+2) { ++count; sum += number; } cout << "Sum of odd numbers is " << sum << endl; cout << "Average is " << (double)sum / count << endl; }

    Example (Sentinel-Controlled Loop): Prompt user for positive integers, and display the count, maximum, minimum and average. Terminate when user enters -1.

    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 32 33 34 35 36 37 38 39 40 41 #include <iostream> #include <climits> #include <iomanip> using namespace std; int main() { int numberIn; int count = 0; int sum = 0; int max = 0;
    Categories: 1

    0 Replies to “Pnge 200 Homework 3-4”

    Leave a comment

    L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *