31
C++ Programming Language -------------------------------------------------------------------------------------------------------------------------------------- (Part I) MOHD. UZIR KAMALUDDIN Faculty of Electrical Engineering Science and Technology Complex University Teknologi MARA (UiTM) 40450 SHAH ALAM Phone 603-5543 5052 • Fax 603-5543 5077

C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

C + + P r o g r a m m i n g

L a n g u a g e --------------------------------------------------------------------------------------------------------------------------------------

( P a r t I )

MOHD. UZIR KAMALUDDIN Faculty of Electrical Engineering

Science and Technology Complex

University Teknologi MARA (UiTM)

40450 SHAH ALAM

Phone 603-5543 5052 • Fax 603-5543 5077

Page 2: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

Copyright © 2015 by Mohd. Uzir Third Edition Mac 2015 All rights reserved. No part of these notes may be used or reproduced in any manner whatsoever without the permission of the author. This book is a work the lecturer while teaching the course on C++ programming language, as to provide a guide for the students in understanding the subject matter. It is hoped that this work will benefit the students. Any mistakes or shortcomings in these notes are due to the error of the author, and all that is correct and true solely are due to ALLAH Subhana huWa Taala. ISBN: not available First Edition: Jan 2010

Page 3: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

Contents

INTRODUCTION .............................................................................................................................................................. 5

Introduction to Computers ............................................................................................................................................. 5

Architecture of a Computer........................................................................................................................................ 5

Computer Programming .................................................................................................................................................. 5

Operating Systems ............................................................................................................................................................ 6

Internet ............................................................................................................................................................................... 6

Introduction to Programming Languages ..................................................................................................................... 6

Advantages of C++ Programming Language .............................................................................................................. 7

Why learn C++? ............................................................................................................................................................. 7

C++ BASICS ......................................................................................................................................................................... 9

The C++'s Character Set ................................................................................................................................................. 9

C++ Program Structure .................................................................................................................................................. 9

Preprocessor Directives ................................................................................................................................................. 10

Predefined Macro Names .............................................................................................................................................. 10

To Compile and Execute C++ Programs .................................................................................................................. 11

Type, Operator and Expression ................................................................................................................................... 11

Variables ...................................................................................................................................................................... 12

Expressions ................................................................................................................................................................... 12

Data Types (Types) .................................................................................................................................................... 12

Basic Input/Output Commands .................................................................................................................................. 13

Output Member Functions ....................................................................................................................................... 13

Input Member Functions .......................................................................................................................................... 13

Declarations & Constants .............................................................................................................................................. 14

Arithmetic Operators ..................................................................................................................................................... 14

Ambiguity .................................................................................................................................................................... 15

Implicit Type Conversion .............................................................................................................................................. 15

Explicit Type Conversion .............................................................................................................................................. 15

Relational, Comparison and Logical Operators ......................................................................................................... 15

Bitwise Operators ........................................................................................................................................................... 15

Assignment Operators and Expressions ..................................................................................................................... 15

Mathematics library ........................................................................................................................................................ 17

Generating random numbers ................................................................................................................................... 17

Software Development Method ................................................................................................................................... 17

Programming Style ......................................................................................................................................................... 18

CONTROL FLOW ............................................................................................................................................................ 19

Statement and Blocks ..................................................................................................................................................... 19

Conditional Expressions ................................................................................................................................................ 19

Decision Making, Branching or Selection Statements .............................................................................................. 19

Iteration or Loops ........................................................................................................................................................... 21

POINTERS .......................................................................................................................................................................... 26

Page 4: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

The new operator ............................................................................................................................................................. 26

The delete operator ........................................................................................................................................................... 27

Alias ................................................................................................................................................................................... 27

FUNCTIONS ...................................................................................................................................................................... 28

Standard C++ Library Functions ................................................................................................................................. 28

User Defined Functions: Basic functions ................................................................................................................... 28

Function Prototypes ....................................................................................................................................................... 29

Pointers & Functions ..................................................................................................................................................... 30

Page 5: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

INTRODUCTION

Introduction to Computers

Computers: A device capable of performing

computations and making logical decisions at

speeds millions (even billions) of times faster than

human beings can. Computers process data under

the control of sets of instructions called computer

programs. Humans need computers to simplify

their tasks, since computers can do computations,

even a complex one, much faster and produce

accurate results. Computers can do many

different jobs because they are programmable.

Architecture of a Computer

A computer basically made up of three

components:-

1. Central Processing Unit (CPU): The part in a computer that does the coordination and is

responsible for supervising the operations of all other sections. An important unit of a CPU is the

Arithmetic and Logic Unit (ALU). The ALU is responsible for performing calculations such as

addition, subtraction, multiplication and division.

2. Memory: This is the rapid access, relatively low capacity storage device of the

computer. It retains information that has been entered, so that the information may be

made immediately available for processing when it is needed. It also retains processed

information until that information can be placed on the output devices.

Primary memory (RAM or ROM) are organized in a linear fashion, where information

are stored in addresses. Each address will store an 8 bit data.

3. Input/Output

Consist of the Input Unit and Output Unit. The Input Unit is where information is

entered to the computer and places this information at the disposal of other units so

that the information can be processed. Common input devices are keyboard and mouse.

The Output Unit takes information that has been processed by the computer and places

it on various output devices to make the information available for use outside the computer.

Common output devices are monitor (screen) and printer.

Computer Programming

Computer programming is both an art and a science. It is an

art because every aspect of a program should be designed

with care and judgment. There is also a scientific or

engineering side to programming. Because programs rarely

work the first time they are written, a lot of experimentation,

correction and redesigning is required. Some design

considerations when writing a program:-

The logical flow of the instructions

The mathematical procedures

The appearance of the screen

The way information is presented to the user (user-friendliness)

Page 6: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

Operating Systems

Operating systems are software that mainly does the

managing of the resources of the computer. The resources

in a computer include the CPU, memory and the I/O. It also

provides services such as user interface, executing

programs, file and database access, and interfaces to

communication systems. Thus the software will keep the

system operating in an efficient manner while allowing the

users access to the system.

Internet

The Internet (or internet) is a global system of interconnected computer networks that use the

standard Internet protocol suite (TCP/IP) to serve billions of users worldwide. It is a network of

networks that consists of millions of private, public,

academic, business, and government networks, of

local to global scope, that are linked by a broad array

of electronic, wireless and optical networking

technologies. The Internet carries an extensive range

of information resources and services, such as the

inter-linked hypertext documents of the World Wide

Web (WWW) and the infrastructure to support email.

Introduction to Programming Languages

BASIC – (Beginner’s All-Purpose Symbolic Instruction Code) was developed in the mid 1960s by

Prof. John Kemeny and Prof. Thomas Kurtz of Dartmouth College as a language for writing simple

programs. It primary purpose was to familiarize novices with programming techniques. Visual

Basic (VB) was introduced by Microsoft in 1991 to simplify the process of developing Microsoft

Windows applications.

Pascal – produced as a result of research activity into structured programming.

Developed by Prof. Niklaus Wirth in 1971, was designed for teaching structured

programming. Unfortunately, it lacks many features needed to make it useful in

commercial, industrial and government applications, so it has not been widely

accepted in these environments.

FORTRAN – (FORmula TRANslator) was developed by IBM Corporation in the 1950s to be used

for scientific and engineering applications that require complex mathematical computations.

COBOL – (COmmon Business Oriented Language) was developed in 1959 by computer

manufacturers, the government and industrial computer users. Used for commercial applications

that requires precise and efficient manipulation of large amount of data.

