Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computer Science

Similar presentations


Presentation on theme: "Introduction to Computer Science"— Presentation transcript:

1 Introduction to Computer Science
Computer Programming Welcome to Introduction to Computer Science: Computer Programming. This is lecture c. The component, Introduction to Computer Science, provides a basic overview of computer architecture; data organization, representation, and structure; structure of programming languages; networking, and data communication. It also includes the basic terminology of computing. Lecture c This material (Comp 4 Unit 4) was developed by Oregon Health & Science University, funded by the Department of Health and Human Services, Office of the National Coordinator for Health Information Technology under Award Number 90WT0001. This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit Health IT Workforce Curriculum Version 4.0

2 Computer Programming Learning Objectives - 1
Define the purpose of programming languages (Lecture a) Differentiate between the different types of programming languages and list commonly used ones (Lecture a) Explain the compiling and interpreting process for computer programs (Lecture b) The learning objectives for this unit, Computer Programming, are to: Define the purpose of programming languages Differentiate between the different types of programming languages and list commonly used ones Explain the compiling and interpreting process for computer programs

3 Computer Programming Learning Objectives - 2
Learn basic programming concepts including variable declarations, assignment statements, expressions, conditional statements and loops (Lectures c, d) Describe advanced programming concepts including objects and modularity (Lecture e) Learn basic programming concepts including variable declarations, assignment statements, expressions, conditional statements, and loops And describe advanced programming concepts including objects and modularity

4 Programming Constructs
Declarations (variables/constants) Assignment Statements Expressions Input and Output (I/O) Statements Control Structures Data Structures Modules Procedures Methods Objects This lecture focuses on basic programming concepts and includes a program-writing exercise to calculate body mass index. This is the first of two lectures covering basic computing concepts. We turn now to the common constructs of most programming languages. A construct is a basic building block used by a programming language, or the language’s basic elements, key words, commands, and statements. For example, when programming in Java, some of the key words you might use are continue, for, switch, package, and Boolean. When programming in C, some of the constructs you might encounter are if…else, switch…case, and loops. Throughout this lecture, we will use examples from Java to illustrate the details. Health IT Workforce Curriculum Version 4.0

5 Variables Variables store data Data stored by a variable is its value
Referred to by unique names Point to memory locations Data stored by a variable is its value Value is stored in the memory location Its value can be changed (i.e., variable) Similar construct for constants (value cannot change) The first topic is variables – every programming language uses them and most require them to be declared. When a variable is declared, it means you are defining its data type and you may even set its initial value. Variables are constructs that store data in a computer program. Within a program, the variable is referred to by a unique name. When the program is executed, the variables point to memory locations that hold the corresponding data. The value of a variable is the value that is stored in the given memory location. This value can be changed an unlimited number of times during the program execution; every time the variable’s value changes, the content of the corresponding memory location is updated. There is a similar construct that holds values that remain the same during the program execution; these are called constants. They, too, are stored in memory, but their values cannot be changed.

6 Data Type Every variable and constant belongs to some data type
Knows how much memory to use Knows how to handle data Common data types Integer Floating point Character Boolean Every variable and constant belongs to some data type; this refers to what kind of data the variable or constant can be assigned. Data types can be integers, which are whole numbers; floating point numbers, which are numbers with a decimal part; characters, which are any alpha-numeric single character; and Boolean values, which are either true or false, among others. Among other things, the data type of a variable determines how much memory needs to be allocated to store its value. For example, floating point numbers require more space than integers. Also, the program and computer need to know how to handle the data. Different data types encode values into binary numbers differently; hence, a value stored in memory needs to have a type associated with it so that it can be used properly.

7 Java Data Types Java is a strongly typed language Java data types
All variables must be declared and their types specified before they can be used Java data types Primitive int, double, float, char, boolean Class String Other user/library defined types Java is a strongly typed language. This means that all variables must be declared with a given data type before they can be used. Many other languages use implicit typing where declarations are not used. Instead, the data type is inferred from the values that are assigned to the variables. Java has two categories of data types: primitive and class types. Primitive types are used for single, simple variables. The slide lists some of the primitive types: int for integer; double and float for floating point numbers; char for character; and Boolean. Class types refer to data types used to create objects. Class types can be defined by users or within Java libraries. A commonly used class type is String, which is a series of characters.

