Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA

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

Chapter 21 - C++ Stream Input/Output

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-

Chapter 21 - C++ Stream Input/Output

Engineering Problem Solving with C++, Etter/Ingber

Getting started with C++ (Part 2)

CHAPTER 3 Expressions, Functions, Output

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

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

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

What we will learn about this week:

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

The C++ Language. Arizona State University 1

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

BITG 1233: Introduction to C++

Basic data types. Building blocks of computation

Number Systems. Binary Numbers. Appendix. Decimal notation represents numbers as powers of 10, for example

OBJECT ORIENTED DESIGN WITH C++ AN INTRODUCTION

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

C++ Input/Output: Streams

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

Independent Representation

Programming. C++ Basics

Standard I/O in C and C++

Contents. 1 Introduction to Computers, the Internet and the World Wide Web 1. 2 Introduction to C Programming 26

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

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

Chapter 3 - Notes Input/Output

Introduction to C++ (Extensions to C)

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

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

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Fig: iostream class hierarchy

Expressions, Input, Output and Data Type Conversions

CS & IT Conversions. Magnitude 10,000 1,

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

Fundamentals of Programming CS-110. Lecture 2

Programming in C++ 4. The lexical basis of C++

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

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

Chapter 3 : Assignment and Interactive Input (pp )

Chapter 2. Outline. Simple C++ Programs

Chapter 3. Numeric Types, Expressions, and Output

Introduction to Programming EC-105. Lecture 2

LECTURE 02 INTRODUCTION TO C++

Number Systems Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur Number Representation

IBM. C/C++ Legacy Class Libraries Reference SC

FLOATING POINT NUMBERS

The type of all data used in a C++ program must be specified

Chapter 2: Introduction to C++

C++ Programming Lecture 10 File Processing

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

Computer System and programming in C

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

Objects and streams and files CS427: Elements of Software Engineering

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Lab 15 Review of Arrays, Array of Objects and Vector Dr. John Abraham, Professor

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

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

Maciej Sobieraj. Lecture 1

Variables and Data Representation

10/23/02 21:20:33 IO_Examples

Window s Visual Studio Output

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

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.

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

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

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

READ THIS NOW! Do not start the test until instructed to do so!

Data Representation 1

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

Signed umbers. Sign/Magnitude otation

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

CS242 COMPUTER PROGRAMMING


Fundamentals of Programming

Input/Output Streams: Customizing

Lecture 4 Tao Wang 1

Computer Programming : C++

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

The type of all data used in a C (or C++) program must be specified

Number Systems and Binary Arithmetic. Quantitative Analysis II Professor Bob Orr

Topic 2. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

int x = 5; double y = 3; // Integer division rounds the result down to the nearest whole number. cout << "1a: " << x / 3 << endl; //1

Chapter 2 - Control Structures

CS 216 Exam 1 Fall SOLUTION

Work relative to other classes

UNIT- 3 Introduction to C++

Chapter 11 Customizing I/O

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

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a =

Reserved Words and Identifiers

LAB 4.1 Relational Operators and the if Statement

Fundamental of Programming (C)

Transcription:

Variables: Lab 6 Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA We learned that a variable is a name assigned to the first byte of the necessary memory to store a value. During compile time the compiler reserves necessary memory for each variable. It may require more than one byte to store a value. The compiler needs to know the size of memory to reserve. This is why a type is always associated with a variable. In a 16-bit computer 2 bytes are used to store an integer, 4 bytes for floats, 8 bytes for double, and 1 byte for character and bool. The size of memory reserved by the compiler you are using can be determined by the operator sizeof. For example, cout << sizeof(x); if x is an integer, either a 2 or 4 will be displayed. Some of these types can be signed or unsigned. Unsigned can hold much larger number. For example, in a signed integer variable the range of values are -32,768 to 32,767. In an unsigned integer this range is from 0 to 65,535. Float and double are real numbers, the difference is in their precision. The major differences between integers and real numbers are as follows. 1. integers are ordinal; an integer has a specific predecessor and successor. They are represented precisely in the computer in binary. Negative numbers are represented in two's complement. 2. Real numbers are not ordinal. They have decimal portions. They are represented in the computer as two portions, mantissa and exponent. Real numbers cannot be represented exactly in the computer; they are approximations only. Therefore, two real numbers cannot be checked for equality. Truncation errors occur when two real numbers are multiplied or divided. Formatting: When outputing a real number it is often necessary to indicate the number of decimal digits we want to display. When dealing with dollars there is little reason to go beyond two decimal points. We can use setprecision(n) which is a manipulator available from <iomanip>, to indicate the decimal precision we require. For example cout << setprecision(2) << dollars; will display dollars with 2 decimal point precision. The last decimal digit will be rounded of. Consider the following program:

Program 6-1 int main() cout << 28 <<" " <<28*1.128 <<endl; cout << 123 << " " <<123*11.228 <<endl; Program Run 6-1: 28 31.584 123 1381.04 Press any key to continue The columns in the above program do not line up. Now consider the following program and its formatted output. The integers line up. But even though we used the setprecion(2), the real numbers are displayed differently. Obviously for real numbers the setprecision alone is not enough. In Program 6-3, setw, setiosflags and setprecision are added. This seems to have fixed the problem. Here the ios::fixed causes the real number to be output in fixed point format instead of exponential format. Program 6-2 int main() cout << setw(5)<<28 <<" " <<setprecision(2) << 28*1.128 <<endl; cout << setw(5) <<123 << " " <<setprecision(2) << 123*11.228 <<endl; Program Run 6-2 28 32 123 1.4e+003 Press any key to continue Program 6-3.

