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

Similar documents
Chapter Two: Fundamental Data Types

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

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

FUNDAMENTAL DATA TYPES

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

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

Engineering Problem Solving with C++, Etter/Ingber

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.

BITG 1233: Introduction to C++

Introduction to Software Development (ISD) David Weston and Igor Razgon

Expressions, Input, Output and Data Type Conversions

Objectives. In this chapter, you will:

Chapter 3. Numeric Types, Expressions, and Output

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

Chapter 2: Basic Elements of C++

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

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

The C++ Language. Arizona State University 1

UNIT- 3 Introduction to C++

Chapter 2. Outline. Simple C++ Programs

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

Lesson 3: Arithmetic & Casting. Pic 10A Ricardo Salazar

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

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

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

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

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

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

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.

Programming with C++ as a Second Language

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

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

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

Chapter 2: Overview of C++

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

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

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

Chapter 2. C++ Basics

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

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

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

Add Subtract Multiply Divide

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Lecture 3 Tao Wang 1

Arithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37

by Pearson Education, Inc. All Rights Reserved. 2

Computer Programming : C++

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter 2: Introduction to C++

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

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

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

Fundamentals of Programming CS-110. Lecture 2

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

Chapter 3 - Functions

Full file at

Lecture 4 CSE July 1992

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

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

Programming in C++ 5. Integral data types

CHAPTER 3 BASIC INSTRUCTION OF C++

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

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

Chapter 2 Basic Elements of C++

Full file at

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

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

Reserved Words and Identifiers

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

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

Visual C# Instructor s Manual Table of Contents

Getting started with C++ (Part 2)

Section we will not cover section 2.11 feel free to read it on your own

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

2 nd Week Lecture Notes

Program Fundamentals

CS313D: ADVANCED PROGRAMMING LANGUAGE

Unit 3. Operators. School of Science and Technology INTRODUCTION

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

Programming. C++ Basics

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

A First Program - Greeting.cpp

LECTURE 02 INTRODUCTION TO C++

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

CEN 414 Java Programming

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First 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

CHAPTER 3 Expressions, Functions, Output

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

Transcription:

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, and how to write simple programs that perform useful tasks with them.

2.1 Variables A variable: is a storage location in a computer program. Each variable has a name and holds a value. is used to store information. can contain one piece of information at a time. has an identifier (name): The programmer picks a good name A good name describes the contents of the variable or what the variable will be used for

Variable Definitions The following statement defines a variable. cans_per_pack is the variable s name. int cans_per_pack = 6; int indicates that the variable cans_per_pack will be used to hold integers. = 6 indicates that the variable cans_per_pack will initially contain the value 6.

Variable Definitions Must obey the rules for valid names

Variable Definitions

Data Types In C++, there are several different types of numbers. You use the integer number type, called int in C++, to denote a whole number without a fractional part. When a fractional part is required (such as in the number 0.355), we use floating point numbers. The most commonly used type for floating-point numbers in C++ is called double. double can_volume = 0.355; To store text and characters we have the char and string data types.

Number Types A number written by a programmer is called a number literal. int cans_per_pack = 6 ; There are rules for writing literal values:

Number Types

Variable Names When you define a variable, you should pick a name that explains its purpose. For example, it is better to use a descriptive name, such as can_volume, than a terse name, such as cv.

Variable Names In C++, there are a few simple rules for variable names: 1. Variable names must start with a letter or the underscore ( _ ) character, and the remaining characters must be letters numbers, or underscores. 2. You cannot use other symbols such as $ or %. 3. Spaces are not permitted inside names; you can use an underscore instead, as in can_volume.

Variable Names 4. Variable names are case-sensitive, that is, can_volume and can_volume are different names. For that reason, it is a good idea to use only lowercase letters in variable names. 5. You cannot use reserved words such as double or return as names; these words are reserved exclusively for their special C++ meanings.

Variable Names

The Assignment Statement The contents in variables can vary over time Variables can be changed by: assigning to them The assignment statement using the increment or decrement operator inputting into them The input statement An assignment statement stores a new value in a variable, replacing the previously stored value.

The Assignment Statement cans_per_pack = 8; This assignment statement changes the value stored in cans_per_pack to be 8. The previous value is replaced. The variable cans_per_pack has to be already declared.

The Assignment Statement This is a Declaration statement

The Assignment Statement There is an important difference between a variable definition and an assignment statement: int cans_per_pack = 6; // Variable definition... cans_per_pack = 8; // Assignment statement The first statement is the definition of cans_per_pack. The second statement is an assignment statement. An existing variable s contents are replaced.