8 Declaration Statements in Java
Variable declarations specifies name and type; variable must be declared before use int age; Java examples double bmi; char gender; boolean completed; Note: Most Java statements end with a semicolon Declaration statements define variables – variables are given a name and their data type is specified, as is required for strongly typed languages. The variable's type determines what values can be assigned to it. For example, a floating point variable cannot hold a character. Typically, we will put variable declarations at the start of a module. Here are some examples of declaration statements in Java: A variable named age that is an integer A variable named bmi that is of type double, which is one of the floating point types A variable named gender that is of type char; this data type will hold one character A variable named completed that is of type Boolean; this type will hold the values true or false, in other words, a one or zero  Note that all these declaration statements have a semicolon at the end of them. Most Java statements end with a semicolon. It should also be noted that not every programming language requires one to explicitly declare variables; some allow implicit declaration of a variable to occur the first time the variable is referenced.

9 Assignment Statements
An assignment statement is used to assign a value to a variable age = 42; The “equal sign” is the assignment operator After a variable is declared, then the variable can be used in the program. One way a variable is used in a program is to have a value assigned to it. That is called an assignment statement. In Java, it looks like this example: age equal sign 42 semicolon. The equal sign is called the assignment operator. Note that this is different from the equality operator, which will appear later.

10 Values and Expressions
Values can be specified by literals such as 18 2.5 'a' Values can be specified by expressions such as weight/2 5 + age 3 + 2/5 * 15 n*m As demonstrated in the previous slide, values can be assigned to variables, but what exactly constitutes a valid value? We can use what are called literals – actual values such as 18, 2.5, or the character “a”. But values can also be specified by expressions. Expressions are composed of some combination of literals, variables, and operators as shown by these examples. The value of the variable “weight divided by 2” is an expression, as is “5 plus the value of the variable age”. An expression can be made up of all literals such as “3 plus 2 divided by 5 multiplied by fifteen”. Or it can be made up of all variables, such as the values of the variables “n” and “m” multiplied together.

11 Arithmetic Expressions
Arithmetic expressions contain operators and evaluate to a value +, -, *, / Order of evaluation is determined by precedence Expressions in parentheses evaluated first Then *,/ Then +, - Same order of precedence evaluated left to right Arithmetic expressions are combinations of arithmetic operators, literals, and variables that evaluate to a value. The arithmetic operators include plus, minus, multiply, and divide. The order in which these operators are evaluated is determined by precedence. Any expression in parentheses is evaluated first. Then, any “multiplies and divides” are evaluated, and then the “adds and subtracts.” If all the operators have the same order of precedence, for example, all are additions, then the expression is evaluated in order from left to right.

12 Expression Examples What is the value of tricky after the assignment?
bmi = weight / (height * height); age = age + 1; tricky = * 2; What is the value of tricky after the assignment? So, here are some examples of expressions used in assignment statements. Assignment statements set or reset the value stored in a variable. The first assignment assigns to the variable “bmi” the value of weight, divided by height times height. Note that because height times height is in parentheses, it will be evaluated first. Then the value will be divided into weight to finish the evaluation. Another assignment statement often seen is incrementing a variable. This is shown by the second example: age gets age plus one. Note that from a mathematical perspective, the statement age equals age plus one makes no sense. But, remember, equality is not the issue here – this is an assignment. So, if age had the value 30, then the assignment statement would change the age to or 31. Finally, consider the order of operations to know what value the final assignment statement has. The variable “tricky” is assigned the value of 3 plus 5 times 2. This evaluates to thirteen since 5 times 2 is evaluated first, for a result of ten, then 3 is added to that which makes 13. Note that it is NOT evaluated in order from left to right – this computation would result in a total of sixteen, 3 plus 5, which is 8 times 2, which is sixteen, which is incorrect.

13 Input and Output All programming languages support data input
Keyboard Files All programming languages support data output Screen All programming languages provide programming statements for inputting and outputting data; most programs need data in order to do anything useful. Programs can get data from users typing in values using the keyboard or by reading input files. If this were more advanced programming, data could come from databases or from elements on a graphical user interface. Similarly, all programs provide output onto the screen or written out to files. There are other options of output to printers or graphical user interfaces. For these examples in Java, we will focus on showing how to get input from the keyboard and display output to the computer screen.