C - a general-purpose programming language initially developed by Dennis Ritchie between 1969

and 1973 at Bell Labs. Its design provides constructs that map efficiently to typical machine

instructions, and therefore it found lasting use in applications that had formerly been coded in

assembly language, most notably system software like the Unix computer operating system.

C++ - is basically an extension of the C Programming Language. C was a

direct descendant of the language B, which was developed by Ken

Thompson as a systems programming language for the fledgling UNIX

operating system. B, in turn, descended from the language BCPL which

was designed in the 1960s by Martin Richards while at MIT.

In 1971 Dennis Ritchie at Bell Labs extended the B language (by adding

types) into what he called NB, for "New B". Ritchie credits some of his changes to language

Page 7: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Feb 2015 Page 7 of 31

constructs found in Algol68, although he states "although it [the type scheme], perhaps, did not

emerge in a form that Algol's adherents would approve of" After restructuring the language and

rewriting the compiler for B, Ritchie gave his new language a name: "C".

In 1983, with various versions of C floating around the computer world, ANSI

established a committee that eventually published a standard for C in 1989.

In 1983 Bjarne Stroustrup at Bell Labs created C++. C++ was designed for the UNIX

system environment, it represents an enhancement of the C programming language

and enables programmers to improve the quality of code produced, thus making

reusable code easier to write.

Java – initially developed by James Gosling at Sun Micro-system in a research

project code named Green in 1991. It was based on C and C++, with the main

purpose to be the language used for developing intelligent consumer electronic

devices. But that doesn’t work, and it changes direction to using Java in creating

Web pages with so called dynamic content. Java is superb language with the

essential of graphics, images, animation, audio, video, database, networking,

multithreading and collaborative computing.

Advantages of C++ Programming Language

1. Powerful language – can handle almost any task

2. Portability – program written on one platform (e.g. on a PC) can be ported without change to

another platform without change

3. Efficiency – C++ compiler generates an efficient executable program from a C++ source file and

close to the machine programming.

4. Expressive power – programmer can extend C++’s built in operations by writing functions that

manipulate either built in or user defined data types.

5. Arithmetic types – programmer has broad control over the formatting of all numeric types.

6. Modularity – programmers can modularize their programs, easy for debugging.

7. Simple syntax and semantics

8. Run time function libraries

9. Good programming support

C++ is not a purely object-oriented language but a hybrid that contains the functionality of the C

programming language. Large quantities of existing C source code can also be used in C++ programs.

C++ supports the concepts of object-oriented programming (OOP) which are:-

1. Data abstraction, that is, the creation of classes to describe objects

2. Data encapsulation for controlled access to object data

3. Inheritance by creating derived classes (including multiple derived classes)

4. Polymorphism (Greek for multiform), that is, the implementation of instructions that can have

varying effects during program execution.

Various language elements were added to C++, such as references, templates, and exception handling.

Even though these elements of the language are not strictly object-oriented programming features,

they are important for efficient program implementation.

Why learn C++?

1. Easiest language to learn. It is the most fundamental, fastest and powerful language.

2. Can have a choice either using structured or object oriented programming.

3. Need to think about what the computer is actually doing to some degree.

4. Have mathematics library to handle common mathematical calculations in engineering.

Page 8: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

5. Can apply knowledge in programming microcontrollers (e.g. PIC, AVR, 8051).

CHECK

1. List four major components of a computer system. Discuss these components in terms of their

functionality.

2. Explain the memory address structure of a computer.

3. Give the advantages of using a computer.

4. Give three functions of an operating system.

5. C++ is not totally an object oriented programming language. Why?

Page 9: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Feb 2015 Page 9 of 31

C++ BASICS

The C++'s Character Set

C++ does not use, nor requires the use of, every character found on a modern computer keyboard.

The only characters required by the C++ Programming Language are as follows:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

abcdefghijklmnopqrstuvwxyz

0123456789

space . , : ; ' $ " ~ # % & ! _ { } [ ] ( ) < > | + - / * =

C++ programming language is case sensitive. Capitals and small letters means different thing. E.g.

Number is not the same as number or numbeR.

Keywords or reserved words are always written in lowercase, each have a special meaning in C++

and can only be used for their intended purposes. Part of learning a programming language is

learning what the key words are, what they mean, and how to use them. Some examples of

keywords: for, if, asm, auto, bool, case, void, union, new, false, class, default …

A program is a set of logically related instructions that is arranged in a sequence (program design)

and guides the computer in solving a problem (to produce desired results). The process of writing a

program is called programming.

Niklaus Wirth stated that: Programs = Algorithms + Data.

An algorithm is a part of the plan for the computer program; an algorithm is an effective procedure

for solving a problem in a finite number of steps. For example: Find the smallest number that can

divide any two integers evenly.

In C++, the start of a comment is signalled by the /* character pair. A comment is ended by */.

/* This is a multiple line comment.

It can go more than one line */

or //This is a single line comment

Use comment as header in a program to ease reader or to give information about the program:

1. programmer’s name

2. date of the current program version

3. lecturer’s name

4. brief description of what the program does

C++ Program Structure

preprocessor directives

int main ( )

{ variables declaration

C++ codes (statements)

return 0;

}

The above program contains module or function main; and a function name is always followed by ( ).

The function main is the function that is executed by the CPU.

#include <iostream> /*preprocessor directive*/

using namespace std;

int main( ) /*function main starts here*/

{ /*beginning of the function main*/

cout <<“\nHello, world!\n”; /*action or statement*/

return 0;

} /*function main ends here*/

Page 10: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

The program shows how two numbers entered by the

user using the keyboard are added, and how the

sum is displayed to the user on the monitor.

Preprocessor Directives

Preprocessor directives are lines included in the code

of our programs that are not program statements but

directives for the preprocessor. These lines are

always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of

code begins, therefore the preprocessor digests all these directives before any code is generated by the

statements.

These preprocessor directives extend only across a single line of code. As soon as a newline character

is found, the preprocessor directive is considered to end. No semicolon (;) is expected at the end of a

preprocessor directive. The only way a preprocessor directive can extend through more than one line

is by preceding the newline character at the end of the line by a backslash (\).

Source file inclusion (#include)

This directive has also been used assiduously in other sections of this notes. When the preprocessor

finds an #include directive it replaces it by the entire content of the specified file. There are two ways

to specify a file to be included: #include “filename” and #include <filename>.

The only difference between both expressions is the folders where the compiler is going to look for

the file. In the first case where the file name is specified between double-quotes ” ”, the file is

searched first in the same directory that includes the file containing the directive. In case that it is not

there, the compiler searches the file in the default directories where it is configured to look for the

standard header files.

If the file name is enclosed between angle-brackets < > the file is searched directly where the compiler

is configured to look for the standard header files. Therefore, standard header files are usually

included in angle-brackets, while other specific header files are included using quotes.

Predefined Macro Names

LINE Integer value representing the current line in the source code file being compiled.

FILE A string literal containing the presumed name of the source file being compiled.

DATE A string literal ("mm dd yyyy") containing the date in which the compilation process

began.

TIME A string literal ("hh:mm:ss") containing the time at which the compilation process

began.

cplusplus An integer value. All C++ compilers have this constant defined to some value. If the

compiler is fully compliant with the C++ standard its value is equal or greater than

199711L depending on the version of the standard they comply.

#include <iostream>

using namespace std;

main( )

{ int a, b, c;

cout << "\nPls enter a number: ";

cin >> a;

cout << "\nPls enter another number: ";

cin >> b;

c=a+b;

cout<<"\nThe sum of the two numbers is " << c; }

// standard macro names

#include <iostream>

using namespace std;

main()

{ cout << "This is the line number " << __LINE__;

cout << " of file " << __FILE__ << ".\n";

cout << "Its compilation began " << __DATE__;

cout << " at " << __TIME__ << ".\n";

cout << "The compiler gives a __cplusplus value of " << __cplusplus; }

Page 11: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Feb 2015 Page 11 of 31

To Compile and Execute C++ Programs

Use the C++ Compiler, which consist of compiler & linker. Such compilers are Code Blocks, Dev

C++ and Borland C++.

the source file (xxx.cpp) is compiled in two steps:-

1) Preprocessor – look for special codes libraries, make substitutions