The Assignment Statement counter = 11; // set counter to 11 counter = counter + 2; // increment 1. Look up what is currently in counter (11) 2. Add 2 to that value (13) 3. copy the result of the addition expression into the variable on the left, changing counter cout << counter << endl; 13 is shown

Constants Sometimes the programmer knows certain values just from analyzing the problem, for this kind of information, programmers use the reserved word const. The reserved word const is used to define a constant. A const is a variable whose contents cannot be changed and must be set when created. (Most programmers just call them constants, not variables.) Constants are commonly written using capital letters to distinguish them visually from regular variables: const double BOTTLE_VOLUME = 2;

Constants It is good programming style to use named constants in your program to explain the meanings of numeric values. For example, compare the statements: double total_volume = bottles * 2; double total_volume = bottles * BOTTLE_VOLUME; A programmer reading the first statement may not understand the significance of the number 2 (magic number). The second statement, with a named constant, makes the computation much clearer.

Constants And it can get even worse Suppose that the number 2 appears hundreds of times throughout a five-hundred-line program? Now we need to change the BOTTLE_VOLUME to 2.23 (because we are now using a bottle with a different shape) How to change only some of those magic numbers?

Constants Constants to the rescue! const double BOTTLE_VOLUME = 2.23; const double CAN_VOLUME = 2;... double bottle_volume = bottles * BOTTLE_VOLUME; double can_volume = cans * CAN_VOLUME; (Look, no magic numbers!)

Comments As your programs get more complex, you should add comments, explanations for human readers of your code. Here is an example: const double CAN_VOLUME = 0.355; // Liters in a 12-ounce can The compiler does not process comments at all. It ignores everything from a // delimiter to the end of the line. You use the // syntax for single-line comments. If you have a comment that spans multiple lines, enclose it between /* and */ delimiters. For example: /* This program computes the volume (in liters) of a sixpack of soda cans and the total volume of a six-pack and a two-liter bottle */

Example The following program shows the use of variables, constants, and the assignment statement. The program displays the volume of a six-pack of cans and the total volume of the six-pack and a two-liter bottle.

Example

Common Error Using Undefined Variables You must define a variable before you use it for the first time. For example, the following sequence of statements would not be legal: double can_volume = 12 * liter_per_ounce; double liter_per_ounce = 0.0296; In your program, the statements are compiled in order. When the compiler reaches the first statement, it does not know that liter_per_ounce will be defined in the next line, and it reports an error.

Common Error Using Uninitialized Variables If you define a variable but leave it uninitialized, then your program can act unpredictably. int bottles; // Forgot to initialize int bottle_volume = bottles * 2; The compiler won t report an error, it s a run time error, the Result is unpredictable. There is no way of knowing what value will be computed.

Numeric Types In C++ In addition to the int and double types, C++ has several other numeric types.

Numeric Ranges And Precisions The int type has a limited range: On most platforms, it can represent numbers up to a little more than two billion. For many applications, this is not a problem If a computation yields a value that is outside the int range, the result overflows. No error is displayed. Instead, the result is truncated to fit into an int, yielding a useless value. For example: int one_billion = 1000000000; cout << 3 * one_billion << endl; displays 1294967296. In situations such as this, you can switch to double values.

Arithmetic Operators C++ has the same arithmetic operators as a calculator: * for multiplication: a * b (not a. b or ab as in math) / for division: a / b (not or a fraction bar as in math) + for addition: a + b - for subtraction: a b

Arithmetic Operations You must write a * b to denote multiplication. Unlike in mathematics, you can not write ab, a. b or a b. Similarly, division is always indicated with a /, never a or a fraction bar. For example: becomes (a + b) / 2.

Arithmetic Operations Parentheses are used just as in algebra: to indicate in which order the subexpressions should be computed. For example, in the expression (a + b) / 2, the sum a + b is computed first, and then the sum is divided by 2. In contrast, in the expression a + b / 2 only b is divided by 2, and then the sum of a and b / 2 is formed.

Arithmetic Operations Multiplication and division have a higher precedence than addition and subtraction. For example, in the expression a + b / 2, the / is carried out first, even though the + operation occurs further to the left. If both arguments of an arithmetic operation are integers, the result is an integer. If one or both arguments are floating point numbers, the result is a floating-point number. For example, 4 * 0.5 is 2.0.

Increment and Decrement Changing a variable by adding or subtracting 1 is so common that there is a special shorthand for it, namely counter++; counter--; The ++ increment operator gave the C++ programming language its name. C++ is the incremental improvement of the C language.