14 Screen Output in Java Output can be written using Code examples
System.out.println() prints the specified string and moves the cursor to a new line System.out.print() prints the specified string and does not move cursor to a new line Code examples System.out.println("Hello World!"); System.out.print("My name is "); System.out.println(name); System.out.println(gender); To write information to the screen in Java, different commands can be used. These are provided in the System.out class – they are “print” and “println”, which stands for printline. Print does not move the cursor to a new line, while println does. Here are some examples of how to use print statements in Java. The first statement, “System-dot-out-dot-println-open parenthesis-quote-hello world-exclamation point-quote-close parenthesis-semicolon” is how to write “Hello World!” to the computer screen. To output the text “Hello World!”, enclose it in quotes. Everything that we want to print goes between the parentheses that appear after the print or println method name. The print command works the same way. The statement “System-dot-out-dot-print-open parenthesis-quote-My name is-quote-close parenthesis-semicolon,” followed by the statement “System-dot-out-dot-println-open parenthesis-name-close parenthesis-semicolon,” would print “My name is” and whatever is stored in the variable name all on one line. Name does NOT have quotes around it, which means that it is a variable. To use a print statement to print a variable, it prints whatever the value is of that variable. Similarly, a user can print out the value of the variable gender by using the statement System-dot-out-dot-println-open parenthesis-gender-close parenthesis-semicolon.

15 Keyboard Input in Java Keyboard input is more complicated
One way is to include package java.util Must create object of the Scanner class Scanner keyboard =new Scanner(System.in); Use methods in Scanner class next(); nextLine(); nextDouble(); nextInt(); Example age = keyboard.nextInt(); Getting input from the keyboard in Java, is more complicated than writing screen output. There are several ways to do it; the one shown here requires the java.util package. Packages in Java are libraries of code that provide special functionality. In this case, this package is predefined within Java itself but is not automatically included in programs as is System.out. To include the package, use the statement “import java-dot-util-dot-star-semicolon” at the top of the code. An example of this appears on slide 18. Next, it is necessary to create an object of the Scanner class and tell Scanner where to get input. In this case, input will be from the keyboard, which is defined as System.in. The statement to do this is shown here: Scanner keyboard gets new Scanner open parenthesis System-dot-in close parenthesis semicolon. These commands created an object called keyboard that is of type Scanner and gets its input from System.in, which is the keyboard. Methods that are defined in the Scanner class will get input from the keyboard. These methods are: next, which gets the next string or word of characters nextLine, which gets the next line of characters nextDouble, which gets the next double value nextInt, which gets the next integer value  Here is an example of using such a method call in Java programming. Because all these methods produce a value, use them wherever a value or an expression is used, like an assignment statement. In this case, a user assigns to the variable age the value returned by keyboard-dot-nextInt. To fully understand the Scanner class and how to use it, you need to understand object-oriented programming. The last lecture of this unit addresses that topic, as does any textbook on Java programming.

16 Example Write a Java program that calculates BMI (body mass index)
Read in weight (kg) Read in height (m) Calculate BMI Output BMI To write a simple interactive program that will calculate body mass index, or BMI, you would enter weight in kilograms and height in meters. The program would then calculate the BMI and output it to the screen. (tom, 2009, PD-US)

17 Program Design Prompt user for weight (kg) Read in weight
Prompt user for height in m Read in height Calculate BMI using the formula BMI = weight/(height * height) Output BMI The first thing to do before writing any code is to design the program. Because it will be a very simple program, the design will not look very different from the program statement. Nevertheless, the design requires listing all the details needed for the program, such as the formula for calculating BMI. Programs are designed using what is called pseudocode. Pseudocode is a written description of what the computer program will do, but written in natural language rather than in a programming language. The pseudocode begins with a prompt to the user for their weight in kilograms. Then, the pseudocode reads in the value entered for the weight and prompts the user to enter their height in meters. Then, the pseudocode reads in the value for their height and calculates the BMI. In metric values, the formula for BMI is weight divided by height squared. Height squared can be written as height times height. Then, the pseudocode outputs the BMI, which finishes the program.

