Connecting with Computer Science, 2e. Chapter 15 Programming II

Similar documents
CS242 COMPUTER PROGRAMMING

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Full file at

Lab # 02. Basic Elements of C++ _ Part1

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Creating a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Data Types & Variables

Course Outline. Introduction to java

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

6.096 Introduction to C++ January (IAP) 2009

IT 1033: Fundamentals of Programming Data types & variables

The C++ Language. Arizona State University 1

Chapter 2: Overview of C++

Chapter 1 Introduction to Computers and C++ Programming

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Chapter 1 INTRODUCTION

AP Computer Science Unit 1. Writing Programs Using BlueJ

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

COMP 202 Java in one week

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Pace University. Fundamental Concepts of CS121 1

COMP 202 Java in one week

Chapter 2: Introduction to C++

Lecture 3 Tao Wang 1

CE221 Programming in C++ Part 1 Introduction

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Introduction to Java Unit 1. Using BlueJ to Write Programs

CS2141 Software Development using C/C++ C++ Basics

C Language, Token, Keywords, Constant, variable

Computer Programming : C++

CHAPTER 7 OBJECTS AND CLASSES

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Getting started with Java

Programming Language Basics

Software Practice 1 Basic Grammar

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

BTE2313. Chapter 2: Introduction to C++ Programming

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Variables. Data Types.

Maciej Sobieraj. Lecture 1

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Fundamentals of Programming CS-110. Lecture 2

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Lesson 2 Variables and I/O

AP Computer Science Unit 1. Writing Programs Using BlueJ

Objectives. In this chapter, you will:

C++ Programming: From Problem Analysis to Program Design, Third Edition

Introduction to Programming EC-105. Lecture 2

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

AP Computer Science Unit 1. Programs

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

COMP 202. Java in one week

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

CHAPTER 7 OBJECTS AND CLASSES

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

3. Java - Language Constructs I

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Introduction to Java & Fundamental Data Types

Array. Prepared By - Rifat Shahriyar

Tutorial-2a: First steps with C++ programming

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

CSCI 123 Introduction to Programming Concepts in C++

CS11 Java. Fall Lecture 1

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Lecture Set 2: Starting Java

Basics of Java Programming

BASIC ELEMENTS OF A COMPUTER PROGRAM

IS 0020 Program Design and Software Tools

LECTURE 02 INTRODUCTION TO C++

Lecture Set 2: Starting Java

Introduction to Java Applications

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Java+- Language Reference Manual

Zheng-Liang Lu Java Programming 45 / 79

REVIEW. The C++ Programming Language. CS 151 Review #2

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

REPETITION CONTROL STRUCTURE LOGO

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CEN 414 Java Programming

Scientific Computing

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Chapter 2. C++ Basics

Transcription:

Connecting with Computer Science, 2e Chapter 15 Programming II

Objectives In this chapter you will: Gain an understanding of the basics of high-level programming languages, using Java and C++ as examples Learn about variable types in Java and C++ and how they re used Explore the different control structures in Java and C+ + Connecting with Computer Science, 2e 2

Why You Need to Know About... Programming Languages Time, money, and effort go into learning computer programming languages The only real way to learn is practice, practice, and more practice After reading this chapter, you must sit down at the computer and practice the concepts frequently Connecting with Computer Science, 2e 3

Java and C++ Programming Languages Criteria for choosing a programming language: Tasks to perform Programmer s skill level Program s lifetime Software complexity being designed C++ and Java characteristics Support an object-oriented environment Usable on different operating systems Provide strong foundation for learning how to program Provide a springboard to other languages Connecting with Computer Science, 2e 4

Learning to Cook with Java and C++ Four ingredients to write programs: Variables Operators Control structures Objects Java and C++ high-level programming languages provide computer interaction Without speaking in binary 1s and 0s Connecting with Computer Science, 2e 5

Learning to Cook with Java and C++ Java history: (cont d.) Designed for Internet use Introduced by Sun Microsystems in 1995 Intended for small tasks or small applications (i.e., applets ) No need to write entire programs Developed into full-blown programming language Language of choice to develop communication devices and media applications (e.g., PDAs, cell phones, Internet, and networks) Connecting with Computer Science, 2e 6

Learning to Cook with Java and C++ Java s advantages: Uses familiar syntax Very portable Powerful and popular C++ history: (cont d.) Created by Bjarne Stroustrup at Bell Labs in 1983 Based on C with added features Object-oriented programming language Offers simplified memory management and access to low-level memory Connecting with Computer Science, 2e 7

Variables Have specific effects on a program s outcome Must have an identifier or name prior to use Declaration: statement associating an identifier with a variable, an action, or another programming element When declared, you specify attributes: Identifier (name) Type (character, numeric, Boolean, and so forth) Content Example: int numticketsbought; Connecting with Computer Science, 2e 8

