The C++ Language. Arizona State University 1

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

Chapter 2: Introduction to C++

LECTURE 02 INTRODUCTION TO C++

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

CHAPTER 3 BASIC INSTRUCTION OF C++

BITG 1233: Introduction to C++

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:

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

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

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

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

Lecture 3 Tao Wang 1

UNIT- 3 Introduction to C++

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

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

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

Engineering Problem Solving with C++, Etter/Ingber

Integer Data Types. Data Type. Data Types. int, short int, long int

Chapter 2. C++ Basics

Chapter Two MULTIPLE CHOICE

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

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

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

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

Creating a C++ Program

2 nd Week Lecture Notes

Full file at

Introduction to Programming EC-105. Lecture 2

Fundamentals of Programming CS-110. Lecture 2

Chapter 2. Outline. Simple C++ Programs

Computer Programming : C++

CS242 COMPUTER PROGRAMMING

BASIC ELEMENTS OF A COMPUTER PROGRAM

Fundamental of Programming (C)

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

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

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

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

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

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

Chapter 2 Basic Elements of C++

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

Chapter 2: Overview of C++

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

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

CSc Introduction to Computing

A Fast Review of C Essentials Part I

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

Programming. C++ Basics

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

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

Basics of Java Programming

6.096 Introduction to C++ January (IAP) 2009

Lecture 2 Tao Wang 1

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

Programming with C++ as a Second Language

Introduction to the C++ Programming Language

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

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

IT 374 C# and Applications/ IT695 C# Data Structures

DEPARTMENT OF MATHS, MJ COLLEGE

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Reserved Words and Identifiers

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Fundamentals of Programming

Visual C# Instructor s Manual Table of Contents

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Unit 3. Constants and Expressions

C: How to Program. Week /Mar/05

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

INTRODUCTION 1 AND REVIEW

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

Work relative to other classes

UNIT-2 Introduction to C++

Maciej Sobieraj. Lecture 1

Topic 2: C++ Programming fundamentals

A First Program - Greeting.cpp

Variables and Constants

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

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Getting started with C++ (Part 2)

Introduction to Programming

3.1. Chapter 3: The cin Object. Expressions and Interactivity

CSCI 1061U Programming Workshop 2. C++ Basics

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

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

UEE1302 (1102) F10: Introduction to Computers and Programming

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

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

Introduction to C# Applications

Chapter 2. Lexical Elements & Operators

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

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

Transcription:

The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University 1

Parts of a C++ Program // sample C++ program #include <iostream> using namespace std; int main() { cout << "Hello, there!"; return 0; } comment preprocessor directive which namespace to use beginning of function named main beginning of block for main output statement send 0 back to operating system end of block for main Arizona State University 2

Special Characters Character Name Description // Double Slash Begins a comment # Pound Sign Begins preprocessor directive < > Open, Close Brackets Encloses filename used in #include directive ( ) Open, Close Parentheses Used when naming a function { } Open, Close Braces Encloses a group of statements " " Open, Close Double Quote Marks Encloses a string of characters ; Semicolon Ends a programming statement Arizona State University 3

Important Details C++ is case-sensitive. Uppercase and lowercase characters are different characters. Main is not the same as main. Every { must have a corresponding }, and vice-versa. Similar for parentheses, and square brackets. Arizona State University 4

cout Displays information on computer screen Use << to send information to cout cout << "Hello, there!"; You can use << to send multiple items to cout cout << "Hello, " << "there!"; Or cout << "Hello, "; cout << "there!"; Arizona State University 5

cout Printing New Lines To get multiple lines of output on screen, - Use endl: cout << "Hello, there!" << endl; - Use \n in an output string: cout << "Hello, there!\n"; Arizona State University 6

cout Escape Sequences Arizona State University 7

cout Escape Sequences (cont.) 1) Don t confuse \ (a back slash) and / (a forward slash). 2) Remember to put \n in double quotation marks. Arizona State University 8

#include Inserts the contents of another file into the program It is a preprocessor directive Not part of the C++ language Not seen by compiler Example: #include <iostream> (no semicolon here) Arizona State University 9

Variables A variable: Is used to refer to a location in memory where a value can be stored. An assignment statement is used to store a value. The value that is stored can be changed, i.e., it can vary. You must define the variable (indicate the name and the type of value that it can hold) before you can use it to store a value. Arizona State University 10

Variables Assignment If a new value is stored in the variable, it replaces the previous value. The previous value is overwritten and can no longer be retrieved. int age; age = 17; // Assigns 17 to age cout << age; // Displays 17 age = 18; // Now age is 18 cout << age; // Displays 18 The assignment statement uses the = operator. Has a single variable on the left side and a value on the right side. Copies the value on the right into the location in memory that is associated with the variable on the left: item = 12; Arizona State University 11

