3.1 The cin Object. Expressions & I/O. Console Input. Example program using cin. Unit 2. Sections 2.14, , 5.1, CS 1428 Spring 2018

Size: px
Start display at page:

Download "3.1 The cin Object. Expressions & I/O. Console Input. Example program using cin. Unit 2. Sections 2.14, , 5.1, CS 1428 Spring 2018"

Transcription

1 Expressions & I/O Unit 2 Sections 2.14, , 5.1, 5.11 CS 1428 Spring 2018 Ji Seaman The cin Object cin: short for consoe input a stream object: represents the contents of the screen that are entered/typed by the user using the keyboard. requires iostream ibrary to be incuded >>: the stream extraction operator use it to read data from cin (entered via the keyboard) cin >> height; when this instruction is executed, it waits for the user to type, it reads the characters unti space or enter (newine) is typed, then it stores the vaue in the variabe. right-hand operand MUST be a variabe. 2 Consoe Input Exampe program using cin Output a prompt (using cout) to te the user what type of data to enter BEFORE using cin: foat diameter; cout << What is the diameter of the circe? ; cin >> diameter; You can input mutipe vaues in one statement: int x, y; cout << Enter two integers: << end; cin >> x >> y; the user may enter them on one ine (separated by a space) or on separate ines. 3 #incude <iostream> using namespace std; int main() { int ength, width, area; cout << "This program cacuates the area of a "; cout << "rectange.\n"; cout << "Enter the ength and width of the rectange "; cout << "separated by a space.\n"; cin >> ength >> width; area = ength * width; cout << "The area of the rectange is " << area << end; return 0; } output screen: This program cacuates the area of a rectange. Enter the ength and width of the rectange separated by a space The area of the rectange is 200

2 2.14 Arithmetic Operators Arithmetic Operators An operator is a symbo that tes the computer to perform specific mathematica or ogica manipuations (caed operations). An operand is a vaue used with an operator to perform an operation. C++ has unary and binary operators: unary (1 operand) -5 binary (2 operands) Unary operators: SYMBOL OPERATION EXAMPLES + unary pus +10, +y - negation -5, -x Binary operators: SYMBOL OPERATION EXAMPLE + addition x + y - subtraction index - 1 * mutipication hours * rate / division tota / count % moduus count % 3 6 Integer Division Moduus If both operands are integers, / (division) operator aways performs integer division. The fractiona part is ost!! cout << 13 / 5; // dispays 2 cout << 91 / 7; // dispays 13 If either operand is foating point, the resut is foating point. cout << 13 / 5.0; // dispays 2.6 cout << 91.0 / 7; // dispays 13 7 % (moduus) operator computes the remainder resuting from integer division cout << 13 % 5; // dispays 3 cout << 91 % 7; // dispays 0 % requires integers for both operands cout << 13 % 5.0; cout << 91.0 % 7; // error // error 8

3 3.2 Mathematica Expressions An expression is a program component that evauates to a vaue. An expression can be a itera, a variabe, or a combination of these using operators and parentheses. Exampes: 4 num x * x * x 16 * x + 3 x * y / z 'A' -15e10 2 * ( + w) Each expression has a type, which is the data type of the resut vaue. 9 Where can expressions occur? The rhs (right-hand-side) of an assignment statement: x = y * 10 / 3; y = 8; x = y; aletter = 'W'; num = num + 1; The rhs of a stream insertion operator (<<) (cout): cout << The pay is << hours * rate << end; cout << num; cout << 25 / y; More paces we don t know about yet Operator Precedence (order of operations) Which operation does the computer perform first? answer = 1 + x + z; resut = x + 5 * y; Precedence Rues specify which happens first, in this order: - (negation) * / % + - If the expression has mutipe operators from the same eve, they associate eft to right or right to eft: - (negation) Right to eft * / % Left to right + - Left to right 11 Parentheses You can use parentheses to override the precedence or associativity rues: Some exampes: a + b / 4 (a + b) / 4 (4 * 17) + (3 1) a (b - c) * 4 10 / * % * 5 /

