Download public static void main(String[ ] args)

Document related concepts
no text concepts found
Transcript
Structure Programming
Programming in Java
Instructed and enhanced by
Dr. Safia Abbas
Computer Science Department
Faculty of Computer and Information Sciences
Ain Shams University
Prepared By
Dr. safia abbas
Computer Science Department
Faculty of Computer and Information Sciences
Ain Shams University
1
The Course
• Instructor: Dr. safia abbas
• Text Book:
• Paul Deitel and Harvey Deitel.
“Java-How to Program. 9th edition,
Pearson,2013.”
Other (Online) Resources
 How to Think Like a Computer Scientist
 http://greenteapress.com/thinkapjava/thinkapjava.pdf
 Introduction to Programming Using Java, 5th Edition
 http://math.hws.edu/javanotes/
 Thinking in Java, 3rd Edition
 http://nyll.com/ebooks/index.html
 Sun Java Tutorial http://download.oracle.com/javase/tutorial/java/
 The Java API
 http://download.oracle.com/javase/1.5.0/docs/api/
Course Contents
•
•
•
•
•
•
•
•
Introduction.
Variables, types and expressions.
Functions and procedural abstraction.
Input/ output and streams.
Branch and loop statements.
Arrays and strings.
Pointers.
Recursions.
Lecture 1: Agenda
• Introduction - computer hardware & Programming Languages
• First Program
• Output Using pint
• Directives
• Comments
• Integer Variables
• Input with Scanner
• Variable Names
• Arithmetic Expressions
• The arithmetic assignment operators
• Character Variables
• Floating Point Types
• const Qualifier
• Type bool
• The setw Manipulator
• Variable Type Summary
• Type Conversion
• Increment Operators
• Math Library Functions
5
Main computer components
• A computer is a machine that can perform
computation. a computation involves the following
three components:
• Input: The user gives a set of input data.
•Processing: The input data is processed by a
well-defined and finite sequence of steps.
•Output: Some data available from the
processing step are output to the user.
Usually, computations are carried out to solve some
meaningful and useful problems. One supplies some
input instances for the problem, which are then
analyzed in order to obtain the answers for the
instances.
Why digital computers & problems types
• Usually, computer perform computations in order to solve some
meaningful and useful problems faster and more accurately. One supplies
some input instances for the problem, which are then analyzed in order to
obtain the answers for the instances.
• Types of problems
– Functional problems A set of arguments a1,a2,...,are send to Some function,
as f(a1,a2,...,an), which in turn calculate the arguments and output to the user.
– Decision problems These form a special class of functional problems whose
outputs are "yes" and "no" (or "true" and "false", or "1" and "0", etc).
– Search problems Given an input object, one tries to locate some particular
configuration pertaining to the object and outputs the located configuration,
or "failure" if no configuration can be located.
– Optimization problems Given an object, a configuration and a criterion for
goodness, one finds and reports the configuration pertaining to the object,
that is best with respect to the different existing paths.
How does a program run in a computer?
• The inputs, the intermediate values and the instructions defining the
processing stage reside in the (main) memory. In order to separate data
from instructions the memory is divided into two parts:
• Data area The data area stores the variables needed for the processing
stage. The values stored in the data area can be read, written and
modified by the CPU.
• Instruction area The instruction area stores a sequence of instructions
that define the steps of the program. Under the control of a clock, the
computer carries out a fetch-decode-execute cycle in which instructions
are fetched one-by-one from the instruction area to the CPU, decoded in
the control unit and executed in the ALU. The CPU understands only a
specific set of instructions. The instructions stored in memory must
conform to this specification.
How does a program run in a computer?
What is programming?
• Programming is a process done by programmers to instruct a
computer on how to do a task .
• It is Planning or scheduling a sequence of steps for a computer
to follow to perform a task.
• Basically, telling a computer what to do and how to do it.
• A program is :
– A sequence of steps to be performed by a computer.
– Expressed in a computer language.
• Unstructured Programming
• Procedural Programming
• Modular & Structural Programming
• Abstract Data Type
• Object-Oriented Programming
• Small and (simple?)
programs.
• Consists only of one main
program.
• Here ``main program'' stands
for a sequence of commands
or statements which modify
data which is global
throughout the whole
program.
Main Program
Data
• This programming technique can only be
used in a very small program. Why?
• For example, if the same statement
sequence is needed at different locations
within the program, the sequence must be
copied. If an error needed to be modified,
every copy needs to be modified.
 This has lead to the idea to extract these