in the code. The result is called translation unit.

2) Translator – convert pseudo code to object module (machine

language). It reads the translation unit and writes the resulting object

module to a file that can be combined with other precompiled units to

form the final program. An object module is the code in machine

language, but it is not yet ready to run (not executable) because it does

not have the required C and other functions included.

- Linker will assemble all functions to produce final executable

program

- During the compilation of a program, if it is not successful, then it

contains error. This error is known as syntax error or compilation error.

The executable file will not be created until this error is corrected.

Compiler: Software that translates a high-level language program into machine language.

Source file: File containing a program written in a high level language; the input for a compiler.

Editor: Software used to create, edit (change), and store a source file on disk.

Syntax: Grammar rules of a programming language.

Object file: File of machine language instructions that are the output of a compiler.

Linker: Software that combines object files to create an executable machine language program.

Loader: Software that copies an executable machine language program into memory and starts its execution.

Integrated Development Environment (IDE): Software package combining an editor, a compiler, a linker, a loader and

tools for finding errors.

CHECK

1. What is the relation between a program and an algorithm?

2. Describe the difference between a keyword and a programmer-defined symbol.

3. Can the name of the function main() be changed?

4. Name the files that are involved in the compilation process.

Type, Operator and Expression

A program can use several data to solve a given problem, for example, characters, integers, or

floating-point numbers. Since a computer uses different methods for processing and saving data, the

data type must be known. The type defines

1. The internal representation of the data

2. The amount of memory to allocate

The C++ compiler recognizes the fundamental types (or built-in types) on which all other types are

based. Fundamental types: integer type, floating-point type, and the void type. Other types: vectors,

pointers, classes…)

Page 12: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

An identifier or name is a sequence of characters invented by the programmer to identify or name a

specific object. The sequence of characters maybe letters, digits, and the special character ‘_’. The first

character must be a letter or underscore. There is no restriction on the length of a name and all the

characters in the name are significant.

Variables

To define a variable is to request storage (memory) for a particular data type. A variable is just a

named area (identifier) of storage that can hold a single value (numeric or character). The data stored

in variables may change while the program is running. All variables must be defined before they are

used in the program.

There are two types of variables:

a) local variables - variables that are declared and used within the current program unit, function or

block. It is accessible only from within that block. Since the body of a function itself is a block,

variables declared within a function are local to that function; they exist only while the function is

executing.

b) global variables - variables that are available to all the program's functions. It is declared outside of

any function, say top of the main( ) function. Global variables are NOT recommended to be used.

Variables are also referred to as objects, particularly if they belong to a class. A variable is an object that

has a name.

Scope

The scope of an identifier is that part of that program where it can be used. Use the scope resolution

operator :: to access the global variable.

Expressions

A sequence of operands & operators that reduces to a single value, e.g. 2 + 5; y + x; s*5; a >= b; n++;

Data Types (Types)

There are 14 different fundamental numeric data types, in which 11 are integral and 3 floating-point

type.

int: integer (6 types): a whole number used for counting and it is an exact value. An int variable

can store a value in the range -2147483648 to +2147483648 and normally associated with a decimal

number. An integer takes four bytes to store.

float: floating point value used for measuring and meant to be approximate: i.e. a number with a

fractional part. A float, or floating point, number has about 7 digits of precision and a range of

about -3.4E-38 to +3.4E+38. A float takes four bytes to store.

double: a double-precision floating point value A double, or double precision, number has about

15 digits of precision and a range of about -1.7E-308 to +1.7E+308. A double takes eight bytes to

store.

char: a single character. A single character stored in one byte.

string: a word or sentence.

bool: Boolean; takes only two values: true or false (stored as integer 1 or 0).

void: valueless special purpose type.

The size in bytes of the variables might be different; it depends on the compiler and the computer.

CHECK

1. Describe the difference between operators and punctuation symbols.

2. Explain the meaning of “C++ is a strong data type language”.

3. What happens to a variable’s current contents when a new value is stored there?

Page 13: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Feb 2015 Page 13 of 31

4. Why programmers must avoid using global variables?

5. How can a variable ‘overflow’? Basic Input/Output Commands

To read a single integer value from the standard input device (i.e. the keyboard) into the variable

called reg use the command:

cin >> reg; /* variable reg must be declared earlier */

To display the value stored in the variable reg to the standard output device (i.e. the monitor) use the

command:

cout << "The value stored in reg is " << reg;

**Data can also be read/written to or from files and ports; more on this in the chapter on I/O.

**The use of cin and cout requires the programmer to include the pre-processor directive #include <iostream>

in the program and using namespace std to simplify the program writing.

Output Member Functions

To print floating point numbers to a certain number of decimal places say 2, use the following

statement: cout << fixed << setprecision(2); All subsequent cout print will have the same format.

Declare the #include <iomanip> in the program in order to use the fixed and setprecision objects.

Another function, width() function is used to

display the output with specified field width. As an

example, the following statements will display 5

blanks spaces before displaying the value 101.

cout.width(8);

cout << 101;

This program converts a decimal integer into its equivalent octal and hexadecimal values using

showbase function.

Input Member Functions

Another way to read input from keyboard is using

the get( ) function, and this function is also a member

of the istream class.

The get( ) function, however, leaves the ‘\n’ character

in the input stream. The following code will not work

because when name is entered, and enter is pressed,

the second get( ) function will take the enter as the

second input.

#include <iostream>

#include <iomanip>

using namespace std;

main( )

{ float a=12.3456, b=0.098, c=4.234E3;

cout << fixed << setprecision(2);

cout << a <<” “<< b <<” “<< c << endl; }

#include <iostream>

using namespace std;

main( )

{ char name[15];

cout << “Please enter your name: “;

cin.get(name,15);

cout << “Your name is “ << name; }

#include <iostream>

using namespace std;

main( )

{ char name[15], address[20];

cout << “Please enter your name: “;

cin.getline(name,15);

cout << “Please enter your address: “;

cin.getline(address,20);

cout<<”\nYour name is “<<name;

cout<<” and you stay at “<<address; }

#include<iostream>

#include<iomanip>

using namespace std;

main()

{int n;

cout<<"Pls enter a decimal number:"<<endl;

cin>>n;

cout<<"The decimal number :"<<n<<endl;

cout<<"Converted to Octal :"<<showbase<<oct<<n<<endl;

cout<<"Converted to Hexadecimal :"<<showbase<<hex<<n<<endl; }

Page 14: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

char name, address;

cout << “Please enter your name: “;

cin.get(name,15);

cout << “Please enter your address: “;

cin.get(address,20);

To solve this, place a dummy statement cin.get( ) after taking the first input. This will read the enter

key. The second method is to use another istream member which is the getline( ).

Some of the control codes used in cout statements: \n new line (cursor go to the next line for subsequent printing)

\t horizontal tab (cursor skip over to the next tab stop)

\a alert or bell (causes the computer to beep)

