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

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

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

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

Introduction to Programming using C++

Scientific Computing

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

Computer Science II Lecture 1 Introduction and Background

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

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

Fast Introduction to Object Oriented Programming and C++

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

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

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)

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

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CS2141 Software Development using C/C++ Compiling a C++ Program

Chapter 2 Basic Elements of C++

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

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

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

Chapter 1 INTRODUCTION

Chapter 2: Basic Elements of C++

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

UNIT- 3 Introduction to C++

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

Lab 1: First Steps in C++ - Eclipse

W3101: Programming Languages C++ Ramana Isukapalli

Dr. Md. Humayun Kabir CSE Department, BUET

CS 376b Computer Vision

Programming. C++ Basics

A First Program - Greeting.cpp

Objectives. In this chapter, you will:

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

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

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

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

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

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

C++ for Python Programmers

Chapter 1 Introduction to Computers and C++ Programming

Introduction to Algorithms and Programming (COMP151)

CE221 Programming in C++ Part 1 Introduction


CSI33 Data Structures

CS201- Introduction to Programming Current Quizzes

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Topics. Functions. Functions

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

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

Fundamentals of Programming CS-110. Lecture 2

Tutorial-2a: First steps with C++ programming

Exercise: Inventing Language

COMP322 - Introduction to C++ Lecture 01 - Introduction

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:

1 Unit 8 'for' Loops

AN OVERVIEW OF C++ 1

BITG 1233: Introduction to C++

Introduction to C++ Systems Programming

Introduction to C ++

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

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

WARM UP LESSONS BARE BASICS

OBJECT ORIENTED PROGRAMMING

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

Introduction to Programming Using Java (98-388)

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

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:

CS242 COMPUTER PROGRAMMING

University of Toronto

Unit 6. Thinking with Functions

Object Oriented Design

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 (!

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

Input And Output of C++

Crash Course into. Prof. Dr. Renato Pajarola

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Short Notes of CS201

Computer Programming : C++

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

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

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

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Object Oriented Design

CSE 303: Concepts and Tools for Software Development

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Lecture 2: C Programming Basic

CS201 - Introduction to Programming Glossary By

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science. Instructor: Final Exam Fall 2011

Data Structures using OOP C++ Lecture 3

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

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

Transcription:

C++ Programming for Non-C Programmers Supplement

ii C++ Programming for Non-C Programmers C++ Programming for Non-C Programmers Published by itcourseware, 10333 E. Dry Creek Rd., Suite 150, Englewood, CO 80112 Contributing Authors: Jeff Howell, Danielle Waleri Editor: Danielle Waleri 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 1998 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., 10333 E. Dry Creek Rd., Suite 150, Englewood, Colorado, 80112. (303) 874-1099. All brand names, product names, trademarks, and registered trademarks are the property of their respective owners.

Table of Contents iii 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 Conditional Expression... 71 Operator Precedence... 73 Precedence and order of evaluation... 75

iv C++ Programming for Non-C Programmers 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 Global (external) variables... 147 Example: Global Variables... 149 Static Variables... 151 External Static Variables... 153 Exercises... 155

Table of Contents v 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

vi C++ Programming for Non-C Programmers

Chapter 1 Course Introduction 7 Chapter 1 - Course Introduction

8 C++ Programming for Non-C Programmers Notes

Chapter 1 Course Introduction 9 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.

10 C++ Programming for Non-C Programmers Notes

Chapter 1 Course Introduction 11 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.

12 C++ Programming for Non-C Programmers Notes

Chapter 2 Getting Started 13 Chapter 2 - Getting Started

14 C++ Programming for Non-C Programmers Notes

Chapter 2 Getting Started 15 Chapter Objectives Compile and run a program. Become familiar with your environment. Get "hands on" the machine immediately.

16 C++ Programming for Non-C Programmers Notes The following line: using namespace std ; is neccessary when including standard header files, like iostream. It will be discussed later in the course.

Chapter 2 Getting Started 17 The First Program (hello.cpp) /* hello.cpp */ #include <iostream> using namespace std ; int main(void) { cout << "hello, world" << endl; return 0; } /* int main(void) */

18 C++ Programming for Non-C Programmers Notes

Chapter 2 Getting Started 19 Compile Steps The source code file is the file that you create with an editor. The compiler compiles the source into an object file from which the linker creates an executable file. hello.cpp Source Code File hello.o Compile Object Code File hello Link Executable Binary File

20 C++ Programming for Non-C Programmers Notes

Chapter 2 Getting Started 21 How to Compile and Run a Program The linker needs to know the names of all of the object files that are part of your executable program. On a Unix platform, you create a makefile that contains the names of all of your files, then run the utility called make which compiles and links your code. In an Integrated Development Environment (IDE) such as Borland C++ or Microsoft Visual C++, you create a project that contains the names of all of your files, then running your program will first cause it to be compiled and linked.

22 C++ Programming for Non-C Programmers Notes

Chapter 2 Getting Started 23 Exercises 1. Edit hello.cpp such that it does not print the endl. Compile and run it. 2. Edit your solution so that it uses a second cout statement to print the endl. 3. Finally, have it print hello followed by your name.

24 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 119 Chapter 6 - Functions

120 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 121 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.

122 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 123 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.

124 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 125 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) */

126 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 127 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.

128 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 129 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) */

130 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 131 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) */

132 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 133 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

134 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 135 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.

136 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 137 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).

138 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 139 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) */

140 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 141 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.

142 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 143 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.

144 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 145 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.

146 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 147 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.

148 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 149 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) */

150 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 151 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) */

152 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 153 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?).

154 C++ Programming for Non-C Programmers Notes

Chapter 6 Functions 155 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.

156 C++ Programming for Non-C Programmers Notes