Variable Naming Conventions Rules for declaring a variable in Java or C++ Use only letters, underscores, numbers Begin name with a letter Avoid Java and C++ reserved words Reserved word Keyword with a specific instructional meaning Name cannot be used for a variable Programming language already using it as an instruction Connecting with Computer Science, 2e 9

Variable Types Java and C++ are strongly typed Must declare type of data a variable can hold Major Java data types: Six number-related data types One character related One for true and false (Boolean) Major C++ data types Adds a type for signed or unsigned numbers Syntax for declaring a variable: type variablename; Connecting with Computer Science, 2e 10

Integer Data Types Used for positive and negative whole numbers Java example int studenttickets; short studentfees; long studenttuition; byte studentgrade; C++ example int studenttickets; short int studentfees; unsigned int totalpoints; Connecting with Computer Science, 2e 11

Integer Data Types (cont d.) Table 15-1, Java integer data types Table 15-2, C++ integer data types Connecting with Computer Science, 2e 12

Floating-Point Data Types Used for positive and negative numbers containing decimals Examples of declaring variables in both languages: float salary; double billgatessalary; Connecting with Computer Science, 2e 13

Floating-Point Data Types (cont d.) Table 15-3, Java floating-point data types Table 15-4, C++ floating-point data types Connecting with Computer Science, 2e 14

Character Data Type Used for variables holding only one character Example: char studentmiddleinit; Table 15-5, Java character data type Table 15-6, C++ character data types Connecting with Computer Science, 2e 15

Boolean Data Type Used for only one of two values: true or false Java and C++ Cannot associate a number with a Boolean value Rely on true or false Java Boolean variable declaration: boolean deserveraise; C++ Boolean variable declaration: bool deserveraise; Connecting with Computer Science, 2e 16

Boolean Data Type (cont d.) Table 15-8, C++ Boolean data type Table 15-7, Java Boolean data type Connecting with Computer Science, 2e 17

String Data Type Stores a piece of information Not a number Contains more than one character Declared using double quotes Uses the String or string keywords Examples of an empty string: String sname; //Java String string sname; //C++ string Connecting with Computer Science, 2e 18

String Data Type (cont d.) Examples of a string with contents assigned: String sname = "Joe Blow"; //Java string sname = "Joe Blow"; //C++ Concatenation operator The (+) operator Process of combining or joining strings into one value See example code on pages 517 518 Connecting with Computer Science, 2e 19

Hungarian Notation Variable-naming method Adds a letter at the beginning of a variable name Indicates data type Table 15-9, Hungarian notation examples Connecting with Computer Science, 2e 20

Variable Content When variable is declared: Use an equal sign (=) to assign a value immediately Variable initialization: supplying value when variable is first declared Do not always have to initialize a variable Programming language may assign a default value Example: int istudentcount; istudentcount = 456; Alternative: int istudentcount = 456; Connecting with Computer Science, 2e 21

Variable Content (cont d.) Assigning a value to a character variable Enclose in single quotes Example: char cmiddleinit; cmiddleinit = 'S'; Alternative: char cmiddleinit = 'S'; Connecting with Computer Science, 2e 22

Variable Content (cont d.) Assigning a value to a string variable Enclose in double quotes Example: String smiddlename = "S"; //Java string smiddlename = "S"; //C++ Connecting with Computer Science, 2e 23

Java and C++ Control Structures and Program Flow Four types of control structures: Invocation Top down Selection Repetition Correct use allows for a(n): Readable program Easy to maintain program Connecting with Computer Science, 2e 24

Invocation The main() function block of code Tells operating system the starting point Function: block of code performing a task Can return a value Example: Save_Ferris.java file public class Save_Ferris { public static void main(string[] args) { System.out.println("I could have been the Walrus!"); } } Connecting with Computer Science, 2e 25

Invocation (cont d.) Parameters: received value assigned to a variable Used by a block of source code Passing parameters as values Enter them on same line After Java program name Example: C:\>hello 10 C++ has a main() function in every program Software engineers often include other files of source code to perform common task Connecting with Computer Science, 2e 26

Invocation (cont d.) C++ allows words inside parentheses Indicates parameters receiving data when the program runs Parameters allow users to pass data to main() and then use the data in the program Examples: int argc, char *argv[ ] //C++ main receiving parameters int main(int argc, char *argv[]) Connecting with Computer Science, 2e 27

Top Down (or Sequence) Used when program statements executed in sequential order Starting at the top and working down to the bottom See example code on pages 522 and 523 Connecting with Computer Science, 2e 28

Blocks of Code Sequence of several statements enclosed with opening and closing braces Indicates a relation Makes program more readable and accurate Braces are used most often when working with invocation, selection, repetition control structures Example: Connecting with Computer Science, 2e 29