\0 null terminator (indicates the end of a string

Declarations & Constants

Variables and constants are declared the following way:

Declarations of variables:

int numb, float rad, double area, char name /*memory for storage is allocated */

**strings are special array of characters, it hold a word or sentence

A constant is a data item that whose value cannot change during the program’s execution.

Declarations of constants can be done in two ways:-

#define PI 3.141593 /* memory is not allocated */

const float PI=3.141593; /*memory is allocated */

Arithmetic Operators

A language specific syntactical token that requires an action to be taken. An operand receives an

operator’s action.

Addition + 12 + 4.9 (16.9)

Subtraction - 3.98 – 4 (-0.02)

Multiply * 2 * 3.4 (6.8)

Divide /

9 / 2.0 (4.5)

9.0 / 2 (4.5)

9.0 / 2.0 (4.5)

9 / 2 (4)

Modulus (Remainder) %

13 % 3 (1)

15 % 4 (3)

9 % 3 (0)

for divide operations (/), if both operands are int, the quotient is int; if either or both operands is float, the quotient is float

for modulus operations (%), both operands must be of type integer (int)

#include <iostream>

using namespace std;

main( )

{ char letter;

letter = 65;

cout << "\nThe letter is "<< letter;

letter = 66;

cout << "\nThe letter is "<< letter; }

#include <iostream>

using namespace std;

main( )

{ char letter;

letter = ‘A’;

cout << "\nThe letter is "<< letter;

letter = ‘B’;

cout << "\nThe letter is "<< letter; }

#include <iostream>

using namespace std;

main( )

{ const float PI=3.141593;

int r = 2;

cout << "\nThe area of a circle with

radius “<< r << “ is “<< PI*r*r;

}

Page 15: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015 Page 15 of 31

Ambiguity

C++ solves ambiguity problem by assigning priorities to operators, operators with high priority are

then evaluated before operators with low priority. Operators with equal priority are evaluated in left

to right order. The priorities of the operators seen so far are, in high to low priority order:

( ) highest priority

* / %

+ -

= lowest priority

This is similar to the golden rule: BODMAS. Multiplication, division and modulus have the same precedence,

also true with the addition and subtraction operators.

Implicit Type Conversion

When an operator’s operands are of different data types, C++ will automatically convert them to the

same data type. This can affect the results of the mathematical expressions. When C++ is working

with an operator, it strives to convert the operands to the same type. This implicit, or automatic,

conversion is known as type coercion. When a value is converted to a higher data type, it is said to be

promoted. To demote a value means to convert it to a lower data type.

Explicit Type Conversion

This type of casting allows to explicitly performing data type conversion on a value or expression. A

type cast expression allows manually promoting or demoting a value or expression.

Relational, Comparison and Logical Operators

Two expressions can be compared using relational and equality operators.

The result of such an operation is either true (T) or false (F) (i.e., a Boolean value).

Less than < 5 < 6 (gives 1)T

Less than or equal <= 5 <= 5 (gives 1)T

Greater than > 5 > 7 (gives 0)F

Greater than or equal >= 5 >= 8 (gives 0)F

Equal == 7 == 7 (gives 1)T

Not equal != 5 != 5 (gives 0)F

Logical AND && 5 < 6 && 6 < 6 (gives 0)F

Logical OR || 5 < 6 || 6 < 5 (gives 1)T

Bitwise Operators

Bitwise operators modify variables considering the bit patterns (binary) that represent the values they

store. For example, if A=60 (00111100) and B=13 (00001101)

AND & A&B=00001100

OR | A|B=00111101

Exclusive OR (XOR) ^ A^B=00110001

NOT (One’s complement) ~ ~A=11000011

Shift bits to the left (SHL) << A<<2 gives 11110000

Shift bits to the right (SHR) >> A>>2 gives 00001111

Assignment Operators and Expressions

assignment: = (means takes the value of or assign with the value of)

expressions: x = p + q (the expression on the right side (rvalue) (i.e. p + q) must be evaluated and

assigned to the variable on the left side (lvalue) i.e. x)

use brackets to avoid ambiguity problems: y = 3 * x + z / q should be written as y = 3 * (x + z) / q

Page 16: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

Composite assignment expressions: +=, -=, /=, %=

c = c + 3 can be written as c += 3 and c = c - 3 can be written as c -= 3

y = y * 7 can be written as y *= 7 and y = y / 7 can be written as y /= 7

Increment and Decrement Operators

Unary increment operator ++ will increment the variable by 1,

i.e. c++ is the same as c = c + 1.

Unary decrement operator -- will decrement the variable by 1,

i.e. c-- is the same as c = c - 1.

#include <iostream>

using namespace std;

main( )

{ float i;

int r;

cout << "\nPls enter current i ";

cin >> i;

cout << "\nPls enter resistance r ";

cin >> r;

cout << "\nThe voltage is "<< i*r; }

#include<iostream>

#include <cmath>

using namespace std;

int main()

{ int x1, x2;

int sum, difference, product, quotient, remainder;

cout<<"Pls enter two integers (separated by space): ";

cin>>x1>>x2;

sum=x1+x2;

difference=x1-x2;

product=x1*x2;

quotient=x1/x2;

remainder=x1%x2;

cout<< "Sum is "<< sum <<endl;

cout<< "Difference is "<< difference <<endl;

cout<< "Product is "<< product <<endl;

cout<< "Quotient is "<< quotient <<endl;

cout<< "Remainder is "<< remainder <<endl; }

#include <iostream>

using namespace std;

main( )

{ float cel, fahr;

cout << "\nPls enter Celcius temperature: ";

cin >>cel;

fahr=1.8*cel+32;

cout << "\nFahrenheit temperature is "<<fahr; }

#include <iostream>

using namespace std;

main() {

float radius, circumference, area;

float pi = 3.14159265;

cout << "Pls enter the radius of circle : ";

cin >> radius; // Compute area & circumference

area = radius * radius * pi;

circumference = 2.0 * radius * pi; // Print the results

cout << "The radius is " << radius << "." << endl;

cout << "The area is " << area << "." << endl;

cout << "The circumference is " << circumference

<< "." << endl; }

#include <iostream>

using namespace std;

main()

{ int t, hours, temp, mins, secs;

cout<<"\nPlease enter time in seconds: \n";

cin >> t;

hours=t/3600;

temp=t%3600;

mins=temp/60;

secs=temp%60;

cout <<"Time in seconds "<< t<<endl;

cout<<"Equivalent to "<<hours<<" hrs "<<mins

<<" mins "<<secs<<" seconds."<<endl; }

Page 17: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

Mathematics library

Some commonly used functions for the mathematics are stored in the cmath header file: sin(x) – sine (in radians) e.g. sin(0.345)

cos(x) – cosine (in radians)

tan(x) – tangent (in radians)

exp – ex exponential e.g. exp(3)

pow - xy raise to the power e.g. pow(23,3)

log10(x) – log10X

sqrt(x) – square root

Standard Library (cstdlib header file)

srand – seed the random number generator

rand() – generate a random integer

Time Library (ctime header file)

time() - get current time

Generating random numbers

1. Random numbers are numbers that are of no specific pattern. The program uses time of the day

to generate integer values.

2. To generate random numbers in a certain range

- to generate random numbers from 0 to 50,

use rand( ) % (max +1), that is rand( ) % 51

- to generate random numbers of a range, say 20 - 30,

use rand( ) % ((max + 1) – min ) + min,

thus we get (rand( ) % 11) + 20

- to generate numbers between 1 – 6, use (rand( )%6)+1

Software Development Method

Programming is a problem solving activity. In order to solve a problem, these steps are

recommended. 1. specify the problem requirements

2. analyze the problem

3. design suitable algorithm to solve the problem

4. implement the algorithm

5. test and verify the completed program

6. maintain and update the program

The solution to any computing problem involves performing a series of actions in specific order. A

procedure for solving a problem in terms of the actions to be executed and the order in which these

actions should be executed is called an algorithm.

Pseudocode is an artificial and informal language that helps programmer develops algorithms.

Pseudocode helps programmer to think out a program before attempting to write it in C++.

Example: Find the sum of squares of the numbers from 1 to n.

Pseudocode:

Input: n

sum « 0

i « 1

repeat while i ≤ n

[ sq « i * i

sum « sum + sq

i « i + 1 ]

Output: sum

PURPOSE -display information about the program

INPUT -ask user to enter required input

PROCESSING -do calculation (algorithm)

OUTPUT -display results

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

main( )

{ int d1, d2;

srand (time (NULL)); /* seed of random no.*/

d1 = rand();

d2 = rand();

cout << ”random number 1 = “ << d1 << endl;

cout << ”random number 2 = “ << d2; }

#include<iostream>

#include <cmath>

using namespace std;

main()

{ float x = 1.0, y = 2.0, z;

z = sin(x); // sine

cout<< "sine of "<< x <<" is "<< z <<endl;

z = sqrt(y); // square root

cout<< "square root of "<< y <<" is "<< z <<endl;

z = exp(y); // exponential function

cout<< "exponential of "<< y <<" is "<< z <<endl;

z = pow(x, y); // x to the power of y

cout<< x<<" to the power of "<< y <<" is "<< z <<endl; }

Page 18: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

Programming Style

Programming style refers to the way a programmer uses identifiers, spaces, tabs, blank lines, and

punctuation characters to visually arrange a program’s source code. These are some, but not all, of

the elements of programming style.

CHECK

1. Write a program that asks for five test scores. The program calculates the test average and

displays it in fixed-point notation, with one decimal point precision.

2. Write a program that calculates the current I in a resistor R using Ohm’s Law V=IR where V is

the voltage across R. The values of V and R are entered by the user.

3. Write a program that convert Malaysian currency to US dollars. Store the exchange rate in

constant variable called RATE.

4. Write a program that asks the user to give the correct answer to the addition of two numbers.

The two numbers is randomly generated and when the user gives an answer, the correct answer

is displayed. The two numbers must be between 10 and 100.

Page 19: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

CONTROL FLOW

Controlling the flow of a program is a very important aspect of programming. Control structures

control the flow of execution in a program or function. That is, the order of which the operations of

a program are executed can be controlled. Thus enables to combine individual instructions into a

single logical unit with one entry point and one exit point.

There are two types of control structures:

1. Selection or Branching statements

2. Iteration or Loop statements

Statement and Blocks

Statements are program lines that are converted to machine language instructions and executed by

the computer. A statement causes the computer to perform an action when a program is executed.

A statement ends with a semicolon ;. Statements are also called C++ codes.

Block (grouped together) is a section of C++ statements bounded by braces { }. Statements

enclosed by braces are called compound statements (or statement blocks).

Conditional Expressions

These expressions used to choose among alternatives statements by testing the value of key

variables.

(x <= 1), (y == 3), (x > 1 && y < 20), (num1 > 12 || num2 <= 20), ( !(x>14) )

The operators used in conditional expressions are called relational operators. Relational operators

usually used to determine whether one is greater than, less than, equal to, or not equal to another

for numeric and char values.

Note: == (equal) is not the same as = (assign)

&& means logical AND, || means logical OR and they are not bitwise operators for binary numbers.

Decision Making, Branching or Selection Statements

Enable to make decisions and to choose among options by testing the value of key variables. There

are three selection statements i.e. if…, if … else and switch… case

1. if (condition) statement;

If condition is met, the statement is executed, otherwise, it is omitted.

Very much limited and not commonly used.

a) if (total > 0) cout << "OK";

