C++ Programming for Non-C Programmers. Supplement

Similar documents
C++ Programming for Non-C Programmers. Supplement

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

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

Scientific Computing

Computer Science II Lecture 1 Introduction and Background

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

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Name SECTION: 12:45 2:20. True or False (12 Points)

CHAPTER 4 FUNCTIONS. 4.1 Introduction

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

Introduction to Programming using C++

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

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

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

Programming. C++ Basics

Fast Introduction to Object Oriented Programming and C++

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Introduction to Algorithms and Programming (COMP151)

Bash Programming. Student Workbook

Introduction to Programming Using Java (98-388)

Chapter 2 Basic Elements of C++

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

CS242 COMPUTER PROGRAMMING

Unit 6. Thinking with Functions

CS201- Introduction to Programming Current Quizzes

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

UNIT- 3 Introduction to C++

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CSI33 Data Structures

CSCE 110 PROGRAMMING FUNDAMENTALS

CS 376b Computer Vision

W3101: Programming Languages C++ Ramana Isukapalli

A First Program - Greeting.cpp

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

1 Unit 8 'for' Loops

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Exercise: Inventing Language

Homework #3 CS2255 Fall 2012

OBJECT ORIENTED PROGRAMMING

C++ (Non for C Programmer) (BT307) 40 Hours

Topics. Functions. Functions

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Name Section: M/W or T/TH. True or False (14 Points)

Introduction to C++ Systems Programming

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Fundamentals of Programming CS-110. Lecture 2

University of Toronto

Introduction to Programming

Tokens, Expressions and Control Structures

2559 : Introduction to Visual Basic.NET Programming with Microsoft.NET

TEMPLATE IN C++ Function Templates

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

Object Oriented Design

Chapter 2: Basic Elements of C++

Input And Output of C++

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

Data Structures using OOP C++ Lecture 3

Pointers. Variable Declaration. Chapter 10

Chapter 1 Introduction to Computers and C++ Programming

C++ for Python Programmers

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

COMP322 - Introduction to C++ Lecture 01 - Introduction

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Chapter 1 INTRODUCTION

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

Introduction to C ++

Why C++? C vs. C Design goals of C++ C vs. C++ - 2

Advanced UNIX Tools. Student Workbook

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

CE221 Programming in C++ Part 1 Introduction

BITG 1233: Introduction to C++

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

Objectives. In this chapter, you will:


Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Lab Instructor : Jean Lai

AN OVERVIEW OF C++ 1

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Dr. Md. Humayun Kabir CSE Department, BUET

CS 31 Discussion 1A, Week 4. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Chapter 7 Array. Array. C++, How to Program

Unit 7. Functions. Need of User Defined Functions

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

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

Transcription:

C++ Programming for Non-C Programmers Supplement

C++ Programming for Non-C Programmers C++ Programming for Non-C Programmers Published by ITCourseware, 7245 S. Havana St, Suite 100, Centennial, CO 80112 Contributing Authors: Jeff Howell, Danielle Waleri Editor: Danielle Waleri Assistant Editor: Ginny Jaranowski Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of this workbook, including Evans Nash, and the many students who have offered comments, suggestions, criticisms, and insights. Copyright 2011 by ITCourseware, Inc. All rights reserved. No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage retrieval system, without permission in writing from the publisher. Inquiries should be addressed to ITCourseware, Inc., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112. (303) 302-5280. All brand names, product names, trademarks, and registered trademarks are the property of their respective owners. ii Rev 1.1.2 2011 ITCourseware, Inc.

Table of Contents Contents Chapter 1 - Course Introduction... 7 Course Objectives... 9 Course Overview... 11 Chapter 2 - Getting Started... 13 Chapter Objectives... 15 The First Program (hello.cpp)... 17 Compile Steps... 19 How to Compile and Run a Program... 21 Exercises... 23 Chapter 3 - Data Types and Variables... 25 Chapter Objectives... 27 Fundamental Data Types... 29 Data Type Values and Sizes... 31 Data Type Values and Sizes... 33 Variable Declarations... 35 Variable names... 37 Constants... 39 Character Constants... 41 String Constants... 43 Exercises... 45 Chapter 4 - Operators and Expressions... 47 Chapter Objectives... 49 What are expressions?... 51 Arithmetic Operators... 53 Relational Operators... 55 Assignment Operator... 57 Expressions have resulting values... 59 True and False... 61 Logical Operators... 63 Increment and Decrement Operators (++ and --)... 65 Increment and Decrement Operators: Examples... 67 'Operate-Assign' Operators (+=, *=,...)... 69 2011 ITCourseware, Inc. Rev 1.1.2 iii