sequences (procedure), name them and
offering a technique to call and return from
these procedures.
• Unstructured Programming
• Procedural Programming
• Modular & Structural Programming
• Abstract Data Type
• Object-Oriented Programming
• With procedural
programming, you are able
to combine sequences of
calling statements into one
single place.
• A procedure call is used to
invoke the procedure. After
the sequence is processed,
flow of control proceeds
right after the position
where the call was made .
Main
Program
Procedure
• With parameters and sub-procedures (procedures
of procedures) , programs can now be written
more structured and with less errors.
• For example, if a procedure is correct, every time
it is used it produces correct results.
• Consequently, in cases of errors you can narrow
your search to those places which are not proven
to be correct.
• Now a program can be viewed as a sequence of
procedure calls.
• The main program is responsible to pass data to
the individual calls, the data is processed by the
procedures and the resulting data is presented.
• Thus, the flow of data can be illustrated as a
hierarchical graph, a tree.
Main Program
Data
Procedure1
Procedure2
Procedure3
• Unstructured Programming
• Procedural Programming
• Modular & Structural Programming
Will be
• Abstract Data Type
discussed
next year
• Object-Oriented Programming
• Modular programming is subdividing your program
into separate subprograms.
• Procedures of a common functionality are grouped
together into separate modules.
• A program no longer consists of only one single part.
It is now divided into several smaller parts which
interact through procedure calls.
• The main program coordinates calls to procedures
in separate modules and hands over appropriate
data as parameters.
Main Program (Also a module)
Data
Module1
+
Data
Data
Data11
Procedure1
Module2
+
Data
Data2
Procedure2
Procedure3
• A subset of procedural programming that enforces
a logical structure on the program being written
to make it more efficient and easier to understand
and modify. “organizing considering time and space”
• Certain languages such as Ada, and Pascal were
designed with features that encourage or enforce
a logical program
Basic structures for programming?
• Three Types of Structures in a
structured program
-Statement sequence(s1,s2,…,sn)
-Branch(if-then-else)
-Loop(for,do, and while loops)
- Keep modules!!!
Programming languages classes?
Programming Languages
• There are many different programming languages, and many
ways to classify them. For example,
– "high-level" programming languages are languages whose
syntax is relatively close to natural language,
– whereas the syntax of "low-level" languages includes many
technical references to the (0's and 1's, etc.)
• C is in many ways hard to categories. Compared to assembly
language it is high-level, but it nevertheless includes many
low-level facilities to directly manipulate the computer's
memory.
25
high – level languages
• Are designed to be easy to read and write
• Use more complicated instructions than the CPU can follow
• Must be translated to zeros and ones for the CPU to execute a
program
26
Machine, Assembler and high level language
• Machine language is a numeric language specifically
understood by a computer’s processor (the CPU).
• Assembly language consist of statements written with short
mnemonics such as ADD, MOV, ….It has a one-to- one
relationship with machine language instructions
• High level language ( such as C++ and Java) has a one–to–
many relationship with machine/assembly language
instructions
27
How computers understand the
instruction?
• Programs are written in a programming
language, then translated into machine code
by a compiler and linker so that the computer
can execute it directly or run it line by line
(interpreted) by an interpreter program.
Compilers
• Translate high-level language to machine language
Linkers
A Linker combines
– The object code for the programs we write
And
– The object code for the pre-compiled routines
Into
– The machine language program, the CPU can run
(executable program)
29
Agenda
• Introduction - computer hardware & Programming Languages
• First Program
• Output Using print
• Directives
• Comments
• Integer Variables
• Input with scanner
• Variable Names
• Arithmetic Expressions
• The arithmetic assignment operators
30
The First Java Program
Type all carefully and save it to a file named
Welcome.java
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
} // end method main
} // end class welcome
The First Java Program
class Welcome {
Java program source files (.java) contain definition of
classes
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
} // end method main
} // end class welcome
The First Java Program
The class name or
identifier
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
} // end method main
} // end class welcome
Class name or identifier
•
class names begin with a capital letter and capitalize the first letter of each word they include
(e.g., SampleClassName).
•
A class name is an identifier—a series of characters consisting of letters, digits, underscores
(_) and dollar signs ($) that does not begin with a digit and does not contain spaces.
•
Ex. valid identifiers such as
Welcome1, $value,_value, m_inputField1 and button7.
•
Ex. Invalid identifiers such as
7button
-not a valid identifier because start with digit
input field - not a valid identifier because it contains a space
•
•
•
identifier that does not begin with a capital letter is not a class name.
Java is case sensitive—uppercase and lowercase letters are distinct—so value and Value are
different.
The First Java Program
class Welcome {
Curly braces pair enclose a block of code, class
Welcome here
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
Don’t miss me!
The First Java Program
class Welcome {
Curly braces pair enclose a block of code,
method main() here
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
Don’t miss me!
The First Java Program
class Welcome {
This is a block of comments, for human, not for
computer
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
It explains to you what happens
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
The First Java Program
class Welcome {
/* and */ pair encloses a comment block
(over several lines)
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
Don’t miss me!
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
} // end of method main
One line comment
} // end of class
The First Java Program
This is a method of the class Welcome, named
main()
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
Declaring a method
• The parentheses after the identifier main indicate that it’s a
program building block called a method.
• Java class declarations can contain one or more methods.
• one of the methods must be called main and must be defined
as shown previously otherwise, the JVM will not execute the
application
The First Java Program
There MUST be a pair of parentheses following
ALL method names
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
Don’t miss me!
The First Java Program
A method may take some input from the caller,
formally known as arguments or parameters
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
The First Java Program
A method may give some output to the caller too,
known as return value
void means no return value
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
The First Java Program
The static keyword before a method definition
indicates this is a class method
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
The First Java Program
This method is a public one, others can call me.
class Welcome {
/* The Welcome Program Illustrates a simple program
displaying a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
The First Java Program
Standard properties of the main() method
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
The First Java Program
A statement (instruction) to display a message
“standard output object”
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
Selecting method print
Class System,
defined in the
Standard Package of
java
System
.
Output stream object,
it is member of
System
Out
Selects an individual
class member of
System
.
Method member of Out
println(“string");
Selects an individual
class member of Out
Parameter of Print
method
The First Java Program
After every statement, there must be a semicolon!
class Welcome {
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
The First Java Program
class Welcome {
How to ask the computer to act according to
the instructions in this program?
/* The Welcome Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.println("Welcome to Java!");
}
}
class Welcome2 {
/* The Welcome2 Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
}
}
The out put will be
Welcome to java programming
class Welcome3 {
/* The Welcome3 Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.print( "Welcome\nto" );
System.out.println( "Java Programming!" );
}
}
The out put will be
Welcome
to java programming

class Welcome3 {
Displaying Text with printf
Format pacifiers begin
with %
/* The Welcome3 Program
Place holder for sting
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.printf("%s\n%s\n",
"Welcome to", "Java Programming!");
}
}
The output
Welcome to
Java Programming!
What do we do with it?
Java program has five steps to be executed
•
•
•
•
•
Creating a program.
Compiling a Java program into byte codes.
Loading program into memory.
Byte code verification.
Execution.
Creating a program
•
consists of editing a file with an editor program.
•
Type a Java program (typically referred to as source code) using the editor,
 Use any text editor you like (preferred IDEs environment)
•
Make any necessary corrections and save the program on a secondary storage
device, such as your hard drive. save as Welcome.java
•
A file name ending with the .java extension indicates that the file contains the
Java source code.
Integrated Development Environments
(IDEs)
• is a software application that provides comprehensive facilities to computer
programmers for software development.
• An IDE normally consists of:
– a source code editor
– build automation tools
– a debugger
• Some IDEs contain compiler, interpreter, or both, such as Eclipse; others do
not,
• An easy way to find where the compiler thinks you’ve gone wrong
• Examples: NetBeans, Eclipse, Together,…
Compiling a Java program into byte
codes
•
use the command javac (the Java compiler) to compile a program.
•
For example, to compile a program called Welcome.java, you’d type in the command prompet javac
Welcome.java
•
the compiler produces a .class file called Welcome.class that contains the compiled version of the
program.
•
The Java compiler translates Java source code into bytecodes that represent the tasks to be executed.
•
Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK and the foundation of the
Java platform.
•
The JVM is one of the most widely used virtual machines that its execution can be used on all those
platforms.
•
JVM is unlike machine language, which is dependent on specific computer hardware, bytecodes are
platform independent
Loading program into memory
• the JVM places the program in
memory to execute it—this is
known as loading.
• The JVM’s class loader takes
the .class files containing the
program’s bytecodes and
transfers them to primary
memory.
Byte code verification
• as the classes are loaded, the bytecode verifier examines
their bytecodes to ensure that they’re valid and do not
violate Java’s security restrictions
Execution/Running.
•
the JVM executes the program’s bytecodes, thus performing the actions specified by the
program.
•
In early Java versions, the JVM was simply an interpreter for Java bytecodes. This caused
most Java programs to execute slowly, because the JVM would interpret and execute one
bytecode at a time.
•
Some modern computer architectures can execute several instructions in parallel.
What do we do with it?
• Editing
– Use any text editor you like (not a word processor!); save
as Welcome.java
• Compiling
– From a DOS or UNIX command line, type
> javac Welcome.java
– This should produce the file Welcome.class
• Running/Executing
– Again from the command prompt, type
> java Welcome
Note
•
That Java programs actually go through two compilation phases—
– one in which source code is translated into bytecodes (for portability across
JVMs on different computer platforms) and
– a second in which, during execution, the bytecodes are translated into
machine language for the actual computer on which the program executes.
•
Problems That May Occur at Execution Time : divide by zero
Test your self
• What will be the out put of the following code:public class FormattingExample
{
public static void main (String [] args)
{
System.out.print("lol\tz\n");
System.out.println("hello\rworld");
System.out.println("\"Geek\" talk slash (\\) com");
}
}
64
solution
• The output will be
Lol
z
hello
world
"Geek" talk slash (\) com
65
Questions (your turn)
•
1-The programs that translate high-level language programs into machine
language are called ____________.
•
2-The command _______from the JDK executes a Java application.
•
3-The command ______from the JDK compiles a Java program.
•
4-A Java program file must end with the file extension______.
•
5-When a Java program is compiled, the file produced by the compiler ends with
the file extension________.
•
6-The file produced by the Java compiler contains _____that are executed by the
Java Virtual Machine.
Your turn …. Cont.
• 12- What is the out put of the following code:
class Display {
/* The Display Program
Illustrates a simple program displaying
a message.
*/
public static void main (String [ ] args) {
System.out.print( “Now is autumn " );
System.out.println( “weather is not stable" );
System.out.print( “sometimes hot " );
System.out.println( “sometimes cold" );
}
}
Answers
•
•
•
•
•
•
•
1- compilers.
2- java (file name).
3- javac (file name).
4-(file name).java.
5- (file name).class.
6- bytecodes.
12- Now is autumn weather is not stable
sometimes hot sometimes called
Self study program
• Design a program to output the following table on the screen.
Not you must use the escape sequence.
Person height
shoe size
===========================
Ahmed 1.7 m
38
Ali
2m
43
solution
public static void main(String[] args) {
System.out.println("person\t heiht\t size");
System.out.println("======================");
System.out.println("Ahmed\t1.7m\t38");
System.out.println("Ali\t2m\t43");
}
70
Agenda
• Introduction - Programming Languages
• First Program
• Output
• Directives
• Comments
• variables & identifiers
• Integer Variables
• Input with scanner
• Variable Names
• Arithmetic Expressions
• The arithmetic assignment operators
71
Variables & Identifiers
• programming is not limited only to printing simple
texts on the screen. In order to go a little further on
and to become able to write programs that perform
useful tasks that really save us work we need to
introduce the concept of variable.
• we can define a variable as a portion of memory to
store a determined value.
• Each variable needs an identifier that distinguishes it
from the others
Variable Names=identifier
• The names given to variables are called identifiers.
• What are the rules for writing identifiers?
– You can use upper- and lowercase letters, and the digits
from 1 to 9.
– You can also use the underscore _.
– The first character must be a letter or underscore.
– Keywords is avoided.
• Identifiers can be as long as you like, but most compilers will
only recognize the first few hundred characters.
• java is case sensitive: The compiler distinguishes between
upper- and lowercase letters, so Var is not the same as var or
VAR.
73
keyword
• A keyword is a predefined word with a special meaning.
• int, class, if, and while are examples of keywords.
• A complete list of keywords can be found in Appendix B, page
886, book “object oriented programming in C++”.
• Note:
• Declarations of variables can be placed almost anywhere in a
program, but they must appear before their corresponding
variables are used in the program.
74
Java Keywords
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
Declaring Variables: Syntax
• Format:
<type of information> <name of variable>;
• Example:
char a;
• Variables can be initialized (set to a starting value) as they’re
declared:
char myFirstInitial = ‘j’;
int age = 30;
Some Built-In Types Of Variables In
Java
Type
Description
byte
8 bit signed integer
short
16 but signed integer
int
32 bit signed integer
long
64 bit signed integer
float
32 bit signed real number
double
64 bit signed real number
char
16 bit Unicode character (ASCII and
beyond)
boolean
1 bit true or false value
String
A sequence of characters between double
quotes ("")
Location Of Variable Declarations
public class <name of class>
{
public static void main (String[] args)
{
// Local variable declarations occur here
<< Program statements >>
:
:
}
}
Style Hint: Initializing Variables
• Always initialize your variables prior to using them!
– Do this whether it is syntactically required or not.
• Example how not to approach:
public class OutputExample1
{
public static void main (String [] args)
{
int num;
System.out.print(num);
}
}
OutputExample1.java:7: error: variable
num might not have been initialized
System.out.print(num);
^
Java Constants
Reminder: constants are like variables in that they have a name
and store a certain type of information but unlike variables they
CANNOT change.
Format:
final <constant type> <CONSTANT NAME> = <value>;
Example:
final int SIZE = 100;
Location Of Constant Declarations
public class <name of class>
{
public static void main (String[] args)
{
// Local constant declarations occur here (more later)
// Local variable declarations
< Program statements >>
:
:
}
}
Why Use Constants?
1. They make your program easier to read and understand
populationChange = (0.1758 – 0.1257) *
currentPopulation;
Vs.
final float BIRTH_RATE = 17.58;
final float MORTALITY_RATE = 0.1257;
int currentPopulation = 1000000;
populationChange = (BIRTH_RATE MORTALITY_RATE) * currentPopulation;
Variables, cont.

int -- integer type: range is system dependent





usually 32-bits -- +/- 2,147,483,648
16-bits on older systems -- +/- 32,768
float -- floating point number
char -- a single character
string -- more than an array of characters (a class)

we’ll look at these in more detail later..
83
Common Java Operators /
Operator Precedence
Precedence
level
Operator
1
expression++ Post-increment
expression--
2
Description
Associativity
Right to left
Post-decrement
++expression Pre-increment
--expression
Pre-decrement
+
Unary plus
-
Unary minus
!
Logical negation
~
Bitwise complement
(type)
Cast
Right to left
Common Java Operators /
Operator Precedence
Precedence
level
Operator
Description
Associativity
3
*
Multiplication
Left to right
/
Division
%
Remainder/modulus
+
Addition or String
concatenation
-
Subtraction
<<
Left bitwise shift
>>
Right bitwise shift
4
5
Left to right
Left to right
Common Java Operators /
Operator Precedence
Precedence Operator
level
Description
Associativity
6
<
Less than
Left to right
<=
Less than, equal to
>
Greater than
>=
Greater than, equal to
==
Equal to
!=
Not equal to
8
&
Bitwise AND
Left to right
9
^
Bitwise exclusive OR
Left to right
7
Left to right
Common Java Operators /
Operator Precedence
Precedence Operator
level
Description
Associativity
10
|
Bitwise OR
Left to right
11
&&
Logical AND
Left to right
12
||
Logical OR
Left to right
Common Java Operators /
Operator Precedence
Precedence Operator
level
Description
Associativity
13
=
Assignment
Right to left
+=
Add, assignment
-=
Subtract, assignment
*=
Multiply, assignment
/=
Division, assignment
%=
Remainder, assignment
&=
Bitwise AND, assignment
^=
Bitwise XOR, assignment
|=
Bitwise OR, assignment
<<=
Left shift, assignment
>>=
Right shift, assignment
Example
89
Arithmetic Operators, cont.
• There is no arithmetic operator for exponentiation in Java, so
x2 is represented as x*x.
90
The arithmetic assignment operators
public static void main(String[ ] args) {
int j = 0,k = 5;
k = k - 5;
}

The same variable may appear on both sides of an assignment operator



on the right hand side of the assignment operator, the variable in
question represents its value prior to the execution of this
statement.
on the left hand side of the assignment operator, the variable
receives a new value which is the result of the evaluation on the
right hand side.
In our example above, k ends up being “0”.
91
The arithmetic assignment operators, cont.
public static void main(String[] args)
{
int j = 0,k = 5;
k -= 5;
// really like k = k - 5;
}

When performing any other operation on a variable and stuffing the value back
into the same variable, use a shortcut (like +=, -=, *=, %=)
92
The arithmetic assignment operators, cont.
93
Post/Pre Operators
The name of the online example is: Order1.java
public class Order1
{
public static void main (String [] args)
{
int num = 5;
System.out.println(num);
num++;
System.out.println(num);
++num;
System.out.println(num);
System.out.println(++num);
System.out.println(num++);
}
}
Post/Pre Operators (2)
The name of the online example is: Order2.java
public class Order2
{
public static void main (String [] args)
{
int num1;
int num2;
num1 = 5;
num2 = ++num1 * num1++;
System.out.println("num1=" + num1);
System.out.println("num2=" + num2);
}
}
Unary Operator/Order/Associativity
The name of the online example: Unary_Order3.java
public class Unary_Order3.java
{
public static void main (String [] args)
{
int num = 5;
float fl;
System.out.println(num);
num = num * -num;
System.out.println(num);
}
}
Accessing Pre-Created Java Libraries
• It’s accomplished by placing an ‘import’ of the appropriate
library at the top of your program.
• Syntax:
import <Full library name>;
• Example:
import java.util.Scanner;
Getting Text Input
• You can use the pre-written methods (functions) in the
Scanner class.
• General structure:
import java.util.Scanner;
main (String [] args)
{
Scanner <name of scanner> = new Scanner (System.in);
<variable> = <name of scanner> .<method> ();
}
Creating a
scanner object
(something
that can scan
user input)
Using the capability of
the scanner object
(actually getting user
input)
Getting Text Input (2)
The name of the online example: MyInput.java
import java.util.Scanner;
public class MyInput
{
public static void main (String [] args)
{
String str1;
int num1;
Scanner input = new Scanner (System.in);
System.out.print ("Type in an integer: ");
num1 = in.nextInt ();
System.out.print ("Type in a line: ");
in.nextLine ();
str1 = input.nextLine ();
System.out.println ("num1:" +num1 +"\t str1:" + str1);
}
}
Useful Methods Of Class Scanner1
•
•
•
•
•
nextInt ()
nextLong ()
nextFloat ()
nextDouble ()
nextLine ();
Reading A Single Character
• Text menu driven programs may require this capability.
• Example:
GAME OPTIONS
(a)dd a new player
(l)oad a saved game
(s)ave game
(q)uit game
• There’s different ways of handling this problem but one
approach is to extract the first character from the string.
• Partial example:
String s = "boo“;
System.out.println(s.charAt(0));
Reading A Single Character
• Name of the (more complete example): MyInputChar.java
import java.util.Scanner;
public class MyInputChar
{
public static void main (String [] args)
{
final int FIRST = 0;
String selection;
Scanner input = new Scanner (System.in);
System.out.println("GAME OPTIONS");
System.out.println("(a)dd a new player");
System.out.println("(l)oad a saved game");
System.out.println("(s)ave game");
System.out.println("(q)uit game");
System.out.print("Enter your selection: ");
Reading A Single Character (2)
selection = in.nextLine ();
System.out.println ("Selection: " + selection.charAt(FIRST));
}
}
The best way to learn a programming
language is to try writing programs
and test them on a computer
104
Your Turn
• 1. Dividing a program into functions
a. is the key to object-oriented programming.
b. makes the program easier to conceptualize.
c. may reduce the size of the program.
d. makes the program run faster.
•
•
•
•
2. A function name must be followed by ________.
3. A function body is delimited by ________.
4. Why is the main() function special?
5. A C++ instruction that tells the computer to do something is
called a ________.
105
Your Turn, cont.
• 9. True or false: A variable of type char can hold the value 301.
• 10. What kind of program elements are the following?
a. 12
b. ‘a’
c. 4.28915
d. JungleJim
e. JungleJim()
106
Your Turn, cont.
• 11. Write statements that display on the screen
a. the character ‘x’
b. the name Jim
c. the number 509
• 12. True or false: In an assignment statement, the value on
the left of the equal sign is always equal to the value on the
right.
• 15. Write a statement that gets a numerical value from the
keyboard and places it in the variable temp.
107
Your Turn, cont.
• 19. The expression 11%3 evaluates to ________.
• 21. Write a statement that uses an arithmetic assignment
operator to increase the value of the variable temp by 23.
Write the same statement without the arithmetic assignment
operator.
• 22. write a program in order to ask the user about the number
of programming language he had before, the out the
statement “enjoy the book” to the screen?
108
• 23- Write a program which asks the user to
insert two integer values then out put on the
screen
– The incrementing by one to each intergers.
– The multiplication of both;
– The adding of both numbers.
Answers
•
•
•
•
•
•
•
1- b,c.
2-parentheses
3- braces { }
4- It’s the first function executed when the program starts
5- statement
9- false
10- a. integer constant
–
–
–
–
•
b. character constant
c. floating-point constant
d. variable name or identifier
e. function name
11.
– a. cout << ‘x’;
– b. cout << “Jim”;
– c. cout << 509;
•
•
•
•
12- false; they’re not equal until the statement is executed
15- cin >> temp;
19- 2
21– temp += 23;
– temp = temp + 23;
•
•
•
•
•
•
•
•
•
•
22- #include <iostream>
using namespace std;
int main( )
{
int numberOfLanguages;
cout << "Hello reader.\n“ << "Welcome to C++.\n";
cout << "How many programming languages have you used? ";
cin >> numberOfLanguages;
cout << "Enjoy the book.\n";
return 0; }
•
22. #include <iostream>
•
•
•
•
•
•
•
•
•
•
•
•
•
using namespace std;
int main(){
int n,m;
cout<<"enter the first number\n";
cin>>n;
cout<<"enter the second number\n";
cin>>m;
n++; m++;
cout<<"the first number after increment is "<<n<<endl;
cout<<"the second number after increment is "<<m << endl;
n--; m--;
cout<< "the multiplication of the two integers are"<<m*n<<endl;
cout<< "the addition of the two integers are"<<m+n<<endl; }
Lecture 3
Agenda
• Text book “absolute C++”
• Chapter1:C++ basics cont.
– Variable types
• Char, string, float, const, boolean.
– Type conversion
– Math operations
• Chapter 2: flow of control
–
–
–
–
Boolean expression.
Branching mechanisms.
Loops.
Introduction to file input.
Character variable
// charvars.cpp
// demonstrates character variables
• #include <iostream>
• using namespace std;
• int main()
• {
• char charvar1='A';
• char charvar2='\t';
• cout << charvar1;
• cout << charvar2;
• cout << charvar1;
• cout << "\n";
• return 0;
• }
//for cout, etc.
//define char variable as character
//define char variable as tab
//display character
//display character
//display character
//display newline character
Character variable : Escape Sequences
• \ xdd
Hexadecimal notation
• Sometimes you need to represent a character
constant that doesn’t appear on the keyboard, such
as the graphics characters above ASCII code 127.
• To do this, you can use the “\xdd” representation,
• where each d stands for a hexadecimal digit.
• cout << “\xE0”;
cout << “\xB2”;
//display α
//display solid rectangle
ASCII Table
String variable
• In order to use string
variable type, we have
to use special library
called “String”.
Cin>> with string variable type
String variable
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
#include <String> //using string variable
using namespace std;
int main()
{
string strname; // identify a string variable
cout<<" enter your name"<< endl;
cin>>strname;
cout<<"you typed the name"<<strname<<endl;
return 0;
}
Floating Point Types
• represent numbers with a decimal place—like 3.1415927, 0.0000625, and
–10.2.
• There are three kinds of floating-point variables in C++:
– type float,
– type double,
– and type long double
• float PI = 3.14159F; //the F specifies that it’s type float
• You can also write floating-point constants using exponential notation.
• Exponential notation is a way of writing large numbers without having to
write out a lot of zeros.
• For example:
– 1,000,000,000 can be written as 1.0E9 in exponential notation.
– 6.35239E–5 is equivalent to 0.0000635239 in decimal notation
12
0
The const Qualifier
• The keyword const (for constant) precedes the
data type of a variable.
• It specifies that the value of a variable will not
change throughout the program.
• Any attempt to alter the value of a variable
defined with this qualifier will elicit an error
message from the compiler.
• const float PI = 3.14159F;
float
//type const
12
1
Example: circarea.cpp
// circarea.cpp
// demonstrates floating point variables
#include <iostream> //for cout, etc.
using namespace std;
int main()
{
float rad;
//variable of type float
const float PI = 3.14159F;
//type const float
cout << "Enter radius of circle: ";
//prompt
cin >> rad;
//get radius
float area = PI * rad * rad;
//find area
cout << "Area is " << area << endl;
//display answer
return 0;
}
12
2
Type bool
• Variables of type bool can have only two
possible values: true and false.
• type bool is most commonly used to hold the
results of comparisons.
12
3
Basic C++ Variable Types
12
4
Type Conversion
• C++ treats expressions involving several different
data types.
int main()
{
int count = 7;
float avgWeight = 155.5F;
double totalWeight = count * avgWeight;
cout << “totalWeight=” << totalWeight << endl;
return 0;
}
12
5
Type Conversion, cont.
• When two operands of different types are
encountered in the same expression, the lower-type
variable is converted to the type of the higher-type
variable.
12
6
Type Conversion, cont.
int count = 7;
float avgWeight = 155.5F;
double totalWeight = count * avgWeight;
• the int value of count is converted to type float and
stored in a temporary variable before being
multiplied by the float variable avgWeight.
• The result (still of type float) is then converted to
double so that it can be assigned to the double
variable totalWeight.
12
7
Type Conversion, cont.
Type Conversion, cont.
12
8
Casts
• Cast convert a value from one type to another.
• CharVar = static_cast<char>(nIntVar);
• Example:
cout<< static_cast<int>('A'); // print ‘A’ as integer , 65
cout<< static_cast<char>(65); // print 65 as ‘A’
Increment and Decrement
Operators, cont.
Increment and Decrement
Operators, cont.
• When you increment (++) or decrement (--) a variable in a
statement by itself, the pre-increment and post-increment
forms have the same effect, and the pre-decrement and postdecrement forms have the same effect.
X++;
++X;
• It’s only when a variable appears in the context of a larger
expression that pre-incrementing the variable and postincrementing the variable have different effects (and similarly
for pre-decrementing and post-decrementing).
• The Next slide shows the precedence and associatively of the
operators introduced to this point.
13
1
Increment and Decrement
Operators, cont.
The precedence of the operators
13
2
Increment and Decrement
Operators, cont.
• totalWeight = avgWeight * ++count;
count is incremented first and then multiply
with avgWeight
• totalWeight = avgWeight * count ++;
the multiplication would have been performed
first, then count would have been
incremented.
13
3
Increment and Decrement
Operators, cont.
13
4
Math Library Function
// sqrt.cpp
// demonstrates sqrt() library function
#include <iostream>
//for cout, etc.
#include <math.h>
//for sqrt()
using namespace std;
int main()
{
double number, answer;
//sqrt() requires type double
cout << “Enter a number: “;
cin >> number;
//get the number
answer = sqrt(number);
//find square root
cout << “Square root is “ << answer << endl;
//display it
return 0;
}
Enter a number: 1000
Square root is 31.622777
13
5
Math Library Function, cont.
13
6
Math Library Function, cont.
13
7
Outlines
• Chapter 2 – flow of control
– Boolean expressions
– Branching mechanisms
– Loops
– Decisions
13
8
Control Structures
• Normally, statements in a program execute one after the
other in the order in which they’re written.
– Called sequential execution.
• Various C++ statements enable you to specify that the next
statement to execute may be other than the next one in
sequence.
– Called transfer of control.
• All programs could be written in terms of only three control
structures
– the sequence structure
– the selection structure and
– the repetition structure
Boolean expressions
13
9• Most branching statements are controlled by Boolean expressions.
• A Boolean expression is any expression that is either true or false.
• The simplest form for a Boolean expression consists of two expressions, such
as numbers or variables, which are compared with one of the comparison
operators as shown.
Building Boolean Expressions
• One can combine two comparisons in order to build a Boolean
expression.
– Ex.
(2 < x) && (x < 7).
– It means that the expression is true if x is greater than 2
and x is less than 7.
• When two comparisons are connected using an && , the
entire expression is true, if both of the comparisons are true;
otherwise, the entire expression is false.
– Ex. (y < 0)||(y < 12)
• When two comparisons are connected using a || , the entire
expression is true provided that one or both of the
comparisons are true; otherwise, the entire expression is
false.
14
1
Evaluating Boolean Expressions
• #include <iostream> //for cout, etc.
• using namespace std;
int main()
{ int y;
bool Opor, Opand;
cout<<"enter number";
cin>>y;
Opor=(y<7)||(y>2);
cout<<"the result of the or operator is\n"<<Opor<<endl;
Opand=Opor=(y<7)&&(y>2);
cout<<"the result of the and operator is \n"<<Opand;
return 0;}
• C++ compiler considers that a true expression has the value 1, while a
false expression has the value 0.
14
2
Evaluating Boolean Expressions cont.
Precedence Rules
14
• Boolean expressions (and arithmetic expressions) need not be
3
fully parenthesized.
• If you omit parentheses, the default precedence will be used.
High
precedence
low
precedence
14
4
Some expressions that use Boolean
expression
•
•
•
•
•
•
•
•
•
•
int x= 44;
int y = 12;
bool b1= (x== y);
bool b2=(y <= 12);
bool b3=(x> y);
bool b4=(x>= 44);
bool b5=(y != 12);
bool b6=(7 < y);
bool b7=(0);
bool b8=(44);
•
Although C++ generates a 1 to indicate true, it assumes that any value other than
0 (such as –7 or 44) is true; only 0 is false.
//assignment statement
//assignment statement
//false
//true
//true
//true
// false
//true
//false (by definition)
//true (since it’s not 0)