b) if (num == 0) cout << “Zero”;

if (num > 0) cout << “Positive”;

if (num < 0) cout << “Negative”;

if (work == 1) { cout << “Work finished! “;

grade = A; }

statements

conditionfalse

true

#include<iostream>

using namespace std;

int main()

{ int x1, x2;

cout<<"Pls enter two integers (separated by space): ";

cin>>x1>>x2;

if(x1>x2) cout<< x1<<" is bigger than "<< x2 <<endl;

if(x2>x1) cout<< x2<<" is bigger than "<< x1 <<endl; }

Page 20: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

2. if (condition) statement1;

else statement2 ;

If the condition is met (true), the statement1 is executed,

otherwise (false), statement2 is executed.

a) if (num >= 0) cout << “Positive”;

else cout << “Negative”;

b) The program reads two numbers from user and divides it, only if the second number (denominator) is not zero.

Nested if : statement2 is also another

if else statement. e.g. if (mark < 40) { cout << “Fail”;}

else { if (mark < 60) { cout << “Pass”;}

else {cout << “Good”} }

/*The use of braces is optional here*/

3. Switch statement lets the value of a variable or expression determines where the program will

branch to. Switch is flexible, but only test for integer and character values and not of type

float/double. switch (integer or character expression) /* evaluated to become const1… */

{ case const1 : statement1;

break; /*optional*/

case const2 : statement2;

break; /*optional*/

default : statement; }

The break statement is required to exit the switch block. The default section (or the last case section

if there is no default) does not need a break statement. The switch statement is a natural mechanism

for building menu-driven systems.

Example 1: Integer variable This program will read an integer value from the user. The statement executed will depend on the user input.

The default case will take up any input which is not covered by the cases. Break is required to get out of the

switch loop, otherwise it will execute the next case statement.

Example 2: Character variable When using a character in the switch condition expression, single quote must be used in the case statements.

#include <iostream>

using namespace std;

main ()

{ int num1, num2;

cout << "\nEnter first number "; cin >> num1;

cout << "\nEnter second number "; cin >> num2;

if (num2 == 0)

cout << "\nCannot divide by zero\n";

else cout<<"\nDividing gives " << (float)num1/num2;

}

#include <iostream>

using namespace std;

main( )

{ int i;

cout << "Enter a number between 1 and 4";

cin >> i;

switch (i) { case 1: cout << "One\n"; break;

case 2: cout << "Two\n"; break;

case 3: cout << "Three\n"; break;

case 4: cout << "Four\n"; break;

default: cout << "Unrecognized number\n"; } }

#include <iostream>

using namespace std;

main( )

{ char code;

cout << "Enter character code : ";

cin >> code;

switch (code) {

case ‘A’: cout << "\nValue is : " << code; break;

case ‘B’: cout << "\nValue is : " << code; break;

…..

default: cout<<”\nUnknown value\n”; } }

Statements set 1

conditionfalse

true

Statements set 2

Page 21: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015 Page 21 of 31

*Use switch statement when each label set contains a reasonable number of case labels (~10). However, if the

number of values is large, use a nested if statement.

CHECK

1. Write a program that asks the user to enter two numbers, and then the program will display

which number is the smaller and which is the larger.

2. The area of a rectangle is the rectangle’s length times its width. Write a program that asks for the

length and width of two rectangles. The program then tell the user which rectangle has the

greater area, or if the area are the same.

3. The formula weight=mass x 9.8 is used calculate the weight of an object in Newtons, given its

mass in Kilograms. Write a program that asks the user to enter the mass of an object, and if it

weighs more than 200 Newtons, display the message ‘Too heavy’. If it weighs less than 20

Newtons, display the message ‘Too light’.

