0% found this document useful (0 votes)
71 views37 pages

CS205-2020 Spring - Lecture 5 PDF

This document discusses C/C++ programming concepts including loops, branching statements, and logical expressions. Loops allow repetitive tasks to be performed and include for, while, and do-while loops. Branching statements like if/else and switch allow programs to make decisions. Logical expressions use operators like &&, ||, and ! to combine conditional tests. The document also covers file input/output and summarizing key points.

Uploaded by

Eason Guan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views37 pages

CS205-2020 Spring - Lecture 5 PDF

This document discusses C/C++ programming concepts including loops, branching statements, and logical expressions. Loops allow repetitive tasks to be performed and include for, while, and do-while loops. Branching statements like if/else and switch allow programs to make decisions. Logical expressions use operators like &&, ||, and ! to combine conditional tests. The document also covers file input/output and summarizing key points.

Uploaded by

Eason Guan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

C/C++ Programming

Language
CS205 Spring
Feng Zheng
2020.03.19
Content
• Brief Review

• Loops

• Branching Statements

• Logical Expressions

• Summary
Brief Review
Content of Last Class
• Pointers
➢ Address of array
➢ new and delete operations

• Managing memory for data


➢ Automatic memory
➢ Dynamic memory
➢ Static memory
Review of The Address of an Array
• Address of an Array
➢ short tell[10];
➢ tell is type pointer-to-short
➢ &tell is type pointer-to-array of 10 shorts
➢ short (*pas)[10] = &tell;
➢ (*pas) = tell is type pointer-to-short
➢ pas = &tell is type pointer-to-array of 10 shorts
➢ short* pas[10];
➢ pas is an array of 10 pointers-to-short (short *)

➢&tell
Loops and Relational
Expressions
Introducing for Loops
• Why needs loop operations?
➢ Perform repetitive tasks
➢ Most tasks have the same process
• Parts of a for Loop
➢ Setting a value initially
➢ Testing whether the loop should
continue
➢ Executing the loop actions - body
➢ Updating value(s) used for the test
for (initialization; test-expression; update-expression)
body;
Introducing for Loops
• Loops
➢ The loop performs initialization just once
➢ Test expression is a relational expression
➢ Test expression is evaluated before each loop cycle
➢ Update expression is evaluated at the end of the loop
• See program example 1
➢ Increment operator: ++ operator (i = i + 1;)
• See program example 2
➢ Decrement operator: -- operator (i = i - 1;)
More Examples
• See program example 3
➢ Factorial definition
✓ Zero factorial, written as 0!, is defined to be 1 (exclamation marks!)
✓ The factorial of each integer being the product of that integer with the
preceding factorial
• See program example 4
➢ Changing the step size

• See program example 5


➢ The increment (++) and decrement (--) operators
Expressions
• A C++ expression is a value or a combination of values and
operators
• Every C++ expression has a value
➢ A for control section uses three expressions
➢ Relational expressions such as x < y evaluate to the bool values
➢ Evaluating the expression is the primary effect
✓ Evaluating x + 15 calculates a new value, but it doesn’t change the value of x
✓ But evaluating ++x + 15 does have a side effect because it involves
incrementing x
Statements
• Statements
➢ From expression to statement is a short step
➢ You just add a semicolon
➢ Declaration is not an expression
• Non-expressions and statements
➢ Removing a semicolon from a statement does not necessarily
convert it to an expression
✓ Return statements
✓ Declaration statements
✓ for statements int fx = for (i = 0; i< 4; i++)
cout >> i; // not possible
Side Effects and Sequence Points
• Side effect: occurs when evaluating an expression (primary
effect) modifies something
• Sequence point: a point which all side effects are
guaranteed to be evaluated before going on to the next step
• What’s a full expression?
➢ A test condition for a while loop
➢ An expression portion of an expression statement
• The end of any full expression is a sequence point
➢ Avoid statements of this kind
y = (4 + x++) + (6 + x++);
More for Increment/Decrement
Operators
• Prefixing versus postfixing: ++x, x++, --x, x--
➢ Prefix form is more efficient
• The increment/decrement operators and pointers
➢ Adding an increment operator to a pointer increases its value by
the number of bytes in the type it points to
➢ The prefix increment, prefix decrement, and dereferencing
operators have the same precedence (from right to left)
➢ Postfix increment and decrement operators have the same
precedence, which is higher than the prefix precedence(from left
to right)
• See program example 6
And More for Loops
• Combination assignment operators
➢ Example: combined addition and assignment operator

• Compound statements, or blocks: {}


➢ Program example 7
• More syntax tricks—the comma operator

