download instant at Introduction to C++

Similar documents
download instant at Introduction to C++

Introductionto C++ Programming

download instant at

Full file at

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to Programming

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Chapter 1 Introduction to Computers and C++ Programming

Introduction to Java Applications

Another Simple Program: Adding Two Integers

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

by Pearson Education, Inc. All Rights Reserved. 2

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 2: Basic Elements of C++

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++ Objectives. Objectives (cont d.) A C++ Program. Introduction

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

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

Chapter 2: Introduction to C++

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

Objectives. In this chapter, you will:

2 nd Week Lecture Notes

Lab # 02. Basic Elements of C++ _ Part1

Lecture 3 Tao Wang 1

Full file at C How to Program, 6/e Multiple Choice Test Bank

Your First C++ Program. September 1, 2010

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

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

Chapter 2: Overview of C++

Computer Programming : C++

The C++ Language. Arizona State University 1

C: How to Program. Week /Mar/05

Chapter 2 - Introduction to C Programming

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

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

CS242 COMPUTER PROGRAMMING

BITG 1233: Introduction to C++

1. In C++, reserved words are the same as predefined identifiers. a. True

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Understanding main() function Input/Output Streams

Chapter 2 Basic Elements of C++

LECTURE 02 INTRODUCTION TO C++

Programming with C++ as a Second Language

IS 0020 Program Design and Software Tools

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

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

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

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

Introduction to Programming

Chapter 1 INTRODUCTION

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

Programming for Engineers Introduction to C

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

4. Structure of a C++ program

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

Introduction to C# Applications

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

Add Subtract Multiply Divide

Introduction to Programming using C++

Chapter 2, Part III Arithmetic Operators and Decision Making

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

Chapter 2. C++ Basics

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

VARIABLES & ASSIGNMENTS

UNIT- 3 Introduction to C++

Programming. C++ Basics

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

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

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

Scientific Computing

Operators. Java operators are classified into three categories:

Course Outline. Introduction to java

Chapter 1 Introduction to Computers and C++ Programming

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

2.8. Decision Making: Equality and Relational Operators

Chapter Two MULTIPLE CHOICE

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Creating a C++ Program

Chapter 2 C++ Fundamentals

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

A First Program - Greeting.cpp

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

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

Computer Programming

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

CS 106 Introduction to Computer Science I

Today in CS161. Week #3. Learn about. Writing our First Program. See example demo programs. Data types (char, int, float) Input and Output (cin, cout)

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

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CSCI 1061U Programming Workshop 2. C++ Basics

Copyright 1999 by Deitel & Associates, Inc. All Rights Reserved.

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

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

Transcription:

Introduction to C++ 2 Programming, Input/Output and Operators What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare High thoughts must have high language. Aristophanes One person can make a difference and every person should try. John F. Kennedy Objectives In this chapter you ll learn: T o write simple computer programs in C++. T o write simple input and output statements. T o use fundamental types. Basic computer memory concepts. T o use arithmetic operators. The precedence of arithmetic operators. T o write simple decisionmaking statements.

2 Chapter 2 Introduction to C++ Programming, Input/Output and Operators Self-Review Exercises 2.1 Fill in the blanks in each of the following. a) Every C++ program begins execution at the function. ANS: main. b) A(n) begins the body of every function and a(n) ends the body. ANS: left brace ({), right brace (}) c) Most C++ statements end with a(n). ANS: semicolon. d) The escape sequence \n represents the character, which causes the cursor to position to the beginning of the next line on the screen. ANS: semicolon. e) The statement is used to make decisions. ANS: if. 2.2 State whether each of the following is true or false. If false, explain why. Assume the statement using std::cout; is used. a) Comments cause the computer to print the text after the // on the screen when the program is executed. ANS: False. Comments do not cause any action to be performed when the program is executed. They re used to document programs and improve their readability. b) The escape sequence \n, when output with cout and the stream insertion operator, causes the cursor to position to the beginning of the next line on the screen. c) All variables must be declared before they re used. d) All variables must be given a type when they re declared. e) C++ considers the variables number and NuMbEr to be identical. ANS: False. C++ is case sensitive, so these variables are different. f) Declarations can appear almost anywhere in the body of a C++ function. g) The modulus operator (%) can be used only with integer operands. h) The arithmetic operators *, /, %, + and all have the same level of precedence. ANS: False. The operators *, / and % have the same precedence, and the operators + and - have a lower precedence. i) A C++ program that prints three lines of output must contain three statements using cout and the stream insertion operator. ANS: False. One statement with cout and multiple \n escape sequences can print several lines. 2.3 Write a single C++ statement to accomplish each of the following (assume that neither using declarations nor a using directive have been used): a) Declare the variables c, thisisavariable, q76354 and number to be of type int (in one statement). ANS: int c, thisisavariable, q76354, number; b) Prompt the user to enter an integer. End your prompting message with a colon (:) followed by a space and leave the cursor positioned after the space. ANS: std::cout << "Enter an integer: "; c) Read an integer from the user at the keyboard and store it in integer variable age. ANS: std::cin >> age;