Iteration or Loops

A loop is a control structure that repeats a group of statements in a program. The number of loops

(repetitions) can be determined mathematically, depending on the requirement by the programmer.

This gives computers the awesome processing power since the same program or part of a program

can be executed many times without having to write the program again and again.

There are three loop statements, while, do…while and for;

1. while (condition) { statements }

This is the simplest loop. The statements are executed if condition is true. Condition is always

evaluated every time the loop is executed. e.g. a) int x = 0;

while ( x != 2 ) x = x + 1; /*the only statement*/

cout << “x = ”<< x << endl;

b) int i = l;

while (i < 10)

{ cout << i<<endl; /*compound statement*/

++i; } /*need to increment i, otherwise loop will never end */

Note: If the statement to be executed in the loop is only one, there is no need to put the

braces { }, but must put braces if there is more than one statement in the loop, otherwise

unexpected results will be obtained.

#include <iostream>

using namespace std;

main( )

{ int count;

count = 0;

while (count < 100)

{ ++count;

cout << "Hello World!\n"; }

}

#include <iostream>

using namespace std;

main( )

{ int lower = 0, upper = 300, step = 20;

float fahr, celsius;

fahr = lower;

while (fahr <= upper) { celsius = (5.0/9.0)*(fahr-32.0);

cout<<fahr<<”\t”<<celsius<<endl;

fahr = fahr + step; } }

Statements

conditionfalse

true

Page 22: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

When tabulating numbers in table form (tabulation),

the output table can be formatted to be right or left

justified. The width of the displayed digits can also be

defined using setw( ). The showpos( ) function will

show the sign of the numbers.

The showpoint will cause the floating point to be

displayed. The number of decimal places is set using

the setprecision( ) function.

Note: These are functions in the iomanip header file.

Program shows the improved version of the previous

program which prints in tabular form the values of

temperatures in Fahrenheit and Celsius, now with

values tabulated right justified.

In order to reject invalid inputs, like entering

character/s for an integer input, the steps are:-

1. Test for this error state.

2. Clear the error state.

3. Either alternatively handle the input data

that generated the error state, or flush it out

and re-prompt the user.

Both programs shows how to do this.

2. do { statements } while (condition);

The loop is always executed once since the condition is tested at the end of the loop. do { cout << “Enter a positive integer : “;

cin >> response;

} while (response <= 0)

The following loop will end when variable a reach 20.

Statements

condition

false

true

#include <iostream>

#include<iomanip>

using namespace std;

main( )

{ int lower = 0, upper = 300, step = 20;

float fahr, celsius;

fahr = lower;

cout<<" Fahr\t Celsius"<<endl;

cout<<"________________"<<endl;

while (fahr <= upper)

{ cout<<showpoint<<setprecision(4);

celsius = (5.0/9.0)*(fahr-32.0);

cout<<right<<setw(6);

cout<<fahr<<" "<<celsius<<endl;

fahr = fahr + step; } }

#include <iostream>

#include <limits>

using namespace std;

int main( )

{ int age = 0;

while ((cout << "How old are you? ")&& !(cin >> age)) {

cout << "That's not a number, please enter again. ";

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n'); }

cout << "You are " << age << " years old.\n"; }

#include <iostream>

using namespace std;

int main ()

{ int a = 10;

do

{ cout << "Value of a: " << a << endl;

a = a + 1;

}while( a < 20 ); }

#include<iostream>

#include<limits>

using namespace std;

int main()

{ cout << "Enter an integer: ";

int x = 0;

while(!(cin >> x)){

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n');

cout << "Invalid input. Try again: "; }

cout << "You have entered: " << x << endl; }

Page 23: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015 Page 23 of 31

Some programs does not have specific number of loops, it depends on the user input or when it has

reach certain conditions. Programs below illustrates the idea.

3. for (initialization; condition; increment) { statements };

The for loop is a pretest loop that combines the initialization, testing, and updating of a loop control

variable in a single loop header.

The initialization is carried out once before the start of the loop. The conditional expression is tested

every time it passes through the loop, and the statements are executed only if the condition is true.

The increment part is used to alter the value of the control variable.

e.g. Printing 1 to 100: for ( i=1; i <= 100; ++i ) cout << i<<” ”;

Terminating and speeding loops

#include <iostream>

#include<cstdlib>

#include<ctime>

using namespace std;

main( )

{ int target, guess, again;

srand(time(NULL));

cout<<"Guessing game: Number between 0 and 100\n";

cout << "Do you want to guess a number? 1=Yes, 0=No >> ";

cin >> again;

while (again)

{ target = rand( ) % 101;

guess = target + 1;

while(target != guess)

{ cout << "\nWhat is your guess ? "; cin >> guess;

if (target > guess) cout << "Too low\n";

else cout << "Too high\n"; }

cout << "\nCorrect. Well done! You got it! \n";

cout<<"The number is "<<guess<<endl;

cout << "Do you want to play again? 1=Yes, 0=No >> ";

cin >> again; } }

#include <iostream>

using namespace std;

main( )

{ int fahr;

for ( fahr = 0 ; fahr <= 300 ; fahr = fahr + 20)

cout << fahr <<" "<< (5.0/9.0)*(fahr-32)<<endl; }

#include <iostream>

using namespace std;

main()

{ int up, down;

for (up=0, down=0; up < 10; up++, down--)

{ cout << " up = "<<up <<" down = "<< down<< endl; } }

#include<iostream>

#include<cmath>

using namespace std;

int main( )

{ int n, d=0, i=0;

cout<<"Converting Binary number to Decimal"<<endl;

cout<<"Enter any number in binary: ";

cin>>n;

while(n!=0)

{ d=d+(n%10)*pow(2,i);

n=n/10;

i=i+1;

cout<<"Loop "<<i<<"\t\t"<<d<<"\t"<<n<<"\t"<<i<<endl; }

cout<<"\nThe equivalent decimal value is "<<d<<endl;

} //Program ends when n==0

#include <iostream>

using namespace std;

int main( )

{ int a, b;

do { cout << "\nEnter first number: ";

cin >> a;

cout << "\nEnter second number: ";

cin >> b;

if (a < b) cout << "\nFirst number is less than second number\n";

if (b < a) cout << "Second number is less than first\n";

} while (a < 999); } //program will end if a>=999

Page 24: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

break – if this statement is encountered, the loop will terminate immediately. The loop will

terminate early, it will not reach the end of the loop. e.g.

for ( num = 1; num <= 100; num++){

if (num == 12) break;

cout << “My number = ”<< num; }

This loop will terminate when num equals 12.

Another way to terminate a loop is by using the exit(0) function. The exit( ) function causes a

program to terminate, regardless of which function or control mechanism is executing. The header

file for the exit() function is cstdlib.

continue – if this statement is encountered, the loop will be skipped (stop its current iteration and

begin the next one) e.g.

for ( num = -10; num <= 10; num++)

{ if (num == 0) continue;

ans = 20/num;

cout << “\n”<< ans; }

goto - unconditional jump

The goto statement is an unconditional jump statement. Its destination is specified by a label within

the statement. A label is simply an identifier followed by a colon placed in front of a statement.

int n;

loop: cout << n <<endl;

n++;

if (n<= 20) goto loop;

The use of goto statement is discouraged to be used since it defeats the purpose of structured

programming language. It is maintained for special needs, if arises, or just for completeness.

Students are not recommended/allowed to use the goto statement.

Special cases

Infinite loops can be created by omitting the second expression or by using a non-zero constant.

a) for ( ; ; ) cout << “\nThis is an infinite loop!”;

