Download Chapter 15: Programming II

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Connecting with Computer
Science, 2e
Chapter 15
Programming II
Objectives
• In this chapter you will:
– Gain an understanding of the basics of high-level
programming languages, using Java and C++ as
examples
– Learn about variable types in Java and C++ and how
they’re used
– Explore the different control structures in Java and
C++
2
Why You Need to Know About...
Programming Languages
• Time, money, and effort go into learning computer
programming languages
– The only real way to learn is practice, practice, and
more practice
• After reading this chapter, you must sit down at the
computer and practice the concepts frequently
3
Java and C++ Programming
Languages
• Criteria for choosing a programming language:
–
–
–
–
Tasks to perform
Programmer’s skill level
Program’s lifetime
Software complexity being designed
• C++ and Java characteristics
–
–
–
–
Support an object-oriented environment
Usable on different operating systems
Provide strong foundation for learning how to program
Provide a springboard to other languages
4
Learning to Cook with Java and C++
• Four ingredients to write programs:
–
–
–
–
Variables
Operators
Control structures
Objects
• Java and C++ high-level programming languages
provide computer interaction
– Without speaking in binary 1s and 0s
5
Learning to Cook with Java and C++
• Java history:
– Designed for Internet use
– Introduced by Sun Microsystems in 1995
– Intended for small tasks or small applications (i.e.,
“applets”)
• No need to write entire programs
– Developed into full-blown programming language
• Language of choice to develop communication
devices and media applications (e.g., PDAs, cell
phones, Internet, and networks)
6
Learning to Cook with Java and C++
• Java’s advantages:
– Uses familiar syntax
– Very portable
– Powerful and popular
• C++ history:
–
–
–
–
Created by Bjarne Stroustrup at Bell Labs in 1983
Based on C with added features
Added “object-oriented programming” language
Offers simplified memory management and access
to low-level memory
7
Variables
• Have specific effects on a program’s outcome
• Must have an identifier or name prior to use
• Declaration: statement associating an identifier with
a variable, an action, or another programming
element
– When declared, you specify attributes:
• Identifier (name)
• Type (character, numeric, Boolean, and so forth)
• Content
– Example: int numTicketsBought;
8
Variable Naming Conventions
• Rules for declaring a variable in Java or C++
– Use only letters, underscores, numbers
– Begin name with a letter
– Avoid Java and C++ reserved words
• Reserved word
– Keyword with a specific instructional meaning
• Name cannot be used for a variable
• Programming language already using it as an
instruction
9
Variable Types
• Java and C++ are strongly typed
– Must declare type of data a variable can hold
• Major Java data types:
– Six number-related data types
– One character related
– One for true and false (Boolean)
• Major C++ data types
– Adds a type for signed or unsigned numbers
• Syntax for declaring a variable:
type variableName;
10
Integer Data Types
• Used for positive and negative whole numbers
– Java example
• int studentTickets;
• float studentFees;
• double studentTuition;
• byte studentGrade;
– C++ example
• int studentTickets;
• float studentFees;
• unsigned int totalPoints;
11
Integer Data Types
Table 15-1, Java integer data types
Table 15-2, C++ integer data types
12
Floating-Point Data Types
• Used for positive and negative numbers containing
decimals
– Examples of declaring variables in both languages:
• float salary;
• double billGatesSalary;
13
Floating-Point Data Types
Table 15-3, Java floating-point data types
Table 15-4, C++ floating-point data types
14
Character Data Type
• Used for variables holding only one character
– Example: char studentMiddleInit;
Table 15-5, Java character data type
Table 15-6, C++ character data types
15
Boolean Data Type
• Used for only one of two values: true or false
• Java and C++
– Cannot associate a number with a Boolean value
– Rely on “true” or “false”
• Java Boolean variable declaration:
– boolean deserveRaise;
• C++ Boolean variable declaration:
– bool deserveRaise;
16
Boolean Data Type
Table 15-8, C++ Boolean data type
Table 15-7, Java Boolean data type
17
String Data Type
• Stores a piece of information
– Not a number
– Contains more than one character
– Terminates with a null character ( ‘\0’ )
• Declared using double quotes
• Uses the String or string keywords
– Examples of an empty string:
• String sName; //Java String
• string sName; //C++ string
18
String Data Type
• Examples of a string with contents assigned:
– String sName = "Joe Blow"; //Java
– string sName = "Joe Blow"; //C++
• Concatenation operator
– The (+) operator
– Process of combining or joining strings into one value
19
Hungarian Notation
• Variable-naming method
– Adds a letter at the beginning of a variable name
• Indicates data type
Table 15-9, Hungarian notation examples
20
Variable Content
• When variable is declared:
– Use an equal sign (=) to assign a value immediately
• Variable initialization: supplying value when variable is first
declared
• Do not always have to initialize a variable
– Programming language may assign a default value
– Example:
• int iStudentCount;
• iStudentCount = 456;
– Could also be written as:
• int iStudentCount = 456;
21
Variable Content
• Assigning a value to a character variable
– Enclose in single quotes
– Example:
• char cMiddleInit;
• cMiddleInit = 'S';
– Alternative:
• char cMiddleInit = 'S';
22
Variable Content
• Assigning a value to a string variable
– Enclose in double quotes
– Example:
• String sMiddleName = "S"; //Java
• string sMiddleName = "S"; //C++
23
Java and C++ Control Structures
and Program Flow
• Four types of control structures:
–
–
–
–
Invocation
Top down
Selection
Repetition
• Correct use allows for a(n):
– Readable program
– Easy to maintain program
24
Invocation
• The main() function block of code
– Tells operating system the starting point
• Function: block of code performing a task
– Can return a value
• Example: Save_Ferris.java file
1
2
3
4
5
6
7
public class Save_Ferris
{
public static void main(String[] args)
{
System.out.println("I could have been the Walrus!");
}
}
25
Invocation
• Parameters: received value assigned to a variable
– Used by a block of source code
• Passing parameters as values
– Enter them on same line
• After Java program name
– Example: C:\>hello 10
• C++ has a main() function in every program
– Software engineers often include other files of
source code to perform common task
26
Invocation
• C++ allows words inside parentheses
– Indicates parameters receiving data when the
program runs
• Parameters allow users to pass data to main() and
then use the data in the program
– Examples:
• //C++ main receiving parameters
• int main(int argc, char *argv[])
27
Top Down ( or Sequence )
• Used when program statements executed in
sequential order
– Starting at the top and working down to the bottom
28
Blocks of Code
• Sequence of several statements enclosed with
opening and closing braces
– Indicates a relation
– Makes program more readable and accurate
– Braces are used most often when working with
invocation, selection, repetition control structures
• Example:
29
Java Output Data
• Java System.out statement sends data to output
device
• Insertion point: where the cursor is placed
– Two methods to output data:
• System.out.print(expression);
• System.out.println(expression);
30
Java Output Data
Table 15-10 Java output statements
31
C++ Output Data
• C++ cout statement
– Sends data to output device
– Uses redirection symbols (<<) to direct output
– Example:
• cout << "15 + 10 = " << iResult <<endl;
• Instructs compiler to direct anything following the
<< symbols to the defined output device
32
C++ Output Data
Table 15-11, Sample C++ output statements
33
Input Data
• Java System.in
– Method to retrieve data from the input device
– Must create a new variable from the Scanner class
• Reads characters from input stream (keyboard)
• Places them into another variable acting as a memory
buffer for storing the entered string
– Input assigned to a string variable declared by
making a call to the next() method
• C++ cin >> someData;
– Used to retrieve data from input device
34
Back to Control Structures
• Java and C++ invocation
– Implemented by calling functions and methods
– Function: performs a task, can return a value
– Method: function belonging to a class
• Java equals() method
– System passes control to code associated with
equals()
– Carries out the statements
– Makes the comparison
– Returns a Boolean value
35
Selection
• First write algorithm with pseudocode
– Ensures program meets language requirements
– Guide or template for writing source code
• Recall Chapter 14 algorithm converting Celsius to
Fahrenheit temperatures and vice versa
• See corresponding code on pages 531–533
36
if and if-else Statements
• Used to weigh results of decision making
– Result exists for every choice
• Syntax:
if (condition)
{
one or more statements;
}
37
if and if-else Statements
• Condition
– Expression returning true or false value
– May add an else part to the control structure
• Performs a function if the if control structure evaluates
to a false value
• Syntax:
if (condition)
{
one or more statements;
}
else
{
one or more statements;
}
38
if-else-if Statement
• Corrects problem in if-else statement
– User enters incorrect input value
• Allows certain blocks of code to execute
– Depends on variable’s state in the program while it is
running
– Easy to use
– Makes program more flexible
39
switch Statement
• Nesting
– Putting one control structure inside another
• Decreases code’s readability
• switch statement:
– Allows testing of many options
– Groups blocks of code to be executed depending on
results
– Test expression’s value
• Jump to some location in the switch statement
• Expression must be a scalar data type
40
switch Statement
• break statement at end of
each case
– Informs system to quit
processing case
statements
– Sends control to end of the
switch statement
• Syntax:
switch (expression)
{
case value_1:
statement_1;
break;
case value_2:
statement_2;
break;
case value_3:
statement_3;
break;
default:
statement_4;
break;
}
41
Repetition ( Looping )
• Allows repeating statements multiple times
– No statement retyping
• Three statements:
– for
– while
– do-while
42
for Statement
• Used to repeat a group of statements a known
number of times
• Variable declaration
– Declare and initialize a variable
– Declare counter variable
• Example: int iCount
• Syntax:
for (variable declaration; expression; increment/decrement)
{
statement(s);
}
43
while Statement
• Processes a group of statements a certain number
of times
– Like the for loop
• Precondition loop
– Loop checks the expression before any source code
in the loop is executed
• Might never be executed
– Difference between for and while loops
• while statement doesn’t provide a specified area for
updating the counter
44
while Statement
• Syntax:
while (expression)
{
statements;
}
45
do-while Statement
• Used when looping is based on an expression and
statements are repeated before the expression is
evaluated
– Mainly when processing a table
• Postcondition loop
– Executes at least one time before the expression is
evaluated
• Syntax:
do
{
statement(s);
} while (expression);
46
One Last Thought
• Most programming languages use the four major
control structures discussed in this chapter
• Organizations select a programming language
based on application’s needs
• Programmers may need to update skills
– C++ and Java is a good start
– Must practice to become proficient
• Software engineers’ responsibility: write easy-toread and easy-to-maintain structured programs
47
Summary
• Java: high-level programming language designed
for the Internet
• C++: high-level programming language based on
the C language
– Incorporates object-oriented principles
• Variables:
– Integer (int), character (char), floating point,
Boolean, and string
– “Initializing a variable”: assigning a value to a
variable
48
Summary
• Four high-level programming language control
structures:
– Invocation, top down, selection, repetition
• Java uses methods for the invocation
• C++ uses methods and functions
• Output data:
– Java uses the System.out statement
– C++ use the cout statement with the << redirection
symbols
49
Summary
• Input data:
– Java Scanner class gathers input
– C++ uses the cin statement
• Selection control structures:
– C++ and Java use if, if-else, if-else-if,
switch
• switch statement is used only with scalar variables
• Repetition:
– C++ and Java use for, while, do-while loops
• Practice, practice, and more practice
50
The End
51