4 Exponents There is no operator for exponentiation in C++ There is a ibrary function caed pow y = pow(x, 3.0); // x to the third power The expression pow(x,3.0) is a ca to the pow function with arguments x and 3.0. Arguments can have type doube or int and the resut is a doube. If x is 2.0, then 8.0 wi be stored in y. The vaue stored in x is not changed. #incude <cmath> is required to use pow Type Conversion The computer (ALU) cannot perform operations between operands of different data types. If the operands of an expression have different types, the compier wi convert one to be the type of the other This is caed an impicit type conversion, or a type coercion. Usuay, the operand with the ower ranking type is converted to the type of the higher one. Order of types: doube foat ong int 14 char Type Conversion Rues 3.5 Type Casting Binary ops: convert the operand with the ower ranking type to the type of the other operand. int years; Aways safe foat interestrate, resut;... resut = years * interestrate; // years is converted to foat before being mutipied Assignment ops: rhs is converted to the type of the variabe on the hs. int x, y = 4; foat z = 2.7; x = 4 * z; //4 is converted to foat, Not aways safe, information oss //then 10.8 is converted to int (10) cout << x << end; OUTPUT: Type casting is an expicit (or manua) type conversion. y = static_cast<int>(x); // converts x to int mainy used to force foating-point division int hits, atbats; foat battingavg;... cin >> hits >> atbats; // assume: 3 8 battingavg = static_cast<foat>(hits)/atbats; why not:? battingavg = static_cast<foat>(hits/atbats); Resut:

5 3.4 Overfow/Underfow Happens when the vaue assigned to a variabe is too arge or sma for its type (out of range). integers tend to wrap around, without warning: short testvar = 32767; cout << testvar << end; testvar = testvar + 1; cout << testvar << end; foating point vaue overfow/underfow: may or may not get a warning resut may be 0 or random vaue // 32767, max vaue //-32768, min vaue Mutipe Assignment You can assign the same vaue to severa variabes in one statement: a = b = c = 12; is equivaent to: a = 12; b = 12; c = 12; Combined Assignment 5.1 Increment and Decrement Assignment statements often have this form: number = number + 1; //add 1 to number tota = tota + x; y = y / 2; //add x to tota //divide y by 2 int number = 10; number = number + 1; cout << number << end; C/C++ offers shorthand for these: number += 1; // short for number = number+1; tota -= x; y /= 2; // short for tota = tota-x; // short for y = y / 2; 19 C++ provides unary operators to increment and decrement. Increment operator: ++ Decrement operator: -- can be used before (prefix) or after (postfix) a variabe Exampes: int num = 10; num++; //equivaent to: num = num + 1; num--; ++num; //equivaent to: num = num - 1; //equivaent to: num = num + 1; --num; //equivaent to: num = num - 1; 20

6 Prefix vs Postfix ++ and -- operators can be used in expressions In prefix mode (++va, --va) the operator increments or decrements, then returns the new vaue of the variabe In postfix mode (va++, va--) the operator returns the origina vaue of the variabe, then increments or decrements int num, va = 12; cout << va++; // cout << va; va = va+1; cout << ++va; // va = va + 1; cout << va; num = --va; // va = va - 1; num = va; num = va--; // num = va; va = va -1; 3.9 More Math Library Functions These require cmath header fie These take doube argument, return a doube Commony used functions: pow y = pow(x,d); returns x raised to the power d abs y = abs(x); returns absoute vaue of x sqrt y = sqrt(x); returns square root of x cei y = cei(x); returns the smaest integer >= x sin y = sin(x); returns the sine of x (in radians) etc. It s confusing, don t do this! Hand Tracing a Program You be the computer. Track the vaues of the variabes as the program executes. step through and execute each statement, one-by-one record the contents of variabes after each statement execution, using a hand trace chart (tabe) or boxes. int main() { doube num1, num2; cout << Enter first number ; cin >> num1; cout << Enter second number ; cin >> num2; } num1 = (num1 + num2) / 2; num2++; cout << num1 is << num1 << end; cout << num2 is << num2 << end; num1 num2???? 10? 10? Formatting Output Formatting: the way a vaue is printed: spacing decima points, fractiona vaues, number of digits cout has a standard way of formatting vaues of each data type use stream manipuators to override this they require #incude <iomanip> 24

