Docsity

STRUCTURED PRGRAMMING WITH C++, Lecture notes of Information and Communications Technology (ICT)

Partial preview of the text

Download STRUCTURED PRGRAMMING WITH C++ and more Lecture notes Information and Communications Technology (ICT) in PDF only on Docsity!

Kjell Bäckman

Structured Programming with

C++

Download free books at

Download free eBooks at bookboon.com

2

Kjell Bäckman

Structured Programming with C++

Download free eBooks at bookboon.com

Click on the ad to read more

Structured Programming with C++

Download free eBooks at bookboon.com

Click on the ad to read more

Structured Programming with C++

2.11 Formatted Output 33 2.12 Invoice Program 35 2.13 Time Conversion Program 37 2.14 Type Conversion 39 2.15 The Random Number Generator 40 2.16 Game Program 41 2.17 Summary 42 2.18 Exercises 42

3 Selections and Loops 45 3.1 Introduction 45 3.2 Selection 45 3.3 if statement 45 3.4 Price Calculation Program 46 3.5 Comparison Operators 48 3.6 Even or Odd 49 3.7 else if 49 3.8 and (&&), or (||) 50 3.9 Conditional Input 51 3.10 The switch statement 52 3.11 Menu Program 52 3.12 Loops 55

© Deloitte & Touche LLP and affiliated entities.

thinking.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

D

© Deloitte & Touche LLP and affiliated entities.

thinking.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

thinking.

Discover the truth at www.deloitte.ca/careers

Download free eBooks at bookboon.com

Click on the ad to read more

Structured Programming with C++

4.9 Product File, Search 85 4.10 Two-Dimensional Array 85 4.11 Sorting 87 4.12 Searching a Sorted Array 90 4.13 Summary 94 4.14 Exercises 94

5 Strings 96 5.1 Introduction 96 5.2 Data Type char 96 5.3 Menu Program 96 5.4 Menu Program with Loop 98 5.5 Christmas Tree 100 5.6 int - char 103 5.7 Å, Ä, Ö 103 5.8 String Array, char[] 103 5.9 Length of a String 105 5.10 Upper/Lower Case 106 5.11 Initials 106 5.12 Comparing Two Strings 108 5.13 Copying Strings 109 5.14 Array with String Arrays 109

Corporate eLibrary

See our Business Solutions for employee learning

Click here

Management

Goal setting Motivation Coaching

Problem solving

Time Management

Project Management

Download free eBooks at bookboon.com

Click on the ad to read more

Structured Programming with C++

5.15 Sorting Strings 110 5.16 Substring 112 5.17 Concatenating Strings 112 5.18 Interchanging First Name and Surname 112 5.19 Encryption 115 5.20 Random Password 116 5.21 Translation Table 117 5.22 Summary 120 5.23 Exercises 120

6 Functions 123 6.1 Introduction 123 6.2 What Is a Function 123 6.3 Average 124 6.4 Calling a Function 124 6.5 Several return Statements 126 6.6 Least of Three Numbers 127 6.7 Least Item of an Array 129 6.8 Array As Parameter 130 6.9 Function and Subfunction 132 6.10 Function without Return Value 135 6.11 Replacing Characters in a String 136

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative know- how is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to mainte- nance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!

The Power of Knowledge Engineering

