Computer Science II Lecture 1 Introduction and Background

Similar documents
CSCI-1200 Computer Science II Fall 2007 Lecture 1 Introduction and Background

CSCI-1200 Data Structures Fall 2011 Lecture 1 Introduction and Background

CSCI-1200 Data Structures Spring 2013 Lecture 1 Introduction to C++, STL, & Strings

CSCI-1200 Data Structures Spring 2015 Lecture 1 Introduction to C++, STL, & Strings

Introduction to Programming using C++

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Computer Programming : C++

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

COMP322 - Introduction to C++ Lecture 01 - Introduction

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Understanding main() function Input/Output Streams

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

Add Subtract Multiply Divide

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

Introduction to Programming

C++ for Python Programmers

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

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

COMP 202 Java in one week

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

4. Structure of a C++ program

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

2 nd Week Lecture Notes

CS111: PROGRAMMING LANGUAGE II

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Programming. C++ Basics

CE221 Programming in C++ Part 1 Introduction

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Computer Science II Lecture 2 Strings, Vectors and Recursion

CS 106 Introduction to Computer Science I

Fundamentals of Programming CS-110. Lecture 2

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

Chapter 2. C++ Basics

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

6.096 Introduction to C++ January (IAP) 2009

Chapter 2: Basic Elements of C++

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

C++ Programming for Non-C Programmers. Supplement

CS 11 java track: lecture 1

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

Cours de C++ Introduction

CS 231 Data Structures and Algorithms, Fall 2016

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

Fundamentals of Structured Programming

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

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements

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

Chapter 2 Basic Elements of C++

Programming with C++ as a Second Language

Objectives. In this chapter, you will:

Full file at

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

Chapter 2: Introduction to C++

MPATE-GE 2618: C Programming for Music Technology. Syllabus

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

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

DM550 Introduction to Programming part 2. Jan Baumbach.

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Your first C++ program

A SHORT COURSE ON C++

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

LECTURE 02 INTRODUCTION TO C++

Getting started with C++ (Part 2)

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Variables. Data Types.

Inf1-OP. Course Overview. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

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

Introduction to C ++

CSCI 1061U Programming Workshop 2. C++ Basics

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

Problem Solving With C++ Ninth Edition

CHAPTER 3 BASIC INSTRUCTION OF C++

Fast Introduction to Object Oriented Programming and C++

Introduction to the C++ Programming Language

Chapter 1 - What s in a program?

C++ Programming for Non-C Programmers. Supplement

Creating a C++ Program

UNIT- 3 Introduction to C++

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Scientific Computing

Chapter 15 - C++ As A "Better C"

Computer Programming

Chapter 2: Overview of C++

Computer Science II CSci 1200 Lecture 8 Iterators; Programming Examples

Exercise 1.1 Hello world

IS 0020 Program Design and Software Tools

Transcription:

Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis, in chronological order: 1. A high-level of abstraction in problem solving, writing programs using the container classes and functions in the standard library 2. Dynamic memory and writing our own container classes. 3. Recursion and algorithm analysis Material: textbooks, lecture notes, and examples posted on the web Overall expectations Prerequisites Lectures and lecture notes C++ vs. Java Requirements: Labs (12%), Homeworks (33)%), Quiz and exams (55%) Late policy Schedule of material Academic integrity

Reading Material The material for today s lecture is covered in the following sections of the two books. Accelerated C++ (Koenig and Moo): Chapter 0 C++ Programming (Malik): Chapter 2, Chapter 3 (pages 96-102 only), Chapters 4-6, Chapter 7 (pages 305-338), Chapter 9 (pages 423-442) If you are just beginning your foray into C++, you should not attempt to read and absorb all of the material in Malik in detail. Instead, you should use the readings as references for more information about the topics covered in class. 2

