basic elements

53
Basic Elements Basic Elements Skill Area 313 Part B Skill Area 313 Part B

Upload: dixie

Post on 12-Jan-2016

27 views

Category:

Documents


0 download

DESCRIPTION

Materials Prepared by Dhimas Ruswanto , BMm. Basic Elements. Skill Area 313 Part B. Lecture Overview. Basic Input/Output Statements Whitespaces Expression Operators IF Statements Logical Operators. Basic Input/Output. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Basic Elements

Basic ElementsBasic ElementsSkill Area 313 Part BSkill Area 313 Part B

Page 2: Basic Elements

Lecture Overview

• Basic Input/Output• Statements• Whitespaces• Expression• Operators• IF Statements• Logical Operators

Page 3: Basic Elements

Basic Input/Output

• Using the standard input and output library, we will be able to interact with the user by printing messages on the screen and getting the user's input from the keyboard.

• C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen or the keyboard

Page 4: Basic Elements

Basic Input/Output

• A stream is an object where a program can either insert or extract characters to/from it.

• The standard C++ library includes the header file iostream, where the standard input and output stream objects are declared.

Page 5: Basic Elements

Standard Output (cout)

• By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout.

• cout  is used in conjunction with the insertion operator, which is written as << (two "less than" signs).

Page 6: Basic Elements

Standard Output (cout)

cout << "Output sentence"; // prints Output sentence on screen

cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen

• The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output streamcout

• Notice that the sentence in the first instruction is enclosed between double quotes (") because it is a constant string of characters

Page 7: Basic Elements

Standard Output (cout)

cout << "Hello"; // prints Hello cout << Hello; // prints the content of Hello

variable

• Whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can be clearly distinguished from variable names.

• these two sentences have very different results

Page 8: Basic Elements

Standard Output (cout)

• The insertion operator (<<) may be used more than once in a single statement:

cout << "Hello, " << "I am " << "a C++ statement";

• This last statement would print the message Hello, I am a C++ statement on the screen.

Page 9: Basic Elements

Standard Output (cout)

• The utility of repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables and constants or more than one variable:

cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;

• If we assume the age variable to contain the value 24 and the zipcode variable to contain 90064 the output of the previous statement would be: 

• Hello, I am 24 years old and my zipcode is 90064

Page 10: Basic Elements

Standard Output (cout)

• It is important to notice that cout does not add a line break after its output unless we explicitly indicate it, therefore, the following statements:

cout << "This is a sentence."; cout << "This is another sentence.";

• will be shown on the screen one following the other without any line break between them:

This is a sentence.This is another sentence. 

Page 11: Basic Elements

Standard Output (cout)

• even though we had written them in two different insertions into cout. In order to perform a line break on the output we must explicitly insert a new-line character into cout.

• In C++ a new-line character can be specified as \n (backslash, n):

cout << "First sentence.\n"; cout << "Second sentence.\nThird sentence.";

• This produces the following output: 

First sentence.Second sentence.Third sentence.

Page 12: Basic Elements

Standard Output (cout)

• Additionally, to add a new-line, you may also use the endl manipulator.

• For example: 

cout << "First sentence." << endl; cout << "Second sentence." << endl;

would print out: 

First sentence.Second sentence. 

Page 13: Basic Elements

Standard Input (cin)

• The standard input device is usually the keyboard. • Handling the standard input in C++ is done by applying the

overloaded operator of extraction (>>) on the cin stream. • The operator must be followed by the variable that will store

the data that is going to be extracted from the stream

int age; cin >> age;

• The first statement declares a variable of type int called age, and the second one waits for an input from cin(the keyboard) in order to store it in this integer variable.

Page 14: Basic Elements

Standard Input (cin)

• cin can only process the input from the keyboard once the RETURN key has been pressed.

• Therefore, even if you request a single character, the extraction from cin will not process the input until the user presses RETURNafter the character has been introduced.

• You must always consider the type of the variable that you are using as a container with cin extractions. I– if you request an integer you will get an integer, – if you request a character you will get a character and – if you request a string of characters you will get a string of

characters. 

Page 15: Basic Elements

Standard Input (cin)

// i/o example #include <iostream> using namespace std; int main () {

int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0;

}

Page 16: Basic Elements

Standard Input (cin)• You can also use cin to request more than one data input from

the user: 

cin >> a >> b;

• is equivalent to:

cin >> a;cin >> b;

• In both cases the user must give two data, one for variable a and another one for variable b that may be separated by any valid blank separator: a space, a tab character or a newline.

Page 17: Basic Elements

Statements

• In C++ a statement controls the sequence of execution, evaluates an expression, or does nothing (the null statement).

• All C++ statements end with a semicolon, even the null statement, which is just the semicolon and nothing else.

• A null statement is a statement that does nothing.

Page 18: Basic Elements

Statements

• One of the most common statements is the following assignment statement:

x = a + b;

• Unlike in algebra, this statement does not mean that x equals a+b.

• This is read, "Assign the value of the sum of a and b to x," or "Assign to x, a+b."

• Even though this statement is doing two things, it is one statement and thus has one semicolon.

• The assignment operator assigns whatever is on the right side of the equal sign to whatever is on the left side.

Page 19: Basic Elements

Whitespace• Whitespace (tabs, spaces, and newlines) is generally

ignored in statements. • The assignment statement previously discussed could be

written asx=a+b; or asx =a + b ;

• Whitespace can be used to make your programs more readable and easier to maintain, or it can be used to create horrific and indecipherable code

• Whitespace characters (spaces, tabs, and newlines) cannot be seen.

• If these characters are printed, you see only the white of the paper.

Page 20: Basic Elements

Blocks and Compound Statements

• Any place you can put a single statement, you can put a compound statement, also called a block.

• A block begins with an opening brace ({) and ends with a closing brace (}).

• Although every statement in the block must end with a semicolon, the block itself does not end with a semicolon. For example

{ temp = a; a = b;

b = temp; }• This block of code acts as one statement and swaps the

values in the variables a and b.

Page 21: Basic Elements

DO

DO use a closing brace any time you have an opening brace. 

DO end your statements with a semicolon. DO use whitespace judiciously to make

your code clearer.

Page 22: Basic Elements

Expressions

• Anything that evaluates to a value is an expression in C++. An expression is said to return a value.

• Thus, 3+2; returns the value 5 and so is an expression.• All expressions are statements.

x = a + b;

• Not only adds a and b and assigns the result to x, but returns the value of that assignment (the value of x) as well.

• Thus, this statement is also an expression. • Because it is an expression, it can be on the right side

of an assignment operator:

Page 23: Basic Elements

Expressions

y = x = a + b;

• This line is evaluated in the following order: – Add a to b.– Assign the result of the expression a + b to x.– Assign the result of the assignment expression x

= a + b to y.– If a, b, x, and y are all integers, and if a has the

value 2 and b has the value 5, both x and y will be assigned the value 7.

Page 24: Basic Elements

Expressions

int main() {

int a=0, b=0, x=0, y=35; cout << "a: " << a << " b: " << b; cout << " x: " << x << " y: " << y << endl; a = 9; b = 7; y = x = a+b; cout << "a: " << a << " b: " << b; cout << " x: " << x << " y: " << y << endl; return 0;

}

Page 25: Basic Elements

Operators

• An operator is a symbol that causes the compiler to take an action.

• Operators act on operands, and in C++ all operands are expressions.

• In C++ there are several different categories of operators.

• Two of these categories are:– Assignment operators.– Mathematical operators.

Page 26: Basic Elements

Assignment Operators

• The assignment operator (=) causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator.

x = a + b;– Assigns the value that is the result of adding a and b to the

operand x.

• An operand that legally can be on the left side of an assignment operator is called an lvalue.

• That which can be on the right side is called an rvalue.• Constants are r-values. They cannot be l-values. Thus,

you can writex = 35; // ok35 = x; // error, not an lvalue!

Page 27: Basic Elements

Assignment Operators

• An lvalue is an operand that can be on the left side of an expression.

• An rvalue is an operand that can be on the right side of an expression.

• Note that all l-values are r-values, but not all r-values are l-values.

• An example of an rvalue that is not an lvalue is a literal.

• Thus, you can write x = 5;, but you cannot write 5 = x;.

Page 28: Basic Elements

Mathematical Operators

• There are five mathematical operators: – addition (+)– subtraction (-)– multiplication (*)– division (/) – modulus (%).

• subtraction with unsigned integers can lead to surprising results, if the result is a negative number

Page 29: Basic Elements

Mathematical Operators

