TM105: Introduction to Computer Programming Meeting 1 Introduction to programs and Java Objectives • • • • • To understand algorithms. To write a simple Java program. To explain the basic syntax of a Java program. To create, compile, and run Java programs. To develop Java programs using IntelliJ. 2 Programs • You tell a computer what to do through programs. • Without programs, a computer is an empty machine. • Computer programs (software) are instructions to the computer. • Computers do not understand human languages, so you need to use computer languages to communicate with them. • Programs are written using programming languages. • Good and logical programming is developed through good pre-code planning and organization (Algorithm). 3 Programs • An algorithm is an ordered set of unambiguous steps that describes a process. • An algorithm can be implemented in more than one programming language. • Algorithms can be designed though the use of flowcharts or pseudocodes. • Pseudocode uses English-like phrases to outline the program. • Flowchart is a graphical representation of an algorithm. 4 Flowchart symbols 5 Statement structures • Sequence – follow instructions from one line to the next without skipping over any lines • Decision - if the answer to a question is “Yes” then one group of instructions is executed. If the answer is “No,” then another is executed • Looping – a series of instructions are executed over and over. 6 The Sequence Structure • The sequence structure is a case where the steps in an algorithm are constructed in such a way that, no condition step is required. Example: • Design an algorithm for finding the average of six numbers, where the sum of the numbers is given from the user. 7 The Sequence Structure Pseudocode : Flowchart : Start Use variables: sum, average Input sum average = sum / 6 Output the average Stop 8 The Sequence Structure Example: Design an algorithm which will accept two numbers from the user and calculate the sum and the product, printing the answers on the screen. 9 The Sequence Structure Pseudocode : Start Use variables: sum, product, number1, number2 Input number1, number2 sum = number1 + number2 print sum product = number1 * number2 print product Stop Flowchart : Start Input number1 Input number2 sum = number1 + number2 Print sum product = number1 x number2 Print product Stop 10 The Decision Structure • The decision (selection) structure allows the program to make a decision and change its behavior based on a condition. • The condition is a logical test whose outcome is either true or false. • The pseudocode and flowchart of the decision structure is shown below. • If the condition is true, Task-A is executed. If it is false, Task-B is executed Pseudocode : Flowchart : IF condition is true task A ELSE task-B 11 The Decision Structure Example: Design an algorithm of a program that reads from the user a number and displays on the screen a message if this number is positive or non-positive. 12 The Decision Structure Pseudocode :Start Flowchart : Use variable: number Input number IF number > 0 print (“Positive”) ELSE print (“Non-positive”) Stop Start Input number true number > 0 Print (“Positive”) false Print (“Nonpositive”) Stop 13 The Decision Structure Example: Design an algorithm of a program that reads from the user a number representing the total score of a student and displays on the screen a message if the student passed or failed. A student passes, if the score is 50 or more. Otherwise, fails. 14 The Decision Structure Pseudocode : Start Use variable: score Input score IF score >= 50 print (“Pass”) ELSE print (“Fail”) Stop Flowchart : Start Input score true score >= 50 Print (“Pass”) false Print (“Fail”) Stop 15 Repetition • Any program instruction that repeats some statement or sequence of statements several times is called an iteration or a loop. • The repetition structure can be done with the while loop. • Loops are based on logical tests. • The While loop: is used to repeat a statement or a block of statements as long as a condition is true. • The pseudocode syntax and flowchart of the while loop are: Pseudocode : WHILE (condition) A statement or block of statements ENDWHILE Flowchart : 16 Repetition Example: Design an algorithm for a program that prints the numbers from 1 to 5. Pseudocode: Flowchart: Use variable: number number = 1 WHILE (number <= 5) Print number Add 1 to number ENDWHILE 17 Repetition Example: Write the pseudocode for reading the values of 6 test scores and finding their sum. a) Pseudocode 1. Start 2. sum = 0 3. Get the 1st testscore 4. Add first testscore to sum 5. Get the 2nd testscore 6. Add to sum 7. Get the 3rd testscore 8. Add to sum 9. Get the 4th testscore 10. Add to sum 11. Get the 5th testscore 12. Add to sum 13. Get the 6th testscore 14. Add to sum 15. Output the sum 16. Stop • Notice that there are repeated steps in the solution. • You should use loop. 18 Repetition The problem can be solved using loop: Pseudocode: Flowchart Start Use variables: testScore, sum, i sum= 0 i=1 WHILE( i<=6) Input testScore sum = sum + testScore i=i+1 ENDWHILE Output sum Stop 19 Popular High-Level Languages 20 Why Java? • Java is one of the most used computer programming languages in the world. • Java is a general purpose programming language. • Java is Object-Oriented (OO) — today’s key programming methodology 21 Interpreting/Compiling Source Code • A program written in a high-level language is called a source program or source code. • Because a computer cannot understand a source code, a source code must be translated into machine code for execution. • The translation can be done using another programming tool called an interpreter or a compiler. 22 Interpreting Source Code • An interpreter reads one statement from the source code, translates it to the machine code or virtual machine code, and then executes it right away. • A statement from the source code may be translated into several machine instructions. 23 Compiling Source Code • A compiler translates the entire source code into a machine-code file. • The machine-code file is then executed. 24 Java Programs • To write Java programs, you need to download and install the Standard Edition of Java Development Kit (JDK), which is a development environment includes tools useful for this purpose. • You need also to download an Integrated Development Environments (IDE) for Java. This is where you can edit and run your Java code. • IntelliJ is recommended since it is one of the most powerful and popular IDEs. • Guidelines for downloading IntelliJ are available on the LMS. 25 Java Programs Java programs normally go through 3 steps: 26 A Simple Java Program Single-line comment // This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } 27 A Simple Java Program Multi-line comment /* This program prints Welcome to Java! Written by:………. Date: ………… */ public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } 28 Reserved words • Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. • Keywords are always spelled with all lowercase letters. • public, class, static and void are all keywords. !This program prints Welcome to Java// {public class Welcome {public static void main(String[] args) ;System.out.println("Welcome to Java!") } } 29 Reserved words 30 Class • Every Java program must have at least one class. • Each class has a name. • Line 2 defines the class: Welcome !This program prints Welcome to Java// {public class Welcome {public static void main(String[] args) ;System.out.println("Welcome to Java!") } } 31 Class name • Class name is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($). • A class name can not: • Start with a digit. • Be a reserved word. • Contain space(s). 32 Class name Invalid class names: Valid class names: • • • • • • • • • • Student student StudentClass Student_class Student$class$ Student1 _tudentClass$ $StudentClass Class Public • • • • • • • • • 123student class public static void Student Class 1StudentClass Student#Class ?StudentClass It is good programming style to: - choose meaningful and descriptive names for the class name. - start the class name with an uppercase character. The main Method • Line 3 defines the main method. • In order to run a class, the class must contain a method named main. • The program starts execution from the main method. !This program prints Welcome to Java// {public class Welcome {public static void main(String[] args) ;System.out.println("Welcome to Java!") } } 34 Statements • A statement represents an action or a sequence of actions. • The statement System.out.println("Welcome to Java!") is a statement to display (print) the message "Welcome to Java! ". • "Welcome to Java! “ is a string. • String simply is any sequence of characters enclosed between 2 double quotations "". !This program prints Welcome to Java// {public class Welcome {public static void main(String[] args) System.out.println("Welcome to Java!"); } } --output-Welcome to Java! 35 Statements • There are 3 different print methods in Java: • print(): It prints its argument and does not add a new line to the output. • println(): It prints its argument and adds a new line to the output. • printf(): Is a formatted print (To e discussed later). 36 Statement Terminator Every statement in Java ends with a semicolon (;). // This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } 37 Blocks A pair of braces in a program forms a block that groups components of a program. Class block Method block // This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } 38 Special Symbols 39 Proper Indentation and Spacing • Indentation • Indent some spaces to make your code neat and readable. // This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } • Spacing • Use blank line to separate segments of the code. 40 Block Styles There are 2 block styles for braces: 1. Next-line style: // This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } 2. End-of-line style: // This program prints Welcome to Java! public class Welcome { public static void main(String[] args){ System.out.println("Welcome to Java!"); } } 41 What must you do before the next meeting? • Read carefully the material of this meeting. • Solve the exercises of the meeting. 42 Exercises Q1. Write Java programs to do the following: 1. Print your name and your student ID on the standard output in 2 lines. 2. Print the below text: I Love Java 3. Print the first letter of your name on the standard output in a nice format. For example, if your name is Ayman, you should print the letter A as: A A A A A AAAAAAAAA A A A A A A 43 Exercises Q2. What is the exact output of the following pieces of code: 1. System.out.print("Java is a "); System.out.print("programming language"); 2. System.out.println("Java is a "); System.out.print("programming language"); 3. System.out.println("Java is a\nprogramming\nlanguage"); 44 Exercises Q3. The following code includes 10 compilation errors (an error per line): 1. Find and correct them. 2. Give the exact output after correcting the cod. / Try to find the errors Public class Test1 { public static main(String[] a) { System.out.println('Welcome'); System.out.printIn("to"); System.out.println(“TM105); System.out.print("Nice ") System.out.println(Program); { ] 45