Java Output Data Java System.out statement sends data to output device Insertion point: where the cursor is placed Two methods to output data: System.out.print(expression); System.out.println(expression); Connecting with Computer Science, 2e 30

Java Output Data (cont d.) Table 15-10 Java output statements Connecting with Computer Science, 2e 31

C++ Output Data C++ cout statement Sends data to output device Uses redirection symbols (<<) to direct output Example: cout << "15 + 10 = " << iresult <<endl; Instructs compiler to direct anything following the << symbols to the defined output device Connecting with Computer Science, 2e 32

C++ Output Data (cont d.) Table 15-11, Sample C++ output statements Connecting with Computer Science, 2e 33

Input Data Java System.in Method to retrieve data from the input device Must create a new variable from the Scanner class Reads characters from input stream (keyboard) Places them into another variable acting as a memory buffer for storing the entered string Input assigned to a string variable declared by making a call to the next() method C++ cin Used to retrieve data from input device Connecting with Computer Science, 2e 34

Back to Control Structures Java and C++ invocation Implemented by calling functions and methods Function: performs a task, can return a value Method: function belonging to a class Java equals() method System passes control to code associated with equals() Carries out the statements Makes the comparison Returns a Boolean value Connecting with Computer Science, 2e 35

Selection First write algorithm with pseudocode Ensures program meets language requirements Guide or template for writing source code Recall Chapter 14 algorithm converting Celsius to Fahrenheit temperatures and vice versa See corresponding code on pages 531 533 Connecting with Computer Science, 2e 36

if and if-else Statements Used to weigh results of decision making Result exists for every choice Syntax: if (condition) { one or more statements; } Connecting with Computer Science, 2e 37

if and if-else Statements (cont d.) Condition Expression returning true or false value May add an else part to the control structure Performs a function if the if control structure evaluates to a false value Syntax: if (condition) { one or more statements; } else { one or more statements; } Connecting with Computer Science, 2e 38

if-else-if Statement Corrects problem in if-else statement User enters incorrect input value Allows certain blocks of code to execute Depends on variable s state in the program while it is running Easy to use Makes program more flexible Connecting with Computer Science, 2e 39

switch Statement Nesting Putting one control structure inside another Decreases code s readability switch statement: Allows testing of many options Groups blocks of code to be executed depending on results Test expression s value Jump to some location in the switch statement Expression must be a scalar data type Connecting with Computer Science, 2e 40

Copy editor: Syntax alignment OK as is? (different in PDF) switch Statement (cont d.) break statement at end of each case Informs system to quit processing case statements Sends control to end of the switch statement Syntax: switch (expression) { case value_1 : statement_1; break; case value_2 : statement_2; break; case value_3 : statement_3; break; default : statement_4; break; } Connecting with Computer Science, 2e 41

Repetition (Looping) Allows repeating statements multiple times No statement retyping Three statements: for while do-while Connecting with Computer Science, 2e 42

for Statement Used to repeat a group of statements a known number of times Variable declaration Declare and initialize a variable Declare counter variable Syntax: Example: int icount for (variable declaration; expression; increment/decrement) { statement(s); } Connecting with Computer Science, 2e 43

while Statement Processes a group of statements a certain number of times Like the for loop Precondition loop Loop checks the expression before any source code in the loop is executed Might never be executed Difference between for and while loops while statement doesn t provide a specified area for updating the counter Connecting with Computer Science, 2e 44

while Statement (cont d.) Syntax: while (expression) { statements; } Connecting with Computer Science, 2e 45

do-while Statement Used when looping is based on an expression and statements are repeated before the expression is evaluated Mainly when processing a table Postcondition loop Executes at least one time before the expression is evaluated Syntax: do { statement(s); } while (expression); Connecting with Computer Science, 2e 46

One Last Thought Most programming languages use the four major control structures discussed in this chapter Organizations select a programming language based on application s needs Programmers may need to update skills C++ and Java is a good start Must practice to become proficient Software engineers responsibility: write easy-toread and easy-to-maintain structured programs Connecting with Computer Science, 2e 47

Summary Java: high-level programming language designed for the Internet C++: high-level programming language based on the C language Incorporates object-oriented principles Variables: Integer (int), character (char), floating point, Boolean, and string Initializing a variable : assigning a value to a variable Connecting with Computer Science, 2e 48

Summary (cont d.) Four high-level programming language control structures: Invocation, top down, selection, repetition Java uses methods for the invocation C++ uses methods and functions Output data: Java uses the System.out statement C++ use the cout statement with the << redirection symbols Connecting with Computer Science, 2e 49

Summary (cont d.) Input data: Java Scanner class gathers input C++ uses the cin statement Selection control structures: C++ and Java use if, if-else, if-else-if, switch switch statement is used only with scalar variables Repetition: C++ and Java use for, while, do-while loops Practice, practice, and more practice Connecting with Computer Science, 2e 50