Professional Documents
Culture Documents
CP Lectures - 2
CP Lectures - 2
This is a list of reserved keywords in C++. Since they are used by the language, these keywords are not available for
re-definition or overloading.
(1) - meaning changed or new meaning added in C++11. Note: the keyword export is also used by Modules TS.
(2) - meaning changed in C++17.
Note that and, bitor, or, xor, compl, bitand, and_eq, or_eq, xor_eq, not, and not_eq (along with the digraphs <%, %>,
<:, :>, %:, and %:%:) provide an alternative way to represent standard tokens.
In addition to keywords, there are identifiers with special meaning, which may be used as names of objects or
functions, but have special meaning in certain contexts.
override (C++11)
final (C++11)
transaction_safe (TM TS)
transaction_safe_dynamic (TM TS)
Also, all identifiers that contain a double underscore __ in any position and each identifier that begins with an
underscore followed by an uppercase letter is always reserved and all identifiers that begin with an underscore are
reserved for use as names in the global namespace. See identifiers for more details.
The namespace std is used to place names of the standard C++ library. See Extending namespace std for the rules
about adding names to it.
The name posix is reserved for a future top-level namespace. The behavior is undefined if a program
(since C++11)
declares or defines anything in that namespace.
The following tokens are recognized by the preprocessor when in context of a preprocessor directive:
if
ifdef include
elif
ifndef line
else
define error
endif
undef pragma
defined
The following tokens are recognized by the preprocessor outside the context of a preprocessor directive:
_Pragma(since C++11)
See also
There are many methods or techniques which can be used to convert numbers from one base to another. In
this chapter, we'll demonstrate the following −
Step 2 − Get the remainder from Step 1 as the rightmost digit leastsignif icantdigit of the new base number.
Step 3 − Divide the quotient of the previous divide by the new base.
Step 4 − Record the remainder from Step 3 as the next digit tothelef t of the new base number.
Repeat Steps 3 and 4, getting remainders from right to left, until the quotient becomes zero in Step 3.
The last remainder thus obtained will be the Most Significant Digit M S D of the new base number.
Example
Step 1 29 / 2 14 1
Step 2 14 / 2 7 0
Step 3 7/2 3 1
Step 4 3/2 1 1
Step 5 1/2 0 1
As mentioned in Steps 2 and 4, the remainders have to be arranged in the reverse order so that the first
remainder becomes the Least Significant Digit LS D and the last remainder becomes the Most Significant
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 1/5
4/24/2018 Computer Number Conversion
Digit M S D .
Step 2 − Multiply the obtained column values inS tep1 by the digits in the corresponding columns.
Step 3 − Sum the products calculated in Step 2. The total is the equivalent value in decimal.
Example
Step 2 111012 16 + 8 + 4 + 0 + 1 10
Step 2 − Convert the decimal number so obtained to the new base number.
Example
Step 2 258 16 + 5 10
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 2/5
4/24/2018 Computer Number Conversion
Step 1 21 / 2 10 1
Step 2 10 / 2 5 0
Step 3 5/2 2 1
Step 4 2/2 1 0
Step 5 1/2 0 1
Step 2 − Convert each group of three binary digits to one octal digit.
Example
Step 2 101012 28 58
Step 2 − Combine all the resulting binary groups of 3digitseach into a single binary number.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 3/5
4/24/2018 Computer Number Conversion
Example
Step 2 − Convert each group of four binary digits to one hexadecimal symbol.
Example
Step 2 − Combine all the resulting binary groups of 4digitseach into a single binary number.
Example
Hexadecimal Number : 1516
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 4/5
4/24/2018 Computer Number Conversion
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 5/5
4/24/2018 Computer Number System
When we type some letters or words, the computer translates them in numbers as computers can understand
only numbers. A computer can understand the positional number system where there are only a few symbols
called digits and these symbols represent different values depending on the position they occupy in the
number.
The digit
Each position represents a specific power of the base 10. For example, the decimal number 1234 consists of
the digit 4 in the units position, 3 in the tens position, 2 in the hundreds position, and 1 in the thousands
position. Its value can be written as
As a computer programmer or an IT professional, you should understand the following number systems
which are frequently used in computers.
3
Hexa Decimal Number System
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 1/3
4/24/2018 Computer Number System
Last position in a binary number represents a x power of the base 2. Example 2x where x represents the
last position - 1.
Example
Binary Number: 101012
Step 2 101012 16 + 0 + 4 + 0 + 1 10
Last position in an octal number represents a x power of the base 8. Example 8x where x represents the
last position - 1
Example
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 2/3
4/24/2018 Computer Number System
Letters represent the numbers starting from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15
Each position in a hexadecimal number represents a 0 power of the base 16. Example, 160
Last position in a hexadecimal number represents a x power of the base 16. Example 16x where x
represents the last position - 1
Example
Step 2 19FDE16 ((1 x 164) + (9 x 163) + (15 x 162) + (13 x 161) + (14 x 160))10
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 3/3
ECE 0142 Computer Organization
1
Floating-point arithmetic
2
Floating-point representation
± mantissa * 2exponent
s e f
3
Sign
s e f
4
Mantissa
s e f
There are many ways to write a number in scientific notation, but
there is always a unique normalized representation, with exactly one
non-zero digit to the left of the point.
0.232 × 103 = 23.2 × 101 = 2.32 * 102 = …
01001 = 1.001× 23 = …
What’s the normalized representation of 00101101.101 ?
00101101.101
= 1.01101101 × 25
5
Mantissa
s e f
There are many ways to write a number in scientific notation, but
there is always a unique normalized representation, with exactly one
non-zero digit to the left of the point.
0.232 × 103 = 23.2 × 101 = 2.32 * 102 = …
01001 = 1.001× 23 = …
The field f contains a binary fraction.
The actual mantissa of the floating-point value is (1 + f).
– In other words, there is an implicit 1 to the left of the binary
point.
– For example, if f is 01101…, the mantissa would be 1.01101…
A side effect is that we get a little more precision: there are 24 bits in
the mantissa, but we only need to store 23 of them.
But, what about value 0?
6
Exponent
s e f
There are special cases that require encodings
– Infinities (overflow)
– NAN (divide by zero)
For example:
– Single-precision: 8 bits in e → 256 codes; 11111111 reserved for
special cases → 255 codes; one code (00000000) for zero → 254
codes; need both positive and negative exponents → half
positives (127), and half negatives (127)
– Double-precision: 11 bits in e → 2048 codes; 111…1 reserved for
special cases → 2047 codes; one code for zero → 2046 codes;
need both positive and negative exponents → half positives
(1023), and half negatives (1023)
7
Exponent
s e f
8
Mapping Between e and Actual Exponent
Actual
e
Exponent
0000 0000 Reserved
0000 0001 1-127 = -126 -12610
0000 0010 2-127 = -125 -12510
… …
0111 1111 010
… …
1111 1110 254-127=127 12710
1111 1111 Reserved
9
Converting an IEEE 754 number to decimal
s e f
(1 - 2s) * (1 + f) * 2e-bias
10
Example IEEE-decimal conversion
1 01111100 11000000000000000000000
(1 - 2s) * (1 + f) * 2e-bias
11
Converting a decimal number to IEEE 754
What is the single-precision representation of 347.625?
101011011.101 x 20 = 1.01011011101 x 28
3. The bits to the right of the binary point comprise the fractional
field f.
4. The number of times you shifted gives the exponent. The field e
should contain: exponent + 127.
5. Sign bit: 0 if positive, 1 if negative.
12
Exercise
639.6875 = 1001111111.10112
= 1.0011111111011×29
s=0
e = 9 + 127 = 136 = 10001000
f = 0011111111011
13
Examples: Compare FP numbers ( <, > ? )
14
Special Values (single-precision)
E F meaning Notes
Valid Unnormalized
00000000 X…X
number =(-1)S x 2-126 x (0.F)
15
E Real F Value
Exponent
0000 0000 Reserved 000…0 010
xxx…x Unnormalized
(-1)S x 2-126 x (0.F)
0000 0001 -12610
0000 0010 -12510
… … Normalized
0111 1111 010 (-1)S x 2e-127 x (1.F)
… …
1111 1110 12710
1111 1111 Reserved 000…0 Infinity
xxx…x NaN
16
Range of numbers
Unnormalized
smallest 00000000000000000000000000000001 +2-126(2-23) = 2-149
2-126 2127(2-2-23)
0 2-149 2-126(1-2-23)
Positive overflow
Positive underflow 17
In comparison
2 4 8 16
Thus, floating-point arithmetic has “issues”
– Small roundoff errors can accumulate with multiplications or
exponentiations, resulting in big errors.
– Rounding errors can invalidate many basic arithmetic
principles such as the associative law, (x + y) + z = x + (y + z).
The IEEE 754 standard guarantees that all machines will produce
the same results—but those results may not be mathematically
accurate!
19
Limits of the IEEE representation
int x = 33554431;
float y = 33554431;
printf( "%d\n", x );
printf( "%f\n", y );
33554431
33554432.000000
0.1010 = 0.0001100110011...2
20
0.10
During the Gulf War in 1991, a U.S. Patriot missile failed to intercept
an Iraqi Scud missile, and 28 Americans were killed.
A later study determined that the problem was caused by the
inaccuracy of the binary representation of 0.10.
– The Patriot incremented a counter once every 0.10 seconds.
– It multiplied the counter value by 0.10 to compute the actual
time.
However, the (24-bit) binary representation of 0.10 actually
corresponds to 0.099999904632568359375, which is off by
0.000000095367431640625.
This doesn’t seem like much, but after 100 hours the time ends up
being off by 0.34 seconds—enough time for a Scud to travel 500
meters!
Professor Skeel wrote a short article about this.
Roundoff Error and the Patriot Missile. SIAM News, 25(4):11, July 1992.
21
Floating-point addition example
22
Steps 1-2: the actual addition
9.999 * 101
+ 0.016 * 101
10.015 * 101
23
Steps 3-5: representing the result
3. Normalize the result if necessary.
This step may cause the point to shift either left or right, and the
exponent to either increase or decrease.
24
Example
25
Multiplication
To multiply two floating-point values, first multiply their magnitudes
and add their exponents.
9.999 * 101
* 1.610 * 10-1
16.098 * 100
You can then round and normalize the result, yielding 1.610 * 101.
The sign of the product is the exclusive-or of the signs of the
operands.
– If two numbers have the same sign, their product is positive.
– If two numbers have different signs, the product is negative.
26
The history of floating-point computation
27
Floating-point hardware
28
FPU like co-processor on chip
29
Summary
30
Arithmetic and
Logic Unit
Cache
Control Unit
Memory
Registers
EE-163 (Computers & Programming) EED FR, IA
Welcome Students,
Course Introduction
EE – 163 Computers & Programming is the fundamental course offered in the First year at
Electrical Engineering Department. The core idea of this course is to familiarize students with
the basic programming concepts and computer history. While it is important to understand
the technical computing, it is also essential to look at the evolution process of computers.
The course comprises of the following topics,
i. Computer History (this is diy topic, you will be provided with a documentary and
other reading material to write a report. Beware this is a graded topic)
ii. Introduction to C++ and Code::Blocks IDE
iii. C++ Building Blocks (data types, variables, standard input/output functions,
operators, comments etc.)
iv. Structured Programming (decision making, logical operators, loops etc.)
v. Functions (Function prototype, functions with multiple arguments, C++ standard
functions, recursion etc.)
vi. Arrays (1d and 2d arrays, algorithms with arrays etc.)
vii. Vectors
viii. Pointers (Pointer Overview, Returning data from functions, Pointers and Arrays,
Pointers and Strings, Double Indirection, Pointers to Pointers etc.)
ix. Files
Course objectives are the following:
1) Understand and identify the fundamental concepts of computing and computer
programming. (cognitive domain)
2) Ability to code algorithmic solutions in a programming language (C++) (cognitive
domain)
3) Ability to use modern IDEs, standard and 3rd party libraries for basic and advanced
problem solving. (psychomotor domain)
Grading Distribution
Credit distribution of the course is 3 -1
Theory
Mode of Assessment Marks
Mid Term 20
Quiz 1 (Before mid-term) 5
Quiz 2 (after mid-term) 5
Group activity 10
Total 40
Practical
Lab Reports Not graded but should be complete
Lab Test 1 10
Lab Test 2 10
Total 20
EE-163 (Computers & Programming) EED FR, IA
Notes:
1) Group size shall be three, the group members shall be picked up by the instructor.
2) The group shall be responsible to complete ‘lab manual exercises’ and ‘group
activity’ together as a combined unit. All other activities shall be assessed
individually.
3) Lab manual exercises shall be checked after every 4th lab session.
4) In order to form the group, a survey form needs to be filled by all students. The form
is attached at the end of this lesson.
5) The ‘group activity’ is an extensive exercise planned to provide you with state-of-the-
art computer skills. You would need to get training first and then a task shall be
assigned to your group to complete before the end of the semester. Brief details of the
activity are provided under the caption Group Activity.
Course Instructors
Fezan Rafique (Sections A, B, C)
Assistant Professor
Electrical Engineering Department
fezan@neduet.edu.pk
Course Group
To facilitate student teacher communication, a Facebook group (strictly for FE Electrical
Spring 2018) is created, students can use this group for academic discussion about EE-163
Computers & Programming (only). The group is public for a 10 days (11-04-2018) and will
be converted to a closed group afterwards.
Group Name: EE-163 Computers and Programming 2018
Group Link: https://www.facebook.com/groups/884768641707756/
Course Registration
All students are requested to fill a simple form to get notifications about course
https://docs.google.com/forms/d/e/1FAIpQLSepHQPI7saYWfVkPA1Vw9yXS3_5o0Ndtr55
DSSUOs6HAEeOog/viewform?c=0&w=1&usp=mail_form_link
ii. Stroustrup, Bjarne. Programming: principles and practice using C++ 2nd Edition.
Pearson Education, 2009.
Group Activity
The group activity requires your group to collect data (in MS Excel), tabulate and analyse the
data (also in MS Excel), draw conclusions and write a professional – 1000 word – report (in
MS Word) and finally present your findings using a professional presentation (in MS
PowerPoint). All this requires you to first master the software packages mentioned above.
This can easily be done by completing the following online course offered by Virtual
University, Pakistan:
Course Name: Computer Proficiency License (CPL) online course
Course Link: http://cpl.vu.edu.pk//Home.html
You must watch all videos and complete all exercises. Questions related to this course may
be asked in the theory quizzes and mid-term exams, however, final evaluation of this whole
exercise will be in terms of your group performance in the three tasks mentioned above.
Data collection, tabulation and analysis in MS Excel = 3 marks
Professional report written in MS Word (1000 words) = 2 marks
Professional presentation in MS PowerPoint (8 slides) = 3 marks
Professional outlook of the team and team cohesion = 2 marks
Total group activity marks = 10 marks
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
Resource: http://www.engr.colostate.edu/ECE251/Lectures/Lecture27connors.pdf
Reading Assignment
Article taken from http://www.explainingcomputers.com/hardware.html
This article is on Computer Hardware and is written by famous computer instructor
Christopher Barnatt. He runs a famous Youtube channel by the name of Explaining
Computers which you should check out if you are a computer geek.
INTRODUCTION
Hardware refers to all of the physical parts of a computer system. For a traditional desktop
computer this comprises the main system unit, a display screen, a keyboard, a mouse, and
sometimes a printer. Speakers, a webcam and an external hard drive for back-up storage are
often also included.
The following gives a basic overview of personal computer (PC) hardware, with the focus
being on desktop computers. Inevitably, other sections of this website -- most notably those
covering storage, mobile computing and networking -- also discuss particular areas of
computer hardware and its application and specification. For a more technical hardware
guide, see the excellent Introduction to Computer Hardware written by Howard Gilbert of
Yale University. And if you are interested in the evolution of computing, you may like to
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
read The History of the Microcomputer Revolution by Frank Delaney or this brief history of
computing.
A DECREASING CONCERN
When the first microcomputers were introduced in the late 1970s, and in particular when the
IBM PC was launched (in 1981 in the USA and 1983 in the UK), the computer industry was
dominated by hardware. This was because most of the money spent on a computer system
went on hardware, with a direct trade-off existing between processing power and overall
system cost. The exact hardware specification was usually also critical. Today, however,
neither of these points remains the case.
Since the turn of the century the cost of a typical desktop PC has fallen in both real and
monetary terms. Almost all new computers are now also capable of performing most of the
tasks that can be demanded of them, with the exact hardware specification being largely
irrelevant for all but the most demanding or specialist users. Indeed, on the 23rd of August
2005, Intel declared the "clock frequency war" to be over, with the new computing mantra to
be performance per watt. Or to put it another way, no longer would the speed of a computer's
processor be the primary measure of its capability in terms of either consumer expectation, or
the market dominance of its microprocessor manufacturer.
To a large extent, time was called on the clock frequency war because of the difficulties
encountered in cooling microprocessors as they became faster and faster. However, another
driver was simply that raw processing power was starting to become a secondary concern for
many purchasers. By 2005, factors such how much noise a computer makes, case style and
size, and a computer's green credentials, were starting to be perceived as important. And such
non-processing-power measures are increasingly driving both consumer and business
computer purchase decisions today.
Decisions on hardware specification are often driven by the minimum hardware required to
run specific software (such as a specific application program or operating system). Indeed, it
remains most sensible for many users to decide on the software they want or need to run, and
to choose or upgrade their hardware accordingly.
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
In broad terms, the performance of a computer depends on four factors: the speed and
architecture of its processor or "central processing unit" (CPU), how much random access
memory (RAM) it has, its graphics system, and its internal hard drive speed and capacity.
Also of importance to most users will be the specification of its Internet connection. Most
computer users -- and in particular those working with a lot of photographs, music files or
videos -- should also think about the most suitable storage devices they will need in order to
keep and back-up all of their valuable data.
Where higher processor speeds become more important is for applications such as video
editing, 3D graphics work and (for the majority of "power users") playing computer games!
For any of these applications, within reason the faster the processor the better. This said,
people in need a very powerful computer have to be aware that CPU performance is now
determined by far more than raw speed alone. Intel made this very clear when it introduced
its system of processor numbers. These provide an indication of a processor's "architecture",
"cache" and "front side bus (FSB) speed" in addition to its clock speed.
Alongside clock speed, the architecture of a processor is the most important factor to
determine its performance, and refers to its basic design and complexity. Some processors are
simply more sophisticated than others, with Intel (for example) producing "basic" processors
called Celerons and Pentiums, as well as more powerful processors under its "Core"
processor family. The later include the Core 2, Core i3, Core i5 and Core i7, with the last of
these being the most powerful.
All Intel Core processors feature more than one "core" -- or in other words more than one
physical processor -- manufactured as a single component. Intel's "Core 2 Duo" chips, for
example, feature two processors core on a single chip, whilst "Core 2 Quad" processors have
four processor cores. In most situations multi-core processors are far more powerful than
traditional single core processors. Quite literally this is because they can do several things at
the same time (something single core processors can only achieve by constantly switching
back and forth between doing one thing and doing another). In turn this means that multi-core
processors can run at lower speeds than single-core processors and yet be far more powerful.
A 2.4GHz Core 2 processor, for example, usually proves far more productive than a single
core 3GHz Pentium processor. All of this hopefully makes it clear why clock speed by itself
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
Intel Celeron, Pentium and Core processors are today all to be found at the heart of new
desktop and laptop PCs. Intel additionally also manufacture very-high-specification chips
named Xeons and Itaniums to drive the most powerful business workstations and servers. If
this range of choice all sounds a bit confusing then to be honest it is -- with Intel itself having
resorted to a range of processor section wizards in an effort to explain its processor ranges on
its own website.
To add further to Intel's abundance of processor choice and complexity, the company also
offers a range of low-power processors called Atoms. These are highly energy efficient, and
were primarily first intended to be used in mobile computers including netbooks. However,
today the latest dual core Atom processors are increasingly finding their way into highly
energy-efficient desktop computers. For many people a computer with the latest 1.66GHz or
1.8GHz dual core Atom processor will be capable of undertaking any computing task they
require, and probably at least four times more energy efficiently than a Celeron, Pentium or
Intel Core based computer. You can watch me construct a dual core Atom-based computer in
the following video:
https://youtu.be/Qv300VDiS2U
In addition to clock speed and architecture, a processor's cache and front side bus (FSB)
speed also determine a computer's overall power. In brief, cache is a form of very fast
memory integrated into the processor chip, and used to store up instructions (work for the
processor) so that it has to slow down as little as possible between tasks. Cache is measured
in megabytes (MB), with (for example) low-end Celeron processors having as little as
0.25MB of cache (256KB), and high-end Itaniums having up to 24MB. The simple message
is, the more cache the better -- though high levels of cache still come at a very significant
price.
Front side bus (FSB) speed is a measure of how fast a microprocessor communicates with the
computer's main circuit board (or "motherboard") into which it is physically connected.
Again, the higher the measure the better for overall performance, with FSB speeds currently
ranging from 533MHz (still perfectly sufficient for the vast majority of applications) up to
1600Mhz.
NOTE: Whilst the examples in the above section all refer to Intel microprocessors, it should
be noted that the PC processor market is dominated by both Intel (with about 80 per cent
market share) and its main rival AMD. AMD's low specification processors are called
Semprons, its mid-range chips called Athlons, and its high-end chips called Phenoms and A-
Series.
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
RAM
RAM -- or "random access memory" -- is the temporary storage space that a computer loads
software applications and user data into when it is running. All current RAM technologies are
"volatile", which means that everything held in RAM is lost when a computer's power is
removed. To a large extent, the more RAM a computer has the faster and more effectively it
will operate. Computers with little RAM have to keep moving data to and from their hard
disks in order to keep running. This tends to make them not just slow in general, but more
annoyingly intermittently sluggish.
[The above all said, those hoping to speed up their PC by installing more RAM need to note
that any PC with a 32 bit operating system can only access a maximum of 4GB of RAM. Add
more, and the PC simply will not recognise it. In practice this that means the vast majority of
PCs in use and being sold today cannot benefit from more than 4GB of RAM -- and this
includes many PCs running Windows 7 (which is very widely sold in its 32 rather than 64 bit
format to maximise compatibility with older software and peripherals).]
RAM is measured in megabytes (MB) and gigabytes (GB), as detailed on the storage page.
Just how much RAM a computer needs depends on the software it is required to run
effectively. A computer running Windows XP will usually function quite happily with 1GB
of RAM, whereas twice this amount (ie 2GB) is the realistic minimum for computers running
Windows 7. Most mobile computers usually feature far less RAM, and indeed even desktop
computers running smaller operating systems (such as some versions of Linux or Windows
98) can run very effectively with as little as 128MB of RAM in certain situations.
GRAPHICS SYSTEM
A computer's graphics system determines how well it can work with visual output. Graphics
systems can either be integrated into a computer's motherboard, or plugged into the
motherboard as a separate "video card". Graphics systems integrated into the motherboard
(also known as "onboard graphics") are now quite powerful, and sufficient for handling the
requirements of most software applications aside from games playing, 3D modelling, and
some forms of video editing.
Any form of modern computer graphics system can now display high-resolution colour
images on a standard-sized display screen (ie any monitor up to about 19" in size). What the
more sophisticated graphics cards now determine is how well a computer can handle the
playback of high definition video, as well as the speed and quality at which 3D scenes
(including games!) can be rendered. Another key feature of separate graphics cards is that
most of them now allow more than one display screen to be connected to a computer. Others
also permit the recording of video.
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
In effect, modern graphics cards have become dedicated computers in their own right, with
their own processor chips and RAM dedicated to video decoding and 3D rendering. Hardly
surprisingly, when it comes to final performance, the more RAM and the faster and more
sophisticated the processor available on a graphics card the better. This said, top-end graphics
cards can cost up to a few thousand dollars or pounds.
Graphics cards connect to what is known as either a "PCI Express" or an "AGP" slot on a
computer's motherboard. PCI Express is the more powerful and modern standard, with the
best graphics cards requiring the use of two PCI Express slots. A PC being upgraded from
onboard graphics sometimes also requires an upgraded power supply if it is to continue to run
in a stable fashion.
Most computers are configured to use a proportion of a computer's internal hard disk to store
temporary files. Such a "swap file" enables the computer to operate effectively, and means
that some free hard disk space always needs to be available for a computer to run properly.
However, providing that a hard disk is large enough to store the required software and user
data without getting beyond about 80 per cent full, hard disk capacity will have no impact on
overall system performance. However, what does impact significantly on overall system
performance is the speed of a computer's main internal hard disk. This is simply because the
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
longer it takes to read software and data from the disk, and to access temporary files, the
slower the computer will run.
Two key factors determine the speed of traditional, spinning hard disks. The first is the
rotational velocity of the physical disk itself. This can currently be 4200, 5400, 7200, 10000
or 15000 rpm (revolutions per minute). The faster the disk spins, the quicker data can be read
from or written to it, hence the faster the disk the better (although faster disks consumer more
power, make more noise, and generate more heat). Most desktop hard disks run at either 5400
or 7200 rpm, whilst most laptop hard disks run at 4200 or 5400. However, upgrading to a
10000 or 15000 rpm disk -- such as a Velociraptor from Western Digital -- can prove one of
the most cost-effective upgrades for increasing the performance and responsiveness of a
desktop computer.
The second key factor that determines performance of a traditional, internal hard disk is the
interface used to connect it to the computer's motherboard. Three types of interface exist:
SATA, which is the most modern and now pretty much the norm on new PCs; IDE (also
known as UDMA), which is a slower and older form of interface, and finally SCSI, which is
happens to be the oldest but in it most modern variant is still the fastest disk interface
standard. This said, SCSI is now all but redundant in desktop computing since the
introduction of SATA, as SATA provides a fairly high speed interface at much lower cost
and complexity than SCSI.
The above points all noted, for users seeking ultimate performance, there is now the option of
installing a computer's operating system, programs and data on a solid state drive (SSD),
rather than a traditional, spinning hard disk. SSDs are far faster and more energy efficient
than traditional, spinning hard disks, which in time they will largely replace. This said, at
present SSDs are still a lot more expensive than traditional spinning hard disks in terms of
cost-per-gigabyte. You can learn more about SSDs on the storage page and/or in the
following video:
https://youtu.be/viac3j6MeII
INPUT DEVICES
Whilst the specification of the components within a computer's system case does matter,
today of far more importance to most users is the range of computer peripherals they have
available -- or in other words the input and output hardware that allows them to interface with
the digital world. Over the past five years in particular, what has mattered most for the
majority of the population have been the quite staggering changes that have taken place in the
ways in which individuals can now create, output and work with computer data. This section
and the next therefore provide a very brief summary of computing input and output devices.
You can also find a more conceptual overview of the development and integration of
computers into the physical world in the Second Digital Revolution section of
ExplainingTheFuture.com.
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
Keyboards remain the dominant means of getting most textual and numeric data into a
computer. Computer keyboards have also changed relatively little over the past couple of
decades. Those developments that have taken place tend to have involved the inclusion of
more and more special function keys, wireless technologies, and improvements to assist with
display screen equipment health and safety regulations. Early IBM PC keyboards, for
example, whilst being extremely robust, had such solid keyboard switches that many people
who typed on them all day soon developed repetitive strain injury problems. In contrast,
modern keyboards (designed for typists rather than engineers who do not spend all day
typing) require a far lighter touch.
Alongside keyboards, mice and pointing devices are the other dominant form of computer
input device. The first mouse was made out of wood at the Stanford Research Institute in the
1960s, with its history now detailed on their MouseSite. The basic principle of moving
around a small, buttoned device to in turn position and select with a pointer on a computer
screen also remains unchanged to this day. What has changed is the variety of "rodents" now
available. Many are now wireless (and hence I guess technically "hamsters"), whilst others
have evolved into pads or trackballs built into laptop computers.
For accurate graphics work such a photo retouching, graphics tablets are now the choice of
many, with a pen or other tool being used on a special surface (the absolute market leader in
this area being Wacom). Many mobile computing devices now also feature a touchscreen that
allows the device used to control a computer to be a pen or finger directly in contact with the
display. Touchscreens are now included on almost all smartphones and tablet computers, as
well as many point of sale systems, and Wacom's lovely Cintiq.
Webcams and digital cameras have over the past ten years also significantly expanded the
way that a great many people work with and think about computers. Digital photography is
now commonplace, with the uploading of images onto a PC for e-mailing, sharing over the
web, or printout, now the norm. I remember in the late 1990s the manager of the largest chain
of photo processing shops in the UK telling me that digital photography would have no real
impact on their business. Oh how wrong he was!
All forms of digital camera continue to converge. Webcams remain devices primarily
designed for capturing movies directly into a PC (perhaps for upload to YouTube), or to
enable desktop videoconferencing. However, many digital stills cameras can also be used as
webcams. Many digital stills cameras can in addition capture video clips, whilst many digital
video cameras can take still photos. Mobile phones of course also share these capabilities.
Developments like Microsoft's surface computer will also make it easier and easier to share
both still and moving images between computers and all kinds of mobile devices in the
future.
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
Alongside cameras, low cost scanners have also allowed millions of us to easily capture
documents and images directly into a computer. In turn, scanners are now converging with
printers -- with multi-function devices (MFDs) now commonly including a printer, scanner,
photocopier and sometimes fax machine. Used with optical character recognition (OCR)
software, scanners also permit the capture not just of images, but of editable text.
Finally on the input side, microphones and audio recorders are now commonly used for
digital data capture. Microphones are obviously needed to permit online audio and video
conferencing. However, the use of portable audio recorders is now also on the increase.
These can capture sound in range of formats, including MP3, WAV, and (for broadcast film
and video purposes) BWF. Fostex is widely regarded as the leading manufacturer of high-end
digital audio recording hardware, although I personally prefer hardware from Tascam!
OUTPUT DEVICES
Display screens remain the dominant form of computing output peripheral, with most new
modern desktop displays being flat panels of between 15" and 19" in diagonal. However, far
more bulky cathode ray tube (CRT) monitors are still favoured by some in high-end graphics
work where absolute colour control is required. For other types of visual output (especially in
education and training) video projectors are now also in widespread use. Whilst most flat
computer displays are currently based on TFT (thin-film transistor) LCD (liquid crystal
display) technology, over the next decade these are likely to be replaced with OLED (organic
light emitting diode) screens as already used on some mobile phones and media players.
[Note that OLED screens should not be confused with LED-backlit LCD screens however
much some manufactures try to confuse potential buyers otherwise. LED-backlit screens are
very nice indeed. OLED are amazing, if currently incredibly expensive.]
With the dream of the paperless office still just that, printers are of course the other dominant
type of computer output hardware. Most printers these days are either laser (where toner is
fused to the paper via a heated drum) or inkjet (where ink is sprayed onto the paper). Both of
these technologies now offer high quality colour output, if with inkjet technologies still just
having the edge for photo printing. Inkjet printers are more expensive to run than laser
printers, but cheaper to buy (largely because most inkjet manufacturers discount the selling
price of the hardware to make their money back on selling ink cartridges and photopaper).
Today, many printers have an integrated scanner and fax machine, and are hence sometimes
referred to as multi-function devices (MFDs) capable of printing, scanning, photocopying and
sending a fax.
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
Printing is also no longer just a flat, 2D process. Whilst yet to become a domestic desktop
technology, 3D printers are now available from companies such as 3D Systems, Solid Scape
and ZCorp. These allow a computer to output a physical 3D object in various plastics, resins
or other materials, or even to print organic tissue! For more information on 3D printing,
please see the 3D printing and bioprinting sections on ExplainingTheFuture.com.
Other computer output hardware includes devices such as speakers (which can cost from a
few pounds to several hundred) as well as Ipods and other music players that millions of
people now use to extract music from their PC to listen to elsewhere. As with digital cameras
(some of which are also music players!), in terms of a paradigm shift this is highly significant
in that a personal computer is rapidly becoming a "digital hub" into which many of our most
used hardware devices are only ever temporarily connected. In turn, one could argue that our
computers are increasingly with us all of the time in the form of those hardware devices that
travel with us, but which functionally depend on at least an occasional interaction with a PC
and often a website.
CONNECTION TECHNOLOGIES
The final thing that really can't be avoided when it comes to explaining hardware is the range
of connection technologies used to plug different input, output and storage devices into a
computer. The following forms of connection physical technology are now in common usage:
USB Ports are now nearly universal. Devices including printers, modems, scanners, digital
cameras and a great many storage devices now connect via USB (the "universal serial bus",
first introduced in 1996). USB currently comes in three standards -- USB 1.1, USB 2.0 and
USB 3.0.
USB 1.1 ports are now only found on older computers, and can transfer data as 12 Mbps
(megabits per second). USB 2.0 ports are by far the most common, and are ten times faster at
480 Mbps. However, recently USB 3.0 has been introduced, with a theoretical maximum data
transfer speed of 4,800 Mbps, or 4.8 Gbps (gigabits per second).
Physically USB 1.1, USB 2.0 and USB 3.0 ports appear pretty much identical. However,
USB 3.0 connectors have an extra set of pins to accommodate higher speed data transfers.
These are positioned in the back of a standard "Type A" plug (and hence in the front of a
standard Type A socket). All other USB 3.0 connectors have been re-designed with a larger
plugs and sockets to accomodate the extra set of pins. This means that USB 3.0 cables cannot
be used with USB 2.0 and USB 1.1 peripherals, although USB 2.0 cables can be used with
USB 3.0 devices, if at USB 2.0 speeds. For ease of identification, all USB cables and
connectors are colour-coded bright blue. You can learn more about USB 3.0 in the following
video:
https://youtu.be/C-N_vN_tmA0
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
VGA or DVI ports are used to connect display screens to computers. DVI is the more modern
standard. However, adapters exist to allow VGA screens to connect to DVI ports and vice-
versa, so in practical terms when purchasing a screen all that really matters is that you get the
right cable. This said a DVI connection should be used if possible when running a high
resolution display (a 19" or greater monitor at anything above 1024x768 resolution) for the
sharpest and most stable picture. This is because the VGA port is an old analogue standard
and was never intended for today's high display resolutions (even thought it often works
reasonably well!).
Some printers still connect to a computer's parallel port. This is starting to cause problems as
many new computers do not have a parallel port! So this is something to check if you are
purchasing a new PC and don't want to change your printer.
Finally in common use are firewire and E-SATA ports. Firewire ports (also known as i-link
or 1394 ports for various legal reasons) are most commonly used to connect digital cameras
and external hard disks to computers. E-SATA ports are used to connect external hard disks
or other external storage devices, such as DVD writers.
ONLINE HARDWARE
High-speed Internet connectivity and cloud computing have recently given rise to a new
phenomenon for hardware resources to be delivered over the Internet. This development was
initially known as "Hardware as a Service" or HaaS. However, this term has now been sub-
divided in common usage into Platform as a Service or PaaS, and Infrastructure as a Service
or IaaS.
Several key cloud computing vendors now offer computing processing capacity and data
storage online. Amazon, for example, now have an IaaS offering called Elastic Compute
Cloud or EC2. This allows users to purchase computer processing power online from
Amazon. Such online hardware capacity is purchased in "instances", with each instance
having its own defined amount of processing power, memory and storage. For example, an
EC2 "small instance" currently comprises 1.7 GB of memory, 1 EC2 Compute Unit (1 virtual
core with 1 EC2 Compute Unit), and 160 GB of storage. Computing instances are charged by
the instance hour consumed, with data transfer charged by the GB.
Renting online hardware can offer many advantages. Amazon, for example, highlight how
EC2 is elastic - because it allows users to increase or decrease their requirements within
minutes, flexible - because users can choose the specification of each individual instance of
computing power, inexpensive - as no dedicated capital investment is required, and reliable -
as EC2 makes use of Amazon's proven data centres and network infrastructure.
EE-163 (Computers & Programming) Department of Electrical Engineering, NEDUET
For many businesses, online hardware is likely to be the future. For more information, please
see the cloud computing page and/or the Cloud Computing Directory for a list of PaaS and
IaaS providers.
SUMMARY
Unless you are a games player, 3D graphics artist or professional video editor, you will
probably find that any modern personal computer will be adequate for your requirements.
The input and output devices you require, as well as the software you wish and need to run,
should therefore primarily drive your hardware needs. So do try to be wary of sales people
trying to flog you hardware of a specification you will not use (such as a PC with a Core i7
processor for accessing the web and running office applications).
Finally, please note that some key hardware issues have not been covered here, as they are
included on the pages for storage (which details back-up devices), networking (which
includes information on wired and wireless networking), the Internet (which details
broadband and how to get online) and green computing (which includes coverage of lower
power hardware). In fact, every other section of this website aside from the Web 2.0 pages
contains some additional information on hardware use or specification. As stated at the start
of this section, computer hardware may in many ways no longer matter as much as it did in
the past. However, equally it has come to provide the infrastructural backbone for so many
human activities that it can now also no longer be completely ignored.
adding conio2 EED FR,IA
Step 5
Go to Linker Settings Tab
In Linker Settings, add a new configuration by clicking ADD. Then in the opened dialog box click
Browse. Locate the following and click Open and then click OK
C:\Program Files\CodeBlocks\MinGW\lib\libconio.a
Page 1 of 3
adding conio2 EED FR,IA
Step 6 Now you shall see the file added in the left window. One final step is to write the command
–lconio (minus sign with lconio, no spaces) in the Other Linker Options (right window). Click OK to
complete.
For 64 Bit OS
Step 1: Locate conio2 folder provided in lesson_06
Step 2: Copy conio2.h file to the following location
C:\ProgramFiles(x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2\include\c++
Step 3: Copy libconio2.a file to the following location
C:\Program Files(x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2
Step 4: Open Code Blocks – Settings – Compiler
Step 5
Go to Linker Settings Tab
Page 2 of 3
adding conio2 EED FR,IA
In Linker Settings, add a new configuration by clicking ADD. Then in the opened dialog box click
Browse. Locate the following and click Open and then click OK
C:\Program Files(x86)\CodeBlocks\MinGW\lib\libconio.a
Step 6 Now you shall see the file added in the left window. One final step is to write the command
–lconio (minus sign with lconio, no spaces) in the Other Linker Options (right window). Click OK to
complete.
Page 3 of 3
EE-163(C&P) Lesson - I EED MHUH, FR
What is Programming?
Computer Programming is defined in wiki books as:
“Computer programming is the craft of writing useful, maintainable, and extensible source code which can
be interpreted or compiled by a computing system to perform a meaningful task.”
Computers are very helpful machines, but we need to program them before using. They can’t do anything
on their own. In order to get a task performed by a computer “you (or someone else) have to tell it exactly
- in excruciating detail - what to do. Such a description of "what to do" is called a program, and
programming is the activity of writing and testing such programs.”
In order to give instructions to the computer, we need to speak to them in a language they understand. Once
we are able to do that we can write instructions for computer. Just like any common language computer
languages also have some vocabulary and grammar. While using those languages it is essential to comply
with the language grammar and use correct vocabulary. Otherwise computer won’t understand us; it may
end up doing something wrong or may get angry at us and throw errors and warnings.
Details about evolution of computer languages can be seen in the book.
Ungraded Assignment:
i. Find differences between Programmers and Users
ii. Create a list of modern programming languages with their preferred targets
Page 1 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Line
Description
No
Pre Processor Directive
to make available facilities from file iostream.h into this program
1 iostream is used when it is required to show some output on monitor, or take input from the
keyboard.
This directive will essentially be present in all the codes we will develop in this course
namespace is an advanced idea, for now just consider it as part of library
2
This line will also be present in all codes
3 A blank space; it has no effect on processing. Used just to make the code look tidy
this is the main function definition (main is a name and reserved keyword for C++)
Every C++ program must have a function called main to tell it where to start. A function is a
named sequence of instructions for computer to execute in order in which they are written. A
function has four parts:
i. A return type (here it is int)
4
ii. Name (main here)
iii. Parameter list (empty here)
iv. Function body, enclosed in a set of curly braces { }, which lists the actions called
statements that the function is to perform.
Understanding endl
les_01_code_02.cpp
1. #include<iostream>
2. using namespace std;
3.
4. int main()
5. {
6. cout<<"Hello"<<endl<<"world!";
7. return 0;
8. }
Page 2 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Exercise
Predict output of the following statements
Statement Output
Ungraded Task
Write a program that prints the following
Bonus Material
IEEE Spectrum Top Ten Programming languages
https://spectrum.ieee.org/computing/software/the-2017-top-programming-languages
Page 3 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
• Names of functions
• Names of arrays
• Names of variables
• Names of classes
Data types are important to understand because certain operations can only be performed on certain data
types. Following chart shows the broad categories of data types available in C++
Data Types
Float (double)
e.g. 3.1413, 53.7
• int can store number hold upto 4 bytes can store number from -2,000,000,000 to +2,000,000,000
(approximately)
• unsigned int can hold up to 4 bytes (only positive numbers) but that doubles the positive range,
ranges between 0 – 4,000,000,000
Data Types for floating point numbers
Page 4 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Only a single character can be stored in a variable of type char, char values are stored as an integer, based
on ASCII value of character e.g. ‘a’
char was important data type when systems had less memory, now a days memory in the systems is ample
so char is not much useful now.
Boolean Data
bool
bool is another data type, it holds true (1) or false (0) values.
Boolean bool
Character char
Integer int
Valueless void
Several of the basic types can be modified using one or more of these type modifiers:
• signed
• unsigned
• short
• long
The following table shows the variable type, how much memory it takes to store the value in memory, and
what is maximum and minimum value which can be stored in such type of variables.
Page 5 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Variables
Variables are named objects with a specific type. (Object is a region of memory with a type.) Variables
can be used to store data of a certain type which can later be used in the program. A variable must be
declared using a legal keyword (listed in table above) and a legal name. Following are the rules to assign
variable names:
Page 6 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
2.
3. using namespace std;
4.
5. int main()
6. {
7. int num1;
8. num1 = 2;
9.
10. char sym;
11. sym = '@';
12.
13. string name;
14. name = "Leo Tolstoy";
15.
16. cout<<"You inserted "<<num1<<" as num1"<<endl;
17. cout<<"You inserted "<<sym<<" as sym"<<endl;
18. cout<<"You inserted "<<name<<" as name"<<endl;
19.
20. return 0;
21. }
Output
les_01_code_04.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7. int num2 = 2.5; // Initialization statement
8. cout<<num2;
9.
10. return 0;
11. }
Output
Page 7 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Common Mistakes
les_01_code_06.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7. int num1 = 7;
8. cout<<Num1;
9.
10. cout<<num2;
11. int num2;
12.
13. strings name;
14.
15. return 0;
16. }
Page 8 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Interactive Computing
Often it is required in a program to take input from the user in run time. This idea of interacting with the
user is called interactive computing. This can be done in C++ thorough standard input stream object cin
(of namespace std) and the stream extraction operator >> (also called get from operator). The following
code will help you to understand the idea.
les_01_code_07.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7. int num1;
8. cout<<"Please enter the value of num1 : ";
9. cin>>num1;
10. cout<<"You Entered : "<<num1;
11.
12. return 0;
13. }
Output
Page 9 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Possible Outputs
i. Entering values separated by space (whitespace is delimiter for cin)
Page 10 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Output
Note that whitespace is delimiter for the cin so everything you typed after Leo is lost
Remedy
Use getline() function to input strings
les_01_code_10.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7. string name;
8. cout<<"Please enter the name : ";
9. getline(cin,name);
10. cout<<"Name you entered is : "<<name;
11.
12. return 0;
13. }
Page 11 of 12
EE-163(C&P) Lesson - I EED MHUH, FR
Output
Run 1
Run 2
Page 12 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
int main()
int number1;
int number2;
int result;
cout<<result;
return 0;
}
In the above program the variable number1 and number2 are called operands and they are connected via
different operators in expressions given on line numbers 16, 17, 18, 19 20. Response of each operation is
stored in the variable result.
Keep in mind that modulus (%) operator is only defined for the data type integers
It is important to emphasis that result of the division is not as we expect in general. This is because the data
type of number1 and number2 is integer, an integer divided by an integer will give an integer response,
while truncating the decimal part of the value. This makes the order of precedence of arithmetic operators
very significant. Consider the following example.
Page 1 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
y = 5 / 2 * 5 + 3 * 5 + 7;
cout<<y;
y = 5 * 5 / 2 + 3 * 5 + 7;
cout<<y;
les_02_code_02.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7.
8. int number1 = 74, number2 = 82, number3 = 88;
9. double average;
10. average = number1 + number2 + number3 / 3;
11. cout<<average;
12. return 0;
13. }
Page 2 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
les_02_code_03.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7.
8. int number1 = 74, number2 = 82, number3 = 88;
9. double average;
10. average = (number1 + number2 + number3) / 3;
11. cout<<average;
12. return 0;
13. }
If the value of constant is tried to be changed during the program the compiler will throw an error
Page 3 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
Page 4 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
Output
Task: Write a program that takes the angle input from the user in degrees and find its
cos, sin and tan.
Page 5 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
Output
Page 6 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
Output
Page 7 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
Output
les_02_code_09.cpp
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main ()
7. {
8. cout<<"fmod(5.3, 2.0) = "<<fmod(5.3,2)<<endl;
9. cout<<"fmod(18.5, 4.2) = "<<fmod (18.5,4.2)<<endl;
10. return 0;
11. }
Output
les_02_code_10.cpp
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main ()
7. {
8. float num1 = -9.5;
9. cout<<fabs(num1);
10.
11. return 0;
12. }
Page 8 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
Write a program that takes a floating point input from the user, finds its square, cube,
square root, floor, truncate, ceiling and round off, natural log, base 10 log.
Type Casting
les_02_code_11.cpp
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main ()
7. {
8. float num1 = -9.5;
9. int num2 = 101;
10. cout<<(int)num1;
11. cout<<endl<<(float)num2/10;
12.
13. return 0;
14. }
Output
Page 9 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
Output
Page 10 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
les_02_code_13.cpp
1. #include<iostream>
2. #include<cmath>
3. #include<iomanip>
4.
5. using namespace std;
6.
7. int main()
8. {
9.
10. cout<<0.1234567809<<endl;
11. cout<<setprecision(10)<<0.1234567809<<endl;
12. cout<<setprecision(12)<<0.123412341234<<endl;
13. cout<<setprecision(8)<<0.12341234<<endl;
14. return 0;
15. }
Output
les_02_code_14.cpp
1. #include<iostream>
2. #include<iomanip>
3. #include<cmath>
5. int main()
6. {
7. double num1 = 2.3,num2 = 3.8,num3 = 5.5,num4 = -2.3,num5 = -
3.8,num6 = -5.5;
8. cout<<setw(8)<<"value"<<setw(8)<<"round"<<setw(8)<<"floor"<<setw(
8)<<"ceil"<<setw(8)<<"trunc\n";
9. cout<<setw(8)<<"-----"<<setw(8)<<"-----"<<setw(8)<<"-----
"<<setw(8)<<"-----"<<setw(8)<<"-----\n";
10. cout<<setw(8)<<num1<<setw(8)<<round(num1)<<setw(8)<<floor(num1)<<
setw(8)<<ceil(num1)<<setw(8)<<trunc(num1)<<"\n";
11. cout<<setw(8)<<num2<<setw(8)<<round(num2)<<setw(8)<<floor(num2)<<
setw(8)<<ceil(num2)<<setw(8)<<trunc(num2)<<"\n";
12. cout<<setw(8)<<num3<<setw(8)<<round(num3)<<setw(8)<<floor(num3)<<
setw(8)<<ceil(num3)<<setw(8)<<trunc(num3)<<"\n";
Page 11 of 12
EE-163(C&P) lesson_02 EED MHUH, FR
13. cout<<setw(8)<<num4<<setw(8)<<round(num4)<<setw(8)<<floor(num4)<<
setw(8)<<ceil(num4)<<setw(8)<<trunc(num4)<<"\n";
14. cout<<setw(8)<<num5<<setw(8)<<round(num5)<<setw(8)<<floor(num5)<<
setw(8)<<ceil(num5)<<setw(8)<<trunc(num5)<<"\n";
15. cout<<setw(8)<<num6<<setw(8)<<round(num6)<<setw(8)<<floor(num6)<<
setw(8)<<ceil(num6)<<setw(8)<<trunc(num6)<<"\n";
16. return 0;
17. }
Output
Exercise
Write a note on the importance of operator precedence, also emphasis why your
portable calculator don’t cause that problem.
Try to use cmath library functions with integer data types and find out the possible
problems.
Page 12 of 12
EE-163(C&P) lesson_03 EED MHUH, FR
String Manipulation
This is a brief and a quick lesson about string manipulation. C++ provides very useful features to
manipulate strings, this is necessary to understand for making useful programs for real projects.
les_03_code_01.cpp
1. #include<iostream>
3. int main()
4. {
5. string _str1, _str2, _str3, _str4, _str5;
6. _str1 = "Pakistan";
7. _str2 = "The quick brown fox jumps over a lazy dog";
8. _str3 = "0010-0100-8763-9921";
9. _str4 = "Hello";
10. _str5 = "World";
21. cout<<endl<<_str4;
Page 1 of 6
EE-163(C&P) lesson_03 EED MHUH, FR
41. _str6.replace(12,3,"for");
42. cout<<endl<<_str6;
43. return 0;
44. }
substr() function
substr() is used to access a portion of a string (sub-string), this function can be used in the following
styles
for a string _str1
_str1.substr(3)
This will pull all the characters starting from location 3, please note that location numbering starts from 0
and not 1
_str1.substr(3,5)
String Concatenation
Two or more strings can be concatenated through concatenation operator ‘+’, see for example
cout<<_str4+_str5;
Page 2 of 6
EE-163(C&P) lesson_03 EED MHUH, FR
find() function
find() is used to get the location (starting location for substring) of a character from the string or a
substring, for example .
cout<<endl<<_str4.find('o');
If a character occurs more than once in a string then find() will return the location of first occurrence.
rfind() (reverse find) can be used to find the location of a character (or a sub string) from the reverse
order
find() can also be used to find the starting location of a substring, for example
cout<<endl<<_str2.find("fox");
size() function
Size of the string can be found using size() function, for example
cout<<endl<<_str2.size();
Page 3 of 6
EE-163(C&P) lesson_03 EED MHUH, FR
erase() function
A portion of the string can be erased with this function, for example
string _str6 = "Application and Project Engineer";
_str6.erase(12,4);
replace() function
This is used to replace a portion of a string (sub string) with another string, for example
cout<<endl<<_str6;
_str6.replace(12,3,"for");
cout<<endl<<_str6;
Another example
string _str1 = "Smile, because it confuses people.\nSmile, because it's
easier than explaining what is killing you inside.";
string _str2 = "killing";
int loc = _str1.find(_str2);
int width = _str2.size();
_str1.replace(loc,width,"burning");
cout<<_str1;
Output
Page 4 of 6
EE-163(C&P) lesson_03 EED MHUH, FR
les_03_code_02.cpp
1. // les_03_code_02.cpp
2. // Some more functions and operations for strings
3. // following functions are explained in this code
14. #include<iostream>
Page 5 of 6
EE-163(C&P) lesson_03 EED MHUH, FR
44. //Modifiers
45. _str2 = "Stretched to the point of no turning back";
46. cout<<"\n_str2 = "<<_str2;
47. //let's modify _str2
48. _str2.append(" A flight of fancy on a windswept field");
49. cout<<"\n_str2 = "<<_str2;
55. return 0;
56. }
Output
Page 6 of 6
EE-163(C&P) lesson_04 EED FR, IA
Decision Making
Often it is required to decide whether a certain block of code be executed or not, based on some predefined
conditions. This decision making requires the use of relational, equality and logical operators. Let us first
introduce these operators.
Equality Operators
S. No Operator Name Description and Example
This operator tests if the given operands are
equal. In case if they are equal it yields a
1 == Equal Boolean true, otherwise false
2 == 5;
This will be false because 2 is not equal to 5
This operator tests if the given operands are not
equal. In case if they are not equal it yields a
2 != Not Equal Boolean true, otherwise false
2 != 5;
This will be true because 2 is not equal to 5
Relational Operators
This operator tests if the first operand is less
than the second operand. If so it yields a
3 < Less than Boolean true, otherwise false
2 < 5;
This will be true because 2 is less than 5
This operator tests if the first operand is greater
than the second operand. If so it yields a
4 > Greater than Boolean true, otherwise false
2 > 5;
This will be false because 2 is not greater than 5
This operator tests if the first operand is less
than or equal to the second operand. If so it
5 <= Less than or equal to yields a Boolean true, otherwise false
2 <= 5;
This will be true because 2 is less than 5
This operator tests if the first operand is greater
than or equal to the second operand. If so it
6 >= Greater than or equal to yields a Boolean true, otherwise false
2 >= 5;
This will be false because 2 is not greater than 5
Page 1 of 13
EE-163(C&P) lesson_04 EED FR, IA
les_04_code_01.cpp
1. #include<iostream>
3. int main ()
4. {
5. int num1 = 10, num2 = 5, num3 = -9, num4 = 5;
6. cout<<(num1>num2)<<endl;
7. cout<<(num2<num3)<<endl;
8. cout<<(num2>=num4)<<endl;
9. cout<<(num3<=num4)<<endl;
10. cout<<(num2==num4)<<endl;
11. cout<<(num1!=num2)<<endl;
12. return 0;
13. }
Logical Operators
In cases where more than one relational and equality operators simultaneously decide the final result, logical
operators help in getting the simultaneous relation. Logical operators work on Binary Operands, their result
depends on the combined states of operands.
There are two logical operators (of our interest right now).
i. OR (||)
ii. AND (&&)
Page 2 of 13
EE-163(C&P) lesson_04 EED FR, IA
Logical operators work on Binary Operands, their result depends on the combined states of operands. For
the two operands x and y (both Boolean), the OR (||) operator works according to the following truth table.
x y x||y
0 0 0
0 1 1
1 0 1
1 1 1
les_04_code_02.cpp
1. #include<iostream>
3. int main ()
4. {
5. int num1 = 10, num2 = 5, num3 = -9, num4 = 5;
7. res1 = (num1<num2)&&(num2>num3);
8. cout<<"\t(num1<num2)&&(num2>num3)\t"<<res1;
9. res2 = (num1<num2)||(num2>num3);
10. cout<<"\n\t(num1<num2)||(num2>num3)\t"<<res2;
13. return 0;
14. }
Page 3 of 13
EE-163(C&P) lesson_04 EED FR, IA
At this point it is important to discuss the associativity and precedence order of these new operators
introduced. The following screenshot from textbook page 55 will help you to understand. Precedence
decrease from top to bottom.
For more details please read section 2.7 of textbook (Dietel & Dietel)
if statement
if statement is used to execute a certain block of a program, based on predefined decision.
------------------------------syntax-----------------------------------------
if (relational expression)
{
//body of if statement
-----------------------------------------------------------------------------
les_04_code_03.cpp
1. #include<iostream>
3. int main()
4. {
5. int hoursWorked;
6. double rate, grossPay;
7. cout << "Enter the hours worked: ";
8. cin >> hoursWorked;
9. cout << "Enter the rate of pay: ";
Page 4 of 13
EE-163(C&P) lesson_04 EED FR, IA
21. }
Output Run 1
Output Run 2
if else statement
if else statement is used to choose between certain blocks based on the relational expression if it is true or
false. Both have a separate block and only one of them will be executed.
Note : There will be only one relational expression for if else
------------------------------syntax-----------------------------------------
if (relational expression)
{
//body of if statement
statements to be executed if relational expression is true
}
else
{
//body of else statement
statements to be executed if relational expression is false
}
----------------------------------------------------------------------------
Page 5 of 13
EE-163(C&P) lesson_04 EED FR, IA
les_04_code_04.cpp
1. #include<iostream>
3. int main()
4. {
5. int hoursWorked;
6. double rate, grossPay;
15. else
16. {
17. grossPay = (40 * rate) + ((hoursWorked-40) * (rate * 1.5));
18. }
19. cout << "Gross pay is: " << grossPay << endl;
20. return 0;
21. }
Nested if else
les_04_code_05.cpp
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int age;
6. cout<<"Please enter your age : ";
7. cin>>age;
8. if(age<18)
9. {
10. cout<<"You can't vote."<<endl;
11. if (age>=16)
12. {
Page 6 of 13
EE-163(C&P) lesson_04 EED FR, IA
19. }
20. else
21. {
22. cout<<"You can vote."<<endl;
23. cout<<"You can drive."<<endl;
24. if(age>=21)
25. {
26. cout<<"You can also participate in elections."<<endl;
27. }
28. else
29. {
30. cout<<"But you can't participate in elections."<<endl;
31. }
32. }
33. return 0;
34. }
Output Run 1
Output Run 2
Page 7 of 13
EE-163(C&P) lesson_04 EED FR, IA
Output Run 3
Output Run 4
if else if construct
Sometimes it is required to decide among several blocks based on certain conditions e.g. To decide the
grade of a student based on marks obtained. This can be achieved by the nested if - else construct. But it is
not a good programming practice. Better way is to use if else if construct.
-----------------------------------------------------------------------------
SYNTAX
-----------------------------------------------------------------------------
if (test condition 1)
{
body of if
}
Page 8 of 13
EE-163(C&P) lesson_04 EED FR, IA
else
{
body of else // this is optional and will only be executed if none of the
test
// conditions are true
}
-----------------------------------------------------------------------------
EXAMPLE
-----------------------------------------------------------------------------
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^GradingScale^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
90 - 100 A
80 - 89 B
70 - 79 C
60 - 69 D
00 - 59 F
les_04_code_06.cpp
1. #include<iostream>
3. int main ()
4. {
5. // suitable variables declaration
6. int marks;
7. string letterGrade;
12. if(marks>=90)
13. {
14. letterGrade = "A";
15. }
Page 9 of 13
EE-163(C&P) lesson_04 EED FR, IA
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Grading Scale^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
97 - 100 A+
93 - 96 A
90 - 92 A-
87 - 89 B+
83 - 86 B
80 - 82 B-
77 - 79 C+
73 - 76 C
70 - 72 C-
67 - 69 D+
63 - 66 D
60 - 62 D-
00 - 59 F
Page 10 of 13
EE-163(C&P) lesson_04 EED FR, IA
les_04_code_07.cpp
1. #include<iostream>
3. int main ()
4. {
5. // suitable variables declaration
6. int marks;
7. string letterGrade;
12. if((marks>=97)&&(marks<=100))
13. {
14. letterGrade = "A+";
15. }
16. else if ((marks >= 93)&&(marks <= 96))
17. {
18. letterGrade = "A";
19. }
20. else if ((marks >= 90)&&(marks <= 92))
21. {
22. letterGrade = "A-";
23. }
24. else if((marks>=87)&&(marks<=89))
25. {
26. letterGrade = "B+";
27. }
28. else if ((marks >= 83)&&(marks <= 86))
29. {
30. letterGrade = "B";
31. }
32. else if ((marks >= 80)&&(marks <= 82))
33. {
34. letterGrade = "B-";
35. }
Page 11 of 13
EE-163(C&P) lesson_04 EED FR, IA
Task
In the lesson_04 folder, there is a file game.exe, run this file and observe how it works
(the correct answer is Watson). Your assignment is to write a code to replicate the
same program.
Bonus Program
les_04_code_08.cpp
1. #include <iostream>
3. int main()
4. {
Page 12 of 13
EE-163(C&P) lesson_04 EED FR, IA
9. if (op == '*')
10. {
11. result = operand1 * operand2;
12. cout << "result: " << result << endl;
13. }
14. else if (op == '/')
15. {
16. result = operand1 / operand2;
17. cout << "result: " << result << endl;
18. }
19. else if (op == '+')
20. {
21. result = operand1 + operand2;
22. cout << "result: " << result << endl;
23. }
24. else if (op == '-')
25. {
26. result = operand1 - operand2;
27. cout << "result: " << result << endl;
28. }
29. else
30. cout << "Bad expression." << endl;
31. return 0;
32. }
Page 13 of 13
EE-163(C&P) lesson_05 EED FR, IA
Loops
One of the very powerful control structures is Repetition Statements in C++. Repetition statements allow
to repeat a block of code until a certain condition is true. Repetition statements are commonly referred
as loops and they can be implemented in the following ways
i. while
ii. for
iii. do while
In this lesson, repetition statements i & ii are discussed. (Students can learn iii by themselves)
while Loop
while loop is implemented using the following style.
Statements written inside the body of the while loop will continue to repeat until the rel exp becomes
false. There must be a statement inside the body that will eventually make the rel exp false. Otherwise the
loop will run infinite times. This is explained in the following codes.
les_05_code_01.cpp
1. #include<iostream>
2. using namespace std;
Page 1 of 10
EE-163(C&P) lesson_05 EED FR, IA
les_05_code_02.cpp
// infinite while loop
// objective of this code is to introduce the idea of infinite loop
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int count = 0;
6. while(count < 10)
7. {
a. cout<<"Hello World!\n";
8. }
9. return 0;
10. }
Page 2 of 10
EE-163(C&P) lesson_05 EED FR, IA
If the relational expression becomes false after a certain count is achieved, the while loop is count
controlled. les_05_code_01.cpp is the example of count controlled while loop. Let’s see another example
of count controlled while loop implementation.
les_05_code_03.cpp
// count controlled while loop
// interest calculation
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. double balance, rate;
6. int years, count;
7. cout<<"What is the starting balance : ";
8. cin>>balance;
9. cout<<"What is the annual interest rate : ";
10. cin>>rate;
11. cout<<"How many years to calculate interest : ";
12. cin>>years;
13. count = 1;
14. while(count <= years)
15. {
16. balance *= rate;
17. ++count;
18. }
19. cout<<"After "<<years<<" years, balance will be "
20. <<balance<<endl;
21. return 0;
22. }
Output
les_05_code_04.cpp
// count controlled while loop
// interest calculation modified
1. #include<iostream>
2. using namespace std;
3. int main()
Page 3 of 10
EE-163(C&P) lesson_05 EED FR, IA
4. {
5. double balance, rate;
6. int years, count;
7. cout<<"What is the starting balance : ";
8. cin>>balance;
9. cout<<"What is the annual interest rate : ";
10. cin>>rate;
11. cout<<"How many years to calculate interest : ";
12. cin>>years;
13. count = 1;
14. while(count <= years)
15. {
16. balance *= rate;
17. cout<<count<<" : "<<balance<<endl;
18. ++count;
19. }
20. cout<<"After "<<years<<" years, balance will be "
21. <<balance<<endl;
22. return 0;
23. }
Output
Page 4 of 10
EE-163(C&P) lesson_05 EED FR, IA
Sentinel Controlled
If the relational expression is controlled on the basis of a certain input, the while loop is termed as sentinel
control. See the example
// les_05_code_05.cpp
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int grade, gradeTotal, numGrades;
6. numGrades = gradeTotal = 0;
7. double average;
8. cout<<"Enter grade or -1 to quit : ";
9. cin>>grade;
10.
11. while(grade != -1)
12. {
13. gradeTotal += grade;
14. ++numGrades;
15. cout<<"Enter grade or -1 to quit : ";
16. cin>>grade;
17. }
18.
19. average = (float)gradeTotal/numGrades;
20. cout<<"Average grade is : "<<average;
21. return 0;
22. }
Output
Write a program that take two numbers from user and multiply them without using *
(multiplication) operator.
Solution is in les_05_code_06.cpp
Page 5 of 10
EE-163(C&P) lesson_05 EED FR, IA
for Loop
One another way to implement the repetition statements in C++ is to use for loop. For loop is always
count controlled. The following code will help you learn the syntax and idea of for loop. (Note it is
possible to use while instead of for and for instead of while in many cases, so as a student you should
learn both and practice enough to recognize when to use what)
les_05_code_07.cpp
// for loop
// syntax
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i = 1; i<11; i++)
6. {
7. cout<<"Hello World\n";
8. }
9. return 0;
10. }
Output
les_05_code_08.cpp
// for loop with manual increment
1. #include<iostream>
2. using namespace std;
3. int main()
Page 6 of 10
EE-163(C&P) lesson_05 EED FR, IA
4. {
5. for(int i = 1; i<11; i+=2)
6. {
7. cout<<i<<" Hello World\n";
8. }
9. return 0;
10. }
Output
les_05_code_09.cpp
// interest calculation with for loop
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. double balance, rate;
6. int years;
7. cout<<"What is the starting balance : ";
8. cin>>balance;
9. cout<<"What is the annual interest rate : ";
10. cin>>rate;
11. cout<<"How many years to calculate interest : ";
12. cin>>years;
13. for(int i = 1; i<=years; ++i)
14. {
15. balance *= rate;
16. }
17. cout<<"After "<<years<<" years, balance will be "
18. <<balance<<endl;
19. return 0;
20. }
Output
Page 7 of 10
EE-163(C&P) lesson_05 EED FR, IA
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. char star = '*';
6. for (int i = 0; i < 5; ++i)
7. {
8. for(int j = 0; j < 5; ++j)
9. {
10. cout<<star;
11. }
12. cout<<endl;
13. }
14. return 0;
15. }
Output
les_05_code_11.cpp
// nested for loop
1. #include<iostream>
2. using namespace std;
Page 8 of 10
EE-163(C&P) lesson_05 EED FR, IA
3. int main()
4. {
5. char star = '*';
6. for (int i = 0; i < 5; ++i)
7. {
8. for(int j = 0; j <= i; ++j)
9. {
10. cout<<star;
11. }
12. cout<<endl;
13. }
14. return 0;
15. }
Output
Page 9 of 10
EE-163(C&P) lesson_05 EED FR, IA
20. cout<<endl;
21. }
22. return 0;
23. }
Output
les_05_code_13.cpp
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. for(int row = 1; row <= 5; ++row)
6. {
7. for(int col = 1; col <= 5; ++col)
8. {
9. cout<<row<<" * "<<col<<" = "
10. <<row * col<<"\t";
11. }
12. cout<<endl;
13. }
14. }
Output
Page 10 of 10
EE-163(C&P) lesson_06 EED FR, IA
Algorithm
According to the author of our reference book [Dietel & Dietel], algorithm is defined as
“Any solvable computing problem can be solved by executing of a series of actions in a specific order. A
procedure for solving a problem in terms of
1. The actions to execute
2. The order in which the actions execute
is called an algorithm.”
Objective of this lesson is to implement some simple algorithms using repetition statements.
les_06_code_01.cpp
Fibonacci Sequence with for loop
1. #include<iostream>
2. using namespace std;
3. int main (void)
4. {
5. // variable definition
6. int counter, n_terms;
7. cout<<"How many terms to generate : ";
8. cin>>n_terms;
9. // initializing newterm and prevterm to 1
10. //sum cantains the next number in the sequence
11. int newterm=1,prevterm=1,sum;
12. cout<<"\t\t Fibonacci Series"<<endl;
13. // display the first term
14. cout<<prevterm<<" ";
15. // for rest of the terms
16. for(counter=1;counter<n_terms;counter++)
17. {
18. if(counter%10==0)cout<<endl;
19. cout<<newterm<<" ";
20. sum=prevterm+newterm;
21. prevterm=newterm;
22. newterm=sum;
23. }
24. return 0;
25. }
Page 1 of 13
EE-163(C&P) lesson_06 EED FR, IA
Sample Output
les_06_code_02.cpp
Generating Fibonacci Series and computing Golden ratio by dividing successive terms
1. #include<iostream>
25. return 0;
26. }
Page 2 of 13
EE-163(C&P) lesson_06 EED FR, IA
Sample Output
les_06_code_03.cpp
Running sum with while loop
1. #include<iostream>
2. using namespace std;
3. int main(void)
4. {
5. // variable definition
6. int num,running_sum=0;
Page 3 of 13
EE-163(C&P) lesson_06 EED FR, IA
16. cin>>num;
17. running_sum=running_sum+num;
18. }
19.
20. // displaying why the program has stopped
21. cout<<"\nSorry. Your running sum exceeded 1000.";
22. return 0;
23. }
Sample Output
les_06_code_04.cpp
Digit counting (UIY Program)
1. #include<iostream>
Page 4 of 13
EE-163(C&P) lesson_06 EED FR, IA
21. return 0;
22. }
23. // NOTE: The program is not valid for -ve numbers but can be made to
work if
24. // we make num_alias +ve, if it is -ve.
les_06_code_05.cpp
Character(s), word(s) and sentence(s) calculation
1. #include<iostream>
2. #include<conio.h>
3. using namespace std;
4. int main(void)
5. {
6. // variable definition
7. // to count characters, words and sentences
8. int ch_cnt=0,word_cnt=0,sentence_cnt=0;
Page 5 of 13
EE-163(C&P) lesson_06 EED FR, IA
Sample Output
Page 6 of 13
EE-163(C&P) lesson_06 EED FR, IA
les_06_code_06.cpp
Finding GCD , the Naive method
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int first_number;
6. cout<<"Enter First Number : ";cin>>first_number;
7. int second_number;
8. cout<<"Enter Second Number: ";cin>>second_number;
9. int gcd;
10. for(int i=1;i<=first_number&&i<=second_number;i++)
11. {
12. if(first_number%i==0 && second_number%i == 0 )
13. {
14. gcd=i;
15. }
16. }
Sample Output
les_06_code_07.cpp
Euclid Subtraction GCD Algorithm
1. #include <iostream>
3. int main()
4. {
Page 7 of 13
EE-163(C&P) lesson_06 EED FR, IA
Sample Output
les_06_code_08.cpp
Faster Euclid GCD
1. #include <iostream>
3. int main()
4. {
5. int a, b;
6. cin >> a >> b;
7. while (b != 0)
8. {
9. int r = a%b;
10. a = b;
11. b = r;
12. }
13. cout <<"GCD : "<< a << endl;
14. return 0;
15. }
Page 8 of 13
EE-163(C&P) lesson_06 EED FR, IA
Sample Output
les_06_code_10.cpp
Prime Testing Naive Method
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int num;
6. cout << "Enter a number: ";
7. cin >> num;
8. for (int i = 2; i < num; i++)
9. {
10. if (num%i == 0)
11. {
12. cout << "The number is not prime" << endl;
13. return 0;
14. }
15. }
16. cout << "The number is prime" << endl;
17. return 0;
18. }
Sample Outputs
les_06_code_11.cpp
Prime Testing improved version
1. #include<iostream>
2. #include<conio2.h>
3. #include<cmath>
4. using namespace std;
Page 9 of 13
EE-163(C&P) lesson_06 EED FR, IA
38. }
39. if(remainder!=0)
40. {
41. cout<<"\n Prime";
42. }
43. return 0;
44. }
Page 10 of 13
EE-163(C&P) lesson_06 EED FR, IA
les_06_code_12.cpp
Square Root using Newton Raphson Method
1. #include<iostream>
2. #include<conio2.h>
3. #include<cmath>
4. using namespace std;
5. int main(void)
6. {
7. float N,low,high,root;
8. cout<<"Enter a +ve number to calculate its square root:";
9. cin>>N;
10. if(N<0)
11. {
12. cout<<"\n Sorry, wrong input, Re-run the program";
13. }
14. else
15. {
16. root=N/2.0;
17. while(fabs(((root*root)-N))>0.0001)
18. {
19. root=root-((root*root-N)/(2.0*root));
20. }
21. }
22. cout<<"\n square root of "<<N<<" = "<<root;
23. return 0;
24. }
les_06_code_12.cpp
Square Root using Bisection Method
1. #include<iostream>
2. #include<conio2.h>
3. #include<cmath>
4. using namespace std;
5. int main(void)
6. {
7. float N,low,high,root;
8. cout<<"Enter a +ve number to calculate its square root:";
9. cin>>N;
10. if(N<0)
11. {
12. cout<<"\nSorry, wrong input, Re-run the program";
13. }
14. else
15. {
16. low=0.0;
17. if(N>1.0)// if number is greater than 1 (eg. 1.7)
Page 11 of 13
EE-163(C&P) lesson_06 EED FR, IA
18. {
19. high=N;
20. }
21. else // if number is less than 1 (eg. 0.5)
22. {
23. high=1.0;
24. }
25. root=(low+high)/2.0;
26. while(fabs(((root*root)-N))>0.0001)
27. {
28. if((root*root)<N)
29. {
30. low=root;
31. }
32. else
33. {
34. high=root;
35. }
36. root=(low+high)/2.0;
37. } // end of while()
38. } // end of else
39. cout<<"\n square root of "<<N<<" = "<<root;
40. return 0;
41. }
les_06_code_14.cpp
Trapezoidal Integration
1. #include<iostream>
2. #include<conio2.h>
3. #include<cmath>
4. using namespace std;
5. int main(void)
6. {
7. double x, delta_x=0.001, xmin, xmax, sum=0.0, fx1, fx2;
8. int counter, counter_max;
9. cout<<"Enter the value of xmin in radian:";
10. cin>>xmin;
11. cout<<"Enter the value of xmax in radian:";
12. cin>>xmax;
13. counter_max=((xmax-xmin)/delta_x)+1;
14. x=xmin;
15. for(counter=1;counter<=counter_max;counter++)
16. {
17. fx1=cos(x);// integrating sin function
18. fx2=cos(x+delta_x);
19. sum=sum+(0.5*(fx1+fx2));
20. x=x+delta_x;
21. }
Page 12 of 13
EE-163(C&P) lesson_06 EED FR, IA
22. sum=sum*delta_x;
23. cout<<"integral= "<<sum;
24. return 0;
25. }
Page 13 of 13
EE-163(C&P) lesson_07 EED FR, IA
9. int main()
10. {
11. int my_num;
12. cout<<"Enter a number : ";
13. cin>>my_num;
14. cout<<"Square of "<<my_num<<" is "<<square(my_num);
15. return 0;
16. }
les_07_code_02.cpp
Alternate implementation of les_07_code_01.cpp
1. #include<iostream>
2. using namespace std;
7. int main()
8. {
9. int my_num;
10. cout<<"Enter a number : ";
11. cin>>my_num;
12. cout<<"Square of "<<my_num<<" is "<<square(my_num);
13. return 0;
14. }
Page 1 of 9
EE-163(C&P) lesson_07 EED FR, IA
les_07_code_03.cpp
Function with multiple parameters
1. #include<iostream>
2. using namespace std;
19. }
les_07_code_04.cpp
Function call from other then main
1. #include<iostream>
2. using namespace std;
3.
4. double ftoc(double temp)
5. {
6. return (temp-32.0)*(5.0/9.0);
7. }
8.
9. double ctof(double temp)
10. {
11. return (temp*(9.0/5.0) + 32.0);
12. }
13.
14. double convertTemp(double temp, char scale)
15. {
16. if(scale == 'c' || scale == 'C')
Page 2 of 9
EE-163(C&P) lesson_07 EED FR, IA
17. {
18. cout<<"Converted from F to C"<<endl;
19. return ftoc(temp);
20. }
21.
22. else if (scale == 'f' || scale == 'F')
23. {
24. cout<<"Converted from C to F"<<endl;
25. return ctof(temp);
26. }
27. else
28. {
29. cout<<"*****ERROR*****"<<endl<<"Invalid Scale"<<endl;
30. return 0;
31. }
32. }
33.
34. int main()
35. {
36. double act_temp, conv_temp;
37. char conv_to;
38. cout<<"Enter temperature and unit to convert to : ";
39. cin>>act_temp>>conv_to;
40. conv_temp=convertTemp(act_temp,conv_to);
41. cout<<"The converted temperature is "<<conv_temp<<endl;
42. return 0;
43. }
les_07_code_05.cpp
Predicate Functions
1. #include<iostream>
2. using namespace std;
3.
4. bool isEven(int num)
5. {
6. if (num%2 == 0)
7. return true;
8. else
9. return false;
10. }
11.
12. int main(void)
13. {
14. int val;
15. cout<<"Enter a number to test : ";
16. cin>>val;
17. if(isEven(val))
Page 3 of 9
EE-163(C&P) lesson_07 EED FR, IA
les_07_code_06.cpp
Predicate function to check vowel
1. #include<iostream>
2. using namespace std;
3.
4. bool isVowel(char letter)
5. {
6. if(letter=='a'||letter=='e'||letter=='i'||letter=='o'||letter=='u')
7. return true;
8. else
9. return false;
10. }
11.
12. int main()
13. {
14. char ltr;
15. cout<<"Enter an alphabet in lower case only : ";
16. cin>>ltr;
17. if(isVowel(ltr))
18. cout<<ltr<<" is a vowel.";
19. else
20. cout<<ltr<<" is a consonant.";
21. return 0;
22. }
les_07_code_07.cpp
Void Functions
1. #include<iostream>
2. using namespace std;
3. void Heading()
4. {
5. cout<<"************************************"<<endl;
6. cout<<"** EE-163 Computers & Programming **"<<endl;
7. cout<<"** FE - Electrical **"<<endl;
8. cout<<"************************************"<<endl;
9. }
Page 4 of 9
EE-163(C&P) lesson_07 EED FR, IA
12. Heading();
13. return 0;
14. }
les_07_code_08.cpp
Void Functions
1. #include<iostream>
2. using namespace std;
3. void Heading(string course, string batch)
4. {
5. cout<<"************************************"<<endl;
6. cout<<"** "<<course<<" **"<<endl;
7. cout<<"** "<<batch<<" **"<<endl;
8. cout<<"************************************"<<endl;
9. }
les_07_code_09.cpp
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int num1, num2;
6. num1 = 13;
7. num2 = 12;
8. cout<<num1<<endl;
9. cout<<num2<<endl;
10. int temp;
11. temp = num2;
12. num2 = num1;
13. num1 = temp;
14. cout<<num1<<endl;
15. cout<<num2<<endl;
16. return 0;
17. }
les_07_code_10.cpp
1. #include<iostream>
2. using namespace std;
Page 5 of 9
EE-163(C&P) lesson_07 EED FR, IA
4. {
5. int temp;
6. temp = b;
7. b = a;
8. a = temp;
9. }
les_07_code_11.cpp
Pass by reference
1. #include<iostream>
2. using namespace std;
9. }
Page 6 of 9
EE-163(C&P) lesson_07 EED FR, IA
Recursion
les_07_code_12.cpp
infinite_recursion.cpp
1. #include<iostream>
2. using namespace std;
3. void infinite_recursion (void);
4. //main
5. int main ()
6. {
7. cout<<"Making an infinite call";
8. infinite_recursion();
9. }
les_07_code_13.cpp
factorial with recursion
1. #include<iostream>
2.
3. using namespace std;
4.
5. unsigned long factorial(unsigned long val); //Prototype for
factorial function
6. int main ()
7. {
8. unsigned long num;
9. cout<<endl<<"Enter a No. to find its factorial ";
10. cin>>num;
11.
12. cout<<endl<<num<<" ! is = "<<factorial(num);
13.
14. return 0;
15.
16. }
17.
18. unsigned long factorial(unsigned long val)
19. {
20. if(val == 1 || val == 0)
Page 7 of 9
EE-163(C&P) lesson_07 EED FR, IA
21. {
22. return 1;
23. }
24.
25. if(val>1)
26. {
27. cout<<endl<<"At Recursive call val was :"<<val;
28. return val* factorial(val-1);
29. }
30. }
les_07_code_14.cpp
exponent of a number with recursion
1. #include<iostream>
2.
3. using namespace std;
4. // Prototype
5. int intpower(int base, int exp);
6. // Calculates power for int base and exponent
7. int main(void)
8. {
9. int a,b;
10. cout<<"\nEnter two integers:";
11. cin>>a>>b;
12. cout<<"\n\n"<<a<<" ^ "<<b<<" = "<<intpower(a,b);
13. return 0;
14. }
15. // Definition
16. int intpower(int base,int exp)
17. {
18. if(base==0) // Base case 1
19. {
20. return 0;
21. }
22. if(exp==0) // Base case 2
23. {
24. return 1;
25. }
26. if(exp==1) // Base case 3
27. {
28. return base;
29. }
30.
31. if(exp>1) // Inductive step
32. {
33. return base*intpower(base,exp-1);
34. }
35. }
Page 8 of 9
EE-163(C&P) lesson_07 EED FR, IA
les_07_code_15.cpp
Multiple Functions
1. #include<iostream>
2. using namespace std;
Page 9 of 9
EE-163
Computers and Programming
FE Electrical
Lesson_08
Arrays
1
1) Array declaration and initialization
1 #include<iostream>
2 using namespace std;
3
4 int main(void)
5 { //array declaration
6 int num1[5];
7
8 //another declaration method
9 const int SIZE=3;
10 int num2[SIZE];
11
12 //array declaration with initialization
13 int num3[5]={12,2,54,7,100};
14
15 //declaration with incomplete initialization
16 int num4[5]={12,2};
17
18 //displaying array contents
19 cout<<num1[0]<<" "<<num1[1]<<" "<<num1[2]
20 <<" "<<num1[3]<<" "<<num1[4]<<endl;
21 cout<<num2[0]<<" "<<num2[1]<<" "<<num2[2]
22 <<endl;
23 cout<<num3[0]<<" "<<num3[1]<<" "<<num3[2]
24 <<" "<<num3[3]<<" "<<num3[4]<<endl;
25 cout<<num4[0]<<" "<<num4[1]<<" "<<num4[2]
26 <<" "<<num4[3]<<" "<<num4[4]<<endl;
27 return 0;
28 }
2
1 #//array declaration and initialization
2 #include<iostream>
3 using namespace std;
4 int main(void)
5 { //array declaration
6 char name[5];
7
8 //another declaration method
9 const int SIZE=3;
10 char pet[SIZE];
11 //array declaration with initialization
12 char vowels[5]={'a','e','i','o','u'};
13 //declaration with incomplete initialization
14 char consonants[21]={'b','c'};
15 //displaying array contents
16 cout<<name[0]<<" "<<name[1]<<" "<<name[2]
17 <<" "<<name[3]<<" "<<name[4]<<endl;
18 cout<<pet[0]<<" "<<pet[1]<<" "<<pet[2]
19 <<endl;
20 cout<<vowels[0]<<" "<<vowels[1]<<" "<<vowels[2]
21 <<" "<<vowels[3]<<" "<<vowels[4]<<endl;
22 cout<<consonants[0]<<" "<<consonants[1]<<" "<<
23 " "<<consonants[3]<<" "<<consonants[4]<<endl;
24 return 0;
25 }
3
3) Array initialization, input and processing
1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4 #define SIZE 6
5
6 int main(void)
7 {
8 // Declaring arrays
9 int subjectscores[SIZE];
10 float weeklytemperature[7];
11 char name[25];
12 // similarly long and double can be defined
13 // NOTE: strings are not arrays
14 // Initializing arrays
15 int monthlyprofits[12]=
16 {1200000,6434564,5564664,5456456,5467787,9788445,4456
17 ,39996534,8745647,3142355,6574347,89676};
18 float subjectpercentages[6]={88.5,85.2,85.0,79.5,81.0,75.1};
19 char vowels[5]={'a','e','i','o','u'};
20 // use curly brackets containing values separated by comma
21
22 // taking input in an array from location 0 to 5 (total 6 elements)
23 cout<<"\nEnter element no.0 :";
24 cin>>subjectscores[0]; // scanning is just like any variable
25 cout<<"\nEnter element no.1 :"; // but using the appropriate index no.
26 cin>>subjectscores[1];
27 cout<<"\nEnter element no.2 :";
28 cin>>subjectscores[2];
29 cout<<"\nEnter element no.3 :";
30 cin>>subjectscores[3];
31 cout<<"\nEnter element no.4 :";
32 cin>>subjectscores[4];
33 cout<<"\nEnter element no.5 :";
34 cin>>subjectscores[5];
35 4
36 // Some manipulation/processing with array:
37 // adding 2 to each element
38 subjectscores[0]=subjectscores[0]+2;
39 subjectscores[1]=subjectscores[1]+2;
40 subjectscores[2]=subjectscores[2]+2;
41 subjectscores[3]=subjectscores[3]+2;
42 subjectscores[4]=subjectscores[4]+2;
43 subjectscores[5]=subjectscores[5]+2;
44
45 // printing the processed array
46 cout<<"\nElement 0 = "<<subjectscores[0];
47 cout<<"\nElement 1 = "<<subjectscores[1];
48 cout<<"\nElement 2 = "<<subjectscores[2];
49 cout<<"\nElement 3 = "<<subjectscores[3];
50 cout<<"\nElement 4 = "<<subjectscores[4];
51 cout<<"\nElement 5 = "<<subjectscores[5];
52 getch();
53 return 0;
54 }
5
4) Processing arrays with for() loop
1 #include<iostream>
2 #include<conio2.h>
3 #include<ctime>
4 #include<cstdlib>
5 using namespace std;
6
7 #define LIM 10
8
9 int main(void)
10 {
11 // variable definition
12 // 10 element float array, numbered 0 to 9
13 float num[LIM]={12.0,3.3,7.6,3.1,9.8,7.9,3.4,8.7,9.0,1.0};
14 int index_count;// an integer variable to access different array locations
15 srand(time(NULL));
16 //Automatic initialization with even numbers
17 for(index_count=0;index_count<LIM;index_count++)
18 {
19 num[index_count]=(index_count+1)*2;
20 } 6
21
22 cout<<"\nPress any key to continue";
23 getch();
24
25 // loop for printing output
26 for(index_count=0;index_count<LIM;index_count++)
27 {
28 cout<<"\nElement no."<<index_count<<" = "<<num[index_count];
29 }
30 cout<<endl<<endl;
31
32 //Automatic initialization with random numbers
33 for(index_count=0;index_count<LIM;index_count++)
34 {
35 num[index_count]=(rand()%100)+1;
36 }
37
38 cout<<"\nPress any key to continue";
39 getch();
40
41 // loop for printing output
42 for(index_count=0;index_count<LIM;index_count++)
43 {
44 cout<<"\nElement no."<<index_count<<" = "<<num[index_count];
45 }
46 cout<<endl<<endl;
47
48 // taking array input through for() loop: index_count runs from 0 to 9
49 for(index_count=0;index_count<LIM;index_count++)
50 {
51 cout<<"\nEnter element number "<<index_count<<":";
52 cin>>num[index_count];
53 }
54
55
56
57 7
58
59 // processing the array: adding 2 to each element
60 for(index_count=0;index_count<LIM;index_count++)
61 {
62 num[index_count]=num[index_count]+2.0;
63 }
64 cout<<"\nTwo (2.0) shall be added to each location now......";
65 cout<<"\nPress any key to continue";
66 getch();
67 // loop for printing output
68 for(index_count=0;index_count<LIM;index_count++)
69 {
70 cout<<"\nElement no."<<index_count<<" = "<<num[index_count];
71 }
72
73 getch();
74 return 0;
75 }
1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4
5 #define LIM 10
6
7 int main(void)
8 {
9 // variable definition
10 float num[LIM]; //10 element float array, numbered 0 to 9
11 float sum=0.0,average;//
12 int index_count; //an integer variable to access different array locations
13
14 // taking array input through for() loop: index_count runs from 0 to 9
15
8
16 for(index_count=0;index_count<LIM;index_count++)
17 {
18 cout<<"\nEnter element number "<<index_count<<":";
19 cin>>num[index_count];
20 }
21
22 cout<<"\nAverage is being calculated now......";
23 cout<<"\nPress any key to continue";
24 getch();
25 // processing the array: calculating running sum
26 for(index_count=0;index_count<LIM;index_count++)
27 {
28 sum=sum+num[index_count];
29 }
30 average=sum/LIM;
31 // printing output
32 cout<<"\nAverage of given 10 nos. ="<<average;
33 getch();
34 return 0;
35 }
10
7) Array with while() loop
1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4
5 int main(void)
6 {
7 const int MAX=100;
8 // Array/variable definition
9 char name[MAX]; // char array of 100 elements
10 int index; // integer variable to address array locations
11 int maxindex; // integer variable to store number of elements utilised
12
13 cout<<"\nEnter your name (press ESC to stop)\n";
14
15 // Taking input in array locations: index goes from 0 to unknown value
16 index=0; // setting index to 0 before loop
17 name[index]=getche();// Initialising first element from user
18 // before running for the first time
19
20 while( name[index]!=27 ) // loop ends when ESC is pressed
21 {
22 index++;
23 if(index==100) //
24 { // Extremely Important 1:
25 cout<<"\nArray Overflow\n"; // Provide breaking mechanism
26 break; // in case of overflow
27 } //
28 name[index]=getche();
29 }
30
31 maxindex=index; //Extremely Important 2: saving the the last element
32 //number given by user
33 // Simple processing of name[] array, converting small into capital case
34 // index goes upto maxindex less 1
35 11
36
37 for(index=0; index<maxindex; index++)
38 {
39 if((name[index]>=97)&&(name[index]<=122))
40 {
41 name[index]=name[index]-32;
42 }
43 }
44 cout<<"\nPrinting the processed array.\n";
45 // Printing array elements to see the change made
46 for(index=0;index<maxindex; index++)
47 {
48 cout<<name[index]; // displaying each location
49 }
50 getch();
51 return 0;
52 }
21
15) Passing arrays to functions
1 //Passing arrays to functions
2 #include<iostream>
3 #include<conio2.h>
4 using namespace std;
5 #define MAX 100
6
7 //Prototype 1:function to display a double array
8 void displaydoublearray(const double arr[],int start,int stop, int SIZE);
9
10 //Prototype 2:function to find and return maximum value of double array
11 double maxofdoublearray(const double arr[],int start,int stop);
12
13 //Prototype 3:Input double array from user
14 void inputdoublearray(double arr[],int start,int stop, int SIZE);
15
16 int main (void)
17 {
18 // Variable definition and declaration
19 double num[MAX];
20 double largest;
21 int elements;
22 cout<<"How many array elements do you need:";
23 cin>>elements;
24 //input array elements from user
25 inputdoublearray(num,0,elements-1,MAX);
26 //display array
27 cout<<"\nThe array you entered is:\n";
28 displaydoublearray(num,0,elements-1,MAX);
29 //find largest element of the given array
30 largest=maxofdoublearray(num,0,elements);
31 cout<<"\nThe largest among the given numbers"
32 <<"is "<<largest;
33 return 0;
34 }
35 22
36 //***************** Definition of displaydoublearray()**********************
37 //Definition 1:
38 void displaydoublearray(const double arr[],int start,int stop,int SIZE)
39 {
40 int index;
41 //Displaying the array
42 if((SIZE>stop)&&(start>=0))
43 {
44 for(index=start;index<=stop;index++)
45 {
46 cout<<arr[index]<<" ";
47 if((index+1)%5==0)
48 {
49 cout<<endl;
50 }
51 }
52 }
53 else
54 {
55 cout<<"\n\nERROR:Array limits exceeded.";
56 }
57 }
58 //*****************Definition of maxofdoublearray()********************
59 //Definition 2:function to find and return maximum value of double array
60 double maxofdoublearray(const double arr[],int start,int stop)
61 {
62 int index;
63 float maximum=arr[start];//assuming the first element to be maximum
64 //Defensive condition: program runs only if this condition is met
65 //Loop to go through all elements start_index---->stopindex
66 for(index=start;index<=stop;index++)
67 {
68 if(arr[index]>maximum)//if current assumption is wrong
69 {
70 maximum=arr[index];// select a new max
71 }
23
72 }
73 return maximum;
74 }
75 //*****************Definition of inputdoublearray()**************************
76 //Definition 3:Input double array from user
77 void inputdoublearray(double arr[],int start,int stop,int SIZE)
78 {
79 int index;
80 if((SIZE>stop)&&(start>=0))
81 {
82 for(index=start;index<=stop;index++)
83 {
84 cout<<"Enter location "<<index<<":";
85 cin>>arr[index];
86 }
87 }
88 else
89 {
90 cout<<"\n\nERROR:Array limits exceeded.";
91 }
92 }
32
20) 2D Array Application: Computing student average and score average
1 #include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 const int rows = 5;
8 const int cols = 5;
9 int total = 0;
10 double average = 0.0;
11 //each row contains scores of 5 test of a student
12 //each column contains score in a single test taken
13 //by all 5 students
14 int grades[rows][cols] = {{75, 82, 84, 79, 91},
15 {85, 81, 94, 96, 89},
16 {92, 91, 94, 89, 90},
17 {74, 72, 81, 78, 80},
18 {84, 82, 82, 83, 81}};
19 //printing student average for all 5 tests
20 for(int r = 0; r < rows; ++r)
21 {
22 cout << "Student " << r+1 << ": ";
23 for(int c = 0; c < cols; ++c)
24 {
25 cout << grades[r][c] << " ";
26 total += grades[r][c];
27 }
28 average = total / cols;
29 cout << "Average: " << average << endl;
30 total = 0;
31 average = 0.0;
32 }
33 cout << endl;
34 //printing test average for all 5 stuents
35 33
36 for(int c = 0; c < cols; ++c)
37 {
38 cout << "Test " << c+1 << ": ";
39 for(int r = 0; r < rows; ++r)
40 {
41 cout << grades[r][c] << " ";
42 total += grades[r][c];
43 }
44 average = total / rows;
45 cout << "Average: " << average << endl;
46 total = 0;
47 average = 0.0;
48 }
49 return 0;
50 }
37
EE-163(C&P) lesson_09 EED FR, IA
Pointers
A pointer in C++ is a variable that holds address of another variable (of a specific type). Just like common
variables, it is essential to declare pointer variable. Pointer declaration, address operator and indirection
(dereferencing is explained in the following code)
les_09_code_01.cpp
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a; // a is an integer
6. int *aPtr; // aPtr is an int * which is a pointer to an integer
7.
8. a = 7; // assigned 7 to a
9. aPtr = &a; // assign the address of a to aPtr
10.
11. cout << "The address of a is " << &a
12. << "\nThe value of aPtr is " << aPtr;
13. cout << "\n\nThe value of a is " << a
14. << "\nThe value of *aPtr is " << *aPtr;
15. cout << "\n\nShowing that * and & are inverses of "
16. << "each other.\n&*aPtr = " << &*aPtr
17. << "\n*&aPtr = " << *&aPtr << endl;
18. } // end main
Output
Page 1 of 4
EE-163(C&P) lesson_09 EED FR, IA
les_09_code_02.cpp
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. double *num1Ptr = nullptr; //Initialize pointers to prevent
pointing to unknown or uninitialized areas of memory.
6. cout<<"num1Ptr holds : "<<num1Ptr<<endl;
7. double num1 = 23.767;
8. num1Ptr = &num1;
9. cout<<"num1Ptr holds : "<<num1Ptr<<endl;
10. return 0;
11. }
nullptr is replacement of NULL in new C++11Std (You must enable C++11 in compiler settings)
Passing Pointer to Function
les_09_code_03.cpp
1. #include<iostream>
2. using namespace std;
3. void cubeByReference( int * ); // prototype
4. int main()
5. {
6. int number = 5;
7. cout<<"number : "<<number;
8. int *numPtr = &number;
9. cubeByReference(numPtr);
10. cout<<"\nnumber after cubing : "<<number;
11. return 0;
12. }
13. void cubeByReference( int *nPtr )
14. {
15. *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
16. }
Output
Page 2 of 4
EE-163(C&P) lesson_09 EED FR, IA
Output
Page 3 of 4
EE-163(C&P) lesson_09 EED FR, IA
Pointer Arithmetic
les_09_code_05.cpp
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. double array[10];
6. for(int i = 0; i<10; i++)
7. {
8. cout<<"\n Address of Element "<<i<<" : "<<(array + i);
9. }
10. return 0;
11. }
Output
Page 4 of 4