Variables Assignment vs. Initialization Assigning a value to a variable Assigns a value to a previously created variable A single variable name must appear on left side of the = symbol int size; size = 5+2; // legal 5 = size; // not legal Initializing a variable Gives an initial value to a variable at the time it is defined Some or all of the variables being defined can be initialized int length = 12; int width = 7, height = 5, area; Arizona State University 12

Variables Defining Variables of the same type can be defined - In separate statements: int length; int width; - In the same statement: int length, width; Variables of different types must be defined in separate statements. Arizona State University 13

Literals A literal is a piece of data that is written directly in the source code of the program. 'A' // character literal "Hello" // string literal 12 // integer literal "12" // string literal 3.14 // floating-point literal Arizona State University 14

Identifiers Programmer-chosen names to represent parts of the program, such as variables Name should indicate the use of the identifier Cannot use C++ key words as identifiers Must begin with alphabetic character or _, followed by any number of alphabetic, numeric, or _ characters. Alphabetic characters may be upper or lowercase Arizona State University 15

Identifiers (cont.) A variable name should reflect its purpose. Descriptive variable names may include multiple words. Two conventions to use in naming variables: Capitalize all words but the first letter of first word. Run words together: quantityonorder Use the underscore _ character as a space: quantity_on_order totalsales total_sales Use one convention consistently throughout a program. Arizona State University 16

Identifiers valid or not? totalsales total_sales total.sales 4thQtrSales total$sales Arizona State University 17

cin cin is the standard input object Like cout, requires iostream file Used to read input from keyboard Often used with cout to display a user prompt first Data is retrieved from cin with >>, the stream extraction operator Input data is stored in one or more variables. User input goes from keyboard to the input buffer, where it is stored as characters cin converts the data to the type that matches the variable int height; cout << "How tall is the room? "; cin >> height; Arizona State University 18

cin (cont.) Can be used to input multiple values cin >> height >> width; Multiple values from keyboard must be separated by spaces or [Enter] Must press [Enter] after typing last value Multiple values need not all be of the same type Order is important; first value entered is stored in first variable, etc. Arizona State University 19

Integers Designed to hold whole (non-decimal) numbers Can be signed or unsigned 12-6 +3 Available in different sizes (i.e., number of bytes): short int, int, long int, and long long int long long int was introduced in C++ 11. Arizona State University 20

Integers (un)signed C++ allocates one bit for the sign of the number. The rest of the bits are for data. If your program will never need negative numbers, you can declare variables to be unsigned. All bits in unsigned numbers are used for data. A variable is signed unless the unsigned keyword is used at variable definition. Arizona State University 21

Integers Definitions int can be omitted from a variable definition for any datatype except an int itself. Examples: short temperatures; unsigned short booksonorder; unsigned long long magnitude; int grades; Arizona State University 22

Integers Literals To store an integer literal in a long memory location, put L at the end of the number: long rooms = 234L; Use LL at the end to put an integer literal in a long long memory location. Literals that begin with 0 (zero) are octal, or base 8: 075 Literals that begin with 0x are hexadecimal, or base 16: 0x75A Arizona State University 23

Floating-Point Designed to hold real numbers 12.45-3.8 Stored in a form similar to scientific notation Numbers are all signed Available in different sizes (number of bytes): float, double, and long double Size of float size of double size of long double Arizona State University 24

Floating-Point Literals Can be represented in - Fixed point (decimal) notation: 31.4159 0.0000625 - E notation: 3.14159E1 6.25e-5 Are double by default Can be forced to be float 3.14159F or long double 0.0000625L Arizona State University 25

Floating-Point Assignment to Integers If a floating-point value (a literal or a variable) is assigned to an integer variable, The fractional part will be truncated (i.e., chopped off and discarded). The value is not rounded: int rainfall = 3.88; cout << rainfall; // Displays 3 Arizona State University 26

char Used to hold single characters or very small integer values Usually occupies 1 byte of memory A numeric code representing the character is stored in memory SOURCE CODE MEMORY char letter = 'C'; letter 67 Arizona State University 27

char Literals A character literal is a single character. When referenced in a program, it is enclosed in single quotation marks: cout << 'Y' << endl; The quotation marks are not part of the literal, and are not displayed. Arizona State University 28

Strings Literals Can be stored as a series of characters in consecutive memory locations: "Hello" Stored in consecutive memory locations with the null terminator, \0, automatically placed at the end: H e l l o \0 Is comprised of characters between the " ". Arizona State University 29

Characters vs. Strings A character literal is a single character, enclosed in single quotes: 'C' A string literal is a sequence of characters enclosed in double quotes: "Hello, there!" A single character in double quotes is a string literal, not a character literal: "C" Arizona State University 30