7 Formatting Output: setw setw is a stream manipuator, ike end setw(n)specifies the minimum width for the next item to be output cout << setw(6) << age << end; specifies to dispay age in a fied at east 6 spaces wide. vaue is right justified (padded with spaces on eft). if the vaue is too big to fit in 6 spaces, it is printed in fu, using more positions. setw: exampes Exampe with no formatting: cout << 2897 << << 5 << << 837 << end; cout << 34 << << 7 << << 1623 << end; Exampe using setw: cout << setw(6) << 2897 << setw(6) << 5 << setw(6) << 837 << end; cout << setw(6) << 34 << setw(6) << 7 << setw(6) << 1623 << end; Prog 3-12 and 3-13 output in the book is not exacty correct Formatting Output: fixed and setprecision These appy to outputting foating point vaues: by defaut, 6 tota significant digits are output. when fixed and setprecision(n) are used together, the n specifies the number of digits to be dispayed after the decima point. it remains in effect unti it is changed cout << << end; cout << fixed << setprecision(2); cout << << end; cout << << end; Note: there is no need for showpoint when using setprecision with fixed output: Formatting Output: right and eft eft causes a subsequent output to be eft justified in its fied right causes a subsequent output to be right justified in its fied. This is the defaut. doube x = , y = 24.2, z = 1.783; cout << setw(10) << x << end; cout << setw(10) << y << end; cout << setw(10) << z << end; doube x = , y = 24.2, z = 1.783; cout << eft << setw(10) << x << end; cout << setw(10) << y << end; cout << setw(10) << z << end;

8 3.8 Working with characters and string objects Using the >> operator to input strings can cause probems: It skips over any eading whitespace chars (spaces, tabs, or ine breaks) It stops reading strings when it encounters the next whitespace character! string name; cout << Pease enter your name: ; cin >> name; cout << Your name is << name << end; Using getine to input strings To work around this probem, you can use a C++ function named getine. getine(cin,var); reads in an entire ine, incuding a the spaces, and stores it in a string variabe. (the \n is not stored) string name; cout << Pease enter your name: ; getine(cin, name); cout << Your name is << name << end; Pease enter your name: Kate Smith Your name is Kate 29 Pease enter your name: Kate Smith Your name is Kate Smith 30 Mixing >> with getine Using cin>>ws Mixing cin>>x with getine(cin,y) in the same program can cause input errors that are VERY hard to detect int number; string name; cout << "Enter a number: "; cin >> number; // Read an integer cout << "Enter a name: "; getine(cin,name); // Read a string, up to end of ine cout << Name << name << end; Enter a number: 100 Enter a name: Name cin>>ws skips whitespace characters (space, tab, newine), unti a non-whitespace character is found. Use it after cin>>var and before getine to consume the newine so it wi start reading characters on the next ine. int number; string name; cout << "Enter a number: "; cin >> number; // Read an integer cin >> ws; // skip the newine cout << "Enter a name: "; getine(cin,name); // Read a string cout << Name << name << end; The program did not aow me to type a name getine(cin,name) then reads the \n and immediatey stops (name is empty) 31 Enter a number: 100 Enter a name: Jane Doe Name Jane Doe 32