int main() {

unsigned int difference; unsigned int bigNumber = 100; unsigned int smallNumber = 50; difference = bigNumber - smallNumber; cout << "Difference is: " << difference; difference = smallNumber - bigNumber; cout << "\nNow difference is: " << difference

<<endl; return 0;

}

Page 30: Basic Elements

Combining Assignment & Mathematical Operators

• If you have a variable myAge and you want to increase the value by two, you can write:

int myAge = 5; int temp; temp = myAge + 2; // add 5 + 2 and put it in tempmyAge = temp; // put it back in myAge

• In C++, you can put the same variable on both sides of the assignment operator, and thus the preceding becomes

myAge = myAge + 2;– add two to the value in myAge and assign the result

to myAge."

Page 31: Basic Elements

Combining Assignment & Mathematical Combining Assignment & Mathematical OperatorsOperators

• Even simpler to write, but perhaps a bit harder to read ismyAge += 2;

• The self-assigned addition operator (+=) adds the rvalue to the lvalue and then reassigns the result into the lvalue.

• This operator is pronounced "plus-equals." • The statement would be read "myAge plus-equals two." • If myAge had the value 4 to start, it would have 6 after

this statement.

• There are self-assigned subtraction (-=), division (/=), multiplication (*=), and modulus (%=) operators as well.

Page 32: Basic Elements

Increment and Decrement

• In C++, increasing a value by 1 is called incrementing, and decreasing by 1 is called decrementing

• The increment operator (++) increases the value of the variable by 1, and the decrement operator (--) decreases it by 1.

• Thus, if you have a variable, C, and you want to increment it, you would use this statement:C++; // Start with C and increment it.

• This statement is equivalent to the more verbose statementC = C + 1;

• which you learned is also equivalent to the statement:C += 1;

Page 33: Basic Elements

Prefix and Postfix

• Both the increment operator (++) and the decrement operator(--) come in two varieties: prefix and postfix.

• The prefix variety is written before the variable name (++myAge); the postfix variety is written after (myAge++).

• The prefix operator is evaluated before the assignment, the postfix is evaluated after.

• The semantics of prefix is this: Increment the value and then fetch it.

• The semantics of postfix is different: Fetch the value and then increment the original.

Page 34: Basic Elements

Prefix and Postfixint main() {

int myAge = 39; // initialize two integers int yourAge = 39; cout << "I am: " << myAge << " years old.\n"; cout << "You are: " << yourAge << " years old\n"; myAge++; // postfix increment ++yourAge; // prefix increment cout << "One year passes...\n"; cout << "I am: " << myAge << " years old.\n"; cout << "You are: " << yourAge << " years old\n"; cout << "Another year passes\n"; cout << "I am: " << myAge++ << " years old.\n"; cout << "You are: " << ++yourAge << " years old\n"; cout << "Let's print it again.\n"; cout << "I am: " << myAge << " years old.\n"; cout << "You are: " << yourAge << " years old\n"; return 0;

}

Page 35: Basic Elements

Relational Operators• The relational operators are used to determine whether two

numbers are equal, or if one is greater or less than the other. Every relational statement evaluates to either 1 (TRUE) or 0 (FALSE).Name Operator Sampe Evaluates

Equals == 100 == 50; False

50 == 50; True

Not Equals != 100 != 50; True

50 != 50; False

Greater Than > 100 > 50; True

50>50; False

Greater Than or Equals

>= 100 >= 50; True

50 >= 50; True

Less Than < 100 < 50; False

50 < 50; False

Less Than or Equals

<= 100 <=50; False

50 <= 50; True

Page 36: Basic Elements

Do & Don’t

• DO remember that relational operators return the value 1 (true) or 0 (false). 

• DON'T confuse the assignment operator (=) with the equals relational operator (==). This is one of the most common C++ programming mistakes--be on guard for it.

Page 37: Basic Elements

The if Statement• Normally, your program flows along line by line in the

order in which it appears in your source code. • The if statement enables you to test for a condition (such

as whether two variables are equal) and branch to different parts of your code, depending on the result.

if (expression) statement;

• The expression in the parentheses can be any expression at all, but it usually contains one of the relational expressions.

• If the expression has the value 0, it is considered false, and the statement is skipped. If it has any nonzero value, it is considered true, and the statement is executed

Page 38: Basic Elements

The if Statement

• Consider the following example:if (bigNumber > smallNumber)

bigNumber = smallNumber;

