Download presentation
Presentation is loading. Please wait.
1
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
2
The Course Instructor: Dr. safia abbas Text Book:
Paul Deitel and Harvey Deitel. “Java-How to Program. 9th edition, Pearson,2013.”
3
Other (Online) Resources
How to Think Like a Computer Scientist Introduction to Programming Using Java, 5th Edition Thinking in Java, 3rd Edition Sun Java Tutorial The Java API
4
Course Contents Introduction. Variables, types and expressions.
Functions and procedural abstraction. Input/ output and streams. Branch and loop statements. Arrays and strings. Pointers. Recursions.
5
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
6
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.
7
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.
8
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.
9
How does a program run in a computer?
10
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.
11
Programming Techniques
2017/4/23 Programming Techniques Unstructured Programming Procedural Programming Modular & Structural Programming Abstract Data Type Object-Oriented Programming 11
12
Unstructured Programming
2017/4/23 Unstructured 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 12
13
2017/4/23 Drawbacks 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. 13
14
Programming Techniques
2017/4/23 Programming Techniques Unstructured Programming Procedural Programming Modular & Structural Programming Abstract Data Type Object-Oriented Programming 14
15
Procedural Programming
2017/4/23 Procedural 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 15
16
2017/4/23 Procedures 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. 16
17
Procedure Program view
2017/4/23 Procedure Program view 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. 17
18
Procedure Program view
2017/4/23 Procedure Program view Main Program Data Procedure3 Procedure1 Procedure2 18
19
Programming Techniques
2017/4/23 Programming Techniques Unstructured Programming Procedural Programming Modular & Structural Programming Abstract Data Type Object-Oriented Programming Will be discussed next year 19
20
Modular Programming 2017/4/23 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. 20
21
Main Program (Also a module)
2017/4/23 Main Program (Also a module) Data Module1 + Module2 + Data Data Data1 Data1 Data Data2 Procedure2 Procedure3 Procedure1 21
22
Structured Programming
2017/4/23 Structured Programming 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 22
23
Structured Programming
2017/4/23 Structured Programming 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!!! 23
24
Programming languages classes?
25
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.
26
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
27
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
28
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.
29
Linkers Compilers Translate high-level language to machine language
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)
30
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
31
Type all carefully and save it to a file named Welcome.java
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
32
Java program source files (.java) contain definition of classes
The First Java Program Java program source files (.java) contain definition of classes 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
33
The class name or identifier
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
34
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.
35
Curly braces pair enclose a block of code, class Welcome here
The First Java Program Curly braces pair enclose a block of code, class Welcome here 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!
36
Curly braces pair enclose a block of code, method main() here
The First Java Program Curly braces pair enclose a block of code, method main() here 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!
37
The First Java Program class Welcome { /* The Welcome Program
This is a block of comments, for human, not for computer class Welcome { /* The Welcome Program Illustrates a simple program displaying a message. */ public static void main (String [ ] args) { System.out.println("Welcome to Java!"); } It explains to you what happens
38
/* and */ pair encloses a comment block
The First Java Program /* and */ pair encloses a comment block (over several lines) 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 of method main } // end of class Don’t miss me! One line comment
39
This is a method of the class Welcome, named main()
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!"); }
40
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
41
There MUST be a pair of parentheses following ALL method names
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!
42
The First Java Program class Welcome { /* The Welcome 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!"); }
43
The First Java Program class Welcome { /* The Welcome 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!"); }
44
The First Java Program class Welcome { /* The Welcome 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!"); }
45
This method is a public one, others can call me.
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!"); }
46
Standard properties of the main() method
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!"); }
47
The First Java Program class Welcome { /* The Welcome 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!"); } System.out.println( "Welcome\n to\n Java\n Programming!" );
48
Selecting method print
Class System, defined in the Standard Package of java Output stream object, it is member of System System . Out . println(“string"); Method member of Out Selects an individual class member of System Selects an individual class member of Out Parameter of Print method
49
After every statement, there must be a semi-colon!
The First Java Program After every statement, there must be a semi-colon! class Welcome { /* The Welcome Program Illustrates a simple program displaying a message. */ public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }
50
The First Java Program class Welcome { /* The Welcome Program
How to ask the computer to act according to the instructions in this program? class Welcome { /* The Welcome Program Illustrates a simple program displaying a message. */ public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }
52
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
53
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
54
Format pacifiers begin with %
Displaying Text with printf Format pacifiers begin with % class Welcome3 { /* The Welcome3 Program 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! Place holder for sting
55
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.
56
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.
57
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,…
58
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
59
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.
60
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
61
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.
62
What do we do with it? Editing Compiling Running/Executing
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
63
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
64
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"); }
65
solution The output will be Lol z hello world
"Geek" talk slash (\) com
66
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.
67
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" ); }
68
Answers 1- compilers. 2- java (file name). 3- javac (file name).
5- (file name).class. 6- bytecodes. 12- Now is autumn weather is not stable sometimes hot sometimes called
69
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 m 38 Ali m 43
70
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"); }
71
Agenda • Introduction - Programming Languages • First Program
• Output • Directives • Comments • variables & identifiers Integer Variables • Input with scanner • Variable Names • Arithmetic Expressions • The arithmetic assignment operators
72
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 a = 5; b = 2; a = a + 1; result = a - b; Please read
73
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
74
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
75
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
76
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;
77
Some Built-In Types Of Variables In Java
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 ("")
78
Location Of Variable Declarations
public class <name of class> { public static void main (String[] args) // Local variable declarations occur here << Program statements >> : : }
79
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); ^
80
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;
81
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 >> : : }
82
Why Use Constants? They make your program easier to read and understand populationChange = ( – ) * currentPopulation; Vs. final float BIRTH_RATE = 17.58; final float MORTALITY_RATE = ; int currentPopulation = ; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation;
83
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..
84
Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 1 expression++ expression-- Post-increment Post-decrement Right to left 2 ++expression --expression + - ! ~ (type) Pre-increment Pre-decrement Unary plus Unary minus Logical negation Bitwise complement Cast
85
Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 3 * / % Multiplication Division Remainder/modulus Left to right 4 + - Addition or String concatenation Subtraction 5 << >> Left bitwise shift Right bitwise shift
86
Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 6 < <= > >= Less than Less than, equal to Greater than Greater than, equal to Left to right 7 = = != Equal to Not equal to 8 & Bitwise AND 9 ^ Bitwise exclusive OR
87
Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 10 | Bitwise OR Left to right 11 && Logical AND 12 || Logical OR
88
Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 13 = += -= *= /= %= &= ^= |= <<= >>= Assignment 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 Right to left
89
Example
90
Arithmetic Operators, cont.
There is no arithmetic operator for exponentiation in Java, so x2 is represented as x*x.
91
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”.
92
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 +=, -=, *=, %=)
93
The arithmetic assignment operators, cont.
94
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++; ++num; System.out.println(++num); System.out.println(num++); } 5,6,7,8,8
95
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); } 7,36
96
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; } 5, -25. it islike - *(5,5)
97
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;
98
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)
99
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); }
100
Useful Methods Of Class Scanner1
nextInt () nextLong () nextFloat () nextDouble () nextLine ();
101
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));
102
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: ");
103
Reading A Single Character (2)
selection = in.nextLine (); System.out.println ("Selection: " + selection.charAt(FIRST)); }
104
The best way to learn a programming language is to try writing programs and test them on a computer
105
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 ________.
106
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 d. JungleJim e. JungleJim()
107
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.
108
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?
109
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.
110
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;
111
cout<<"enter the first number\n"; cin>>n;
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> 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; }
112
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.
113
Character variable // charvars.cpp // demonstrates character variables
#include <iostream> //for cout, etc. using namespace std; int main() { char charvar1='A'; //define char variable as character char charvar2='\t'; //define char variable as tab cout << charvar1; //display character cout << charvar2; //display character cout << "\n"; //display newline character return 0; }
114
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”; //display α cout << “\xB2”; //display solid rectangle
115
ASCII Table
116
String variable In order to use string variable type, we have to use special library called “String”.
117
Cin>> with string variable type
118
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; } If the user write more thane one name part strname variable will use only the first name.
119
Floating Point Types represent numbers with a decimal place—like , , and –10.2. There are three kinds of floating-point variables in C++: type float, type double, and type long double float PI = F; //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. E–5 is equivalent to in decimal notation
120
The const Qualifier 120120 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 = F; //type const float
121
Example: circarea.cpp 121121 // 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 = F; //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; }
122
Type bool 122122 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.
123
Basic C++ Variable Types
123123
124
Type Conversion 124124 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; }
125
Type Conversion, cont. 125125 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.
126
Type Conversion, cont. int count = 7; float avgWeight = 155.5F;
126126 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.
127
Type Conversion, cont. 127127
128
Type Conversion, cont. Casts
128128 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’
129
Increment and Decrement Operators, cont.
130
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 post-decrement 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 post-incrementing 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. 130
131
Increment and Decrement Operators, cont
Increment and Decrement Operators, cont. The precedence of the operators 131131
132
Increment and Decrement Operators, cont.
132132 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.
133
Increment and Decrement Operators, cont.
133133
134
Math Library Function 134134 // 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
135
Math Library Function, cont.
135135
136
Math Library Function, cont.
136136
137
Outlines Chapter 2 – flow of control Boolean expressions
137137 Chapter 2 – flow of control Boolean expressions Branching mechanisms Loops Decisions
138
Control Structures 138138 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
139
Boolean expressions 139139 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.
140
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.
141
Evaluating Boolean Expressions
141141 #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.
142
Evaluating Boolean Expressions cont.
142142
143
Precedence Rules Boolean expressions (and arithmetic expressions) need not be fully parenthesized. If you omit parentheses, the default precedence will be used. 143143 High precedence low precedence
144
Some expressions that use Boolean expression
144144 int x= 44; //assignment statement int y = 12; //assignment statement bool b1= (x== y); //false bool b2=(y <= 12); //true bool b3=(x> y); //true bool b4=(x>= 44); //true bool b5=(y != 12); // false bool b6=(7 < y); //true bool b7=(0); //false (by definition) bool b8=(44); //true (since it’s not 0) 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.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.