9 5.11 Using Fies for Data Storage Fie Stream Variabes Variabes are stored in Main Memory/RAM Fie stream data types: vaues are ost when program is finished executing ifstream To preserve the vaues computed by the program: save them to a fie Fies are stored in Secondary Storage To have your program manipuate vaues stored in a fie, they must be input into variabes first. ofstream use #incude <fstream> for these variabes of type ofstream can be used to output (write) vaues to a fie. (ike cout) variabes of type ifstream can be used to input (read) vaues from a fie. (ike cin) Define and open fie stream objects Writing to Fies To input from a fie, decare an ifstream variabe, and open a fie by its name: ifstream fin; fin.open( mydatafie.txt ); If the fie mydatafie.txt does not exist, it wi cause an error. To output to a fie, decare an ofstream variabe, and open a fie by its name: ofstream fout; fout.open( myoutputfie.txt ); If the fie myoutputfie.txt does not exist, it wi be created. If it does exist, it wi be overwritten 35 Use the stream insertion operator (<<) on the fie output stream variabe: #incude <iostream> #incude <fstream> using namespace std; int main() { ofstream fout; fout.open( demofie.txt ); } int age; cout << Enter your age: ; cin >> age; fout << Age is: << age << end; fout.cose(); return 0; Output demofie.txt: Age is: 20 36

10 Reading from Fies Use the stream extraction operator (>>) on the fie input stream variabe: #incude <iostream> #incude <fstream> using namespace std; int main() { string name; Names.txt: Tom Dick Harry Cosing fie stream objects To cose a fie stream when you are done reading/writing: fin.cose(); fout.cose(); Not required, but good practice. ifstream fin; fin.open( Names.txt ); fin >> name; Screen output: Tom } cout << name << end; fin.cose(); Reading from fies When opened, the fie stream's read position points to first character in fie. The stream extraction operator (>>) starts at the read position and skips whitespace to read data into the variabe. The read position then points to whitespace after the vaue it just read. The next extraction (>>) starts from the new read position. This is how cin works as we. 39

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.

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. Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific

More information

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

l A program is a set of instructions that the l It must be translated l Variable: portion of memory that stores a value char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fa 2018 Ji Seaman Programming A program is a set of instructions that the computer foows to perform a task It must be transated from

More information

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

The cin Object. cout << Enter the length and the width of the rectangle? ; cin >> length >> width; The cin Object Short for console input. It is used to read data typed at the keyboard. Must include the iostream library. When this instruction is executed, it waits for the user to type, it reads the

More information

Week 3: File I/O and Formatting 3.7 Formatting Output

Week 3: File I/O and Formatting 3.7 Formatting Output Week 3: File I/O and Formatting 3.7 Formatting Output Formatting: the way a value is printed: Gaddis: 3.7, 3.8, 5.11 CS 1428 Fall 2014 Jill Seaman spacing decimal points, fractional values, number of digits

More information

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

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program? Intro to Programming & C++ Unit 1 Sections 1.1-3 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2018 Ji Seaman 1.1 Why Program? Computer programmabe machine designed to foow instructions Program a set of

More information

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

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Hardware Components Illustrated Intro to Programming & C++ Unit 1 Sections 1.1-3 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Fa 2017 Ji Seaman 1.1 Why Program? Computer programmabe machine designed to foow instructions Program instructions

More information

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

3.1. Chapter 3: The cin Object. Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-1 The cin Object Standard input stream object, normally the keyboard,

More information

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14 Chapter 3: Expressions and Interactivity 3.1 The cin Object The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information retrieved from cin with >>

More information

Straight-line code (or IPO: Input-Process-Output) If/else & switch. Relational Expressions. Decisions. Sections 4.1-6, , 4.

Straight-line code (or IPO: Input-Process-Output) If/else & switch. Relational Expressions. Decisions. Sections 4.1-6, , 4. If/ese & switch Unit 3 Sections 4.1-6, 4.8-12, 4.14-15 CS 1428 Spring 2018 Ji Seaman Straight-ine code (or IPO: Input-Process-Output) So far a of our programs have foowed this basic format: Input some

More information

Functions. 6.1 Modular Programming. 6.2 Defining and Calling Functions. Gaddis: 6.1-5,7-10,13,15-16 and 7.7

Functions. 6.1 Modular Programming. 6.2 Defining and Calling Functions. Gaddis: 6.1-5,7-10,13,15-16 and 7.7 Functions Unit 6 Gaddis: 6.1-5,7-10,13,15-16 and 7.7 CS 1428 Spring 2018 Ji Seaman 6.1 Moduar Programming Moduar programming: breaking a program up into smaer, manageabe components (modues) Function: a