b) for ( ; 1 ; ) cout << “\nThis is another an infinite loop!”;

Infinite loop is useful in certain cases, but must use an

exit from the loop using either the break or return statement.

Timing Loops

A statement in C++ may be empty.

for (dt=0; dt<20000; dt++);

This for loop pauses for 20000 milliseconds by simply

cycling through the loop many times.

#include <iostream>

using namespace std;

main()

{ int x, m=1;

cout << "Printing multiplication table"<< endl;

cout << "Pls enter multiplication table required "<< endl;

cin >> x;

loop: cout<<m<<" x "<<x<<" = "<< m*x <<endl;

m=m+1;

if (m < 15) goto loop; }

#include <iostream>

using namespace std;

main()

{ char selection;

for ( ; ; )

{ cout << “\n MENU \n”;

cout << “\n A – Add records”;

cout << “\n M – Modify records”;

cout << “\n D – Delete records”;

cout << “\n X – Exit”;

cout << “Pls select item: “;

cin >> selection;

if (selection == ‘X’) break; } }

Page 25: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015 Page 25 of 31

Sentinels

A sentinel is a special value that marks the end of a list of values.

This is useful in program loops that do not know in advance the number of loops to be taken. Thus

in these situations, the user will enter a sentinel to end the input.

A sentinel must not be mistaken as a member of the input; it is just used to terminate the program

loop.

Example: Write a program using a while loop to read the test marks of a class. Then print out the

number of marks entered and the average of all the marks. Use -99 as the sentinel value.

Deciding which loop to use

Although most repetitive algorithms can be written with any of the three types of loops, each works

best in different situations.

The while loop is a pretest loop. It is ideal in situations where the programmer do not want the loop

to iterate if the test condition is false from the beginning.

The do-while loop is a post test loop. It is ideal in situations where the programmer always want

the loop to iterate at least once.

The for loop is a pretest loop with built-in expressions for initializing, testing, and updating a

counter variable. The for loop is ideal in situations where the exact number of iterations is known.

Nested Loops

A loop that is inside another loop is called a nested loop.

It is possible to have a loop inside another loop. The first loop is called the outer loop, and the loop

nested inside it is called the inner loop.

CHECK

1. Write a program that asks the user to enter a number. Then the program will print out the

number multiplied by 2 until it exceeds 50.

2. Write a program that asks the user to enter two numbers. The numbers are added and its sum is

displayed. Then the program asks the user either to repeat the operation again or to stop.

3. Write a program to display the following set of numbers: 0, 10, 20, 30, 40, 50, … 1000

4. Write a program that asks the user to enter ten numbers. Each time a number is entered, the

program display the running total of the numbers entered.

5. Write a program that displays the characters for each ASCII code 32 through 127. Display 16

characters on each line with one space between characters.

Page 26: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

POINTERS

A pointer is a special type of variable, which contains the address in memory of another variable.

That is, it points to a variable that contains a value. A pointer to can points to any variable type: int,

float, char.

The advantages of using pointers are:

It is the only way to express some computations.

It produces compact and efficient code.

It provides a very powerful tool.

Pointers are used explicitly with:

Arrays

Structures

Functions

The unary or monadic operator & gives the “address of a variable”. The indirection or dereference

operator * gives the “contents of an object pointed to by a pointer”.

Eg. int x; declare x as integer variable

int *pt; declare pt as pointer variable

pt = &x; variable pt now contains the address of variable x

*pt = 3; dereference the pointer pt (i.e. put 3 into memory address held by pt)

In effect is the same as: int x; x = 3;

Although pointers offer tremendous

power and flexibility to the

programmer, care must be taken to use

them properly. If misused, pointers can result in bugs that are difficult to track.

The new operator

The new operator allocate memory explicitly for the pointer itself. Let’s look at this example:-

float *q;

q = new float; //allocates storage for one float

*q = 3.14159;

The new operator returns the address of a block of s unallocated bytes in memory, where s is the

size of a float, typically for a float is 4 bytes. Assigning that address to q guarantees that *q is not

currently in use by any other variables.

//Pointer demonstration

#include <iostream>

using namespace std;

main( )

{ int a, *p;

a = 14;

p = &a;

cout << a<<”\t”<< &a<<endl;

cout << p<<”\t“<< *p<<”\t “<< a<<endl; }

//Using pointer to store data in memory and manipulate them

#include <iostream>

using namespace std;

main( )

{ int a, b, r;

int *pa=&a, *pb=&b, *pr=&r;

cout << "Enter first number\n";

cin >> *pa;

cout << "Enter second number\n";

cin >> *pb;

*pr = *pa * *pb;

cout << *pa<<" multiplied by "<<*pb<<" is "<< *pr<<endl;

cout << a<<" multiplied by "<<b<<" is "<< r<<endl; }

Page 27: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015 Page 27 of 31

The delete operator

The delete operator reverses the action of the new operator, returning allocated memory to the free

store. It should only be applied to pointers that have been allocated explicitly by the new operator.

float *q = new float (3.14159); //allocates storage for one float and immediately

//initialize it

delete q; //de-allocates q once it is not used anymore

De-allocating q returns the block of sizeof(float) bytes to the free store, making it available for

allocation to other objects. Once q has been de-allocated, it should not be used again until it has

been re-allocated. A de-allocated pointer, also called a dangling pointer, is like an uninitialized

pointer, it does not point to anything.

Alias

It is also possible to make a variable having two names. The following codes makes variable y also

known as x. Change x will change y, and changing y will change x since they are the same (alias).

float y;

float &x = y; /* address of x is y */

i.e. float &x=y is translated to as float *x=&y and thus all subsequent x are replaced by *x.

CHECK

1. The formula to calculate the power in a resistor is given as P=I2R where I is the current flowing

in resistor R. Using pointer syntax only, calculate the power in resistor R where the values of R

and I are entered by the user.

2. The formula for converting a temperature from Fahrenheit to Celsius is C=(5/9)(F-32) where F

is the Fahrenheit temperature and C is the Celsius temperature. Write a program that displays

a table of the Fahrenheit temperatures 0 through 20 and their Celsius equivalent where all

references to the variables uses pointers.

3. The following formula can be used to determine the distance an object falls due to gravity in a

specific time period d=½gt2 where d is the distance in meters, g is 9.8, and t is the time in

seconds that the object has been falling. Write a program that accepts an objects falling time in

seconds, and then the program will display the distance the object has fallen during that time

interval. The program must use pointers to reference the variables.

#include <iostream>

using namespace std;

main( )

{ float a=12.657; /* set a with a value */

float &b = a; /* a is now also known as b */

b = 87.432; /* set b, which is also a and thus a has 87.432 also */

cout <<”a contains ”<< a<<endl; /* printing a */

cout <<”b contains ”<< b<<endl; /* printing b */ }

Page 28: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

FUNCTIONS A function is a self-contained block of program statements that performs a particular or specific

task. It is simply C++ codes (statements) that is grouped together and given a name. A function

breaks down a problem into small manageable modules, thus simplifying programs. Summarizing,

the advantages are:

1. Software reusability, by use the existing functions and provides abstraction (hiding details).

2. Manageable program development, doing it in small parts or modules

3. Avoid code repetition (write once, use many times)

The main( ) program is actually a function. That is why it is called main( ) function, and the caller is

the Operating Systems of the computer, i.e. Windows-A.

Standard C++ Library Functions

It is a collection of pre-defined functions and other program elements which are accessed through

the header files. Like rand() function defined in <cstdlib> and pow(m,n),sqrt() functions defined in

<cmath>.