int main() cout << setw(5)<<28 <<setw(10)<<setiosflags(ios::fixed) <<setprecision(2) << 28*1.128 <<endl; cout << setw(5) <<123 <<setw(10)<<setiosflags(ios::fixed) <<setprecision(2) << 123*11.228 <<endl; Program Run 6-3. 28 31.58 123 1381.04 Press any key to continue. Neither setw nor width truncates values. If formatted output exceeds the width, the entire value prints, subject to the stream s precision setting. Both setw and width affect the following field only. Field width reverts to its default behavior (the necessary width) after one field has been printed. However, the other stream format options remain in effect until changed. Here are some useful escape characters. Recall that you already used \n for a new line. \b move back one space \f move to next page \t tab over \\ prints a back slash \' prints a single quote. IOMANIP provides several input and output format manipulators. Here is a summary of the most commonly used ones. An explanation of numeric formatting also is given. This section is obtained from the Visual C++ help. SETIOSFLAGS ios::skipws Skip white space on input. ios::left Left-align values; pad on the right with the fill character. ios::right Right-align values; pad on the left with the fill character (default alignment).

ios::internal Add fill characters after any leading sign or base indication, but before the value. ios::dec Format numeric values as base 10 (decimal) (default radix). ios::oct Format numeric values as base 8 (octal). ios::hex Format numeric values as base 16 (hexadecimal). ios::showbase Display numeric constants in a format that can be read by the C++ compiler. ios::showpoint Show decimal point and trailing zeros for floating-point values. ios::uppercase Display uppercase A through F for hexadecimal values and E for scientific values. ios::showpos Show plus signs (+) for positive values. ios::scientific Display floating-point numbers in scientific format. ios::fixed Display floating-point numbers in fixed format. ios::unitbuf Cause ostream::osfx to flush the stream after each insertion. By default, cerr is unit buffered. ios::stdio Cause ostream::osfx to flush stdout and stderr after each insertion. More on Loops: Suppose you already have a program and you want to add a loop around it to make it run many times. Let us modify the program from Lab 3 (the grades program) to add a while loop. First step is to decide which of the variables can be selected as loop control variable. If no variables are available to select, you can add new variable - for example, a char variable - and ask " Do you want to run the program again? ". However this is extra work for the user to answer yes or no each time and is not a preferred method. In the grades program we asked for three scores, found the average and letter grade and displayed these values. We could choose the first score as the loop control variable. If a negative number was entered for the first score, we can exit the while loop. Remember the steps required for a while loop, (1) decided on a LCV; (2) initialize the LCV; (4) setup the while loop condition; (5) write the body of the loop; and (6) change the value of LCV within the body of the loop.

Program 6-4 /****************************************** Accept three grades, find the average and display the letter grade. Teaching objective - multiple alternatives By Dr. John Abraham Created for 1370 students *****************************************/ float findave (int, int, int); char getlettergrade(float); void Message(int, int, int, float, char); int main () int one, two, three; float average; char grade; cout << "This program will calculate letter grade given three scores for any number of students."; cout << "\n\nenter the first score or a negative number to quit-> "; cin >> one; while (one >0) cout << "Enter the second score-> "; cin >> two; cout << "Enter the third score-> "; cin >> three; average= findave (one, two, three); grade = getlettergrade(average); Message (one, two, three, average, grade); cout << "\n\nenter the first score or a negative number to quit-> "; cin >> one; float findave(int one, int two, int three) float a; a = (float(one+two+three) / float(3.0)); //convert numbers to float to avoid warning return (a);

char getlettergrade (float average) char grade; if (average >=90) grade = 'A'; else if (average>= 80) grade = 'B'; else if (average >=70) grade ='C'; else if (average >= 60) grade ='D'; else grade ='F'; return (grade); void Message (int one, int two, int three, float average, char grade) cout << "Three grades are: " <<one <<setw(4)<<two <<setw(4)<<three <<endl; cout << "The average is : " <<average <<endl; cout << "\nthe letter grade is : "<< grade << endl; switch (grade) case 'A' : cout << "Very impressive grade indeed!\n";break; case 'B' : cout << "A solid performance, congratulations!\n"; break; case 'C' : cout << "C++ is a tough course, but YOU MADE IT!\n";break; case 'D' : cout << "Made it eh? \n";break; case 'F' : cout << "Don't give up. Try keeping up with all the homework!\n"; Program Run 6-4 This program will calculate letter grade given three scores for any number of students. Enter the first score or a negative number to quit-> 90 Enter the second score-> 88 Enter the third score-> 93 Three grades are: 90 88 93 The average is : 90.3333 The letter grade is : A Very impressive grade indeed!

Enter the first score or a negative number to quit-> 78 Enter the second score-> 66 Enter the third score-> 77 Three grades are: 78 66 77 The average is : 73.6667 The letter grade is : C C++ is a tough course, but YOU MADE IT! Enter the first score or a negative number to quit-> -1 Assignment: Write a program to find the average, and the smallest and largest of numbers from a series of positive numbers entered. Here is the program run: Enter a number or enter a negative number to quit-->88 Enter a number or enter a negative number to quit-->89 Enter a number or enter a negative number to quit-->78 Enter a number or enter a negative number to quit-->62 Enter a number or enter a negative number to quit-->99 Enter a number or enter a negative number to quit-->12 Enter a number or enter a negative number to quit-->45 Enter a number or enter a negative number to quit-->77 Enter a number or enter a negative number to quit-->-1 Average : 68 Largest number entered is: 99 Smallest number entered is: 12