More information

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

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object Chapter 3: Expressions and Interactivity 3.1 The cin Object The cin Object The cin Object in Program 3-1 Standard input object Like cout, requires iostream file Used to read input from keyboard Information

More information

Chapter 3: Expressions and Interactivity

Chapter 3: Expressions and Interactivity Chapter 3: Expressions and Interactivity 3.1 The cin Object The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information retrieved from cin with >>

More information

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

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma. REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout

More information

Tutorial 3 Concepts for A1

Tutorial 3 Concepts for A1 CPSC 231 Introduction to Computer Science for Computer Science Majors I Tutoria 3 Concepts for A1 DANNY FISHER dgfisher@ucagary.ca September 23, 2014 Agenda script command more detais Submitting using

More information

Expressions, Input, Output and Data Type Conversions

Expressions, Input, Output and Data Type Conversions L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with

More information

Chapter 3. Numeric Types, Expressions, and Output

Chapter 3. Numeric Types, Expressions, and Output Chapter 3 Numeric Types, Expressions, and Output 1 Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and Explicit Type Conversion Calling a Value-Returning

More information

CHAPTER 3 Expressions, Functions, Output

CHAPTER 3 Expressions, Functions, Output CHAPTER 3 Expressions, Functions, Output More Data Types: Integral Number Types short, long, int (all represent integer values with no fractional part). Computer Representation of integer numbers - Number

More information

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

Structures. Data Types Structures. Data Types (C/C++) Gaddis: A Data Type consists of: Unit 7. example: Integer. CS 1428 Spring 2018

Structures. Data Types Structures. Data Types (C/C++) Gaddis: A Data Type consists of: Unit 7. example: Integer. CS 1428 Spring 2018 Structures Data Types A Data Type consists of: Unit 7 Gaddis: 11.2-8 set of vaues set of operations over those vaues CS 1428 Spring 2018 Ji Seaman exampe: Integer whoe numbers, -32768 to 32767 +, -, *,

More information

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

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7-1 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Conversation / Casting Name Constant - const, #define X When You Mix Apples and Oranges: Type Conversion Operations

More information

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-3,5

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-3,5 Arrays Unit 5 Gaddis: 7.1-3,5 CS 1428 Spring 2018 Ji Seaman Array Data Type Array: a variabe that contains mutipe vaues of the same type. Vaues are stored consecutivey in memory. An array variabe decaration

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

More information

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-4,6

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-4,6 Arrays Unit 5 Gaddis: 7.1-4,6 CS 1428 Fa 2017 Ji Seaman Array Data Type Array: a variabe that contains mutipe vaues of the same type. Vaues are stored consecutivey in memory. An array variabe definition

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

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

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. Engineering Problem Solving With C++ 4th Edition Etter TEST BANK Full clear download (no error formating) at: https://testbankreal.com/download/engineering-problem-solving-with-c-4thedition-etter-test-bank/

More information

Window s Visual Studio Output

Window s Visual Studio Output 1. Explain the output of the program below. Program char str1[11]; char str2[11]; cout > str1; Window s Visual Studio Output Enter a string: 123456789012345678901234567890 Enter

More information

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

I/O Streams and Standard I/O Devices (cont d.)

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

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

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 4-5 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 3 Assignment, Formatting, and Interactive Input

More information

WARM UP LESSONS BARE BASICS

WARM UP LESSONS BARE BASICS WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions

More information

Searching, Sorting & Analysis

Searching, Sorting & Analysis Searching, Sorting & Anaysis Unit 2 Chapter 8 CS 2308 Fa 2018 Ji Seaman 1 Definitions of Search and Sort Search: find a given item in an array, return the index of the item, or -1 if not found. Sort: rearrange

More information

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

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

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

Chapter Two: Fundamental Data Types

Chapter Two: Fundamental Data Types Chapter Two: Fundamental Data Types Slides by Evan Gallagher Chapter Goals To be able to define and initialize variables and constants To understand the properties and limitations of integer and floating-point