Example 1: Hello World Here is the standard introductory program in almost any programming language: // a small C++ program #include <iostream> int main() std::cout << "Hello, world!" << std::endl; return 0; Small though it is, it may be used to illustrate a number of important points. Basic Syntax Here Comments are indicated using // for single line comments and /* and */ for multi-line comments. #include asks the compiler for parts of the standard library that we wish to use (e.g. the input/output stream function std::cout). int main() is a necessary component of all C++ programs; it returns a value (integer in this case) and it could have parameters (later in the semester). : the curly braces indicate to C++ to treat everything between them as a unit. The Standard Library The standard library is not a part of the core C++ language. Instead it contains types and functions that are important extensions. In our programming we will use the standard library to such a great extent that it will feel like part of the C++ core language. 3

streams are the first component of the standard library that we see. std is a namespace that contains the standard library std::cout and std::endl are defined in the standard library (in particular, in the standard library header file iostream). Expressions Each expression has a value and 0 or more side effects. An expression followed by a semi-colon is a statement. The semi-colon tells the computer to throw away the value of the expression. The line std::cout << "Hello, world!" << std::endl; is really two expressions and one statement. We will go over this in detail in class. "Hello, world!" is a string literal. C++ vs. Java The following is provided as additional material for students who have learned Java and are now learning C++. In Java, everything is an object and everything inherits from java.lang.object. In C++, functions can exist outside of classes. In particular, the main function is never part of a class. Source code file organization in C++ does not need to be related to class organization as it does in Java. On the other hand, the requirement of one C++ class (when we get to classes) per file is the preferred organization, with the main function in a separate file on its own. Compare the hello world example above in C++ to the same example in Java: 4

public class HelloWorld public static void main(string args[]) System.out.println("Hello World"); The Java object member function declaration public static void main(string Plays the same role as int main() args[]) in the C++ program. A primary difference is that there are no string arguments to the C++ main function. Later we will add these arguments, although in a somewhat different syntactic form. The statement System.out.println("Hello is analogous to World"); std::cout << "Hello, world!" << std::endl; The std::endl is required to end the line of output (and move the output to a new line), whereas the Java println does this as part of its job. Example 2: Temperature Conversion Our second introductory example converts a Fahrenheit temperature to a Celsius temperature and decides if the temperature is above the boiling point or below the freezing point: #include <iostream> using namespace std; // Eliminates the need for std:: int main() // Request and input a temperature. cout << "Please enter a Fahrenheit temperature: "; float fahrenheit_temp; 5

cin >> fahrenheit_temp; // Convert it to Celsius and output it. float celsius_temp = (fahrenheit_temp - 32) * 5.0 / 9.0; cout << "The equivalent Celsuis temperature is " << celsius_temp << " degrees.\n"; // Output a message if the temperature is above boiling or below freezing. const int BoilingPointC = 100; const int FreezingPointC = 0; if ( celsius_temp > BoilingPointC ) cout << "That is above the boiling point of water.\n"; else if ( celsius_temp < FreezingPointC ) cout << "That is below the freezing point of water.\n"; return 0; Variables and Constants A variable is an object with a name (a C++ identifier such as fahrenheit_temp and celsius_temp). An object is computer memory that has a type. Too abstract? Think about float variables: Each variable has its own 4 bytes of memory, and this memory is formatted according floating point standards for what represents the exponent and mantissa. Many operations are defined on floats, including addition, subtraction... A float is an object A constant such as BoilingPointC and FreezingPointC is an object with a name, but the object can not be changed once it is defined (and initialized). Any operations on integer types may be applied to a constant int, except operations that change the value. 6

Note that the use of capitals and _ in the identifiers is merely a matter of style. Expressions, Assignments and Statements Consider the statement float celsius_temp = (fahrenheit_temp - 32) * 5.0 / 9.0; The calculation on the right hand side of the = is an expression. You should review the definition of C++ arithmetic expressions and operator precedence. The rules are pretty much the same in C++ and in Java. The value of this expression is assigned stored in the memory location of the newly created float variable celsius_temp. Conditionals and IF statements Intuitively, the meaning of the code if ( celsius_temp > BoilingPointC ) cout << "That is above the boiling point of water.\n"; else if ( celsius_temp < FreezingPointC ) cout << "That is below the freezing point of water.\n"; should be pretty clear. The general form of an if-else statement is if ( conditional-expression ) statement; else statement; Each statement may be a single statement, such as the cout statement above, a structured statement, or a compound statement delimited by... The second if is actually a structured statement that is part of the else of the first if. 7

