CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Similar documents
Chapter 2: Basic Elements of C++

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++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Objectives. In this chapter, you will:

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

Main Memory Organization

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

Chapter 2 Basic Elements of C++

Another Simple Program: Adding Two Integers

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

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

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

Full file at

The C++ Language. Arizona State University 1

UNIT- 3 Introduction to C++

CS242 COMPUTER PROGRAMMING

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

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

BASIC ELEMENTS OF A COMPUTER PROGRAM

BITG 1233: Introduction to C++

Chapter 2: Introduction to C++

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

Chapter 2: Overview of C++

LECTURE 02 INTRODUCTION TO C++

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

1. In C++, reserved words are the same as predefined identifiers. a. True

Computer Programming : C++

Creating a C++ Program

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

A First Program - Greeting.cpp

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

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

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

Chapter 2. Outline. Simple C++ Programs

CHAPTER 3 BASIC INSTRUCTION OF C++

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Programming. C++ Basics

Chapter 2: Using Data

Engineering Problem Solving with C++, Etter/Ingber

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Reserved Words and Identifiers

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Lecture 3 Tao Wang 1

Topic 2: C++ Programming fundamentals

6.096 Introduction to C++ January (IAP) 2009

CSc Introduction to Computing

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

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

Fundamental of Programming (C)

Computer System and programming in C

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

BTE2313. Chapter 2: Introduction to C++ Programming

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

Programming with C++ as a Second Language

These are reserved words of the C language. For example int, float, if, else, for, while etc.

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

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

Chapter 1 Introduction to Computers and C++ Programming

CS201 Some Important Definitions

Chapter 1 INTRODUCTION

Introduction to C# Applications

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

CHAPTER 3 Expressions, Functions, Output

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Fundamentals of Programming CS-110. Lecture 2

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

Chapter 2. C++ Basics

UNIT-2 Introduction to C++

2 nd Week Lecture Notes

Introduction to Programming

Chapter 2 C++ Fundamentals

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Getting started with C++ (Part 2)

CSCI 1061U Programming Workshop 2. C++ Basics

Program Fundamentals

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

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

Introduction to Programming EC-105. Lecture 2

C Programming Primer 8/31/15 1

Introduction to Programming using C++

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Java Notes. 10th ICSE. Saravanan Ganesh

CS2255 HOMEWORK #1 Fall 2012

Visual C# Instructor s Manual Table of Contents

Review of Important Topics in CS1600. Functions Arrays C-strings

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

Introduction to the C++ Programming Language

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

A Fast Review of C Essentials Part I

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Lecture 2 Tao Wang 1

Chapter 7. Additional Control Structures

Transcription:

CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel identical. 9 of the 10 stacks contain coins that weigh 1 gram each while the 10th stack has coins that weigh 1.1 grams each Difference is undistinguishable by humans You have a digital scale which measures the number of grams of the total items on the scale, accurate to 0.1 grams. You can only use the scale ONCE! Select a set of coins to put on the scale all at once in such a way that you can identify which stack has the heavy coins 2

10 Stacks of Coins Solution Choose 1 coin from the 1 st stack, 2 coins from the 2 nd stack, etc. and weigh that collection The non-integer portion of the weight returned should indicate which stack 3

4 C++ Programming Computer program Sequence of statements whose objec9ve is to accomplish a task Programming Process of planning and crea9ng a program Real- world analogy: a recipe for cooking 4

5 A C++ Program 5

6 A C++ Program Output Sample run: 6

7 Dissec9ng: A C++ Program 7

8 Dissec9ng: A C++ Program 8

9 Memory for A C++ Program Variable: a memory loca9on whose contents can be changed 9

10 The Basics of a C++ Program Func9on (or subprogram): collec9on of statements; when executed, accomplishes something May be predefined or standard Syntax rules: rules that specify which statements (instruc9ons) are legal or valid Seman9c rules: determine the meaning of the instruc9ons Programming language: a set of rules, symbols, and special words 10