More information

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment PIC 10A Lecture 3: More About Variables, Arithmetic, Casting, Assignment Assigning values to variables Our variables last time did not seem very variable. They always had the same value! Variables stores

More information

Chapter 2. Outline. Simple C++ Programs

Chapter 2. Outline. Simple C++ Programs Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

CS2141 Software Development using C/C++ Stream I/O

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS

CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS CS103L FALL 2017 UNIT 1: TYPES, VARIABLES,EXPRESSIONS,C++ BASICS LOGISTICS Homework due tonight and Thursday Should be able to do after reading textbook - go to TA/CP office hours Do the lab Go to lab

More information

CS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil

CS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil CS 1428 Review CS 2308 :: Spring 2016 Molly O Neil Structure of a C++ Program Hello world // This program prints a greeting to the screen #include using namespace std; int main() { cout

More information

A SHORT COURSE ON C++

A SHORT COURSE ON C++ Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Lecture 4 Tao Wang 1

Lecture 4 Tao Wang 1 Lecture 4 Tao Wang 1 Objectives In this chapter, you will learn about: Assignment operations Formatting numbers for program output Using mathematical library functions Symbolic constants Common programming

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 2. Overview of C++ Prof. Amr Goneid, AUC 1 Overview of C++ Prof. Amr Goneid, AUC 2 Overview of C++ Historical C++ Basics Some Library

More information

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:

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: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

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.

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. 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. B. Outputs to the console a floating point number f1 in scientific format

More information

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands Performing Computations C provides operators that can be applied to calculate expressions: tax is 8.5% of the total sale expression: tax = 0.085 * totalsale Need to specify what operations are legal, how

More information

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary Topic 2 1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary Arithmetic Operators C++ has the same arithmetic operators as a calculator:

More information

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

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1 300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1 Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard

More information

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Operators. Lecture 3 COP 3014 Spring January 16, 2018 Operators Lecture 3 COP 3014 Spring 2018 January 16, 2018 Operators Special built-in symbols that have functionality, and work on operands operand an input to an operator Arity - how many operands an operator

More information

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

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 1 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 variables. Apply C++ syntax rules to declare variables, initialize

More information

Chapter 4: Basic C Operators

Chapter 4: Basic C Operators Chapter 4: Basic C Operators In this chapter, you will learn about: Arithmetic operators Unary operators Binary operators Assignment operators Equalities and relational operators Logical operators Conditional

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 3 Introduction

More information

Input and Expressions Chapter 3 Slides #4

Input and Expressions Chapter 3 Slides #4 Input and Expressions Chapter 3 Slides #4 Topics 1) How can we read data from the keyboard? 2) How can we calculate values? 3) How can we manage the type of a value? 4) How can we round or get random numbers?

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

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

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas Introduction to C++ Dr M.S. Colclough, research fellows, pgtas 5 weeks, 2 afternoons / week. Primarily a lab project. Approx. first 5 sessions start with lecture, followed by non assessed exercises in

More information

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Lecture outline Graphics and Interaction Scan Converting Polygons and Lines. Inside or outside a polygon? Scan conversion.

Lecture outline Graphics and Interaction Scan Converting Polygons and Lines. Inside or outside a polygon? Scan conversion. Lecture outine 433-324 Graphics and Interaction Scan Converting Poygons and Lines Department of Computer Science and Software Engineering The Introduction Scan conversion Scan-ine agorithm Edge coherence

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Topics 1. Expressions 2. Operator precedence 3. Shorthand operators 4. Data/Type Conversion 1/15/19 CSE 1321 MODULE 2 2 Expressions

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

Declaration and Memory

Declaration and Memory Declaration and Memory With the declaration int width; the compiler will set aside a 4-byte (32-bit) block of memory (see right) The compiler has a symbol table, which will have an entry such as Identifier

More information

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1 ELEC 330 1 Structured Programming Control Structures ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne Algorithm Development Conditional Expressions Selection Statements Loops 206_C3

More information

Chapter 3: Input/Output

Chapter 3: Input/Output Chapter 3: Input/Output I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters

More information

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

File Operations. Lecture 16 COP 3014 Spring April 18, 2018 File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 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

More information

Setting Justification

Setting Justification Setting Justification Formatted I/O 1 Justification - Justification refers to the alignment of data within a horizontal field. - The default justification in output fields is to the right, with padding

More information

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types. The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

VARIABLES & ASSIGNMENTS

VARIABLES & ASSIGNMENTS Fall 2018 CS150 - Intro to CS I 1 VARIABLES & ASSIGNMENTS Sections 2.1, 2.2, 2.3, 2.4 Fall 2018 CS150 - Intro to CS I 2 Variables Named storage location for holding data named piece of memory You need

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Introduction to C ++

Introduction to C ++ Introduction to C ++ Thomas Branch tcb06@ic.ac.uk Imperial College Software Society October 18, 2012 1 / 48 Buy Software Soc. s Free Membership at https://www.imperialcollegeunion.org/shop/ club-society-project-products/software-products/436/

More information

C/C++ Programming Lecture 7 Name:

C/C++ Programming Lecture 7 Name: 1. The increment (++) and decrement (--) operators increase or decrease a variable s value by one, respectively. They are great if all you want to do is increment (or decrement) a variable: i++;. HOWEVER,

More information

Operations. Making Things Happen

Operations. Making Things Happen Operations Making Things Happen Object Review and Continue Lecture 1 2 Object Categories There are three kinds of objects: Literals: unnamed objects having a value (0, -3, 2.5, 2.998e8, 'A', "Hello\n",...)

More information

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

On a 64-bit CPU. Size/Range vary by CPU model and Word size. On a 64-bit CPU. Size/Range vary by CPU model and Word size. unsigned short x; //range 0 to 65553 signed short x; //range ± 32767 short x; //assumed signed There are (usually) no unsigned floats or doubles.

More information

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output? Arithmetic Operators Section 2.15 & 3.2 p 60-63, 81-89 1 Today Arithmetic Operators & Expressions o Computation o Precedence o Associativity o Algebra vs C++ o Exponents 2 Assigning floats to ints int

More information

Introduction to Programming EC-105. Lecture 2

Introduction to Programming EC-105. Lecture 2 Introduction to Programming EC-105 Lecture 2 Input and Output A data stream is a sequence of data - Typically in the form of characters or numbers An input stream is data for the program to use - Typically

More information

C Programming

C Programming 204216 -- C Programming Chapter 3 Processing and Interactive Input Adapted/Assembled for 204216 by Areerat Trongratsameethong A First Book of ANSI C, Fourth Edition Objectives Assignment Mathematical Library

More information

Study recommendations for the Mid-Term Exam - Chapters 1-5

Study recommendations for the Mid-Term Exam - Chapters 1-5 Study recommendations for the Mid-erm Exam - Chapters 1-5 Review Chapters 1-5 in your textbook, the Example Pages, and in the Glossary on the website Standard problem solving steps used in program development

More information

Professor: Alvin Chao

Professor: Alvin Chao Professor: Avin Chao Anatomy of a Java Program: Comments Javadoc comments: /** * Appication that converts inches to centimeters. * * @author Chris Mayfied * @version 01/21/2014 */ Everything between /**

More information

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O

More information

Computing and Statistical Data Analysis Lecture 3

Computing and Statistical Data Analysis Lecture 3 Computing and Statistical Data Analysis Lecture 3 Type casting: static_cast, etc. Basic mathematical functions More i/o: formatting tricks Scope, namspaces Functions 1 Type casting Often we need to interpret

More information

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

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents: Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language Dr. Amal Khalifa Lecture Contents: Introduction to C++ Origins Object-Oriented Programming, Terms Libraries and Namespaces

More information

Chapter 7. Additional Control Structures

Chapter 7. Additional Control Structures Chapter 7 Additional Control Structures 1 Chapter 7 Topics Switch Statement for Multi-Way Branching Do-While Statement for Looping For Statement for Looping Using break and continue Statements 2 Chapter

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information