# Expressions, Input, Output and Data Type Conversions

Size: px
Start display at page:

## Transcription

1 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 constants and mathematical functions PROCEDURE 1. Students should read the Pre-lab Reading Assignment before coming to lab. 2. Students should complete the Pre-lab Writing Assignment before coming to lab. Contents Pre-requisites Approximate completion time Pre-lab Reading Assignment 20 min. 26 Pre-lab Writing Assignment Pre-lab reading 10 min. 32 LESSON 3A Lab 3.1 Working with the cin Confidence in 15 min. 33 Statement use of data types Lab 3.2 Formatting Output Basic understanding 15 min. 35 of cout and formatted output Lab 3.3 Arithmetic Operations and Understanding of 20 min. 36 Math Functions pre-defined functions pow and sqrt LESSON 3B Lab 3.4 Working with Type Casting Understanding of 20 min. 37 type casting (implicit and explicit data conversion) Page number Check when done continues 25

2 26 LESSON SET 3 Expressions, Input, Output and Data Type Conversions Lab 3.5 Student Generated Code Understanding of all 30 min. 39 Assignments concepts covered in this section. P R E - LAB R E A D I N G A S S I G N M E N T Review of the cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. Example: cout << "Hi there"; The insertion operator << inserts the string of characters Hi there into the output stream that goes to the screen. The cout statement can be thought of as an ostream (output stream) data type. Input Instructions Just as the cout statement transfers data from the computer to the outside world, the cin statement transfers data into the computer from the keyboard. Example: cin >> grade; The extraction operator >> extracts an item from the input stream. In this case, since grade is an integer, this instruction will wait for an integer to be entered at the keyboard and then will place that number in the memory location called grade. Just as cout is of type ostream, cin is considered to be an istream (input stream) data type. In order to use cin and cout in a C++ program, the #include <iostream> directive should be included in the header. The >> extraction operator also serves as a separator between input variables, allowing more than one memory location to be loaded with a single cin instruction. The values read must be the same data type as their corresponding variables, although a floating point variable could receive an integer since the conversion will be made automatically. Conversion is discussed later in this lesson. Example: float rate; float hours; cin >> rate >> hours; The cin statement will wait for two floating point numbers (separated by at least one blank space) to be input from the keyboard. The first will be stored in rate and the second in hours.

5 Pre-lab Reading Assignment 29 The order in which these stream manipulators appear does not matter. In fact, the above statements could have been written as one instruction: cout << setprecision(2) << fixed << showpoint; Spacing is handled by an indication of the width of the field that the number, character, or string is to be placed. It can be done with the cout.width(n); where n is the width size. However it is more commonly done by the setw(n) within a cout statement. The #include <iomanip> directive must be included in the header (global section) for features such as setprecision() and setw(). Example: float price = 9.5; float rate = 8.76; cout << setw(10) << price << setw(7) << rate; The above statements will print the following: There are seven blank spaces before 9.5 and three blank spaces between the numbers. The numbers are right justified. The computer memory stores this as follows: Note: So far we have used endl for a new line of output. '\n' is an escape sequence which can be used as a character in a string to accomplish the same thing. Example: Both of the following will do the same thing. cout << "Hi there\n"; cout << "Hi there" << endl; Expressions Precedence Rules of Arithmetic Operators Recall from Lesson Set 2 that the assignment statement consists of two parts: a variable on the left and an expression on the right. The expression is converted to one value that is placed in the memory location corresponding to the variable on the left. These expressions can consist of variables, constants and literals combined with various operators. It is important to remember the mathematical precedence rules which are applied when solving these expressions. 1. Anything grouped in parentheses is top priority 2. Unary negation (example: 8) 3. Multiplication, Division and Modulus * / % 4. Addition and Subtraction + Example: ( 8 * 4/ /2 + 6 * (4+3) ) ( 8 * 4/ /2 + 6 * 7 ) ( 32 / /2 + 6 * 7 ) ( /2 + 6 * 7 ) ( * 7 ) ( ) ( ) ( ) = 65