Combining Assignment and Arithmetic In C++, you can combine arithmetic and assignments. For example, the statement: total += cans * CAN_VOLUME; is a shortcut for total = total + cans * CAN_VOLUME; Similarly, total *= 2; is another way of writing total = total * 2; Many programmers prefer using this form of coding.

Integer Division And Remainder Division works as you would expect, as long as at least one of the numbers involved is a floating-point number. That is, 7.0 / 4.0, 7 / 4.0, and 7.0 / 4 all yield 1.75. However, if both numbers are integers, then the result of the division is always an integer, with the remainder discarded. That is: 7 / 4 evaluates to 1 because 7 divided by 4 is 1 with a remainder of 3 (which is discarded).

Integer Division And Remainder If you are interested in the remainder only, use the % operator. The remainder of the integer division of 7 by 4 is 3 x = 7 % 4 ; x is assigned the value 3 The operator % is called modulus symbol, it has no analog in algebra. Note: you can use the modulus operator with intger division only, that is: the two operands has to be integers.

Integer Division and Remainder Example: You want to determine the value in dollars and cents stored in the piggy bank. You obtain the dollars through an integer division by 100. The integer division discards the remainder. To obtain the remainder, use the % operator: int pennies = 1729; // value in cents int dollars = pennies / 100; // Sets dollars to 17 int cents = pennies % 100; // Sets cents to 29 (yes, 100 is a magic number)

Integer Division and Remainder dollars = / 100; cents = % 100;

Converting Floating-Point Numbers to Integers When a floating-point value is assigned to an integer variable, the fractional part is discarded: double price = 2.55; int dollars = price; // Sets dollars to 2 You probably want to round to the nearest integer. To round a positive floating-point value to the nearest integer, add 0.5 and then convert to an integer: int dollars = price + 0.5; // Rounds to the nearest integer

Powers and Roots How to write the following mathematical expression in C++ x b r 1 100 n

Powers and Roots In C++, there are no symbols for powers and roots. To compute them, you must call functions. The C++ library defines many mathematical functions such as sqrt (square root) and pow (raising to a power). To use the functions in this library, called the cmath library, you must place the line: #include <cmath> at the top of your program file. It is also necessary to include using namespace std; at the top of your program file.

Powers and Roots The power function has the base followed by a comma followed by the power to raise the base to: pow(base, exponent) Using the pow function we can write: x b r 1 100 n x = b * pow(1 + r / 100, n);

Other Mathematical Functions

Common Error Unintended Integer Division If both arguments of / are integers, the remainder is discarded: 7 / 3 is 2, not 2.5 but 7.0 / 4.0 7 / 4.0 7.0 / 4 all yield 1.75.

Common Error Unintended Integer Division It is a common error to use integer division by accident. Consider this segment that computes the average of three integers: cout << "Please enter your last three test scores: "; int s1; int s2; int s3; cin >> s1 >> s2 >> s3; double average = (s1 + s2 + s3) / 3; cout << "Your average score is " << average << endl;

Common Error Unintended Integer Division The remedy is to make the numerator or denominator into a floating-point number: double total = s1 + s2 + s3; double average = total / 3; or double average = (s1 + s2 + s3) / 3.0;