Self-Review Exercises 3 d) If the variable number is not equal to 7, print "The variable number is not equal to 7". ANS: if ( number!= 7 ) std::cout << "The variable number is not equal to 7\n"; e) Print the message "This is a C++ program" on one line. ANS: std::cout << "This is a C++ program\n"; f) Print the message "This is a C++ program" on two lines. End the first line with C++. ANS: std::cout << "This is a C++\nprogram\n"; g) Print the message "This is a C++ program" with each word on a separate line. ANS: std::cout << "This\nis\na\nC++\nprogram\n"; h) Print the message "This is a C++ program". Separate each word from the next by a tab. ANS: std::cout << "This\tis\ta\tC++\tprogram\n"; 2.4 Write a statement (or comment) to accomplish each of the following (assume that using declarations have been used for cin, cout and endl): a) State that a program calculates the product of three integers. ANS: // Calculate the product of three integers b) Declare the variables x, y, z and result to be of type int (in separate statements) and initalize each to 0. ANS: int x = 0; int y = 0; int z = 0; int result = 0; c) Prompt the user to enter three integers. ANS: cout << "Enter three integers: "; d) Read three integers from the keyboard and store them in the variables x, y and z. ANS: cin >> x >> y >> z; e) Compute the product ofthe three integers contained in variables x, y and z, and assign the result to the variable result. ANS: result = x * y * z; f) Print "The product is " followed by the value of the variable result. ANS: cout << "The product is " << result << endl; g) Return a value from main indicating that the program terminated successfully. ANS: return 0; 2.5 Using the statements you wrote in Exercise 2.4, write a complete program that calculates and displays the product of three integers. Add comments to the code where appropriate. [Note: You ll need to write the necessary using declarations or directive.] ANS: (See program below.) 1 // Calculate the product of three integers 2 #include <iostream> // allows program to perform input and output 3 using namespace std; // program uses names from the std namespace 4 5 // function main begins program execution 6 int main() 7 { 8 int x = 0; // first integer to multiply 9 int y = 0; // second integer to multiply 10 int z = 0; // third integer to multiply 11 int result = 0; // the product of the three integers 12

4 Chapter 2 Introduction to C++ Programming, Input/Output and Operators 13 cout << "Enter three integers: "; // prompt user for data 14 cin >> x >> y >> z; // read three integers from user 15 result = x * y * z; // multiply the three integers; store result 16 cout << "The product is " << result << endl; // print result; end line 17 } // end function main 2.6 Identify and correct the errors in each of the following statements (assume that the statement using std::cout; is used): a) if ( c < 7 ); cout << "c is less than 7\n"; ANS: Error: Semicolon after the right parenthesis of the condition in the if statement. Correction: Remove the semicolon after the right parenthesis. [No t e : The result of this error is that the output statement executes whether or not the condition in the if statement is true.] The semicolon after the right parenthesis is a null (or empty) statement that does nothing. We ll learn more about the null statement in Chapter 4. b) if ( c => 7 ) cout << "c is equal to or greater than 7\n"; ANS: Error: The relational operator =>. Correction: Change => to >=, and you may want to change equal to or greater than to greater than or equal to as well. Exercises NOTE: Solutions to the programming exercises are located in the ch02solutions folder. 2.7 Discuss the meaning of each of the following objects: a) std::cin ANS: This object refers to the standard input device that is normally connected to the keyboard. b) std::cout ANS: This object refers to the standard output device that is normally connected to the screen. 2.8 Fill in the blanks in each of the following: a) are used to document a program and improve its readability. ANS: Comments b) The object used to print information on the screen is. ANS: std::cout c) A C++ statement that makes a decision is. ANS: if d) Most calculations are normally performed by statements. ANS: assignment e) The object inputs values from the keyboard. ANS: std::cin 2.9 Write a single C++ statement or line that accomplishes each of the following: a) Print the message "Enter two numbers". ANS: cout << "Enter two numbers"; b) Assign the product of variables b and c to variable a. ANS: a = b * c;