11 Comments Comments are for the reader, not the compiler Two types: Single line: begin with // // This is a C++ program. // Welcome to C++ Programming. Mul9ple line: enclosed between /* and */ /* */ You can include comments that can occupy several lines. 11

12 Special Symbols Token: the smallest individual unit of a program wriren in any language C++ tokens include special symbols, word symbols, and iden9fiers Special symbols in C++ include: 12

13 Reserved Words (Keywords) Reserved word symbols (or keywords): Cannot be redefined within program Cannot be used for anything other than their intended use Examples: int float double char const void return 13

14 Iden9fiers Iden9fier: the name of something that appears in a program Consists of lerers, digits, and the underscore character (_) Must begin with a lerer or underscore C++ is case sensi9ve NUMBER is not the same as number Two predefined iden9fiers are cout and cin Unlike reserved words, predefined iden9fiers may be redefined, but it is not a good idea 14

15 Iden9fiers Legal iden9fiers in C++: first conversion payrate 15

16 Whitespaces Every C++ program contains whitespaces Include blanks, tabs, and newline characters Used to separate special symbols, reserved words, and iden9fiers Proper u9liza9on of whitespaces is important Can be used to make the program more readable 16

17 Data Types Data type: set of values together with a set of opera9ons C++ data types fall into three categories: Simple data type Structured data type Pointers 17

18 Simple Data Types Three categories of simple data Integral: integers (numbers without a decimal) Can be further categorized: char, short, int, long, bool, unsigned char, unsigned short, unsigned int, unsigned long Floa9ng- point: decimal numbers Enumera9on type: user- defined data type 18

19 Simple Data Types Different compilers may allow different ranges of values 19

20 int Data Type Examples: -6728 0 78 +763 Cannot use a comma within an integer Commas are only used for separa9ng items in a list 20

21 bool Data Type bool type Two values: true and false Manipulate logical (Boolean) expressions true and false Logical values bool, true, and false Reserved words 21

22 char Data Type The smallest integral data type Used for single characters: lerers, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character WriRen ' ', with a space le\ between the single quotes 22

23 char Data Type (cont d.) Different character data sets exist ASCII: American Standard Code for Informa9on Interchange Each of 128 values in ASCII code set represents a different character Characters have a predefined ordering based on the ASCII numeric value Colla9ng sequence: ordering of characters based on the character set code 23

24 Floa9ng- Point Data Types C++ uses scien9fic nota9on to represent real numbers (floa9ng- point nota9on) 24

25 Floa9ng- Point Data Types float: represents any real number Range: - 3.4E+38 to 3.4E+38 (four bytes) double: represents any real number Range: - 1.7E+308 to 1.7E+308 (eight bytes) Minimum and maximum values of data types are system dependent 25

26 Floa9ng- Point Data Types Maximum number of significant digits (decimal places) for float values: 6 or 7 Maximum number of significant digits for double: 15 Precision: maximum number of significant digits Float values are called single precision Double values are called double precision 26

27 Data Types and Variables To declare a variable, must specify the data type it will store Syntax: datatype identifier; Examples: int counter; double interestrate; char grade; 27

28 Arithme9c Operators, Operator Precedence, and Expressions C++ arithme9c operators: + addi9on - subtrac9on * mul9plica9on / division % modulus (or remainder) operator +, -, *, and / can be used with integral and floa9ng- point data types Use % only with integral data types 28

29 Arithme9c Operators, Operator Precedence, and Expressions When you use / with integral data types, the integral result is truncated (no rounding) Arithme9c expressions: contain values and arithme9c operators Operands: the number of values on which the operators will work Operators can be unary (one operand) or binary (two operands) 29

30 Order of Precedence All opera9ons inside of () are evaluated first *, /, and % are at the same level of precedence and are evaluated next + and have the same level of precedence and are evaluated last When operators are on the same level Performed from le\ to right (associa9vity) 3 * 7-6 + 2 * 5 / 4 + 6 means (((3 * 7) 6) + ((2 * 5) / 4 )) + 6 30