Common Error Unbalanced Parentheses Consider the expression: (-(b * b - 4 * a * c) / (2 * a) What is wrong with it? The parentheses are unbalanced. This is very common with complicated expressions.?

Common Error Forgetting Header Files Every program that carries out input or output needs the <iostream> header. If you use mathematical functions such as sqrt, you need to include <cmath>. If you forget to include the appropriate header file, the compiler will not know symbols such as cout or sqrt. If the compiler complains about an undefined function or symbol, check your header files.

Common Error Forgetting Header Files Sometimes you may not know which header file to include. Suppose you want to compute the absolute value of an integer using the abs function. As it happens, this version of abs is not defined in the <cmath> header but in <cstdlib>. How can you find the correct header file? Why do you think Tim Berners-Lee invented going online? A reference site on the Internet such as: http://www.cplusplus.com is a great help.

Input Sometimes the programmer does not know what should be stored in a variable but the user does. The programmer must get the input value from the user Users need to be prompted (how else would they know they need to type something? Prompts are done in output statements The keyboard needs to be read from This is done with an input statement cout << "Enter the number of bottles: "; cin >> bottles // bottles should be already declared

Input Note: bottles doesn t need to be initialized

Input You can read more than one value in a single input statement: cout <<"Please enter the number of bottles and cans:"; cin >> bottles >> cans; The user can supply both inputs on the same line: Please enter the number of bottles and cans: 2 6 Alternatively, the user can press the Enter key after each input: Please enter the number of bottles and cans: 2 6

Formatted Output When you print the result of a computation, you often want some control over its appearance. For example, when you print an amount you usually want it to be rounded to two significant digits. That is, you want the output to look like: Price per ounce: 0.04 instead of Price per ounce: 0.0409722

Formatted Output The following command instructs cout to use two digits after the decimal point for all floating-point numbers: cout << fixed << setprecision(2); This command does not produce any output it just manipulates cout to change the output format. The values fixed and setprecision are called manipulators. To use manipulators, you must include the <iomanip> header in your program: #include <iomanip>

Formatted Output You can combine the manipulators and the values to be displayed into a single statement. cout << fixed << setprecision(2)<< "Price per ounce: " << price_per_ounce << endl; When you display several rows of data, you usually want the columns to line up. If you want columns of certain widths, use the setw manipulator You use the setw manipulator to set the width of the next output field. cout<< setw(8)<< volume; The width is the total number of characters used for showing the value, including digits, the decimal point, and spaces.

Formatted Output Example: price_per_ounce_1 = 10.2372; price_per_ounce_2 = 117.2; price_per_ounce_3 = 6.9923435; cout << setprecision(2); cout << setw(8) << price_per_ounce_1; cout << setw(8) << price_per_ounce_2; cout << setw(8) << price_per_ounce_3; cout << "--------" << endl; produces this output: 10.24 117.20 6.99 --------

Formatted Output There is a notable difference between the setprecision and setw manipulators. Once you set the precision, that width is used for all floating-point numbers until the next time you set the precision. But setw affects only the next value. Subsequent values are formatted without added spaces

String Many programs process text, not numbers. Text consists of characters: letters, numbers, punctuation, spaces, and so on. A string is a sequence of characters. For example, the string "Harry" is asequence of five characters.

String You can define variables that hold strings. string name = "Harry"; The string type is a part of the C++ standard. To use it, simply include the header file,<string>: #include <string> using namespace std;

String Unlike number variables, string variables are guaranteed to be initialized even if you do not supply an initial value. By default, a string variable is set to an empty string: a string containing no characters "". The definition: string response; has the same effect as string response = "";

String Concatenation Given two strings, such as "Harry" and "Morgan", you can concatenate them to one long string. The result consists of all characters in the first string, followed by all characters in the second string. Example: string fname = "Harry"; string lname = "Morgan"; string name = fname + lname; results in the string "HarryMorgan name = fname + " " + lname; results in the string "Harry Morgan

Common Error Concatenation of literal strings string greeting = "Hello, " + " World!"; // will not compile Literal strings cannot be concatenated.

String Input You can read a string from the console: cout << "Please enter your name: "; string name; cin >> name; When a string is read with the >> operator, only one word is placed into the string variable. For example, suppose the user types Harry Morgan This input consists of two words. Only the string "Harry" is placed into the variable name.

String Input You can use another input to read the second word. cout << "Please enter your name: "; string fname, lname; cin >> fname >> lname; gets Harry gets Morgan

String Functions The number of characters in a string is called the length of the string. For example, the length of "Harry" is 5. You can compute the length of a string with the length function. Unlike the sqrt or pow function, the length function is invoked with the dot notation. int n = name.length(); Many C++ functions require you to use this dot notation, and you must memorize (or look up) which do and which don t. These functions are called member functions.

String Functions Once you have a string, you can extract substrings by using the substr member function. s.substr(start, length) returns a string that is made from the characters in the string s, starting at character start, and containing length characters. (start and length are integer values).

String Functions Example: string greeting = "Hello, World!"; string sub = greeting.substr(0, 5); // sub contains "Hello

String Functions The first position in a string is labeled 0, the second one 1, and so on. And don t forget to count the space character after the comma but the quotation marks are not The position number of the last character is always one less than the length of the string. The! is at position 12 in "Hello, World!". The length of "Hello, World!" is 13.

String Functions If you do not specify how many characters to take, you get all the rest. string greeting = "Hello, World!"; string w = greeting.substr(7); // w contains "World!" To have the last three characters in a string you can use: string w = greeting.substr(greeting.length()-3); // w contains "ld!"

String Functions string greeting = "Hello, World!"; string w = greeting.substr(); // w contains "Hello World!" If you omit the starting position and the length, you get all the characters. (not much of substring!)

String Operations

String Operations

Example Write a simple program that asks the user to enter his name and the name of his significant other. It then prints out their initials. Sample: if the user enter Amal and Heba the output will be A&H Solution: The operation first.substr(0, 1) makes a string consisting of one character, taken from the start of first. The program does the same for the second. Then it concatenates the resulting one-character strings with the string literal "&" to get a string of length 3.

Example Continue..

End Chapter Two