6 30 LESSON SET 3 Expressions, Input, Output and Data Type Conversions Converting Algebraic Expressions to C++ One of the challenges of learning a new computer language is the task of changing algebraic expressions to their equivalent computer instructions. Example: 4y(3-2)y+7 How would this algebraic expression be implemented in C++? 4 * y * (3-2) * y + 7 Other expressions are a bit more challenging. Consider the quadratic formula: b ± b 2 4ac 2a We need to know how C++ handles functions such as the square root and squaring functions. There are several predefined math library routines that are contained in the cmath library. In order to use these we must have the #include <cmath> directive in the header. Exponents in C++ are handled by the pow(number,exp) function, where number indicates the base and exp is the exponent. For example, Data Type Conversions 2 3 would be written as pow(2,3) 5 9 would be written as pow(5,9) Square roots are handled by sqrt(n). For example, 9 would be written as sqrt(9) Look at the following C++ statements and try to determine what they are doing. formula1 = ( -b + sqrt(pow(b,2) -(4 * a * c))) / (2 * a); formula2 = ( -b - sqrt(pow(b,2) -(4 * a * c))) / (2 * a); (These are the roots from the quadratic formula in C++ format.) Recall the discussion of data types from Lesson Set 2. Whenever an integer and a floating point variable or constant are mixed in an operation, the integer is changed temporarily to its equivalent floating point. This automatic conversion is called implicit type coercion. Consider the following: int count; count = 7.8; We are trying to put a floating point number into an integer memory location. This is like trying to stuff a package into a mailbox that is only large enough to contain letters. Something has to give. In C++ the floating point is truncated (the entire fractional component is cut off) and, thus, we have loss of information. Type conversions can be made explicit (by the programmer) by using the following general format: static_cast<datatype>(value). This is called type casting or type conversion.

7 Pre-lab Reading Assignment 31 Example: int count; float sum; count = 10.89; // Float to integer This is Type coercion // 10 is stored in count count = static_cast<int>(10.89); // Also float to integer; however this is // type casting If two integers are divided, the result is an integer that is truncated. This can create unexpected results. Example: int num_as = 10; int totalgrade = 50; float percent_as; percent_as = num_as / totalgrade; In this problem we would expect percent_as to be.20 since 10/50 is.20. However since both num_as and totalgrade are integers, the result is integer division which gives a truncated number. In this case it is 0. Whenever a smaller integer value is divided by a larger integer value the result will always be 0. We can correct this problem by type casting. percent_as = static_cast<float>(num_as)/totalgrade; Although the variable num_as itself remains an integer, the type cast causes the divide operation to use a copy of the num_as value which has been converted to a float. A float is thus being divided by the integer totalgrade and the result (through type coercion) will be a floating-point number.

8 32 LESSON SET 3 Expressions, Input, Output and Data Type Conversions P R E - LAB W R I T I N G A S S I G N M E N T Fill-in-the-Blank Questions 1. What is the final value (in C++) of the following expression? (5-16 / 2 * 3 + (3 + 2 / 2) - 5) 2. How would the following expression be written in C++? 2x Implicit conversion is also known as data type. 4. Explicit type conversion is also known as type. 5. List the preprocessor directive that must be included for cin and cout to be used in a C++ program. 6. Blank spaces or unseen control characters in a data file are referred to as. 7. The << in a cout statement is called the operator. 8. The #include< > is needed for formatted output. 9. The '\n' is a special character that.

9 Lesson 3A 33 L E S S O N 3 A LAB 3.1 Working with the cin Statement Bring in the program bill.cpp from the Lab 3 folder. The code is listed below: // This program will read in the quantity of a particular item and its price. // It will then print out the total price. // The input will come from the keyboard and the output will go to // the screen. // PLACE YOUR NAME HERE #include <iostream> #include <iomanip> using namespace std; int main() { int quantity; // contains the amount of items purchased float itemprice; // contains the price of each item float totalbill; // contains the total bill. cout << setprecision(2) << fixed << showpoint; // formatted output cout << "Please input the number of items bought" << endl; // Fill in the input statement to bring in the quantity. // Fill in the prompt to ask for the price. // Fill in the input statement to bring in the price of each item. // Fill in the assignment statement to determine the total bill. // Fill in the output statement to print total bill, // with a label to the screen. } return 0; Exercise 1: Complete the program so that a sample run inputting 22 for the number of items bought and for the price of each item will produce the results below. Sample run of the program.