18 Example Java Program Here is what the Java program looks like, line by line. For reference, the line numbers are shown on the left; these are not part of the code. What is written on the right side of the double forward slashes are the comments. Comments are used to clarify and document a program and do not effect code execution. One, the first statement imports the package java-dot-util. Two, the next line is the first line of the class CalcBMI. This is the name of the class that contains the program. In Java all code must belong to a class; the name of this code is CalcBMI. Three, the next line is the open curly bracket, which is used to signify the start of a class, a method, and so forth. Four, the next line is the first line of the main method. All code in Java is either an instance variable declaration or part of a method definition. Every program in Java must contain a main method. Because this program is short, all the code can be put in the main method without being concerned about the exact syntax of how the main method is defined in this line. Five, the next line is another open curly bracket. This signifies the start of the main method. Six, now come the variable declarations, which are needed to store the weight, height, and BMI. The code gives them the data type “double” since they may have decimal values. Note that because they all have the same type, they can all be declared in one statement, with the variable names separated by commas. Seven, the Scanner object, named keyboard, is just like the example on the previous slide. Eight, the next line is blank to separate the variable declarations from the rest of the code. There can be as many blank lines in our code as necessary—Java does not care. Nine, now the programmer can write code. The first line of output will say, "Welcome to the BMI calculator.” Ten, the, the next output line gives the direction to the user to enter their weight in kilograms. Without this line, the user would not know what to do. Eleven, next, the nextDouble method in the keyboard object will read in the value the user entered and then assign it to the variable weight. Twelve, the program repeats the process for the height and outputs a prompt to the user to enter the height in meters. Thirteen, the nextDouble method in the keyboard object is used to read in the value that the user entered and then assign it to the variable height. Fourteen, now the program is ready to calculate the BMI, assigning the variable “bmi” to the value “weight divided by height times height.” Fifteen, then the program outputs the label "BMI is" without a line return. Sixteen, finally, the program outputs the value of the bmi variable. Seventeen, the next line is a close curly bracket which ends the main method. Eighteen, the final line is a close curly bracket which ends the CalcBMI class definition. And that's all the code!

19 Sample Output Welcome to the BMI calculator Enter weight in kg 68 Enter height in m 1.72 BMI is Note: Values in purple are entered by the user Here is a sample output from running the program. The statement "Welcome to the BMI calculator" is output. Then, the screen prompts the user to enter their weight in kilograms. In this case, the user enters 68 - all values shown in purple are user-entered values. Next, it prompts the user to enter the height in meters. The user enters Finally, after calculating the BMI, the program outputs it. In this case, it is …and so on. Some more formatting would be necessary to output the decimal value with only 2 or 3 decimal places, but that is not necessary for this example. At this point, feel free to go back to the previous slides to review the code again, comparing it with what the computer outputs on the screen. It is not necessary to understand every little syntax detail, but it is valuable to understand the basics of variables, data types, declarations, assignment statements, and input and output statements.

20 Computer Programming Summary – Lecture c
There are constructs common for most programming languages Variables store data and have a data type Variables can be assigned values or expressions Java provides variable declaration, assignment, and expression statements Java has input and output statements and classes This concludes lecture c of Computer Programming. To summarize, there are constructs common for most programming languages. They provide ways to store values in variables. Because there are different types of values or data, there are different data types such as integer, character, and boolean, among others. The variables can be assigned values or expressions containing variables and values. Java requires that variables be declared with their data type before they are used. Values can be assigned to variables using the equals sign. Java also provides statements for getting input and output from the user during the execution of the program. One way to do output is to use System.out.print(). Input can be done using an object from the Scanner class.

21 Computer Programming References – Lecture c
Eck, D. (2011). Introduction to Programming Using Java (6th ed.). Retrieved from Morley, D., & Parker, C.S. (2010). Chapter 13: Program Development and Programming Languages. In Understanding Computers Today and Tomorrow, 12th Edition introductory. Boston: Course Technology. Parsons, J.J., & Oja, D. (2010). Chapter 12: Computer Programming. In New Perspectives on Computer Concepts 2011: Comprehensive (13th ed.). Boston: Course Technology. The Java Language: An Overview. (2007, December). Retrieved March 21, 2011, from Sierra, K., & Bates, B. (2009). Head First Java (2nd Ed.). O’Reilly Media. Images Slide 16: Bathroom scale. [image on the Internet]. User: tom. (2009, April 1). Retrieved November 12, 2011, from This file has been released into the Public Domain. References slide. No audio.

22 Introduction to Computer Science Computer Programming Lecture c
This material was developed by Oregon Health & Science University, funded by the Department of Health and Human Services, Office of the National Coordinator for Health Information Technology under Award Number 90WT0001. No audio.


Download ppt "Introduction to Computer Science"

Similar presentations


Ads by Google