Function call: A statement that causes a function to execute. A function is executed by using its

name as a variable in a statement, e.g. y=pow(3,5); sometimes this is called invoking the function.

Function definition contains the statements that make up the function.

User Defined Functions: Basic functions

To create a function that prints the sentence "Hello, Welcome to C++ Programming" on the screen,

first write the statements: cout << "Hello";

cout << “Welcome to C++ Programming”;

These statements are called the function definition. To turn it into a function, simply wrap the codes

in a pair of curly brackets to convert it into a single compound statement and give it a name and put it

in front of the brackets: demo( ) /* demo is the name of this function or function header */

{ cout << "Hello"); /* function definition or function body */

cout << “Welcome to C++ Programming”; }

Once the function has been defined, the function can be used within a program by: main( ) { demo( ); }

In this program the instruction demo( ); is entirely equivalent to writing out all of the statements in

the function. This is of course, is the power of functions.

*depending on the compiler, sometimes it is required to write the keyword void in front of the function name

when defining the function.

To be useful, there has to be a way of getting data into and out of a function, and this is the role of

the curved brackets. Special variables called parameters which are used to carry data values into a

function need to be defined. Parameters are listed and declared in between the ( ) brackets in the

function's definition. For example: sum( int a, int b)

Page 29: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015 Page 29 of 31

{ int result;

result=a + b; }

defines a function called sum with two parameters a and b, both integers and they are local

variables and have nothing at all to do with any variables called a and b defined in any other

function.

The simplest way to get a value out of a function is to use the return instruction. A function can

return a value via its name - it's as if the name was a variable and had a value. The value that is

returned is specified by the instruction:- return value; which can occur anywhere within the

function, not just as the last instruction - however, a return always terminates the function and

returns control back to the calling function. The only complication is that as the function's name is

used to return the value it has to be given a data type. This is achieved by writing the data type in

front of the function's name. For example: int sum (a, b);

So now the correct version of the sum function is written as:

and to use it just write something like: r = sum(1,2); which would add 1 to 2 and store the result in r.

Function Prototypes

One of the most important features of C++ is function prototypes. It tells the compiler the type of

data returned by the function, the number of parameters the function expects to receive, the types

of the parameters, and the order in which these parameters are expected. The compiler uses function

prototypes to validate function calls. The function prototypes eliminate the need to place a function

definition before all calls to the function. Function prototypes are also known as function

declarations.

Function prototypes are usually placed near the top of a program so the compiler will encounter

them before any function calls.

Function can be classified into two types:

1. void function. This type of function does not return any value to the caller, though it may have

input parameters when called. Void functions are called just by a single statement, that is, its

name, with parameters if any.

2. returning value function. The function when called, returns a value to caller, it may or may not

have input parameters when called. The function must be called in an expression because

int sum (int a, int b)

{ return (a+b); }

int sum (int a, int b)

{ int result;

result = a + b;

return result; }

#include <iostream>

using namespace std;

void show (int x); /* function prototype*/

main( )

{ int a = 6;

show (a); }

/* Function receives parameter & returns nothing */

void show (int x)

{ cout << “\n”<< x);

return; } /* statement return is optional */

#include <iostream>

using namespace std;

void area (int, int ); /* function prototype*/

main( )

{ int l = 6, w = 4;

area (l,w); }

/* Function receives parameter & returns nothing */

void area (int x, int y)

{ cout << “\nArea is ”<< x*y);

}

Page 30: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

there is a value passed by the

function back to the caller.

The above examples show how functions are called by

passing values during the call (parameters). The only

problem is that the function can only return one value

back to the caller. Functions operates in this manner is

called pass by value.

Pointers & Functions

One of the most useful applications of pointer is in

functions. When calling a function, pointers are passed

to it, so that the function can manipulate the variables

pointed to by the pointers. This method is called

pass by address.

The function does not return any value to the caller

since it manipulates the data directly in the memory using

the address passed by the caller.

/* Here is a function which raises a double to the power of an unsigned integer,

and returns the result. */

#include <iostream>

#include <cmath>

using namespace std;

double power(double val, unsigned pow); /* function prototype */

main( )

{ int val = 20, pow = 3;

result = power(val, pow);

cout << “The value of “<<val<<” to the power of ”<<pow<<” is “<< result); }

double power(double val, unsigned pow) /* The function */

{ double ret_val = 1.0; unsigned i;

for(i = 0; i < pow; i++)

ret_val *= val;

return (ret_val); }

#include <iostream>

using namespace std;

int factorial (int n); /* function prototype */

main ( )

{ int num, fact;

cout << “Enter integer 1 to 10 > “;

cin >> num;

if (num < 0) {cout << “\nFactorial of negative number “

<<num<<” is undefined\n”;

} else if (num <= 10) { fact = factorial (num);

cout << “The factorial of “<<num<<” is ”<< fact;

} else { cout << “Number out of range: ”<< num); } }

/* function that calculates the factorial and return the value

to main */

int factorial (int n)

{ int i, product = 1;

for ( i= n; i > 1; i = i-1) { product *= i }

return (product) }

#include <iostream>

using namespace std;

void fun (int *val);

main( )

{ int a= 5;

fun (&a); /* call function fun and pass address a to the function */

cout << “\n”<< a); }

/* Function */

void fun (int *x) /* *x is a reference to the variable a in main */

{ *x = *x +3; /* function does not create a copy of the variable a, but manipulates */

return; } /* directly the variable a, thus no need to return any value */

#include <iostream>

using namespace std;

void exchange (int *, int *);

main( )

{ int a=5, b=7;

cout << “\n: “<< a <<” “<< b);

exchange (&a, &b);

cout << “\n: ”<< a <<” “<< b);}

void exchange (int *x, int *y)

{ int temp;

temp = *x;

*x = *y;

*y = temp;

return; }

Page 31: C++ Programming Language - mohduzir.uitm.edu.my · C++ programming language is case sensitive. Capitals and small letters means different thing. E.g. Number is not the same as number

COMPUTER PROGRAMMING (C++)

Mohd Uzir Kamaluddin / 3rd Ed. Mac 2015 Page 31 of 31

An example of recursion, using a function:

CHECK

1. Using the formula V=IR to find voltage V across a resistor R for a current I that flows through

the resistor, write a function named voltage that accepts values of R and I as arguments. The

function should return the voltage. Demonstrate the function in a complete program.

2. Using the formula C=(5/9)(F-32) to convert the temperature in Fahrenheit to Celsius, write a

function named celsius that accepts a Fahrenheit temperature as an argument. The function

should return the temperature, in Celsius. Demonstrate the function in a complete program.

3. An object that is in motion is said to have kinetic energy KE=½mv2, where KE is the kinetic

energy in Joules, m is the object’s mass in kilograms, and v is the velocity of the object in m/s.

Write a function named kineticEnergy that accepts an object’s mass (in Kg) and velocity (in m/s)

as arguments. The function should return the amount of kinetic energy that the object has.

Demonstrate the function in a complete program.

4. A prime number is an integer greater than 1 that is evenly divisible by only 1 and itself. Write a

Boolean function names isPrime which takes an integer as an argument and returns true if the

argument is a prime number, and false otherwise. Demonstrate the function in a complete

program.

END OF PART I

#include <iostream>

using namespace std;

int fib (int );

main( )

{ int n;

cout << “\nEnter n for Fibonacci sequence: “;

cin >> n;

cout << “\nFibonacci (“ << n << “) = “ << fib(n); }

int fib(int n)

{ int fn;

if (n==0 || n==1) return 1;

fn = fib(n-1) + fib(n-2);

return fn; }