string Must #include <string> to create and use string objects Can define string variables in programs string name; Can assign values to string variables with the assignment operator name = "George"; Can display them with cout cout << "My name is " << name; Arizona State University 31

string Inputting Reading in a string object: string str; cin >> str; // Reads in a string // with no blanks getline(cin, str); // Reads in a string // that may contain // blanks Arizona State University 32

char Inputting Reading in a character: char ch; cin >> ch; // Reads in any non-blank char cin.get(ch); // Reads in any char ch=cin.get();// Reads in any char cin.ignore();// Skips over next char in // the input buffer Arizona State University 33

cin.ignore() General form: cin.ignore(n,c); n number of characters to skip c stop when character c is encountered How it works: It stops if c is encountered before n characters have been skipped. Otherwise, n characters are skipped. Use cin.ignore(); to skip a single character Arizona State University 34

string Functions length() length() the number of characters in a string string firstprez="george Washington"; int size=firstprez.length(); // size is 17 length() includes blank characters, and does not include the '\0' null character that terminates the string. Arizona State University 35

string Functions assign() assign() put repeated characters in a string. It can be used for formatting output. string equals; equals.assign(80,'=');... cout << equals << endl; cout << "Total: " << total << endl; Arizona State University 36

bool Represents values that are true or false bool values are stored as integers false is represented by 0, true by 1 bool alldone = true; bool finished = false; alldone 1 0 finished Arizona State University 37

What s the Size? The sizeof operator gives the size in number of bytes of any data type or variable. double amount; cout << "A float is stored in " << sizeof(float) << " bytes\n"; cout << "Variable amount is stored in " << sizeof(amount) << " bytes\n"; Arizona State University 38

auto If you are initializing a variable when it is defined, the auto keyword will determine the data type to use based on the initialization value. Introduced in C++11. auto length = 12; // length is // an int auto width = length; // also int auto area = 100.0; // area is a // double Arizona State University 39

Scope The scope of a variable is that part of the program where the variable may be used A variable cannot be used before it is defined int num1 = 5; cout << num1; cout << num2; int num2 = 12; // legal // illegal Arizona State University 40

Comments Are used to document parts of a program Are written for persons reading the source code of the program Indicate the purpose of the program Describe the use of variables Explain complex sections of code Are ignored by the compiler Arizona State University 41

Comments Single-Line Begin with // and continue to the end of line int length = 12; // length in inches int width = 15; // width in inches int area; // calculated area // Calculate rectangle area area = length * width; Arizona State University 42

Comments Multi-Line Begin with /* and end with */ Can span multiple lines: /*---------------------------- Here's a multi-line comment ----------------------------*/ Can also be used as single-line comments int area; /* Calculated area */ Arizona State University 43

Operators Arithmetic Used for performing numeric calculations C++ has unary, binary, and ternary operators unary (1 operand) -5 binary (2 operands) 13-7 ternary (3 operands) exp1? exp2 : exp3 SYMBOL OPERATION EXAMPLE ans + addition ans = 7 + 3; 10 - subtraction ans = 7-3; 4 * multiplication ans = 7 * 3; 21 / division ans = 7 / 3; 2 % modulus ans = 7 % 3; 1 Arizona State University 44

Operators / C++ division operator (/)performs integer division if both operands are integers: cout << 13 / 5; // displays 2 cout << 2 / 4; // displays 0 If either operand is floating-point, the result is floating-point: cout << 13 / 5.0; // displays 2.6 cout << 2.0 / 4; // displays 0.5 Arizona State University 45

Operators % C++ modulus operator (%) computes the remainder resulting from integer division: cout << 9 % 2; // displays 1 % requires integers for both operands: cout << 9 % 2.0; // error Arizona State University 46

Constants Also called constant variables Variables whose content cannot be changed during program execution Used for representing constant values with descriptive names const double TAX_RATE = 0.0775; const int NUM_STATES = 50; Often named in uppercase letters Arizona State University 47

Constants Initialization The value of a named constant must be assigned when the variable is defined: const int CLASS_SIZE = 24; An error occurs if you try to change the value stored in a named constant after it is defined: // This won t work CLASS_SIZE = CLASS_SIZE + 1; Arizona State University 48

Constants Benefits They make program code more readable by documenting the purpose of the constant in the name: const double TAX_RATE = 0.0775;... salestax = purchaseprice * TAX_RATE; They improve accuracy and simplify program maintenance: const double TAX_RATE = 0.0775; Arizona State University 49

Programming Style Refers to the visual arrangement of the source code. Provides information to the reader about the organization of the program. Includes alignment of matching { and } and the use of indentation and whitespace. Should be used consistently throughout a program. Arizona State University 50