Relational Expressions
• C++ provides six relational operators to compare numbers
➢ Exclamation mark
Comparisons in Test Expression
• Program example 8
➢ A mistake you’ll probably make
➢ = or ==
• Program example 9
➢ Comparing C-style strings
➢ strcmp(str1,str2)
• Program example 10
➢ Comparing string class strings
➢ Using relational symbol (!=)
The while Loop
• while is entry-condition loop
• It has just a test condition
and a body
➢ Do something to affect the
test-condition expression
• See Program example 11
➢ Two types of condition
expression
while (name[i] != '\0’)
while (name[i])
for Versus while
• In C++ the for and while loops are essentially equivalent
More Loops
• The do while Loop
➢ It’s an exit-condition loop
➢ Such a loop always executes at
least once
➢ See Program example 12
• The range-based for loop (C++11)
➢ See Program example 13
✓ Colon symbol :
✓ & symbol: reference variable
✓ To modify the array contents
Example: Loops and Text Input
• Using unadorned cin for input
➢ When to stop?
✓ A sentinel character
➢ See program example 14
✓ The program omit the spaces
✓ Program and operating system both work
• cin.get(char) to the rescue
➢ See program example 15
✓ Read the space
✓ Declare the argument as a reference
Example: Nested Loops and Two-
Dimensional Arrays
• Example:
int maxtemps[4][5];

• See program example 16


Branching Statements
The if Statement
• One of the keys to
designing intelligent
programs is to give them
the ability to make
decisions
➢ Looping
➢ if statement

• See program example 17


More than one selections
• The if else Statement
➢ Decide which of two
statements or blocks is
executed
➢ Must use braces to collect
statements into a single
block
➢ Remember the conditional
compilation #if, #else
• The if else if else Construction
• See program example 18
Logical Expressions
The Logical OR Operator: ||
• Three operators
➢ Logical OR, written ||
➢ Logical AND, written &&
➢ Logical NOT, written !

• The logical OR operator: ||


➢ || has a lower precedence than the
relational operators
➢ The || operator is a sequence point
➢ C++ won’t bother evaluating the bool a = 1,b=1;
expression on the right if the if (a||b++)
expression on the left is true {
}
AND Operator: &&
NOT Operator: !
• AND Operator
➢ Lower precedence than the relational
operators
➢ Acts as a sequence point
➢ C++ doesn’t bother evaluating the right
side in some cases
• See program example 19
• NOT Operator
➢ Exclamation point
➢ If expression is true, or nonzero,
then !expression is false
➢ If expression is false, then !expression is true
Logical Operator Facts
• Precedence
➢ The NOT(!) operator has a higher precedence than any of the relational
or arithmetic operators
➢ The AND operator has a higher precedence than the OR operator
➢ Use parentheses to tell the program the interpretation you want
NOT-----relational-----AND-----OR
• Alternative Representations

• The cctype library of character functions


• A handy package of character-related functions
The ?: Operator
• Conditional operator (question mark)
➢ More concise
The switch Statement
• Acts as a routing device that tells the computer which line
of code to execute next
• You must use the break

• See program example 20


More About switch
• Using enumerators as labels
➢ See program example 21

• switch and if else


➢ Let a program select from a list of alternatives
➢ A switch statement isn’t designed to handle ranges
➢ Each switch case label must be a single value
➢ Also that value must be an integer
➢ A switch statement can’t handle floating-point tests
The break and continue Statements
• The break and continue
statements enable a program
to skip over parts of the code
➢ break causes program execution
to pass to the next statement
following the switch or the loop
➢ continue statement is used in
loops and causes a program to
skip the rest of the body of the
loop and then start a new loop
cycle
• See program example 22
Example: Number-Reading Loops
• What happens if the user responds by entering a word
instead of a number?

• See program example 23


➢ The preceding example doesn’t attempt to read any input after
non-numeric input
• See program example 24
Simple File Output
• Main steps for using file output
➢ Include the fstream header file

➢ Create an ofstream object

➢ Associate the ofstream object with a file (C-style) using open()

➢ Use the ofstream object in the same manner you would use cout

➢ Use the close() method to close the file


• See program example 25
Simple File Input
• Main steps for using file input
➢ Include the fstream header file and account for the std
➢ Declare one or more ifstream variables, or objects
➢ Associate a ifstream object with a file using open()
➢ Use the close() method to close the file
➢ Use >> operator, get(), getline(), …… method
• See program example 26
➢ What happens if you attempt to open a non-existent file for input?
➢ exit(EXIT_FAILURE);
➢ Communicate with the operating system
➢ Terminate the program
Summary
• Loops
➢ Increment/decrement operators: ++; --
➢ Rational expressions: 6
➢ for, while, do while
• Branch statements
➢ if; if else; if else if else; switch
• The Logical Operator
➢ OR, AND, NOT
• Jump operations
➢ break and continue
• File fstream
➢ Simple File Output: ofstream
➢ Simple File Input: ifstream
Thanks

[email protected]

You might also like