• Because a block of statements surrounded by braces is exactly equivalent to a single statement, the following type of branch can be quite large and powerful:

if (expression) {

statement1; statement2; statement3;

}

Page 39: Basic Elements

The if Statement

if (bigNumber > smallNumber) {

bigNumber = smallNumber; cout << "bigNumber: " << bigNumber << "\n"; cout << "smallNumber: " << smallNumber << "\n";

}

• if bigNumber is larger than smallNumber, not only is it set to the value of smallNumber, but an informational message is printed

Page 40: Basic Elements

The if Statement

See -> ifelse.txt• The variables are compared in the if statement on

lines 15, 18, and 24.• If one score is higher than the other, an informational

message is printed. If the scores are equal, the block of code that begins on line 24 and ends on line 38 is entered.

• The second score is requested again, and then the scores are compared again.

• if the initial Yankees score was higher than the Red Sox score, the if statement on line 15 would evaluate as FALSE, and line 16 would not be invoked.

• The test on line 18 would evaluate as true, and the statements on lines 20 and 21 would be invoked.

Page 41: Basic Elements

The if Statement

• Then the if statement on line 24 would be tested, and this would be false (if line 18 was true).

• Thus, the program would skip the entire block, falling through to line 39.

• In this example, getting a true result in one if statement does not stop other if statements from being tested.

Page 42: Basic Elements

else

• Often your program will want to take one branch if your condition is true, another if it is false.

• The keyword else can make for far more readable code:

if (expression) statement;

else statement;

Page 43: Basic Elements

elseint main() {

int firstNumber, secondNumber; cout << "Please enter a big number: "; cin >> firstNumber; cout << "\nPlease enter a smaller number: "; cin >> secondNumber; if (firstNumber > secondNumber)

cout << "\nThanks!\n"; else

cout << "\nOops. The second is bigger!"; return 0;

}

Page 44: Basic Elements

The If statement

if (expression) statement1;

else statement2;

next statement;

• If the expression evaluates TRUE, statement1 is executed; otherwise, statement2 is executed.

• Afterwards, the program continues with the next statement.

if (SomeValue < 10) cout << "SomeValue is less than 10”;

else cout << "SomeValue is not less than 10!”;

cout << "Done." << endl;

Page 45: Basic Elements

Advanced If statementif (expression1) {

if (expression2) statement1;

else {

if (expression3) statement2; else statement3;

} } else

statement4;

Page 46: Basic Elements

Logical Operators

Operator Symbol

Example

AND && Expression1 && expression 2

OR || Expression1 || expression2

NOT ! !expression

•  To ask more than one relational question at a time

Page 47: Basic Elements

Logical AND

• A logical AND statement evaluates two expressions, and if both expressions are true, the logical AND statement is true as well

if ( (x == 5) && (y == 5) )

• valuate TRUE if both x and y are equal to 5, and it would evaluate FALSE if either one is not equal to 5.

• Note that both sides must be true for the entire expression to be true.

Page 48: Basic Elements

Logical OR

• A logical OR statement evaluates two expressions. If either one is true, the expression is true

if ( (x == 5) || (y == 5) )

• evaluates TRUE if either x or y is equal to 5, or if both are.

Page 49: Basic Elements

Logical NOT

• A logical NOT statement evaluates true if the expression being tested is false. Again, if the expression being tested is false, the value of the test is TRUE!

if ( !(x == 5) )

• is true only if x is not equal to 5. This is exactly the same as writing

if (x != 5)

Page 50: Basic Elements

Note

• It is often a good idea to use extra parentheses to clarify what you want to group.

• Remember, the goal is to write programs that work and that are easy to read and understand.

• DO use braces in nested if statements to make the else statements clearer and to avoid bugs.

Page 51: Basic Elements

Conditional (Tenary) Operator

• The conditional operator (?:) is C++'s only ternary operator; that is, it is the only operator to take three terms.

• The conditional operator takes three expressions and returns a value:

(expression1) ? (expression2) : (expression3)• "If expression1 is true, return the value of

expression2; otherwise, return the value of expression3."

• Typically, this value would be assigned to a variable.

Page 52: Basic Elements

Conditional (Tenary) Operator

z = (x > y) ? x : y;

• If x is greater than y, return the value of x; otherwise, return the value of y.

Page 53: Basic Elements

--- continue to next slide --- continue to next slide ------