C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh
|
|
- Neal McCoy
- 6 years ago
- Views:
Transcription
1 C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh
2 CHAPTER TWO: Fundamental Data Types
3 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.
4 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
5 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.
6 Variable Definitions Must obey the rules for valid names
7 Variable Definitions
8 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.
9 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:
10 Number Types
11 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.
12 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.
13 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.
14 Variable Names
15 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.
16 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.
17 The Assignment Statement This is a Declaration statement
18 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.
19 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
20 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;
21 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.
22 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?
23 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!)
24 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 */
25 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.
26 Example
27 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 = ; 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.
28 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.
29 Numeric Types In C++ In addition to the int and double types, C++ has several other numeric types.
30 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 = ; cout << 3 * one_billion << endl; displays In situations such as this, you can switch to double values.
31 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
32 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.
33 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.
34 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.
35 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.
36 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.
37 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 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).
38 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.
39 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)
40 Integer Division and Remainder dollars = / 100; cents = % 100;
41 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
42 Powers and Roots How to write the following mathematical expression in C++ x b r n
43 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.
44 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 n x = b * pow(1 + r / 100, n);
45 Other Mathematical Functions
46
47 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 all yield 1.75.
48 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;
49 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;
50 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.?
51 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.
52 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: is a great help.
53 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
54 Input Note: bottles doesn t need to be initialized
55 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
56 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:
57 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>
58 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.
59 Formatted Output Example: price_per_ounce_1 = ; price_per_ounce_2 = 117.2; price_per_ounce_3 = ; 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:
60 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
61 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.
62 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;
63 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 = "";
64 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
65 Common Error Concatenation of literal strings string greeting = "Hello, " + " World!"; // will not compile Literal strings cannot be concatenated.
66 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.
67 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
68 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.
69 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).
70 String Functions Example: string greeting = "Hello, World!"; string sub = greeting.substr(0, 5); // sub contains "Hello
71 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.
72 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!"
73 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!)
74 String Operations
75 String Operations
76 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.
77 Example Continue..
78 End Chapter Two
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 information1. 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 informationDefine a method vs. calling a method. Chapter Goals. Contents 1/21/13
CHAPTER 2 Define a method vs. calling a method Line 3 defines a method called main Line 5 calls a method called println, which is defined in the Java library You will learn later how to define your own
More informationChapter Two PROGRAMMING WITH NUMBERS AND STRINGS
Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS Introduction Numbers and character strings are important data types in any Python program These are the fundamental building blocks we use to build more
More informationFUNDAMENTAL DATA TYPES
CHAPTER 2 FUNDAMENTAL DATA TYPES Copyright 2013 by John Wiley & Sons. All rights reserved. Slides by Donald W. Smith TechNeTrain.com Final Draft Oct. 15, 2011 Chapter Goals To declare and initialize variables
More informationC++ 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 informationCS 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 informationEngineering 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 informationWeek 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 informationBITG 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 informationIntroduction to Software Development (ISD) David Weston and Igor Razgon
Introduction to Software Development (ISD) David Weston and Igor Razgon Autumn term 2013 Course book The primary book supporting the ISD module is: Java for Everyone, by Cay Horstmann, 2nd Edition, Wiley,
More informationExpressions, 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 informationObjectives. 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 informationChapter 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 informationObjectives. 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 informationChapter 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 informationChapter 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 informationOn 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 informationThe 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 informationUNIT- 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 informationChapter 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 informationThe 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 informationLesson 3: Arithmetic & Casting. Pic 10A Ricardo Salazar
Lesson 3: Arithmetic & Casting Pic 10A Ricardo Salazar (2.4) Constants Sometimes we want a 'variable' that does not vary!? (OK that does not make sense... but how about a 'house' whose guest is always
More informationReview: 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 informationEngineering 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 informationChapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
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
More informationBig Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann
Big Java Fifth Edition Cay Horstmann Chapter 3 Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of
More informationProgramming 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,
More informationChapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 1 C++ Basics Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment
More information1. 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 informationProgramming with C++ as a Second Language
Programming with C++ as a Second Language Week 2 Overview of C++ CSE/ICS 45C Patricia Lee, PhD Chapter 1 C++ Basics Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Introduction to
More informationThis 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
More informationComputer 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 informationStructured 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 informationChapter 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
More informationChapter 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 information3.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 informationChapter 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 informationChapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
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
More informationChapter 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
More information3.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 informationREVIEW. 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,
More informationCSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York
CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this
More informationAdd Subtract Multiply Divide
ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient
More informationCompilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors
First Program Compilation and Execution Simplifying Fractions Loops If Statements Variables Operations Using Functions Errors C++ programs consist of a series of instructions written in using the C++ syntax
More informationLecture 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 informationArithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37
2.2 Arithmetic 37 This is particularly important when programs are written by more than one person. It may be obvious to you that cv stands for can volume and not current velocity, but will it be obvious
More informationby Pearson Education, Inc. All Rights Reserved. 2
1992-2010 by Pearson Education, Inc. All Rights Reserved. 2 1992-2010 by Pearson Education, Inc. All Rights Reserved. 3 1992-2010 by Pearson Education, Inc. All Rights Reserved. 4 1992-2010 by Pearson
More informationComputer Programming : C++
The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program
More informationPIC 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 informationCSCE 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 informationChapter 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++
More informationIntroduction 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! 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 informationChapter 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
More informationFundamentals 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 information3.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 informationChapter 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 informationFull 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
More informationLecture 4 CSE July 1992
Lecture 4 CSE 110 6 July 1992 1 More Operators C has many operators. Some of them, like +, are binary, which means that they require two operands, as in 4 + 5. Others are unary, which means they require
More informationData and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence
Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public
More informationIT 374 C# and Applications/ IT695 C# Data Structures
IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation
More informationProgramming in C++ 5. Integral data types
Programming in C++ 5. Integral data types! Introduction! Type int! Integer multiplication & division! Increment & decrement operators! Associativity & precedence of operators! Some common operators! Long
More informationCHAPTER 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
More informationChapter 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
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationChapter 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
More informationChapter 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 informationFull file at
Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional
More information2.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
More informationc++ 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 informationReserved Words and Identifiers
1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the
More informationCSc 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 information12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.
Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started
More informationVisual C# Instructor s Manual Table of Contents
Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms
More informationGetting 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
More informationSection we will not cover section 2.11 feel free to read it on your own
Operators Class 5 Section 2.11 we will not cover section 2.11 feel free to read it on your own Data Types Data Type A data type is a set of values and a set of operations defined on those values. in class
More informationLESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:
LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics
Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional
More information2 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
More informationProgram Fundamentals
Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting
More informationUnit 3. Operators. School of Science and Technology INTRODUCTION
INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.
More informationModule 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 informationProgramming. 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++
More informationIntroduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language
Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions
More informationA 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 informationLECTURE 02 INTRODUCTION TO C++
PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION
More informationChapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved
Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test
More informationGE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout
More informationCEN 414 Java Programming
CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea
More informationObject-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering
Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering Lecture 3 Winter 2011/12 Oct 25 Visual C++: Problems and Solutions New section on web page (scroll down)
More informationC++ 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
More informationDiscussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:
Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;
More informationChapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.
Chapter 4 Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of causes for overflow and roundoff errors
More informationOverview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program
Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of
More informationBy 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 informationCHAPTER 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 informationComputer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2
More informationC++ 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
More information