Brain power

Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com Structured Programming with C++

  • About the Book and the Course Contents
  • 1 Introduction to Programming
  • 1.1 What Does It Mean to Program
  • 1.2 Coding
  • 1.3 Compiling and linking
  • 1.4 The First Steps with Visual C++
  • 2 Variables
  • 2.1 Introduction
  • 2.2 Why Variables
  • 2.3 Declaring Variables
  • 2.4 Assignment
  • 2.5 Initiating Variables
  • 2.6 Constants
  • 2.7 More about Assignment of Values
  • 2.8 The main function
  • 2.9 Input and Output
  • 2.10 An Entry Program
  • 6.12 Declaration Space
  • 6.13 The Word Program
  • 6.14 Override Functions
  • 6.15 Declaration - Definition
  • 6.16 Header Files
  • 6.17 Reference Parameters
  • 6.18 Parameters with Default Values
  • 6.19 Recursive Functions
  • 6.20 Summary
  • 6.21 Exercises
  • 7 Files
  • 7.1 Introduction
  • 7.2 Streams
  • 7.3 Reading from a Stream
  • 7.4 Writing to a Stream
  • 7.5 Attaching a File to a Stream
  • 7.6 A Complete Write Program
  • 7.7 A Complete Reading Program
  • 7.8 New Item at the End of the File
  • 7.9 Products and Prices
  • 7.10 Search for a Product Price
  • 7.11 Sorting a File in Memory
  • 7.12 Updating File Content
  • 7.13 Copying Files
  • 7.14 Summary
  • 7.15 Exercises
  • 8 Pointers
  • 8.1 Introduction
  • 8.2 What Is a Pointer
  • 8.3 Declaring a Pointer
  • 8.4 Assigning Values to Pointers
  • 8.5 Addresses and char Pointers
  • 8.6 cout and char Pointers
  • 8.7 Price Program with Pointers
  • 8.8 Pointer Arithmetics
  • 8.9 Tax Program
  • 8.10 Functions and Pointers
  • 8.11 Dynamic Memory
  • 8.12 Summary
  • 8.13 Exercises
  • 9 Structures
  • 9.1 Introduction
  • 9.2 What Is a Structure
  • 9.3 Defining a Structure
  • 9.4 Declaring and Initiating Structure Variables
  • 9.5 Assigning Values to Structure Members
  • 9.6 A Structure Program
  • 9.7 Array with Structure Variables
  • 9.8 Pointer to Structure
  • 9.9 Structures in the Dynamic Memory
  • 9.10 Structure As Function Parameter
  • 9.11 Summary
  • 9.12 Exercises
  • 10 Answers
  • 10.1 Variables
  • 10.2 Selections and Loops
  • 10.3 Arrays
  • 10.4 Strings
  • 10.5 Functions
  • 10.6 Files
  • 10.7 Pointers
  • 10.8 Structures

Download free eBooks at bookboon.com

Structured Programming with C++

About the Book and the Course

About the Book and the Course

This book is intended as course material for the course Structured Programming with C/C++ at university level. It contains eight chapters, one for each lecture of the course. The chapters are:

  1. Introduction to programming. Here we go through general principles about what programming means. You will be introduced to the development tool Microsoft Visual C++ and build your first programs.
  2. Variables. Here we start from the beginning and explain all details in the first programs. You will learn what variables are and how they are used for storing of values needed in the program.
  3. Selections and loops. This chapter will teach you to include intelligence into the programs, which will be capable of doing different things depending on given conditions. The programs will also be able to repeat operations any number of times.
  4. Arrays. Arrays are very useful tools for storing of and working with information items of the same kind, like for instance sampled measurement values, product files with prices, or customer data.
  5. Strings. Texts (strings) are handled in a special and tricky way in C++. Because of that a special chapter is dedicated for this subject.
  6. Functions. In this chapter, when our programs are getting to some size, we divide the code into subroutines or functions.
  7. Files. Many times data needs to be stored or accessed. Here we will learn the basics of file management.
  8. Pointers. This chapter goes deeper into the more advanced aspects of C++ programming and implies a springboard to professional level.
  9. Structures. Data is often organized into structures, which means easier input and output of structured data. Here we also use pointers together with structures.

Each chapter contains theoretical parts and programming examples. At the end of each chapter there is a bunch of exercises for your practice. At the end of the book you will find solutions to the exercises. Remember, though, that each problem could in general be solved in different ways, and maybe your own solution is as good as, or even better than the one presented. Therefore, my recommendation is that you as far as possible try to manage without the solutions.