11 Lesson 3A 35 LAB 3.2 Formatting Output Look at the following table: Assume that from the left margin, the price takes up fifteen spaces. We could say that the numbers are right justified in a 15-width space. Starting where the price ends, the next field (quantity) takes up twelve spaces. We can use the formatted output from Lab 3.1 and the statement setw(n) where n is some integer to indi- cate the width to produce such tables. Bring in the program tabledata.cpp from the Lab 3 folder. The code is as follows: // This program will bring in two prices and two quantities of items // from the keyboard and print those numbers in a formatted chart. //PLACE YOUR NAME HERE #include <iostream> #include using namespace std; // Fill in the code to bring in the library for // formatted output. int main() { float price1, price2; // The price of 2 items int quantity1, quantity2; // The quantity of 2 items cout << setprecision(2) << fixed << showpoint; cout << "Please input the price and quantity of the first item" << endl; // Fill in the input statement that reads in price1 and // quantity1 from the keyboard. // Fill in the prompt for the second price and quantity. // Fill in the input statement that reads in price2 and // quantity2 from the keyboard. cout << setw(15) << "PRICE" << setw(12) << "QUANTITY\n\n"; // Fill in the output statement that prints the first price // and quantity. Be sure to use setw() statements. // Fill in the output statement that prints the second price // and quantity. return 0; }

12 36 LESSON SET 3 Expressions, Input, Output and Data Type Conversions Exercise 1: Finish the code above by filling in the blanks and the instructions necessary to execute the following sample run. Note that two or more data items can be input at one time by having at least one blank space between them before hitting the enter key. LAB 3.3 Arithmetic Operations and Math Functions Bring in the program righttrig.cpp from the Lab 3 folder. The code is as follows: // This program will input the value of two sides of a right triangle and then // determine the size of the hypotenuse. // PLACE YOUR NAME HERE #include <iostream> #include <cmath> using namespace std; // needed for math functions like sqrt() int main() { float a,b; float hyp; // the smaller two sides of the triangle // the hypotenuse calculated by the program cout << "Please input the value of the two sides" << endl; cin >> a >> b; // Fill in the assignment statement that determines the hypotenuse cout << "The sides of the right triangle are " << a << " and " << b << endl; cout << "The hypotenuse is " << hyp << endl; } return 0; The formula for finding the hypotenuse is hyp = a 2 + b 2.

13 Lesson 3B 37 How can this be implemented in C++? Hint: You will use two pre-defined math functions (one of them twice) learned in this lesson. One of them will be inside the other. Exercise 1: Fill in the missing statement so that the following sample run is implemented: Exercise 2: Alter the program so that the sample run now looks like the following: Note: This is not a trivial change. You must include another directive as well as use the formatted features discussed in the earlier labs of this lesson. Notice that the change is made only to the value of the hypotenuse and not to the values of 9 and 3. L E S S O N 3 B LAB 3.4 Working with Type Casting Bring in the program batavg.cpp from the Lab 3 folder. The code follows. // This program will determine the batting average of a player. // The number of hits and at bats are set internally in the program. // PLACE YOUR NAME HERE #include <iostream> using namespace std; const int AT_BAT = 421; const int HITS = 123; int main() { int batavg; batavg = HITS / AT_BAT cout << "The batting average is " << batavg << endl; // an assignment statement // output the result } return 0;

14 38 LESSON SET 3 Expressions, Input, Output and Data Type Conversions Exercise 1: Run this program and record the results. The batting average is. Exercise 2: There is a logic error in this program centering around data types. Does changing the data type of batavg from int to float solve the problem? Make that change and run the program again and record the result. The batting average is. Exercise 3: Continue to work with this program until you get the correct result. The correct result should be Do not change the data type of the two named constants. Instead, use a typecast to solve the problem.

15 Lesson 3B 39 LAB 3.5 Student Generated Code Assignments Option 1: Write a program that will read in 3 grades from the keyboard and will print the average (to 2 decimal places) of those grades to the screen. It should include good prompts and labeled output. Use the examples from the earlier labs to help you. You will want to begin with a design. The Lesson Set 1 Pre-lab Reading Assignment gave an introduction for a design similar to this problem. Notice in the sample run that the answer is stored in fixed point notation with two decimal points of precision. Sample run: Option 2: The Woody furniture company sells the following three styles of chairs: Style Price Per Chair American Colonial \$ Modern \$ French Classical \$ Write a program that will input the amount of chairs sold for each style. It will print the total dollar sales of each style as well as the total sales of all chairs in fixed point notation with two decimal places. Sample run:

16 40 LESSON SET 3 Expressions, Input, Output and Data Type Conversions Option 3: Write a program that will input total sales (sales plus tax) that a business generates for a particular month. The program will also input the state and local sales tax percentage. It will output the total sales plus the state tax and local tax to be paid. The output should be in fixed notation with 2 decimal places. Sample run:

### 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

### 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,

### 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

### 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

### 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

### 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 >>

### 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

### 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 >>

### 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

### 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

### 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,

### 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

### 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

### 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

### 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

### 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

### 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

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

### 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.

### 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

### 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

### 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

### ! 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

### 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

### 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

### 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

### 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++

### 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:

### 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