Students should review the rules of logical expressions and conditionals. These rules and the meaning of the if - else structure are essentially the same in Java and in C++. Example 3: Julian Day Our third example illustrates the use of constant arrays, functions, and for loops #include <iostream> using namespace std; const int DaysInMonth[13] = 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ; // The following function returns true if the given year is a leap year // and returns false otherwise. bool is_leap_year( int year ) return year % 4 == 0 && ( year % 100!= 0 year % 400 == 0 ); // Calculate and return the Julian day associated with the given // month and day of the year. int julian_day( int month, int day, int year ) int jday = 0; for ( unsigned int m=1; m<month; ++m ) jday += DaysInMonth[m]; if ( m == 2 && is_leap_year(year) ) ++jday; jday += day; return jday; // February 29th 8

int main() cout << "Please enter three integers (a month, a day and a year): "; int month, day, year; cin >> month >> day >> year; cout << "That is Julian day " << julian_day( month, day, year ) << endl; return 0; Arrays and Constant Arrays An array is a fixed, consecutive sequence of objects all of the same type. The following declares an array of 15 double values: double a[15]; The values are accessed through subscripting operations: int i = 5; a[i] = 3.14159; assigns the value 3.14159 to location i=5 of the array. Here i is the subscript or index C++ array indexing starts at 0. Arrays are fixed size, and each array knows NOTHING about its own size. The programmer must write code that keeps track of the size of each array. In the next few weeks we will see a standard library generalization of arrays, called vectors, which do not have these restrictions. In the statement: const int DaysInMonth[13] = 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ; 9

DaysInMonth is an array of 13 constant integers. The list of values within the braces initializes the 13 values of the array, so that DaysInMonth[0] == 0, DaysInMonth[1]==31, etc. The array is global, meaning that it is accessible in all functions within the code (after the line in which the array is declared). Functions and Arguments Functions are used to: Break code up into modules for ease of programming and testing, and for ease of reading by other people (never, ever, under-estimate the importance of this!). Create code that is reusable at several places in one program and by several programs Each function has a sequence of parameters and a return type. For example, int julian_day( int month, int day, int year ) has a return type of int and three parameters, each of type int. The order of the parameters in the calling function (the main function in this example) must match the order of the parameters in the function prototype. for loops The basic form of a for loop is for ( expr1; expr2; expr3 ) statement; where expr1 is the initial expression executed at the start before the loop iterations begin; 10

expr2 is the test applied before the beginning of each loop iteration, the loop ends when this expresion evaluates to false or 0; expr3 is evaluated at the end of each iteration; statement is the loop body The for loop from the julian_day function, for ( unsigned int m=1; m<month; ++m ) jday += DaysInMonth[m]; if ( m == 2 && is_leap_year(year) ) ++jday; // February 29th adds the days in the months 1..month-1, and adds an extra day for Februarys that are in leap years. for loops are essentially the same in Java and in C++. A More Difficult Logic Example Consider the code in the function is_leap_year: return year % 4 == 0 && ( year % 100!= 0 year % 400 == 0 ); This is important to understand. If the year is not divisible by 4, the function immediately returns false. For years that are divisible by 4, if the year is not divisible by 100 or is divisible by 400 (and is obviously divisible by 100 as well), the function returns true. Otherwise the function returns false. The function would not work properly if the parentheses are removed, in part because && has higher precedence than. 11

Summary Three introductory examples. Basic structure of C++ code and the C++ main function iostreams and the standard library Java vs. C++ Variables, constants, operators, expressions and statements if-else arrays functions for loops logic All of this material should be review of your C++ knowledge or should be easily transferred from your experience with other programming languages. 12