Chap 1 c++

39
BTE2313 – Computer Programming C++ Programing Lecturer: Samson Mekbib

Transcript of Chap 1 c++

BTE2313 – Computer Programming

C++ Programing

Lecturer: Samson Mekbib

Learning Outcomes (BTE2313)

Ability to analyze basic algorithms and elements of C++.

Ability to write computer programs using C++.

Work in teams to develop, design and implement simple computer programs.

What this course is all about?

Introduction on the concepts of computational thinking.

To help you learn how to think like a computer scientist

Make the computer do what you want it to do

To help you develop a computational mind set

Whenever you face technical problem thinking how to solve it computationally.

To help you acquire the skills of developing algorithms (set of instructions for solving technical problems).

To develop the skill of using the basic computational tools to write C++ programs.

Ability to use the vocabulary of computational tools in order to understand programs written by others (Reading is as important as writing a code, it help you modify existing codes to solve related problems. Save you time and energy).

CHAPTER ONE

INTRODUCTION TO COMPUTER PROGRAMMING

References:

1. C++ How to program, Deital, H.M. and Deital, P.J. Prentice Hall, Eaglewood (NJ), 2008.

2. Code complete: A practical Handbook of Software Construction. McConnell, S. Microsoft Press, Redmond (WA), 1993.

3. C++ Program Design An Introduction to Programming and Object-Oriented Design.

Lesson Outcomes (Chap. 1)

1. To understand basic computer science concepts

2. To become familiar with different types of programming languages

3. Learn about the evolution of programming languages

4. To understand the difference of structured and object oriented design of programming approaches.

5. To understand the C++ program development environment

6. Learn what an algorithm is and explore problem-solving techniques

Computers and Computation

Computer

A computer is a machine that can perform computation.

It could be a fixed program computer like ATM, Calculator, Control system component of machineries and vehicles or a general purpose personal computer we are more often familiar with.

What is Computation?

computations are carried out to solve meaningful and useful problems

computation involves the following three components

Input data

The input data is processed by a well-defined and finite sequence of steps (algorithm - set of instructions like a RECIPE)

Output / results

Computation Computation : How to deduce the unknown based on existing knowledge using a planned sequence of steps (algorithm or recipe).

EXAMPLE : How to solve the square root of a number:

2