Exercises 5 c) State that a program performs a payroll calculation (i.e., use text that helps to document a program). ANS: // Payroll calculation program d) Input three integer values from the keyboard into integer variables a, b and c. ANS: cin >> a >> b >> c; 2.10 State which of the following are true and which are false. If false, explain your answers. a) C++ operators are evaluated from left to right. ANS: False. Some operators are evaluated from left to right, while other operators areevaluated right to left. b) The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales, his_account_total, a, b, c, z, z2. c) The statement cout << "a = 5;"; is a typical example of an assignment statement. ANS: False. The statementis an output statement. The text a = 5; is output to the screen. d) A valid C++ arithmetic expression with no parentheses is evaluated from left to right. ANS: False. Arithmetic operators can appear in any order in an expression, so the expression is a = b + c * d; actually evaluates from right to left because of the rules of operator precedence. e) The following are all invalid variable names: 3g, 87, 67h2, h22, 2h. ANS: False. h22 is a valid variable name. The others are invalid because they each begin with a digit. 2.11 Fill in the blanks in each of the following: a) What arithmetic operations are on the same level of precedence as multiplication?. ANS: division and modulus. b) When parentheses are nested, which set of parentheses is evaluated first in an arithmetic expression?. ANS: innermost. c) A locationinthe computer s memory that may contain different values at various times throughout the execution of a program is called a(n). ANS: variable. 2.12 What,if anything, prints when eachof the following C++ statementsis performed?if nothing prints, then answer nothing. Assume x = 2 and y = 3. a) cout << x; ANS: 2 b) cout << x + x; ANS: 4 c) cout << "x="; ANS: x= d) cout << "x = " << x; ANS: x = 2 e) cout << x + y << " = " << y + x; ANS: 5 = 5 f) z = x + y; ANS: nothing. g) cin >> x >> y; ANS: nothing. h) // cout << "x + y = " << x + y; ANS: nothing (because it is a comment).

6 Chapter 2 Introduction to C++ Programming, Input/Output and Operators i) cout << "\n"; ANS: A newline is output which positions the cursor at the beginning of the next line on the screen. 2.13 Which of the following C++ statements contain variables whose values are replaced? a) cin >> b >> c >> d >> e >> f; b) p = i + j + k + 7; c) cout << "variables whose values are replaced"; d) cout << "a = 5"; ANS: Parts (a) and (b). 2.14 Given the algebraic equation y = ax 3 + 7, which of the following, if any, are correct C++ statements for this equation? a) y = a * x * x * x + 7; b) y = a * x * x * ( x + 7 ); c) y = ( a * x ) * x * ( x + 7 ); d) y = (a * x) * x * x + 7; e) y = a * ( x * x * x ) + 7; f) y = a * x * ( x * x + 7 ); ANS: Parts (a), (d) and (e). 2.15 (Order of Evalution) State the order of evaluation of the operators in each of the following C++ statements and show the value of x after each statement is performed. a) x = 7 + 3 * 6 / 2-1; ANS: *, /, +, -, =, 15 b) x = 2 % 2 + 2 * 2-2 / 2; ANS: %, *, /, +, -, =, 3 c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) ); ANS: innermost parentheses around 3, *, /, +, *, *, 324 2.22 What does the following code print? cout << "*\n**\n***\n****\n*****" << endl; ANS: * ** *** **** *****