C++ Programming for Non-C Programmers Conditional Expression... 71 Operator Precedence... 73 Precedence and order of evaluation... 75 Evaluation of Logical Operators... 77 Type Conversions... 79 Type conversions (cont.)... 81 The cast operator... 83 Exercises... 85 Chapter 5 - Control Flow... 87 Chapter Objectives... 89 Statements... 91 if - else... 93 if() - else if()... 95 switch()... 97 Example: Switch()... 99 switch() (cont.)... 101 while()... 103 do - while()... 105 for()... 107 The for() loop - diagram... 109 Example: for() loop...111 The break statement... 113 The continue statement... 115 Exercises... 117 Chapter 6 - Functions... 119 Chapter Objectives... 121 What is a function?... 123 Example: findbig3()... 125 Why use functions?... 127 Anatomy of a function... 129 Example: find_big_int()... 131 Arguments passed by value... 133 When to Use the return Statement... 135 Returning Non-integer Values... 137 Example: Returning Non-integer Values... 139 Functions in Multiple Source Files... 141 The Concept of Variable Scope... 143 Automatic Variables... 145 iv Rev 1.1.2 2011 ITCourseware, Inc.

Table of Contents Global (external) variables... 147 Example: Global Variables... 149 Static Variables... 151 External Static Variables... 153 Exercises... 155 Chapter 7 - Pointers and Arrays... 157 Chapter Objectives... 159 What is a pointer?... 161 Pointer Operators... 163 Example: pointers... 165 Why use pointers?... 167 Example... 169 Arrays:... 171 Arrays (a picture)... 173 The & Operator... 175 Pointers and arrays... 177 Passing arrays to functions... 179 Initializing arrays... 181 Strings and character pointers... 183 What is char s[7]???... 185 Arrays of pointers... 187 Arrays of pointers - diagram... 189 Command-line arguments... 191 Exercises... 193 Chapter 8 - Structures... 195 Chapter Objectives... 197 Comparison of structures and arrays... 199 Structure definitions... 201 Structure declarations... 203 Arrays of structures... 205 Exercises... 207 2011 ITCourseware, Inc. Rev 1.1.2 v

C++ Programming for Non-C Programmers vi Rev 1.1.2 2011 ITCourseware, Inc.

Chapter 1 Course Introduction Chapter 1 - Course Introduction 2011 by ITCourseware, Inc. 1.1.2 7

C++ Programming for Non-C Programmers Notes 8 2011 by ITCourseware, Inc. 1.1.2

Chapter 1 Course Introduction Course Objectives Write applications using the C++ programming language. Use all of the basic syntax and semantics of the C and C++ languages. Write modular programs using functions. Use pointers and arrays to maintain data. Create classes that represent real-world objects with data and functionality. Inherit classes from existing classes to gain a reuse of functionality. Properly use references and constants to maintain data integrity and minimize errors. Write your own operators to work with the new data types that you create. Create template classes to avoid redundant coding and increase code reuse. Program object-oriented applications of moderate complexity. 2011 by ITCourseware, Inc. 1.1.2 9

C++ Programming for Non-C Programmers Notes 10 2011 by ITCourseware, Inc. 1.1.2

Chapter 1 Course Introduction Course Overview Audience: This course is designed for programmers who want to move from procedural thinking to object-oriented programming using C++. Prerequisites: This course assumes that the student is an experienced professional programmer. Student Materials: Student workbook. A C++ text. Reference sheets. Classroom Environment: One terminal per student using the UNIX operating system, or a PC with a current C++ compiler. 2011 by ITCourseware, Inc. 1.1.2 11

C++ Programming for Non-C Programmers Notes 12 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Chapter 6 - Functions 2011 by ITCourseware, Inc. 1.1.2 119