The purpose of the course Structured Programming with C/C++ is primarily to teach how to ”think programming” and secondarily to teach C++ code. Therefore, I will emphasize how to focus on the problem solution and prepare the coding. JSP (Jackson Structured Programming) is a common tool within programming and is used to structure a problem. You will learn how to use JSP to build your solution. Flow charts is an alternate tool to JSP, which we also will make some notice to.

Primarily, this is a beginner’s course in C, but we will utilize some C++ tools for e.g. input and output.

Learning to program is not made in short time. It requires long-term and patient work with reading, coding, testing and debugging. There is no shortcut, but if you work with endurance, you will have many times of inspiration and nice experiences.

I would also like to stress that, when you write your programs, you will make many mistakes. This is normal. No programmer writes the correct code already from the beginning. Error tracing and correction is a natural ingredience of the development process.

Download free eBooks at bookboon.com

Structured Programming with C++

1 Introduction to Programming

1 Introduction to Programming

1.1 What Does It Mean to Program

1.1.1 Algorithm

Programming is not only coding. Primarily it implies structuring of the solution to a problem and then refine the solution step by step. When refined to a level deep enough, you have created an algorithm. Then it is time to translate each step of the algorithm to program code. Suppose you have a problem that needs to be solved. Then you begin with writing a sequence of operations at an overview level that need to be performed to solve the problem. Then you start from the beginning again and focus on one operation at a time and find out whether the operation needs to be refined to more detailed steps. Then you proceed to the next level and refine further. This refinement process goes on until you arrive at a level deep enough to start coding.

Creating an algorithm to solve a problem is in general the most laboursome task of the programming work. Many people do the mistake of starting to code at once, which makes you focus on code details and forget the actual problem to be solved. That gives an unstructured and inefficient code hard to understand and maintain. That’s why we emphasize that you structure your logic train of thought and construct a good algorithm before starting to code.

1.1.2 JSP

A JSP graph is a tool to create an algorithm. JSP is an abbreviation for Jackson Structured Programming and is a commonly used instrument for logic structuring. Let’s take an example. You are supposed to create a program that calculates the price of a product to be bought by a customer. The customer specifies the product id and the requested quantity. The program should then calculate the relevant discount, add tax and show the customer price. A JSP graph could look as follows:

University West, Trollhättan Structured Programming with C++ Department of Economy and Informatics

calculate the relevant discount, add tax and show the customer price. A JSP graph could look as follows:

The upper box is the name of the program. We have split the solution into four steps at an overview level. You read the steps from left to right. As you probably realize the algorithm is too rough to be able to write code. So we proceed by refining the solution to the next level:

Price

Enter information Deduct discount Add tax Print

Show instructions to the user

Read product id & quantity

Calculate gross price

Deduct 10% discount

Price

Enter information Deduct discount Add tax Print

The upper box is the name of the program. We have split the solution into four steps at an overview level. You read the steps from left to right. As you probably realize the algorithm is too rough to be able to write code. So we proceed by refining the solution to the next level:

Download free eBooks at bookboon.com

Structured Programming with C++

1 Introduction to Programming

Copyright Page: 6

The upper box is the name of the program. We have split the solution into four steps at an overview level. You read the steps from left to right. As you probably realize the algorithm is too rough to be able to write code. So we proceed by refining the solution to the next level:

The box ”Enter information” has been split into two steps, ”Show instructions to the user” and “Read product id & quantity”. In the same way we have refined the box “Deduct discount”.

Show instructions to the user

Read product id & quantity

Calculate gross price

Deduct 10% discount

Price

Enter information Deduct discount Add tax Print

The box ”Enter information” has been split into two steps, “Show instructions to the user” and “Read product id & quantity”. In the same way we have refined the box “Deduct discount”.

We could break down the box ”Calculate gross price” further:

University West, Trollhättan Structured Programming with C++ Department of Economy and Informatics

We could break down the box ”Calculate gross price” further:

We could refine the algorithm further, but let us say that we are satisfied with the detail level. The shadowed boxes in the graph are the end points at the lowest level, the “leaves of the tree”. These are the boxes to be used for coding, from left to right. We will work a great deal with JSP graphs in the program examples of the course.