### Definition Matching (10 Points)

Name SOLUTION Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. There are no syntax errors

### 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

### 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

### 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.

### 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

### 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

### 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

### 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

### Introduction to the C++ Programming Language

LESSON SET 2 Introduction to the C++ Programming Language OBJECTIVES FOR STUDENT Lesson 2A: 1. To learn the basic components of a C++ program 2. To gain a basic knowledge of how memory is used in programming

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

C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

### Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

L E S S O N S E T 6.2 Functions that Return a Value PURPOSE PROCEDURE 1. To introduce the concept of scope 2. To understand the difference between static, local and global variables 3. To introduce the

### Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called

### Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

Input and Output Outline Formatting outputs String data type Interactive inputs File manipulators CS 1410 Comp Sci with C++ Input and Output 1 CS 1410 Comp Sci with C++ Input and Output 2 No I/O is built

### 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

### 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:

### 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

### Loops and Files. of do-while loop

L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.

### 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

### 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

### 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

### 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

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

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 1: An Overview of Computers and Programming Languages Updated by: Malak Abdullah The Evolution of Programming Languages (cont'd.)

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

REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,

### Chapter 7 Arithmetic

Chapter 7 Arithmetic 7-1 Arithmetic in C++ Arithmetic expressions are made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition) - (subtraction)

### Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

### Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

Lecture 3 Input and Output Review from last week Variable - place to store data in memory identified by a name should be meaningful Has a type- int double char bool Has a value may be garbage change value

### Getting started with C++ (Part 2)

Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

### 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:

### 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.

### Full file at

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

### CPE Summer 2015 Exam I (150 pts) June 18, 2015

Name Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. You can assume that there is one

### LAB: INTRODUCTION TO FUNCTIONS IN C++

LAB: INTRODUCTION TO FUNCTIONS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 2 Introduction This lab will provide students with an

### Programming. C++ Basics

Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

### 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

### This watermark does not appear in the registered version - Slide 1

Slide 1 Chapter 1 C++ Basics Slide 2 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output Program Style

### LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM Contents 1. Statements 2. C++ Program Structure 3. Programming process 4. Control Structure STATEMENTS ASSIGNMENT STATEMENTS Assignment statement Assigns a value

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

### Chapter 2. C++ Basics

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

### We will exclusively use streams for input and output of data. Intro Programming in C++

C++ Input/Output: Streams 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: 1 istream

### Sequential Program Execution

Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.

### 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

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

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

### String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

String Variables and Output/Input Adding Strings and Literals to Your Programming Skills and output/input formatting A group of characters put together to create text is called a string. Strings are one

### Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

### 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

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

Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

### CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ 2017 Spring Exam 1 Monday, February 13, 2017 Total - 100 Points B Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

### CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ 2017 Spring Exam 1 Monday, February 13, 2017 Total - 100 Points A Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

### 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

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

Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

### Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

### Chapter 2: Overview of C++

Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

### 2 nd Week Lecture Notes

2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

### C++ Input/Output Chapter 4 Topics

Chapter 4 Topics Chapter 4 Program Input and the Software Design Process Input Statements to Read Values into a Program using >>, and functions get, ignore, getline Prompting for Interactive Input/Output

### Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1

Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.1 Introduction of Compiler, Comments, Program Structure, Input Output, Data Types and Arithmetic Operators

### Starting Out With C++: Early Objects, Seventh Edition Solutions to End-of-Chapter Review Questions

Starting Out With C++: Early Objects, Seventh Edition Solutions to End-of-Chapter Review Questions Chapter 1 1. programmed 12. key 2. CPU 13. programmer-defined symbols 3. arithmetic logic unit (ALU) and

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

EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

### Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.7 User Defined Functions II Prepared for By: Name: ID: Section: Semester: Total Marks: Obtained Marks:

### Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs)

Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs) a. You should be able to list two significant characteristics for each of the basic data types (bool, int, double, and char).

C / C++ PROGRAMMING Program Organization and Comments Copyright 2013 Dan McElroy Programming Organization The layout of a program should be fairly straight forward and simple. Although it may just look

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

Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

### Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

### 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

### 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

Expressions & I/O Unit 2 Sections 2.14, 3.1-10, 5.1, 5.11 CS 1428 Spring 2018 Ji Seaman 1 3.1 The cin Object cin: short for consoe input a stream object: represents the contents of the screen that are

### CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 3 BASIC INSTRUCTION OF C++ MOHD HATTA BIN HJ MOHAMED ALI Computer programming (BFC 20802) Subtopics 2 Parts of a C++ Program Classes and Objects The #include Directive Variables and Literals Identifiers