Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
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++
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
5
Learning to Cook with Java and C++
(cont’d.)
• 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)
Connecting with Computer Science, 2e
6
Learning to Cook with Java and C++
(cont’d.)
• 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
Object-oriented programming language
Offers simplified memory management and access to
low-level memory
Connecting with Computer Science, 2e
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;
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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;
Connecting with Computer Science, 2e
10
Integer Data Types
• Used for positive and negative whole numbers
– Java example
• int studentTickets;
• short studentFees;
• long studentTuition;
• byte studentGrade;
– C++ example
• int studentTickets;
• short int studentFees;
• unsigned int totalPoints;
Connecting with Computer Science, 2e
11
Integer Data Types (cont’d.)
Table 15-1, Java integer data types
Table 15-2, C++ integer data types
Connecting with Computer Science, 2e
12
Floating-Point Data Types
• Used for positive and negative numbers containing
decimals
– Examples of declaring variables in both languages:
• float salary;
• double billGatesSalary;
Connecting with Computer Science, 2e
13
Floating-Point Data Types (cont’d.)
Table 15-3, Java floating-point data types
Table 15-4, C++ floating-point data types
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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;
Connecting with Computer Science, 2e
16
Boolean Data Type (cont’d.)
Table 15-8, C++ Boolean data type
Table 15-7, Java Boolean data type
Connecting with Computer Science, 2e
17
String Data Type
• Stores a piece of information
– Not a number
– Contains more than one character
• Declared using double quotes
• Uses the String or string keywords
– Examples of an empty string:
• String sName; //Java String
• string sName; //C++ string
Connecting with Computer Science, 2e
18
String Data Type (cont’d.)
• 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
• See example code on pages 517–518
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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;
– Alternative:
• int iStudentCount = 456;
Connecting with Computer Science, 2e
21
Variable Content (cont’d.)
• Assigning a value to a character variable
– Enclose in single quotes
– Example:
• char cMiddleInit;
• cMiddleInit = 'S';
– Alternative:
• char cMiddleInit = 'S';
Connecting with Computer Science, 2e
22
Variable Content (cont’d.)
• Assigning a value to a string variable
– Enclose in double quotes
– Example:
• String sMiddleName = "S"; //Java
• string sMiddleName = "S"; //C++
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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
public class Save_Ferris
{
public static void main(String[] args)
{
System.out.println("I could have been the Walrus!");
}
}
Connecting with Computer Science, 2e
25
Invocation (cont’d.)
• 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
Connecting with Computer Science, 2e
26
Invocation (cont’d.)
• 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:
• int argc, char *argv[ ]
• //C++ main receiving parameters
• int main(int argc, char *argv[])
Connecting with Computer Science, 2e
27
Top Down (or Sequence)
• Used when program statements executed in
sequential order
– Starting at the top and working down to the bottom
– See example code on pages 522 and 523
Connecting with Computer Science, 2e
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:
Connecting with Computer Science, 2e
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);
Connecting with Computer Science, 2e
30
Java Output Data (cont’d.)
Table 15-10 Java output statements
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
32
C++ Output Data (cont’d.)
Table 15-11, Sample C++ output statements
Connecting with Computer Science, 2e
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
– Used to retrieve data from input device
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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;
}
Connecting with Computer Science, 2e
37
if and if-else Statements (cont’d.)
• 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;
}
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
40
Copy editor:
Syntax
alignment OK
as is? (different
in PDF)
switch Statement (cont’d.)
• break statement at end of
each case
– Informs system to quit
processing case
statements
– Sends control to end of the
switch statement
• Syntax:
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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);
}
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
44
while Statement (cont’d.)
• Syntax:
while (expression)
{
statements;
}
Connecting with Computer Science, 2e
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);
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
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
Connecting with Computer Science, 2e
48
Summary (cont’d.)
• 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
Connecting with Computer Science, 2e
49
Summary (cont’d.)
• 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
Connecting with Computer Science, 2e
50