Sequence - Selection - Iteration Each program is logically built up from three basic logic principles:

  • Sequence – the program performs instructions in sequence, one after the other.
  • Selection – the program selects one of several operations depending on the prerequisites. The program thus makes a selection based on some condition.
  • Iteration – the program repeats a series of instructions a certain number of times. The logic principles can also be combined. For instance, a sequence of

Look for the product in product file

Pick the product’s price

Multiply by quantity

Show instructions to the user

Read product id & quantity

Calculate gross price

Deduct 10% discount

Price

Enter information Deduct discount Add tax Print

We could refine the algorithm further, but let us say that we are satisfied with the detail level. The shadowed boxes in the graph are the end points at the lowest level, the “leaves of the tree”. These are the boxes to be used for coding, from left to right.

We will work a great deal with JSP graphs in the program examples of the course.

1.1.3 Sequence - Selection - Iteration

Each program is logically built up from three basic logic principles:

- Sequence – the program performs instructions in sequence, one after the other.

Download free eBooks at bookboon.com

Click on the ad to read more

Structured Programming with C++

1 Introduction to Programming

C++ is a very extensive language that can be used both within basic structured programming and object oriented programming. Furthermore, windows programming in the graphic Windows environment is supported. C++ has, thanks to its level of detail, its strength in digging deeply into the most obscure corners of the computer, control the operating system, communicate with hardware, circuit boards and external equipment like measurement units and communication devices. In this course, however, we will stick to basic structured programming.

C++ is a compact language with many symbols having their own meanings. This means that C++ code looks complicated to the novice. On the other hand it provides many tools for efficient coding. Programs written in C++ are very rapid due to the fact that the compiler optimizes them to each specific processor type. That is the reason why you mostly use C++ in situations where processor time and performance are ultimate.

1.3 Compiling and linking

When you have written the code of your program, it should be compiled, i.e. translate it to machine code consisting of 1’s and 0’s. That is the level understood by the processor. Before reaching this level, there is an interim level of code, called object code. Thus the compilation is made in two steps, first from source code to object code, and then from object code to machine code. In Microsoft Visual C++ you don’t have to bother about these two steps, because the compilation from source code to machine code is taken care of by just clicking a button.

When writing a program, you often split the code into several files of source code. The different files contain references to each other. When all source code has been compiled the different parts of the program must be linked together to one single executable program (exe file). In some environments the linking must be initiated manually. In Visual C++ the linking is taken care of automatically directly after the compilation.

With us you can

shape the future.

Every single day.

For more information go to: www.eon-career.com

Your energy shapes the future.

Download free eBooks at bookboon.com

Structured Programming with C++

1 Introduction to Programming

1.4 The First Steps with Visual C++

We will start with creating a program that prints ’Hello World’ on the screen.

Click the Start button and select:

1.4.1 All programs – Visual C++ 2008 Express Edition -Microsoft Visual C++ 2008 Express Edition

The Visual C++ Start Panel is displayed:

To create a new program, select from the menu:

Download free eBooks at bookboon.com

Structured Programming with C++

1 Introduction to Programming

1.4.3 Win32 – Win32 Console Application

Also specify the name of the program, for instance Hello, in the box after ’Name’, and indicate a suitable folder with the ’Browse’ button, where the programme is to be stored. A particular sub-folder will be created with that name.

Click ’OK’. A new window will be displayed:

Click on ’Application Settings’, check the box ’Empty project’ and click on ’Finish’.

The project is now created but contains no code files yet. Add one by selecting from the menu:

Download free eBooks at bookboon.com

Click on the ad to read more

Structured Programming with C++

1 Introduction to Programming

1.4.4 Project – Add New Item

A window is displayed:

TMP PRODUCTION NY026057B PSTANKIE

gl/rv/rv/baf

ACCCTR Bookboon Ad Creative

4 6 x 4

12/13/

Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon

All rights reserved. © (^) 2013 Accenture.