C++ Programming for Non-C Programmers Notes 120 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Chapter Objectives Understand the use of functions in program structure. Write modular programs consisting of functions. Pass data to functions by value and by reference. "Build" a program from multiple source files. Initialize variables at definition time. Understand the scope of variables. Know when to use global variables. 2011 by ITCourseware, Inc. 1.1.2 121

C++ Programming for Non-C Programmers Notes 122 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions What is a function? A function is a set of instructions. A function may operate on data passed to it. A program "calls" a function, passing it data, if required. A function can be called with different data and from different places. A function can "return" data to its caller. 2011 by ITCourseware, Inc. 1.1.2 123

C++ Programming for Non-C Programmers Notes 124 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Example: findbig3() /* findbig3.cpp */ #include <iostream> using namespace std ; int find_big_3(int, int, int); int main(void) { int x,y,z; int largest; x = 10; y = 15; z = 12; largest = find_big_3(x, y, z); cout << "Largest: " << largest << endl; return 0; } /* int main(void) */ /* --- Function find_big_3 --- */ int find_big_3(int a, int b, int c) { int big; big = a > b? a : b; /* Bigger of a and b */ big = big > c? big : c; /* Bigger of big and c */ return big; } /* int find_big_3(int a, int b, int c) */ 2011 by ITCourseware, Inc. 1.1.2 125

C++ Programming for Non-C Programmers Notes 126 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Why use functions? To design a program into modules. To perform the same instructions on different sets of data. To create a library of reusable tools. 2011 by ITCourseware, Inc. 1.1.2 127

C++ Programming for Non-C Programmers Notes 128 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Anatomy of a function void main(void) { int arg1; float arg2; char arg3; func(arg1, arg2, arg3); /* Three arguments passed */ func(100, 85.463, 'X'); /* Constants as arguments */ } /* void main(void) */ /* Function returns a float, takes three parameters */ float func(int p1, float p2, char p3) /* Arguments in calls to func agree with */ /* parameters in number and type. */ /* They need not be of same name. */ {... define any needed local variables... operate on parameters... calculate a result (the function s "return value") return 3.14F; }/* float func(int p1, float p2, char p3) */ 2011 by ITCourseware, Inc. 1.1.2 129

C++ Programming for Non-C Programmers Notes 130 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Example: find_big_int() /* findbigi.cpp */ #include <iostream> using namespace std ; int find_big_int(int [], int); int main(void) { int a[5]; a[0] = 985; a[1] = 255; a[2] = 868; a[3] = 1105;; a[4] = 499; cout << "Biggest: " << find_big_int(a, 5) << endl; return 0; } /* int main(void) */ /* --- Function find_big_int --- */ int find_big_int(int a[], int num_elem) /* int a[] - Tells compiler that a is an array */ /* int num_elem - Size of array passed in */ { int i; /* Automatic local variables */ int big; big = a[0]; /* To start, assume first element is biggest */ cout << big << endl; for (i = 1; i < num_elem; i++) if (a[i] > big) { /* If i'th element is bigger, */ big = a[i]; /* then update big holder */ cout << big << endl; } return big; } /* int find_big_int(int a[], int num_elem) */ 2011 by ITCourseware, Inc. 1.1.2 131

C++ Programming for Non-C Programmers Notes 132 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Arguments passed by value The data passed to a function are copies of the caller's actual data. Functions can use passed in variables, but can't change them. /* passval.cpp */ #include <iostream> using namespace std ; int passval(int); int main(void) { int x; x=99; cout << "x before call: " << x << endl; passval(x); cout << "x after call: " << x << endl; return 0; } /* int main(void) */ /* --- Function passval --- */ int passval(int a) { a = a * 10; return a; } /* int passval(int a) */ Program will print: x before call: 99 x after call: 99 2011 by ITCourseware, Inc. 1.1.2 133

C++ Programming for Non-C Programmers Notes 134 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions When to Use the return Statement Typically, use return when the function calculates and returns a single value. Use pass-by-reference when multiple values will be returned. In the second case, maybe you need more than one function. 2011 by ITCourseware, Inc. 1.1.2 135

C++ Programming for Non-C Programmers Notes 136 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Returning Non-integer Values By default, functions are assumed to return type int. If return value type is non-int, there must be two declarations: 1. The function type must be declared. 2. The calling function must declare the called function (usually in a prototype). 2011 by ITCourseware, Inc. 1.1.2 137