(X/G))(GGwithtrialrepeatelse

G)x(i.e.Gstop

X,Gif

GnumberguessedawithStart

Solution

0yforx,yyx

:

2

2

knowweWhat

Basic components of computers CPU - central processing unit

Where decisions are made, computations are performed, and input/output requests are delegated

Memory

Stores information being processed by the CPU

Two major types

Main memory / Random Access Memory (RAM) (High speed and limited space memory, contents maybe lost during power down)

Secondary memory (relatively inexpensive, bigger and low speed memory e.g. hard disk (HDD, CD-ROM etc.)

Input devices

Used to supply information to computers

Output devices

Used to receive information from computers

BUS – A bus is a set of data transfer wires that connect the above components.

Simplified computer architecture

CPU consists of:

1. Control unit – responsible for flow of data and instructions.

2. An Arithmetic and Logical unit (ALU) – has a processor that perform arithmetic functions (like Addition, Subtraction etc.), and another processor for logical manipulation (AND, OR etc.)

3. Registers - A finite number of small memory cells for storing intermediate

results.

CPU The brain of the computing device

Arithmetic calculations and logic operations are performed using the Arithmetic/Logical Unit or ALU

Control unit decodes and executes instructions

All arithmetic operations inside the computer are performed using binary number system (0’s & 1’s)

Fetch/Execute Cycle The fetch/execute cycle is the steps the CPU takes to execute an instruction

Performing the action specified by an instruction is known as executing the instruction

The program counter (PC) holds the memory address of the next instruction Fetch the instruction to

which the PC points

Increment the PC

Execute the fetched

instruction

Input and Output Devices

Accessories that allow computer to perform specific tasks

Receive information for processing

Return the results of processing

Store information

Accessories that allow computer to perform specific tasks

Receive information for processing

Return the results of processing

Store information

Common input and output devices

Speakers Mouse Scanner

Printer Joystick CD-ROM

Keyboard Microphone DVD

Accessories that allow computer to perform specific tasks

Receive information for processing

Return the results of processing

Store information

Common input and output devices

Speakers Mouse Scanner

Printer Joystick CD-ROM

Keyboard Microphone DVD

Some devices are capable of both input and output

Floppy drive Hard drive Magnetic tape units

Monitor Display device that operates like a television

Also known as CRT (cathode ray tube)

Controlled by an output device called a graphics card

Displayable area

Measured in dots per inch, dots are often referred to as pixels (short for picture element)

Standard resolution is 640 by 480

Many cards support resolution of 1280 by 1024 or better

Number of colors supported varies from 16 to billions

1280

pixels

across

screen

1024

pixels

down

screen

Application software

Programs designed to perform specific tasks that are transparent to the user

System software

Programs that support the execution and development of other programs

Two major types

Operating systems

Translation systems

Software

Application software is the software that has made using computers very important and popular

Application software involves solving a problem or providing a service in a particular problem domain.

Common application software

Word processors

Desktop publishing programs

Spreadsheets

Presentation managers

Drawing programs (like AutoCAD)

Learning how to develop small application software is our focus

Application Software

The operating system is the most important program that runs on a computer (Examples Windows®, UNIX®, Mac OS X®)

Every general purpose computer should have an operating system to run other programs.

Tasks performed by an operating system include:

Recognizing input from input devices (like keyboard & mouse)

Sending output to the display screen

Control peripheral devices (printers, disk drive etc.)

Keep track of files and directories on the disk

Commands that allow for manipulation of the file system

Sort, delete, copy

Operating System/Software

Translation System

Set of programs used to develop software

A key component of a translation system is a translator

Some types of translators

Compiler

Converts from one language to another

Linker

Combines resources

Examples

Microsoft Visual C++®, CBuilder®, g++, Code Warrior®

Performs compilation, linking, and other activities.

Software Development Cycle

Compile

Link

Library routines

Other object files

Think

Edit

Load

Execute

Source Program

As a programmer you need to be concerned only with writing the source code, run the program and see how it behaves and edit your code again if necessary.

Definitions Source code – an original computer program written by a programmer using high level programming language like C++.

Object code – is a binary code machine language translated from the source code into machine language by compiler or assembler.

Compiler – a type of translator that verify if the program obeys the programming language rule (i.e. check if the program is syntactically correct).

Linker - is a type of program that combines the object code received from the compiler with files and objects from the library.

Loader – is a type of program that loads the executable program into the main memory for execution.

IDEs

Integrated Development Environments or IDEs

Supports the entire software development cycle

E.g., MS Visual C++, Borland, Code Warrior

C++ IDE Provides all the capabilities for developing software

Editor

Compiler

Linker

Loader

Debugger

Viewer

Programming Languages There are a number of programming languages

C++

Visual Basics

Python

MATLAB

Java etc.

If you can write computer programs using one language it is easier to learn the other languages. The concept of computation and the programming structure is common for all languages.

Basically anything you can do with one programming language you can also do with another language

There is no best language but some languages are good in some specific job than others

History of C++ Programming C++ as the name implies, is essentially based on the C – programing language.

The C programming language was developed in 1970’s at Bell Laboratories by Dennis Ritchie

C++ began in 1979 with first commercialization in 1985

C++ is essentially C taken to the next level, i.e. C++ supports all C commands and also has many additions. Hence C++ is a super set of the C programming language.

Though there are different improvement the most obvious difference between C and C++ is, C++ supports object orientation (Object Oriented Design, ODD)

Structured and Object Oriented Programming

Structured programming approach (step wise refinement):

Dividing a problem into smaller sub problems

Each sub problem will be analyzed and a solution obtained

Solutions of sub problems are then combined to solve the overall problem

Object-oriented design or programming approach:

Identify the components called objects which form the basis of the solution

Examine how this objects interact

Develop algorithm for operations on objects

Object Oriented Design (OOD) Consider writing a program to automate a video rental process for a video sore

What are the two main objects in this problem?

The Video

The customer

After identifying the objects the next step is to specify relevant data for each object and possible operation to be performed on that data

Video object data (movie name, producer, number of copies in stock …)

Operations on a video object (checking the name of the movie, reduce the number of copies by one when a copy is rented, increment the number of copies by one when a customer returns a particular video.

The decimal (base ten) numeral system has ten possible values (0,1,2,3,4,5,6,7,8, or 9) for each place-value.

In contrast, the binary (base two) numeral system has two possible values represented as 0 or 1 for each place-value.

Since the binary system is the internal language of electronic computers, serious computer programmers should understand how to convert from decimal to binary and vice versa.

Simpler method for conversion of decimal to binary – division by 2 and account for the reminders.

To avoid confusion before and after conversion, write the number of the base system that you are working with as a subscript of each number. In this case, the decimal number will have a subscript of 10 and the binary equivalent will have a subscript of 2.

Decimal & Binary Arithmetic

Conversion decimal to binary

Both the decimal and binary number systems are positional number systems, i.e. position of digit indicates its relative value.

The individual digits of a binary number are referred to as bits (where, 1 byte = 8 bits)

Each bit represents a power of two

01011 = 0 • 24 + 1 • 23 + 0 • 22 + 1 • 21 + 1 • 20 = 11

00010 = 0 • 24 + 0 • 23 + 0 • 22 + 1 • 21 + 0 • 20 = 2

Binary Arithmetic

Binary

addition

13

+ 23

36

Equivalent

decimal

addition

1 1 1 1 1 (carried digits)

0 1 1 0 1

+ 1 0 1 1 1

1 0 0 1 0 0 = 36

Binary Arithmetic

5

× 3

15

Equivalent decimal

multiplication

0101

× 0011

0101

0101

0000

0000

0001111

Binary

multiplication

Two’s Complement

Representation for signed binary numbers (i.e. –ve and +ve )

Leading bit is a sign bit

Binary number with leading 0 is positive

Binary number with leading 1 is negative

Magnitude of positive numbers is just the binary representation

Magnitude of negative numbers is found by

Complement the bits

Replace all the 1's with 0's, and all the 0's with 1's

Add one to the complemented number

The carry in the most significant bit position is thrown away when performing arithmetic

Two’s Complement

Performing two's complement on the decimal 7 to get -7

Using a five-bit representation

7 = 00111 Convert to binary

11000 Complement the bits

11000 Add 1 to the complement

+ 00001

11001 Result is -7 in two's complement

Two's Complement Arithmetic

Computing 8 - 7 using a two's complement representation with five-bit numbers

8 - 7 = 8 + (-7) = 1

01000 Two's complement of 8

11001 Two's complement of -7

01000 Add 8 and -7

+ 11001

100001

00001 Is the five-bit result

Throw away the

high-order

carry as we are

using a five bit

representation

Simple C++ program exercise

Contd.

Contd.

Problem analysis and Algorithms

Example: Design an algorithm to find the perimeter and area of a rectangle:

1. Get the length of the rectangle

2. Get the width of the rectangle

3. Find the perimeter using the equation

Perimeter = 2 * (Length + Width)

4. Calculate the area using the relation

Area = Length * Width

Problem analysis and Algorithms

Example: Design an algorithm that calculates the total sales

tax and the price of the item after tax. The state’s share of the sales tax is 4%, and the city’s portion of the sales tax is 1.5%. If the item is a luxury item, such as a car costing over RM50,000.00, there will be a 10% luxury tax.

1. Get the selling price of the item

2. Determine whether the item is a luxury item

3. Find the states portion of the sales tax using the formula

StatesSalesTax = SalesPrice * 0.04

4. Find the city’s portion of the sales ta using the relation

CitySalesTax = SalePrice * 0.015

Cntd.

5. Find the luxury tax using the formula

If (item is a luxury item)

LuxuryTax = SalePrice * 0.1

Otherwise

LuxuryTax = 0

6. Find SalesTax using the formula

SalesTax = StateSalesTax + CitySalesTax + LuxuryTax

7. Find amount due using the formula

amountDue = SalesPrice + SalesTax

Problem analysis and Algorithms

Example: Design an algorithm to play a number game so that

you generate a random number from 0 to 100 and prompt the player (user) to guess the number. If the player guessed a number less than the random number you generate, tell him his guess is lower and ask him to guess again, if the number is higher then tell him his guess is higher and ask him to try again. When the player guess the correct number end of game.

1. Generate a random number and call it num

2. If (guess is equal to num) print “you guessed the correct number.”

3. Otherwise if guess is < num print “your guess is lower than the number, Guess again!”

4. Otherwise if guess is > num print “your guess is lower than the number, guess again!”

Next Chapter

Writing, compiling, editing and running C++ programs

Become familiar with functions special symbols, and identifiers in C++.

Explore simple data types

Discover how a program evaluates arithmetic expressions and more …