31 Expressions Integral expression: all operands are integers Yields an integral result Example: 2 + 3 * 5 Floa9ng- point expression: all operands are floa9ng- point Yields a floa9ng- point result Example: 12.8 * 17.5-34.50 31

32 Mixed Expressions Mixed expression: Has operands of different data types Contains integers and floa9ng- point Examples of mixed expressions: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 13.6 + 18 / 2 32

33 Mixed Expressions Evalua9on rules: If operator has same types of operands Evaluated according to the type of the operands If operator has both types of operands Integer is changed to floa9ng- point Operator is evaluated Result is floa9ng- point En9re expression is evaluated according to precedence rules 33

34 Type Conversion (Cas9ng) Implicit type coercion: when value of one type is automa9cally changed to another type Cast operator: provides explicit type conversion static_cast<datatypename>(expression) 34

35 string Type Programmer- defined type supplied in ANSI/ISO Standard C++ library Sequence of zero or more characters enclosed in double quota9on marks Null (or empty): a string with no characters Each character has a rela9ve posi9on in the string Posi9on of first character is 0 Length of a string is number of characters in it Example: length of "William Jacob" is 13 35

36 Allocating Memory with Constants and Variables Named constant: memory loca9on whose content can t change during execu9on Syntax to declare a named constant: In C++, const is a reserved word 36

37 Alloca9ng Memory with Variables Variable: memory loca9on whose content may change during execu9on 37

38 Assignment Statement The assignment statement takes the form: Expression is evaluated and its value is assigned to the variable on the le\ side A variable is said to be ini9alized the first 9me a value is placed into it In C++, = is called the assignment operator 38

39 Assignment Statement 39

40 Saving and Using the Value of an Expression To save the value of an expression: Declare a variable of the appropriate data type Assign the value of the expression to the variable that was declared Use the assignment statement Wherever the value of the expression is needed, use the variable holding the value 40

41 Declaring & Ini9alizing Variables Not all types of variables are ini9alized automa9cally Variables can be ini9alized when declared: int first=13, second=10; char ch=' '; double x=12.6; All variables must be ini9alized before they are used But not necessarily during declara9on 41

42 Input (Read) Statement cin is used with >> to gather input This is called an input (read) statement The stream extrac9on operator is >> For example, if miles is a double variable cin >> miles; Causes computer to get a value of type double and places it in the variable miles 42

43 Input (Read) Statement Using more than one variable in cin allows more than one value to be read at a 9me Example: if feet and inches are variables of type int, this statement: cin >> feet >> inches; Inputs two integers from the keyboard Places them in variables feet and inches respec9vely 43

44 Input (Read) Statement.) 44

45 Increment and Decrement Operators Increment operator: increase variable by 1 Pre- increment: ++variable Post- increment: variable++ Decrement operator: decrease variable by 1 Pre- decrement: --variable Post- decrement: variable What is the difference between the following? x = 5; y = ++x; x = 5; y = x++; 45

46 Output The syntax of cout and << is: Called an output statement The stream inser9on operator is << Expression evaluated and its value is printed at the current cursor posi9on on the screen 46

47 Output A manipulator, like endl, is used to format the output 47

48 Preprocessor Direc9ves Many func9ons and symbols needed to run a C++ program are provided as collec9on of libraries Every library has a name and is referred to by a header file Preprocessor direc9ves are commands supplied to the preprocessor program All preprocessor commands begin with # No semicolon at the end of these commands 48

49 Preprocessor Direc9ves Syntax to include a header file: For example: #include <iostream> Causes the preprocessor to include the header file iostream in the program Preprocessor commands are processed before the program goes through the compiler 49

50 namespace and Using cin and cout in a Program cin and cout are declared in the header file iostream, but within std namespace To use cin and cout in a program, use the following two statements: #include <iostream> using namespace std; 50

51 Crea9ng a C++ Program A C++ program is a collec9on of func9ons, one of which is the func9on main The first line of the func9on main is called the heading of the func9on: int main() The statements enclosed between the curly braces ({ and }) form the body of the func9on 51