C++ Programming for Non-C Programmers Notes 138 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Example: Returning Non-integer Values /* max3.cpp */ #include <iostream> using namespace std ; int main(void) { float one, two,three, big, max3(float, float, float); cout << "Enter three float values: "; cin >> one >> two >> three; big = max3(one, two, three); cout << "Big = " << big << endl; return 0; } /* int main(void) */ float max3(float a, float b, float c) { float big; big = a > b? a : b ; big = big > c? big : c ; return big; } /* float max3(float a, float b, float c) */ 2011 by ITCourseware, Inc. 1.1.2 139

C++ Programming for Non-C Programmers Notes 140 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Functions in Multiple Source Files Functions can reside in separate source files. They are compiled separately then linked together to form the executable program: On Unix: CC main.cpp func1.cpp func2.cpp -o progname In an IDE: Add main.cpp, func1.cpp and func2.cpp to your project. Each file is compiled separately and automatically linked together to create the executable. 2011 by ITCourseware, Inc. 1.1.2 141

C++ Programming for Non-C Programmers Notes 142 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions The Concept of Variable Scope Variables are "written to" and "read from". The scope of a variable is all the functions in a program that can access that variable. Variables can be automatic (local), global, static or extern. 2011 by ITCourseware, Inc. 1.1.2 143

C++ Programming for Non-C Programmers Notes 144 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Automatic Variables Are local to a function (including main()). Are accessible only to the function in which they are defined. Are created "automatically" each time the function is called. Memory locations that store automatic variables are deallocated upon function exit. 2011 by ITCourseware, Inc. 1.1.2 145

C++ Programming for Non-C Programmers Notes 146 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Global (external) variables Are defined outside of any function. Are available to all functions, even those compiled separately (by using the extern keyword). Provide an alternative to function arguments and return values for communicating between functions. Local variables with same name as global will prevail. 2011 by ITCourseware, Inc. 1.1.2 147

C++ Programming for Non-C Programmers Notes 148 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Example: Global Variables /* gcount.cpp */ #include <iostream> using namespace std ; void f(void); int count; /* Global variable */ int main(void) { count = 0; f(); /* Once */ f(); /* Twice */ f(); /* Thrice */ cout << "f called " << count << " times" << endl; return 0; } /* int main(void) */ void f(void) { count++; } /* void f(void) */ 2011 by ITCourseware, Inc. 1.1.2 149

C++ Programming for Non-C Programmers Notes 150 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Static Variables Two uses for static (We'll see the second in a minute). Within a function, static variables retain their values "for next call" when a function exits. /* statv.cpp */ #include <iostream> using namespace std ; void statfunc(int); int main(void) { statfunc(10); statfunc(20); return 0; } /* int main(void) */ void statfunc(int i) { static hold = 0; cout << "Previous hold: " << hold << endl; hold = i; cout << "Current hold: " << hold << endl; } /* void statfunc(int i) */ 2011 by ITCourseware, Inc. 1.1.2 151

C++ Programming for Non-C Programmers Notes 152 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions External Static Variables External (defined outside any function) static variables are only accessible within that source file. Useful for preventing name conflicts between separately compiled modules. Because... identically named external statics in different files are different, not the same (huh?). 2011 by ITCourseware, Inc. 1.1.2 153

C++ Programming for Non-C Programmers Notes 154 2011 by ITCourseware, Inc. 1.1.2

Chapter 6 Functions Exercises 1. Write a program that reads four numbers from the keyboard and prints out the minimum, maximum, and average of the numbers. Define four separate float variables for the numbers. BE SURE to modularize the program into separate tasks that input the data, perform the calculations, and report the results. Do you think that an array version of this program would be better? 2. Starting with swmenu.cpp (from the previous chapter), create a menu-driven user interface for a program. Loop till the user chooses exit, and call a function for each switched choice. For now, just confirm to the user that the program entered the function. 3. Split the program from Exercise 1 into separately compilable source files, then compile and run the executable. 4. Write a simple program that calls a function which adds two floats and returns the sum. 2011 by ITCourseware, Inc. 1.1.2 155

C++ Programming for Non-C Programmers Notes 156 2011 by ITCourseware, Inc. 1.1.2