1 / 53

Basic Elements

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.

dixie
Download Presentation

Basic Elements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Materials Prepared by DhimasRuswanto, BMm Basic Elements Skill Area 313 Part B

  2. Lecture Overview • Basic Input/Output • Statements • Whitespaces • Expression • Operators • IF Statements • Logical Operators

  3. 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

  4. 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.

  5. 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).

  6. 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

  7. 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

  8. 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.

  9. 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

  10. Standard Output (cout) • It is important to notice that coutdoes 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.

  11. 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.

  12. 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. 

  13. 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.

  14. 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. 

  15. 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; }

  16. 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.

  17. 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.

  18. 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.

  19. Whitespace • Whitespace (tabs, spaces, and newlines) is generally ignored in statements. • The assignment statement previously discussed could be written as x=a+b; or as x =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.

  20. 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.

  21. 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.

  22. 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:

  23. 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.

  24. 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; }

  25. 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.

  26. 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 write x = 35; // ok 35 = x; // error, not an lvalue!

  27. 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;.

  28. 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

  29. 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; }

  30. 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 temp myAge = 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."

  31. Combining Assignment & Mathematical Operators • Even simpler to write, but perhaps a bit harder to read is myAge += 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-assignedsubtraction (-=), division (/=), multiplication (*=), and modulus (%=) operators as well.

  32. 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 statement C = C + 1; • which you learned is also equivalent to the statement: C += 1;

  33. 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.

  34. Prefix and Postfix int 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; }

  35. 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).

  36. 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.

  37. 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

  38. 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; }

  39. 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

  40. 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.

  41. 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.

  42. 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;

  43. else int 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; }

  44. 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;

  45. Advanced If statement if (expression1) { if (expression2) statement1; else { if (expression3) statement2; else statement3; } } else statement4;

  46.  To ask more than one relational question at a time Logical Operators

  47. 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.

  48. 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.

  49. 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)

  50. 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.

More Related