52 Crea9ng a C++ Program A C++ program contains two types of statements: Declara9on statements: declare things, such as variables Executable statements: perform calcula9ons, manipulate data, create output, accept input, etc. 52

53 Crea9ng a C++ Program C++ program has two parts: Preprocessor direc9ves The program Preprocessor direc9ves and program statements cons9tute C++ source code (.cpp) Compiler generates object code (.o) Executable code is produced and saved in a file 53

54 Syntax Syntax rules: indicate what is legal and what is not legal Errors in syntax are found in compila9on int x; //Line 1 int y //Line 2: error double z; //Line 3 y = w + x; //Line 4: error 54

55 Use of Blanks In C++, you use one or more blanks to separate numbers when data is input Blanks are also used to separate reserved words and iden9fiers from each other and from other symbols Blanks must never appear within a reserved word or iden9fier 55

56 Use of Semicolons, Brackets, and Commas All C++ statements end with a semicolon Also called a statement terminator { and } are not C++ statements Can be regarded as delimiters Commas separate items in a list 56

57 Seman9cs Seman9cs: set of rules that gives meaning to a language Possible to remove all syntax errors in a program and s9ll not have it run Even if it runs, it may s9ll not do what you meant it to do Ex: 2 + 3 * 5 and (2 + 3) * 5 are both syntac9cally correct expressions, but have different meanings 57

58 Naming Iden9fiers Iden9fiers can be self- documen9ng: CENTIMETERS_PER_INCH Avoid run- together words : annualsale Solu9on: Capitalizing the beginning of each new word: annualsale Inser9ng an underscore just before a new word: annual_sale 58

59 Prompt Lines Prompt lines: executable statements that inform the user what to do cout << "Please enter a number between 1 and 10 and " << "press the return key" << endl; cin >> num; Always include prompt lines when input is needed from users 59

60 Documenta9on A well- documented program is easier to understand and modify You use comments to document programs Comments should appear in a program to: Explain the purpose of the program Iden9fy who wrote it Explain the purpose of par9cular statements 60

61 Form and Style Consider two ways of declaring variables: Method 1 int feet, inch; double x, y; Method 2 int feet,inch;double x,y; Both are correct; however, the second is hard to read 61

62 Processing a C++ Program #include <iostream> using namespace std; int main() { cout << Hello, World" << endl; return 0; } Sample Run: Hello, World 62

63 Processing a C++ Program #include <iostream> using namespace std; int main(){ cout << Hello, World" << endl; return 0;} Sample Run: Hello, World 63

64 #include <iostream> using namespace std; int main() { cout << Hello, World" << endl; return 0; } Sample Run: Hello, World 64

65 Algorithm Development Algorithm: Get length of the rectangle Get width of the rectangle Find the perimeter using the following equa9on: perimeter = 2 * (length + width) Find the area using the following equa9on: area = length * width 65

66 Algorithm Development Problem: Calculate students grades and class average 10 students in a class; each student has taken five tests; each test is worth 100 points Design algorithms to: Calculate the grade for each student and class average Find the average test score Determine the grade Data: students names; test scores 66

67 Algorithm Algorithm to determine the average test score: Get the five test scores Add the five test scores Suppose sum stands for the sum of the test scores Suppose average stands for the average test score: average = sum / 5; 67

68 Algorithm Algorithm to determine the grade: if average is greater than or equal to 90 grade = A otherwise if average is greater than or equal to 80 and less than 90 grade = B otherwise if average is greater than or equal to 70 and less than 80 grade = C otherwise if average is greater than or equal to 60 and less than 70 grade = D otherwise grade = F 68

69 Algorithm Main algorithm is as follows: totalaverage = 0; Repeat the following for each student: Get student s data (name and test scores) Use the algorithm to find the average test score Use the algorithm to find the grade Update totalaverage by adding current student s average test score Determine the class average as follows: classaverage = totalaverage / 10 69

Algorithm Development: Fibonacci Number Consider the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34,... Called the Fibonacci sequence Given the input n The n th number a n, n >= 3, of this sequence is given by: a n = a n- 1 + a n- 2 70 70