Download as pdf or txt
Download as pdf or txt
You are on page 1of 176

C++ keywords

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.

alignas (since C++11) dynamic_cast reinterpret_cast


alignof (since C++11) else requires (concepts TS)
enum return
and
explicit short
and_eq
export(1) signed
asm
atomic_cancel (TM TS) extern(1) sizeof(1)
atomic_commit (TM TS) false static
float static_assert (since C++11)
atomic_noexcept (TM TS)
for static_cast
auto(1)
friend struct(1)
bitand goto
bitor switch
if synchronized (TM TS)
bool inline(1)
break template
int this
case
import (modules TS) thread_local (since C++11)
catch
long throw
char
module (modules TS) true
char16_t (since C++11)
mutable(1) try
char32_t (since C++11)
namespace typedef
class(1)
new typeid
compl
noexcept (since C++11) typename
concept (concepts TS)
not union
const
not_eq unsigned
constexpr (since C++11)
nullptr (since C++11) using(1)
const_cast
operator virtual
continue
or void
decltype (since C++11)
or_eq volatile
default(1) private wchar_t
delete(1) protected while
do public xor
double register(2) xor_eq

(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

C documentation for C keywords

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/keyword&oldid=85622"


4/24/2018 Computer Number Conversion

COMPUTER - NUMBER CONVERSION


https://www.tutorialspoint.com/computer_fundamentals/computer_number_conversion.htm Copyright © tutorialspoint.com

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 −

Decimal to Other Base System


Other Base System to Decimal
Other Base System to Non-Decimal
Shortcut method - Binary to Octal
Shortcut method - Octal to Binary
Shortcut method - Binary to Hexadecimal
Shortcut method - Hexadecimal to Binary

Decimal to Other Base System


Step 1 − Divide the decimal number to be converted by the value of the new base.

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

Decimal Number: 2910

Calculating Binary Equivalent −

Step Operation Result Remainder

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 .

Decimal Number : 2910 = Binary Number : 111012.

Other Base System to Decimal System


Step 1 − Determine the column positional value of each digit
thisdependsonthepositionof thedigitandthebaseof thenumbersystem .

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

Binary Number: 111012

Calculating Decimal Equivalent −

Step Binary Number Decimal Number

Step 1 111012 ((1 x 24) + (1 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Step 2 111012 16 + 8 + 4 + 0 + 1 10

Step 3 111012 2910

Binary Number : 111012 = Decimal Number : 2910

Other Base System to Non-Decimal System


Step 1 − Convert the original number to a decimal number base10 .

Step 2 − Convert the decimal number so obtained to the new base number.

Example

Octal Number : 258

Calculating Binary Equivalent −

Step 1 - Convert to Decimal

Step Octal Number Decimal Number

Step 1 258 ((2 x 81) + (5 x 80))10

Step 2 258 16 + 5 10

Step 3 258 2110

https://www.tutorialspoint.com/cgi-bin/printpage.cgi 2/5
4/24/2018 Computer Number Conversion

Octal Number : 258 = Decimal Number : 2110

Step 2 - Convert Decimal to Binary

Step Operation Result Remainder

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

Decimal Number : 2110 = Binary Number : 101012

Octal Number : 258 = Binary Number : 101012

Shortcut Method ─ Binary to Octal


Step 1 − Divide the binary digits into groups of three startingf romtheright .

Step 2 − Convert each group of three binary digits to one octal digit.

Example

Binary Number : 101012

Calculating Octal Equivalent −

Step Binary Number Octal Number

Step 1 101012 010 101

Step 2 101012 28 58

Step 3 101012 258

Binary Number : 101012 = Octal Number : 258

Shortcut Method ─ Octal to Binary


Step 1 − Convert each octal digit to a 3-digit binary number
theoctaldigitsmaybetreatedasdecimalf orthisconversion.

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

Octal Number : 258

Calculating Binary Equivalent −

Step Octal Number Binary Number

Step 1 258 210 510

Step 2 258 0102 1012

Step 3 258 0101012

Octal Number : 258 = Binary Number : 101012

Shortcut Method ─ Binary to Hexadecimal


Step 1 − Divide the binary digits into groups of four startingf romtheright .

Step 2 − Convert each group of four binary digits to one hexadecimal symbol.

Example

Binary Number : 101012

Calculating hexadecimal Equivalent −

Step Binary Number Hexadecimal Number

Step 1 101012 0001 0101

Step 2 101012 110 510

Step 3 101012 1516

Binary Number : 101012 = Hexadecimal Number : 1516

Shortcut Method - Hexadecimal to Binary


Step 1 − Convert each hexadecimal digit to a 4-digit binary number
thehexadecimaldigitsmaybetreatedasdecimalf orthisconversion.

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

Calculating Binary Equivalent −

Step Hexadecimal Number Binary Number

Step 1 1516 110 510

Step 2 1516 00012 01012

Step 3 1516 000101012

Hexadecimal Number : 1516 = Binary Number : 101012

https://www.tutorialspoint.com/cgi-bin/printpage.cgi 5/5
4/24/2018 Computer Number System

COMPUTER - NUMBER SYSTEM


https://www.tutorialspoint.com/computer_fundamentals/computer_number_system.htm Copyright © tutorialspoint.com

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 value of each digit in a number can be determined using −

The digit

The position of the digit in the number

The base of the number system


wherethebaseisdef inedasthetotalnumberof digitsavailableinthenumbersystem

Decimal Number System


The number system that we use in our day-to-day life is the decimal number system. Decimal number system
has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions to the left of
the decimal point represent units, tens, hundreds, thousands, and so on.

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

(1 x 1000)+ (2 x 100)+ (3 x 10)+ (4 x l)


(1 x 103)+ (2 x 102)+ (3 x 101)+ (4 x l00)
1000 + 200 + 30 + 4
1234

As a computer programmer or an IT professional, you should understand the following number systems
which are frequently used in computers.

S.No. Number System and Description

Binary Number System


1
Base 2. Digits used : 0, 1

Octal Number System


2
Base 8. Digits used : 0 to 7

3
Hexa Decimal Number System

Base 16. Digits used: 0 to 9, Letters used : A- F

https://www.tutorialspoint.com/cgi-bin/printpage.cgi 1/3
4/24/2018 Computer Number System

Binary Number System


Characteristics of the binary number system are as follows −

Uses two digits, 0 and 1

Also called as base 2 number system

Each position in a binary number represents a 0 power of the base 2. Example 20

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

Calculating Decimal Equivalent −

Step Binary Number Decimal Number

Step 1 101012 ((1 x 24) + (0 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Step 2 101012 16 + 0 + 4 + 0 + 1 10

Step 3 101012 2110

Note − 101012 is normally written as 10101.

Octal Number System


Characteristics of the octal number system are as follows −

Uses eight digits, 0,1,2,3,4,5,6,7

Also called as base 8 number system

Each position in an octal number represents a 0 power of the base 8. Example 80

Last position in an octal number represents a x power of the base 8. Example 8x where x represents the
last position - 1

Example

Octal Number: 125708

Calculating Decimal Equivalent −

Step Octal Number Decimal Number

https://www.tutorialspoint.com/cgi-bin/printpage.cgi 2/3
4/24/2018 Computer Number System

Step 1 125708 ((1 x 84) + (2 x 83) + (5 x 82) + (7 x 81) + (0 x 80))10

Step 2 125708 4096 + 1024 + 320 + 56 + 0 10

Step 3 125708 549610

Note − 125708 is normally written as 12570.

Hexadecimal Number System


Characteristics of hexadecimal number system are as follows −

Uses 10 digits and 6 letters, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

Letters represent the numbers starting from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15

Also called as base 16 number system

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

Hexadecimal Number: 19FDE16

Calculating Decimal Equivalent −

Step Binary Decimal Number


Number

Step 1 19FDE16 ((1 x 164) + (9 x 163) + (F x 162) + (D x 161) + (E x 160))10

Step 2 19FDE16 ((1 x 164) + (9 x 163) + (15 x 162) + (13 x 161) + (14 x 160))10

Step 3 19FDE16 65536 + 36864 + 3840 + 208 + 14 10

Step 4 19FDE16 10646210

Note − 19FDE16 is normally written as 19FDE.

https://www.tutorialspoint.com/cgi-bin/printpage.cgi 3/3
ECE 0142 Computer Organization

Lecture 3 Floating Point Representations

1
Floating-point arithmetic

 We often incur floating-point programming.


– Floating point greatly simplifies working with large (e.g., 270) and
small (e.g., 2-17) numbers
 We’ll focus on the IEEE 754 standard for floating-point arithmetic.
– How FP numbers are represented
– Limitations of FP numbers
– FP addition and multiplication

2
Floating-point representation

 IEEE numbers are stored using a kind of scientific notation.

± mantissa * 2exponent

 We can represent floating-point numbers with three binary


fields: a sign bit s, an exponent field e, and a fraction field f.

s e f

 The IEEE 754 standard defines several different precisions.


— Single precision numbers include an 8-bit exponent field
and a 23-bit fraction, for a total of 32 bits.
— Double precision numbers have an 11-bit exponent field
and a 52-bit fraction, for a total of 64 bits.

3
Sign

s e f

 The sign bit is 0 for positive numbers and 1 for negative


numbers.
 But unlike integers, IEEE values are stored in signed magnitude
format.

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

 What’s the normalized representation of 0.0001101001110 ?


0.0001101001110
= 1.110100111 × 2-4

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

 The e field represents the exponent as a biased number.


– It contains the actual exponent plus 127 for single precision, or
the actual exponent plus 1023 in double precision.
– This converts all single-precision exponents from -126 to +127
into unsigned numbers from 1 to 254, and all double-precision
exponents from -1022 to +1023 into unsigned numbers from 1 to
2046.
 Two examples with single-precision numbers are shown below.
– If the exponent is 4, the e field will be 4 + 127 = 131 (100000112).
– If e contains 01011101 (9310), the actual exponent is 93 - 127 = -
34.
 Storing a biased exponent means we can compare IEEE values as if
they were signed integers.

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

 The decimal value of an IEEE number is given by the formula:

(1 - 2s) * (1 + f) * 2e-bias

 Here, the s, f and e fields are assumed to be in decimal.


– (1 - 2s) is 1 or -1, depending on whether the sign bit is 0
or 1.
– We add an implicit 1 to the fraction field f, as mentioned
earlier.
– Again, the bias is either 127 or 1023, for single or double
precision.

10
Example IEEE-decimal conversion

 Let’s find the decimal value of the following IEEE number.

1 01111100 11000000000000000000000

 First convert each individual field to decimal.


– The sign bit s is 1.
– The e field contains 01111100 = 12410.
– The mantissa is 0.11000… = 0.7510.
 Then just plug these decimal values of s, e and f into our formula.

(1 - 2s) * (1 + f) * 2e-bias

 This gives us (1 - 2) * (1 + 0.75) * 2124-127 = (-1.75 * 2-3) = -0.21875.

11
Converting a decimal number to IEEE 754
 What is the single-precision representation of 347.625?

1. First convert the number to binary: 347.625 = 101011011.1012.


2. Normalize the number by shifting the binary point until there is
a single 1 to the left:

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

 What is the single-precision representation of 639.6875

639.6875 = 1001111111.10112
= 1.0011111111011×29

s=0
e = 9 + 127 = 136 = 10001000
f = 0011111111011

The single-precision representation is:


0 10001000 00111111110110000000000

13
Examples: Compare FP numbers ( <, > ? )

1. 0 0111 1111 110…0 0 1000 0000 110…0


+1.112 × 2 (127-127) =1.7510 +1.112 × 2 (128-127) = 11.12=3.510

0 0111 1111 110…0 0 1000 0000 110…0


+ 0111 1111 < + 1000 0000
directly comparing exponents as unsigned values gives result

2. 1 0111 1111 110…0 1 1000 0000 110…0


-f × 2(0111 1111 ) -f × 2(1000 0000)
For exponents: 0111 1111 < 1000 0000
So -f × 2(0111 1111 ) > -f × 2(1000 0000)

14
Special Values (single-precision)

E F meaning Notes

00000000 0…0 0 +0.0 and -0.0

Valid Unnormalized
00000000 X…X
number =(-1)S x 2-126 x (0.F)

11111111 0…0 Infinity

11111111 X…X Not a Number

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

 Normalized (positive range; negative is symmetric)

smallest 00000000100000000000000000000000 +2-126(1+0) = 2-126

largest 01111111011111111111111111111111 +2127(2-2-23)

 Unnormalized
smallest 00000000000000000000000000000001 +2-126(2-23) = 2-149

largest 00000000011111111111111111111111 +2-126(1-2-23)

2-126 2127(2-2-23)

0 2-149 2-126(1-2-23)

Positive overflow
Positive underflow 17
In comparison

 The smallest and largest possible 32-bit integers in two’s


complement are only -231 and 231 - 1
 How can we represent so many more values in the IEEE 754
format, even though we use the same number of bits as regular
integers?

what’s the next representable FP number?


2-126

+2-126(1+2-23) differ from the smallest number by 2-149


18
Finiteness

 There aren’t more IEEE numbers.


 With 32 bits, there are 232, or about 4 billion, different bit patterns.
– These can represent 4 billion integers or 4 billion reals.
– But there are an infinite number of reals, and the IEEE format
can only represent some of the ones from about -2128 to +2128.
– Represent same number of values between 2n and 2n+1 as 2n+1
and 2n+2

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

 Even some integers cannot be represented in the IEEE


format.

int x = 33554431;
float y = 33554431;
printf( "%d\n", x );
printf( "%f\n", y );

33554431
33554432.000000

 Some simple decimal numbers cannot be represented exactly


in binary to begin with.

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

 To get a feel for floating-point operations, we’ll do an addition


example.
– To keep it simple, we’ll use base 10 scientific notation.
– Assume the mantissa has four digits, and the exponent
has one digit.
 An example for the addition:

99.99 + 0.161 = 100.151

 As normalized numbers, the operands would be written as:

9.999 * 101 1.610 * 10-1

22
Steps 1-2: the actual addition

1. Equalize the exponents.


The operand with the smaller exponent should be rewritten by
increasing its exponent and shifting the point leftwards.

1.610 * 10-1 = 0.01610 * 101

With four significant digits, this gets rounded to: 0.016

This can result in a loss of least significant digits—the rightmost 1 in


this case. But rewriting the number with the larger exponent could
result in loss of the most significant digits, which is much worse.

2. Add the mantissas.

9.999 * 101
+ 0.016 * 101
10.015 * 101

23
Steps 3-5: representing the result
3. Normalize the result if necessary.

10.015 * 101 = 1.0015 * 102

This step may cause the point to shift either left or right, and the
exponent to either increase or decrease.

4. Round the number if needed.

1.0015 * 102 gets rounded to 1.002 * 102

5. Repeat Step 3 if the result is no longer normalized.


We don’t need this in our example, but it’s possible for rounding to
add digits—for example, rounding 9.9995 yields 10.000.

Our result is 1.002*102 , or 100.2 . The correct answer is 100.151, so we have


the right answer to four significant digits, but there’s a small error already.

24
Example

 Calculate 0 1000 0001 110…0 plus 0 1000 0010 00110..0


both are single-precision IEEE 754 representation

1. 1st number: 1.112 × 2 (129-127); 2nd number: 1.00112 × 2(130-127)


2. Compare the e field: 1000 0001 < 1000 0010
3. Align exponents to 1000 0010; so the 1st number becomes:
0.1112 × 23
4. Add mantissa
1.0011
+0.1110
10.0001
5. So the sum is: 10.0001 × 23 = 1.00001 × 24
So the IEEE 754 format is: 0 1000 0011 000010…0

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.

0⊕0=0 0⊕1=1 1⊕0=1 1⊕1=0

 This is one of the main advantages of using signed magnitude.

26
The history of floating-point computation

 In the past, each machine had its own implementation of


floating-point arithmetic hardware and/or software.
– It was impossible to write portable programs that would
produce the same results on different systems.
 It wasn’t until 1985 that the IEEE 754 standard was adopted.
– Having a standard at least ensures that all compliant
machines will produce the same outputs for the same
program.

27
Floating-point hardware

 When floating point was introduced in microprocessors, there


wasn’t enough transistors on chip to implement it.
– You had to buy a floating point co-processor (e.g., the
Intel 8087)
 As a result, many ISA’s use separate registers for floating
point.
 Modern transistor budgets enable floating point to be on chip.
– Intel’s 486 was the first x86 with built-in floating point
(1989)
 Even the newest ISA’s have separate register files for floating
point.
– Makes sense from a floor-planning perspective.

28
FPU like co-processor on chip

29
Summary

 The IEEE 754 standard defines number representations and


operations for floating-point arithmetic.
 Having a finite number of bits means we can’t represent all
possible real numbers, and errors will occur from
approximations.

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

Muhammad Hassan ul Haq (Sections D, E, F)


Assistant Professor
Electrical Engineering Department
hassanulhaq@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

Course Reference Book


There is no textbook in particular, students can choose any basic programming book for C++.
However they are highly recommended to choose one of the following as Reference Material
i. Deitel, Paul, and Harvey Deitel. C++ How to Program 8th Edition. Prentice Hall,
2010.
EE-163 (Computers & Programming) EED FR, IA

ii. Stroustrup, Bjarne. Programming: principles and practice using C++ 2nd Edition.
Pearson Education, 2009.

Performa to be filled for ‘Group Activity’


(Submit by 18-04-2018 in class)
Name:
Section:
Roll No:
Place of birth:
Place of residence (city and town/mohalla/tehsil/district):
School name:
Aggregate marks (percentage, preferably) in Matric (or equivalent):
College name:
Aggregate marks (percentage, preferably) in Intermediate (or equivalent):
Hobbies (max 3):
Vision or dream of life:

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

Introduction to Modern Computer Hardware and Software


You will get decent understanding of the modern hardware from the VU CPL course (hope
that you are doing it - ). We will discuss some of the more crucial details here. Our primary
source for this lecture is the article written by Christopher Barnett
(http://www.explainingcomputers.com/hardware.html), however, we will extend those ideas a
bit further.

The Computer Processor


aa

Block diagram representation of the Von Neumann architecture

Modern computer system – under the hood


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.

THE BASIC TECHNICAL SPECIFICATIONS


Having said that the technical specification of a computer matters far less than it did even a
few years ago, some understanding of a little hardware technobabble will still inevitably
prove useful. Most obviously such knowledge is handy when purchasing or upgrading a
computer and/or related peripherals to ensure that everything will connect together and work
OK.

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.

PROCESSOR SPEED AND ARCHITECTURE


The speed of a computer's processor chip (technically known as its "clock speed") in
measured in gigahertz (GHz), with the fastest modern processors currently running at up to
4.7GHz. However, for most computing tasks -- including web browsing, sending e-mails,
word processing and spreadsheet work -- any processor running at 1GHz or more remains
perfectly sufficient. (No really guys, it does!).

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

is no longer a straight-forward indicator of processor power, with the architecture of the


processor -- and most notably including its number of cores -- now being at least as
significant.

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.

As a basic rule, unless a computer is going to be used to handle 3D graphics or to undertake a


significant volume of video editing or recording, today there is little point in opting for
anything other than onboard graphics (not least because separate graphics cards consume
quite a lot of electricity and create quite a lot of heat and noise). Adding a new graphics card
to a computer with onboard graphics is also a very easy upgrade if required in the future.

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.

HARD DRIVE SPEED AND CAPACITY


Hard disk drives are the high capacity storage devices inside a computer from which software
and user data are loaded. Like most other modern storage devices, the capacity of the one or
more internal hard disks inside a computer is measured in gigabytes (GB), as detailed on the
storage page. Today 40GB is an absolute minimum hard drive size for a new computer
running Windows 7, with a far larger capacity being recommended in any situation where
more than office software is going to be installed. Where a computer will frequently be used
to edit video, a second internal hard disk dedicated only to video storage is highly
recommended for stable operation. Indeed, for professional video editing using a program
like Premiere Pro CS5, Adobe now recommend that a PC has at least three internal hard disks
(one for the operating system and programs, one for video project files, and one for video
media). This is also not advice to be lightly ignored if you want your computer to actually
work!

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

Steps to Include conio2


For 32 Bit OS
Step 1: Locate conio2 folder provided in lesson_06
Step 2: Copy conio2.h file to the following location
C:\ProgramFiles\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2\include\c++
Step 3: Copy libconio2.a file to the following location
C:\Program Files\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2
Step 4: Open Code Blocks – Settings – Compiler

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

Integrated Development Environment (IDE)


In order to write programs using C++ language you need C++ compiler and a text editor. C++ compiler
converts the source code to computer understandable form. Text editor is required to type the source code.
Often there are computer programs that are combination of compiler and text editor. These programs are
referred as Integrated Development Environment (IDE) (they may be free of cost or paid). For this course
it is recommend to use an IDE called Code::Blocks. It is open source free of cost application targeting
Windows, Mac and Linux environment. Further details about code blocks can be obtained from
http://www.codeblocks.org/

Your First Code


les_01_code_01.cpp
1. #include<iostream>
2. using namespace std;
3.
4. int main()
5. {
6. cout<<"Hello world!";
7. return 0;
8. }

Page 1 of 12
EE-163(C&P) Lesson - I EED MHUH, FR

Let us traverse the code line by line

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.

5 Opening brace { of the main function.


cout (see out) it’s the standard output stream (print to console).
followed by the symbol << this is put to operator (stream insertion operator) which indicates
what ever follows this will be put to standard output (monitor).
Then we have “Hello world!” this is string, a fundamental data type in C++ and it is
6
recogonized with “ ” .
then we have a semicolon ; this is the end of the statement.
Every C++ statement should terminate with a semicolon, this is how compiler recognize that
a statement is completed.
return 0; this is the return value of main (for time being just consider this is the standard
7 procedure until we discuss functions).
A zero (0) returned by main() indicates the program terminated successfully.
8 Closing brace } of the main function.

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

cout << "Hello” world!" << endl;

cout << "Hello”; world!" << endl;

cout << "Hello" ;


cout <<" world!" << endl;

Ungraded Task
Write a program that prints the following

Hello Your Name!


Welcome to C++ Programming

Bonus Material
IEEE Spectrum Top Ten Programming languages

https://spectrum.ieee.org/computing/software/the-2017-top-programming-languages

Understanding Data Types


Data types, defines the proper use of an identifier and expression. An expression is a sequence of operators
and their operands that specifies a computation. Various data items with symbolic names in C++ is called
as identifiers. Following data items are identifier in C++

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

Numeric String Character Boolean

(bool) True (1)


Integer (int) e.g. (string) e.g (char) Single
or False (0)
32, 107, 13390 "Hello World" Letter e.g. 'a', 'f'
Value

Float (double)
e.g. 3.1413, 53.7

Numeric Data Types


Whole Numbers or Integers

• 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

• double Size is 8 bytes +-1.7 e + - 308;


• float 4 bytes

Data Types for Alpha Numeric


string
a string is zero or more characters surrounded by double quotes. E.g. “Hello World!”, “100”,
char

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.

Primitive Built-in Types


C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table
lists down seven basic C++ data types:
Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double

Valueless void

Wide character wchar_t

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.

Type Typical Bit Width Typical Range

char 1byte -127 to 127 or 0 to 255

Page 5 of 12
EE-163(C&P) Lesson - I EED MHUH, FR

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int Range 0 to 65,535

signed short int Range -32768 to 32767

long int 4bytes -2,147,483,647 to 2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

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:

• Variable name must start with a letter or _ (underscore)


• May contains letter, numbers and the underscore character
• Examples: salary, firstName, name3, first_name, _newVal
• Illegal : 3name, first name, new, class, struct, while, for, my@val
• Uppercase and lower case are distinct

Programs to Understand Variables and Data Types


les_01_code_03.cpp
1. #include<iostream>

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

Declaring Multiple Variables of same type


les_01_code_05.cpp
1. #include<iostream>
2.
3. using namespace std;
4. int main ()
5. {
6. int num1, num2, num3;
7. int num4, num5 = 10, num6;
8. int num7 = 20, num8 = 30, num9 = 40;
9.
10. return 0;
11. }

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

Taking Multiple Inputs


les_01_code_08.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7. int num1, num2, num3;
8. cout<<"Please enter the value of num1, num2, num3 : ";
9. cin>>num1>>num2>>num3;
10. cout<<"You Entered : num1 "<<num1<<endl;
11. cout<<"You Entered : num2 "<<num2<<endl;
12. cout<<"You Entered : num3 "<<num3<<endl;
13. return 0;
14. }

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)

Notice the space

ii. Entering Values separated by Return Key

Notice the Enter Key

Page 10 of 12
EE-163(C&P) Lesson - I EED MHUH, FR

Careful with Strings


les_01_code_09.cpp
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7. string name;
8. cout<<"Please enter the name : ";
9. cin>>name;
10. cout<<"Name you entered is : "<<name;
11. return 0;
12. }

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

Beware that getline can only be used to input strings


Exercise
Write a program that stores speed of light, Planck’s constant, charge on electron,
Avagadro’s number, your age, your full name, your department, your cgpa in
appropriate variables and print them on console.
Re implement the same program, this time making it interactive by involving user
input.

Page 12 of 12
EE-163(C&P) lesson_02 EED MHUH, FR

Basic Math Operations


C++ can be used to perform basic mathematical operations. The following program can be used to
illustrate this.
les_02_code_01.cpp
#include<iostream>

using namespace std;

int main()

int number1;
int number2;
int result;

cout<<"Please enter number1 & number2";


cin>>number1>>number2;

result = number1 + number2;


result = number1 - number2;
result = number1 * number2;
result = number1 / number2;
result = number1 % number2;

cout<<result;
return 0;
}

S.No number1 number2 operation result


1 12 8 + 20
2 12 8 - 4
3 12 8 * 96
4 12 8 / 1
5 12 8 % 4

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;

What will be the value of y in above cases?


Case – I y = 32
Case – II y = 34

Precedence of Arithmetic Operators


Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first.
[Caution: If you have an
expression such as (a + b) * (c - d) in which two
sets of parentheses are not nested, but appear “on the
same level,” the C++ Standard does not specify the order
in which these parenthesized sub expressions will be
evaluated.]
*, /, % Multiplication, Evaluated second. If there are several, they’re evaluated
Division, left to right.
Modulus
+, - Addition Evaluated last. If there are several, they’re evaluated left
Subtraction to right.

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. }

Using Constant Variable


les_02_code_04.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. const int numGrades = 3;
11. average = (number1 + number2 + number3) / numGrades;
12. cout<<average;
13. return 0;
14. }

If the value of constant is tried to be changed during the program the compiler will throw an error

Error: assignment of read only variable


Constants are much helpful in situations when a certain constant is required again and again. For example
value of pi used in a program for different calculations.

Advanced Mathematical Functions


Some very useful and advanced mathematical functions are present in <cmath> library. Which can be
included in a program through preprocessor directive #include<cmath>. Following are the few
functions which are available in this library.

Page 3 of 12
EE-163(C&P) lesson_02 EED MHUH, FR

Category Function Description

cos Returns the cosine of an angle of x radians.


sin Returns the sine of an angle of x radians.
tan Returns the tangent of an angle of x radians.
acos The acos function computes the principal value of
the arc cosine of x. A domain error occurs
Trigonometry for arguments not in the range [-I. +I].
asin The asin function computes the principal value of the
arc sine of x. A domain error occurs
for arguments not in the range [-I, +I].
atan The atan function returns the arc tangent in the range
[[-pi/2, +pi/2]]
exp Returns the base-e exponential function of x, which
is e raised to the power x: ex.
Exponential and log Returns the natural logarithm of x.
logarithmic If the argument is negative, a domain error occurs.
function log10 Returns the common (base-10) logarithm of x.
If the argument is negative, a domain error occurs.

pow Returns base raised to the power exponent:


e.g. pow(7.0, 3.0); will find 7 ^ 3
Power Functions sqrt Returns the square root of x.
If x is negative, a domain error occurs:
cbrt Returns the cubic root of x.
ceil Rounds x upward, returning the smallest integral
value that is not less than x.

floor Rounds x downward, returning the largest integral


Rounding and value that is not greater than x.
Remainder fmod Returns the floating-point remainder
Functions of numer/denom
trunc Rounds x toward zero, returning the nearest integral
value that is not larger in magnitude than x.
round Returns the integral value that is nearest to x, with
halfway cases rounded away from zero.
fabs Returns the absolute value of x: |x|.
Other Functions
abs Returns the absolute value of x: |x|.

Page 4 of 12
EE-163(C&P) lesson_02 EED MHUH, FR

How to use trigonometric functions


les_02_code_05.cpp
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8.
9. const double pi = 3.141592;
10. double angle = pi/6;
11. cout<<endl<<"******** Calculating Trigonometric Ratios
********"<<endl;
12. cout<<endl<<"All calculations on Angle "<<angle<<"
Radians"<<endl;
13. cout<<endl<<"cos("<<angle<<") "<<"= "<<cos(angle)<<endl;
14. cout<<endl<<"sin("<<angle<<") "<<"= "<<sin(angle)<<endl;
15. cout<<endl<<"tan("<<angle<<") "<<"= "<<tan(angle)<<endl;
16. cout<<endl<<"******** Calculations Terminated ********"<<endl;
17.
18. return 0;
19. }

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

How to use exponential and logarithmic functions


les_02_code_06.cpp
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8. double num = 10.3;
9. cout<<endl<<"exp("<<num<<") "<<"= "<<exp(num)<<endl;
10. cout<<endl<<"log("<<num<<") "<<"= "<<log(num)<<endl;
11. cout<<endl<<"log10("<<num<<") "<<"= "<<log10(num)<<endl;
12.
13. return 0;
14. }

Output

How to use power functions


1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8. double num1 = 10.3, num2 = 2.0;
9. cout<<endl<<"pow("<<num1<<","<<num2<<") "<<"=
"<<pow(num1,num2)<<endl;
10. cout<<endl<<"sqrt("<<num1<<") "<<"= "<<sqrt(num1)<<endl;
11. cout<<endl<<"cbrt("<<num1<<") "<<"= "<<cbrt(num1)<<endl;
12.
13. return 0;
14. }

Page 6 of 12
EE-163(C&P) lesson_02 EED MHUH, FR

Output

How to use rounding and remainder functions


les_02_code_08.cpp
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8. double num1 = 2.3,num2 = 3.8,num3 = 5.5,num4 = -2.3,num5 = -3.8,num6 =
-5.5;
9. cout<<"value\tround\tfloor\tceil\ttrunc\n";
10. cout<<"-----\t-----\t-----\t----\t-----\n";
11. cout<<num1<<"\t"<<round(num1)<<"\t"<<floor(num1)<<"\t"<<ceil(num1
)<<"\t"<<trunc(num1)<<"\n";
12. cout<<num2<<"\t"<<round(num2)<<"\t"<<floor(num2)<<"\t"<<ceil(num2
)<<"\t"<<trunc(num2)<<"\n";
13. cout<<num3<<"\t"<<round(num3)<<"\t"<<floor(num3)<<"\t"<<ceil(num3
)<<"\t"<<trunc(num3)<<"\n";
14. cout<<num4<<"\t"<<round(num4)<<"\t"<<floor(num4)<<"\t"<<ceil(num4
)<<"\t"<<trunc(num4)<<"\n";
15. cout<<num5<<"\t"<<round(num5)<<"\t"<<floor(num5)<<"\t"<<ceil(num5
)<<"\t"<<trunc(num5)<<"\n";
16. cout<<num6<<"\t"<<round(num6)<<"\t"<<floor(num6)<<"\t"<<ceil(num6
)<<"\t"<<trunc(num6)<<"\n";
17.
18. return 0;
19. }

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

Formatting with <iomanip>


A header file contains function to control output stream
les_02_code_12.cpp
1. #include<iostream>
2. #include<cmath>
3. #include<iomanip>
4.
5. using namespace std;
6.
7. int main()
8. {
9.
10. double planck = 6.62607004e-34;
11. double gravitation = 6.67408e-11;

Page 9 of 12
EE-163(C&P) lesson_02 EED MHUH, FR

12. double charge = 1.60217662e-19;


13. cout<<"********Output Without Precision********"<<endl;
14. cout<<endl<<endl;
15. cout<<"Planck's Constant = "<<planck<<endl;
16. cout<<"Gravitational Constant = "<<gravitation<<endl;
17. cout<<"Charge on electron = "<<charge<<endl;
18. cout<<endl<<endl;
19. cout<<"********Output with Precision of 10********"<<endl;
20. cout<<endl<<endl;
21. cout<<setprecision(10);
22. cout<<"Planck's Constant = "<<planck<<endl;
23. cout<<"Gravitational Constant = "<<gravitation<<endl;
24. cout<<"Charge on electron = "<<charge<<endl;
25.
26. return 0;
27. }

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>

4. using namespace std;

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.

Explore the usage of functions scientific and fixed in C++

Implement the following expressions in C++


i. | 𝑥 + 𝑦 |
ii. |𝑥| + |𝑦|
𝑥3
iii. 𝑦
+𝑦
iv. √𝑥 6 + 𝑦 5
7
v. (𝑥 + √𝑦)

Try to give wrong inputs to the following functions


i. sqrt, ii. acos, iii. atan, iv. asin

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>

2. using namespace std;

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";

11. // start at 3 at take all characters


12. cout<<"_str1.substr(3) "<<_str1.substr(3)<<endl;

13. // start at 3 and take out 5 characters


14. cout<<"_str1.substr(3,5) "<<_str1.substr(3,5)<<endl;

15. // string concatenation


16. cout<<_str4+_str5;

17. //compound assignment also work for concatenation


18. // see for example

19. _str4 += " ";


20. _str4 += _str5;

21. cout<<endl<<_str4;

22. //resetting _str4


23. _str4 = "Hello";

24. //finding location of a value


25. cout<<endl<<_str4.find('o');

26. //trying to find location of a value that does not exist


27. cout<<endl<<_str4.find('f');

28. //finding location of a value that exist multiple times


29. cout<<endl<<_str4.find('l'); //returns first location
30. cout<<endl<<"_str4.rfind('l') = ";
31. cout<<_str4.rfind('l');

Page 1 of 6
EE-163(C&P) lesson_03 EED MHUH, FR

32. //finding substring


33. cout<<endl<<_str2.find("fox");

34. //size of the string


35. cout<<endl<<_str2.size();

36. //erase function


37. string _str6 = "Application and Project Engineer";
38. _str6.erase(12,4); //this will erase 4 characters from
i. //location 12
39. cout<<endl<<_str6;
40. _str6 = "Application and Project Engineer"; //resetting _str6

41. _str6.replace(12,3,"for");
42. cout<<endl<<_str6;

43. return 0;
44. }

Let’s discuss this code in pieces

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)

Start from location 3 and pull 5 characters.

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

We can also perform concatenation through compound assignment, for example.


_str4 += " ";
_str4 += _str5;
cout<<endl<<_str4;

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);

This will erase 4 characters from location 12

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;

This will replace 3 characters starting from location no 12 with for

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

4. // ---------- length() ---------- //


5. // ---------- max_size() ---------- //
6. // ---------- capacity() ---------- //
7. // ---------- resize() ---------- //
8. // ---------- empty() ---------- //
9. // ---------- at() ---------- //
10. // ---------- append() ---------- //

11. // these functions are used as member function


12. // for more documentations please visit
13. // http://www.cplusplus.com/reference/string/string/

14. #include<iostream>

15. using namespace std;

16. int main()


17. {
18. string _str1, _str2;
19. _str1 = "This is a string sample";

20. // To test size and capacity of a string


21.
22. cout<<_str1.size();
23. cout<<"\n_str1.length() = "<<_str1.length();
24. cout<<"\n_str1.max_size() = "<<_str1.max_size(); //finds the
maximum possible string size
25. cout<<"\n_str1.capacity() = "<<_str1.capacity(); //finds the
memory consumed

26. // To change size of the string


27. cout<<"\n"<<_str1;
28.
29. // now resizing
30.
31. _str1.resize(10); //decreasing the size to 10 characters
32. cout<<"\n"<<_str1;
33. _str1 = "This is a string sample"; //resetting the actual string

34. _str1.resize(50, '$'); //resizing to 50 characters with


additional character $
35. cout<<"\n"<<_str1;

Page 5 of 6
EE-163(C&P) lesson_03 EED MHUH, FR

36. _str1.resize(23); //resizing to the original size


37. cout<<"\n"<<_str1;

38. //to test if a string is empty or not

39. cout<<"\n_str1.empty() = "<<_str1.empty();


40. cout<<"\n_str2.empty() = "<<_str2.empty();

41. //Element access


42. cout<<"\n"<<_str1[5]; //access 5th element of string starting
from 0
43. cout<<"\n"<<_str1.at(5);//access 5th element of string starting
from 0

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;

50. // learn the following functions yourself


51. // ---------- push_back() ----------
52. // ---------- pop_back() ----------
53. // ---------- assign() ----------
54. // ---------- swap() ----------

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.

Relational & Equality Operators


Relational operators and equality operators are used to compare numerical data. Both the equality and
relational operators check for a particular relationship between two numeric values and results if the
relationship holds or not if the relationship holds, then it returns a Boolean true (1) otherwise it returns a
Boolean false (0).
Here is a list of Relational and Equality 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>

2. using namespace std;

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

AND operator (&&) works according to the following truth table.


x y x&&y
0 0 0
0 1 0
1 0 0
1 1 1
Where 0 is false and 1 is true

les_04_code_02.cpp
1. #include<iostream>

2. using namespace std;

3. int main ()

4. {
5. int num1 = 10, num2 = 5, num3 = -9, num4 = 5;

6. bool res1, res2, res3, res4;

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;

11. res3 = (num1>=num3)&&(num2<=num4);


12. cout<<"\n\t(num1>=num3)&&(num2<=num4)\t"<<res3;

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

statement to be executed if relational expression is true

-----------------------------------------------------------------------------
les_04_code_03.cpp

1. #include<iostream>

2. using namespace std;

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

10. cin >> rate;


11. if (hoursWorked <= 40)
12. {
13. grossPay = hoursWorked * rate;
14. }
15. if (hoursWorked > 40)
16. {
17. grossPay = (40 * rate) + ((hoursWorked-40) * (rate * 1.5));
18. }
19. cout << "Gross pay is: " << grossPay << endl;
20. return 0;

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>

2. using namespace std;

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: ";
10. cin >> rate;

11. if (hoursWorked <= 40)


12. {
13. grossPay = hoursWorked * rate;
14. }

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

13. cout<<"But you can drive."<<endl;


14. }
15. else
16. {
17. cout<<"You can't drive either."<<endl;
18. }

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
}

else if (test condition 2)


{
body of else if
}

else if (test condition 3)


{
body of else if
}
.
.
.
.

else if (test condition n)


{
body of else 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
-----------------------------------------------------------------------------

Let's implement the following example


Based on these given conditions, our program will decide the letter grade of
a student provided his/her marks

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^GradingScale^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

90 - 100 A
80 - 89 B
70 - 79 C
60 - 69 D
00 - 59 F
les_04_code_06.cpp

1. #include<iostream>

2. using namespace std;

3. int main ()

4. {
5. // suitable variables declaration
6. int marks;
7. string letterGrade;

8. //data input phase


9. cout<< "Enter Marks Obtained : ";
10. cin>>marks;

11. // now decision making for multiple selection

12. if(marks>=90)
13. {
14. letterGrade = "A";
15. }

16. else if (marks >= 80)


17. {

Page 9 of 13
EE-163(C&P) lesson_04 EED FR, IA

18. letterGrade = "B";


19. }

20. else if (marks >= 70)


21. {
22. letterGrade = "C";
23. }

24. else if (marks >= 60)


25. {
26. letterGrade = "D";
27. }
28. else
29. {
30. letterGrade = "F";
31. }

32. cout<<"For a score of "<<marks<<" marks letter grade is


"<<letterGrade;
33. return 0;
34. }

Using Logical Operators


-----------------------------------------------------------------------------
EXAMPLE
-----------------------------------------------------------------------------

Let's implement the following example


Based on these given conditions, our program will decide the letter grade of
a student
provided his/her marks

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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

Note this distribution can be programmed similarly like les_04_code_06.cpp


But for learning purpose we are implementing with the help of
logical operator

les_04_code_07.cpp

1. #include<iostream>

2. using namespace std;

3. int main ()

4. {
5. // suitable variables declaration
6. int marks;
7. string letterGrade;

8. //data input phase


9. cout<< "Enter Marks Obtained : ";
10. cin>>marks;

11. // now decision making for multiple selection

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

36. else if((marks>=77)&&(marks<=79))


37. {
38. letterGrade = "C+";
39. }
40. else if ((marks >= 73)&&(marks <= 76))
41. {
42. letterGrade = "C";
43. }
44. else if ((marks >= 70)&&(marks <= 72))
45. {
46. letterGrade = "C-";
47. }
48. else if((marks>=67)&&(marks<=69))
49. {
50. letterGrade = "D+";
51. }
52. else if ((marks >= 63)&&(marks <= 66))
53. {
54. letterGrade = "D";
55. }
56. else if ((marks >= 60)&&(marks <= 62))
57. {
58. letterGrade = "D-";
59. }
60. else
61. {
62. letterGrade = "F";
63. }

64. cout<<"For a score of "<<marks<<" marks letter grade is


"<<letterGrade;
65. return 0;
66. }

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>

2. using namespace std;

3. int main()
4. {

Page 12 of 13
EE-163(C&P) lesson_04 EED FR, IA

5. double operand1, operand2, result;


6. char op;
7. cout << "Enter an expression (operand1 operator operand2): ";
8. cin >> operand1 >> op >> operand2;

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;

3. int main (void)


4. {
5. int count = 1;
6. while (count <= 10)
7. {
8. cout<<"Hello world!\n";
9. ++count;
10. }
11. return 0;
12. }
Output

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. }

Generally, a while loop contains the following components


i. Loop control variable: A variable mostly inside the relational expression.
ii. Relational Expression
iii. Body (Multiple statements)
iv. A statement that makes the relational expression false
Based on the way, the statement which makes the relational expression false, while loop can be
categorized into two types.
i. Count Controlled
ii. Sentinel Controlled

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

Nested for Loop


les_05_code_10.cpp
// nested for loop

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

les_05_code_12 (UIY Understand it yourself)


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 <= i; ++j)
9. {
10. cout<<star;
11. }
12. cout<<endl;
13. }

14. for (int i = 5; i > 0; --i)


15. {
16. for(int j = i; j > 0; --j)
17. {
18. cout<<star;
19. }

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

Applications with Repetition Statements


This lesson is aimed to introduce the ideas of algorithm implementation. Algorithm implementation is an
important job of engineer. We have learnt sufficient basic tools to implement programming solution for
some real world problems. Some tools will be taught afterwards and they will further strengthen your
ability to implement algorithms.

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>

2. using namespace std;


3. int main (void)
4. {
5. // variable definition
6. int counter, loopruns;
7. // initializing newterm and prevterm to 1
8. //sum cantains the next number in the sequence
9. int newterm=1,prevterm=1,sum;
10. cout<<"\t\t Fibonacci Series with Golden Ratio";
11. // Input
12. cout<<"\nHow many Fibonacci numbers do you want to see:";
13. cin>>loopruns;
14. // display the first term
15. cout<<"\n The fibonacci numbers you ordered
are:\nnumber:"<<prevterm;
16. // for rest of the terms
17. for(counter=1;counter<loopruns;counter++)
18. {
19. cout<<"\nnumber: "<<newterm;
20. cout<<",Ratio of
"<<newterm<<"/"<<prevterm<<"="<<((float)newterm/(float)prevterm);
21. sum=prevterm+newterm;
22. prevterm=newterm;
23. newterm=sum;
24. }

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;

7. // Taking inputs and doing processing before loop starts


8. cout<<"\nEnter a number to start running sum:";
9. cin>>num;
10. running_sum=running_sum+num;

11. // while loop to calculate the running sum of input


12. while(running_sum<=1000) // loop terminates when running_sum
exceeds
13. { //n= 1000
14. cout<<"\nRunning sum="<<running_sum;
15. cout<<"\nEnter another number:";

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>

2. using namespace std;


3. int main(void)
4. {
5. // variable definition
6. int num,num_alias,digitcnt=0;
7. // Taking input

Page 4 of 13
EE-163(C&P) lesson_06 EED FR, IA

8. cout<<"\nEnter an integer to find "<<


9. "the number of digits in it:";
10. cin>>num;
11. num_alias=num; // saving num so that it can be used at the
end
12. // while loop to calculate the running sum of input
13. while(num_alias>0) // loop terminates when num_alias becomes zero
14. {
15. num_alias=num_alias/10;
16. digitcnt=digitcnt+1;
17. }
18. // displaying result
19. cout<<"\nNo of digits in "<<num<<
20. " = "<<digitcnt;

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;

9. // Taking one character at a time


10. // as input in chinput
11. char chinput;
12. cout<<"\nEnter any text,"<<
13. " press ESC to stop:\n";
14. chinput=getche(); // taking input in
15. //loop control variable
16. //(chinput) before
17. // entering the loop

18. while(chinput!=27)// loop terminates when


19. { // chinput is ASCII 27,
20. // which is for ESC key
21. ch_cnt=ch_cnt+1;

Page 5 of 13
EE-163(C&P) lesson_06 EED FR, IA

22. if(chinput==' ') // we could have used


23. { // ASCII value over here
24. word_cnt=word_cnt+1;
25. }

26. // any condition where a sentence ends


27. if((chinput=='.')||(chinput=='?'))
28. {
29. sentence_cnt=sentence_cnt+1;
30. word_cnt=word_cnt+1;
31. }

32. if(chinput==13) // The ASCII character for ENTER, its


character mask is '\n'
33. {
34. cout<<endl;
35. }

36. chinput=getche(); // taking next character before the loop


starts again
37. }

38. ch_cnt=ch_cnt-1; // to subtract the last ESC key

39. // displaying why the program has stopped


40. cout<<"\n\nYou entered "<<ch_cnt<<
41. " character(s), "<<word_cnt<<
42. " word(s) and "<<sentence_cnt<<
43. " sentence(s).";
44. getch();
45. return 0;
46. }

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. }

17. cout<<"Greatest Common Divison (GCD) : "<<gcd<<endl;


18. return 0;
19. }

Sample Output

les_06_code_07.cpp
Euclid Subtraction GCD Algorithm
1. #include <iostream>

2. using namespace std;

3. int main()
4. {

5. int num1, num2;


6. cout << "Enter num1 : ";
7. cin >> num1;

Page 7 of 13
EE-163(C&P) lesson_06 EED FR, IA

8. cout << "Enter num2 : ";


9. cin >> num2;

10. while (num1 != num2 )


11. {
12. if (num1 > num2)
13. {
14. num1 = num1 - num2;
15. }
16. else
17. {
18. num2 = num2 - num1;
19. }
20. }

21. cout << "GCD is " << num1;


22. return 0;
23. }

Sample Output

les_06_code_08.cpp
Faster Euclid GCD
1. #include <iostream>

2. using namespace std;

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

5. int main (void)


6. {
7. int num,divisor,remainder;
8. cout<<"Enter a number:";
9. cin>>num;
10. // Some conditions to increase program speed
11. if((num>2) && (num%2==0))
12. {
13. cout<<"\n The no. is composite";
14. return 0;
15. }
16. if((num>3)&&(num%3==0))
17. {
18. cout<<"\n The no. is composite";
19. return 0;
20. }
21. // some defensive conditions
22. if(num==2)
23. {
24. cout<<"\nThe number is prime";
25. return 0;
26. }

27. //int count = 0;


28. // divisor is required to increment only till
29. //sqrt(num) and not num, prove it yourself.
30. for(divisor=2;divisor<=(int)sqrt((double)num);divisor++)
31. {
32. remainder=num%divisor;
33. if(remainder==0)
34. {
35. cout<<"\n Composite";
36. break;
37. }

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

Functions & Recursion


A function is an individual set of instructions invoke able for a single purpose. Functions allow to structure
programs in segments of code to perform individual tasks. In C++ a function is a group of statements that
is given a name, and which can be called from some point of the program. Following codes will explain the
idea.
les_07_code_01.cpp
1. #include<iostream>
2. using namespace std;

3. int square(int num1)


4. {
5. int squared;
6. squared = num1 * num1;
7. return squared;
8. }

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;

3. int square(int num1)


4. {
5. return num1*num1;
6. }

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;

3. int maximum(int a, int b, int c)


4. {
5. int largest;
6. if (a>b)
a. largest = a;
7. else
a. largest = b;
8. if (c>largest)
a. largest = c;
9. return largest;
10. }

11. int main()


12. {
13. int num1, num2, num3, max;
14. cout<<"Enter three numbers : ";
15. cin>>num1>>num2>>num3;
16. max = maximum(num1,num2,num3);
17. cout<<"Largest number you entered is "<<max;
18. return 0;

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

18. cout<<val<<" is Even";


19. else
20. cout<<val<<" is Odd";
21. return 0;
22.
23. }

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. }

10. int main(void)


11. {

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. }

10. int main(void)


11. {
12. Heading("EE-163 Computers & Programming","FE - Electrical");
13. return 0;
14. }

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;

3. void swap(int a, int b)

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. }

10. int main()


11. {
12. int num1, num2;
13. num1 = 13;
14. num2 = 12;
15. cout<<num1<<endl;
16. cout<<num2<<endl;
17. swap(num1, num2);
18. cout<<num1<<endl;
19. cout<<num2<<endl;
20. return 0;
21. }

les_07_code_11.cpp
Pass by reference
1. #include<iostream>
2. using namespace std;

3. void swap(int &a, int &b)


4. {
5. int temp;
6. temp = b;
7. b = a;
8. a = temp;

9. }

10. int main()


11. {
12. int num1, num2;
13. num1 = 13;
14. num2 = 12;
15. cout<<num1<<endl;
16. cout<<num2<<endl;
17. swap(num1, num2);
18. cout<<num1<<endl;
19. cout<<num2<<endl;
20. return 0;
21. }

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. }

10. void infinite_recursion (void)


11. {
12. cout<<endl<<"Function call within function";
13. infinite_recursion();
14. }

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;

3. int fibonacci(int num); // Function Prototype for fibonacci()


4. int main(void)
5. {
6. int a,b;
7. cout<<endl<<"Enter the Fibonacci number you wish to find:\n";
8. cin>>a;
9. b=fibonacci(a); // Function Call
10. cout<<"\nTerm "<<a<<" of Fibonacci sequence is "<<b<<endl;
11. return 0;
12. }
13. int fibonacci(int num) // Function Prototype
14. {
15. if(num==0)
16. {
17. return 0;
18. }
19. if(num==1)
20. {
21. return 1;
22. }
23. if(num>1)
24. {
25. return fibonacci(num-1)+fibonacci(num-2);
26. }
27. }

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) Some more declaration and initialization

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 }

5) Computing average of 10 numbers with arrays

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 }

6) Using for loop to display array contents – a better method


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 int index_count;//an integer variable to access different array locations
12
13 // taking array input through for() loop: index_count runs from 0 to 9
14
9
15 for(index_count=0;index_count<LIM;index_count++)
16 {
17 cout<<"\nEnter element number "<<index_count<<":";
18 cin>>num[index_count];
19 }
20 cout<<endl<<endl;
21 cout<<"press any key to continue.....";
22 getch();
23 // printing array: method 1
24 for(index_count=0;index_count<LIM;index_count++)
25 {
26 cout<<index_count<<":"<<num[index_count]<<endl;
27 }
28 cout<<endl<<endl;
29 // printing array: method 2
30 for(index_count=0;index_count<LIM;index_count++)
31 {
32 cout<<index_count<<":"<<num[index_count]<<" ";
33 if((index_count+1)%5==0)
34 {
35 cout<<endl;
36 }
37 }
38 return 0;}

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 }

8) Average of array elements with while loop ( UIY)


1 // Proper method of processing arrays with while() loop
2 #include<iostream>
3 #include<conio2.h>
4 using namespace std;
5 #define LIM 100
6 // when we want to process arrays partially, while() loop
7 // provides an elegant structure but requires careful thinking.
8 int main(void)
9 {
10 // variable definition
11 float num[LIM]; // 100 element float array, numbered 0 to 99
12 int index_count=0;// an integer variable to access different array locations
13 int max_index; // an integer variable to store the number of elements
14 // actually used
15 char option; // char variable to control the while loop
16 float sum=0.0,average; //running sum and average
17 // asking user to start array input before starting while() loop
18 cout<<"\nWould you like to enter array value (y or n):";
12
19 option=getche();
20 / while(option=='y') // condition as per given message
21 {
22 cout<<"\nEnter element number "<<index_count<<":";
23 cin>>num[index_count];
24 cout<<"\nWould you like to enter another value? (y or n):";
25 option=getche();
26 ++index_count;
27 if(index_count>=1000) // separate breaking condition
28 {
29 cout<<"\nArray Overflow.";
30 break; // we can also write option='n';
31 }
32 }
33 max_index=index_count; // saving the the last element number given by user
34 cout<<"\n\n";
35 // calculating running sum
36 for(index_count=0;index_count<max_index;index_count++)
37 {
38 sum=sum+num[index_count];
39 }
40 //calculating and printing average
41 average=sum/index_count;
42 cout<<"\n\nAverage of given "<<index_count<<" numbers is "<<average;
43 getch();
44 return 0;
45 }
46 // Note: 1) A while() loop is feasible when we have to process a subset of array
47 // elements from the total array locations.
48 // 2) When taking array input with while() loop, two steps can be taken to
49 // reduce further complexity:
50 // a) Storing the total number of elements actually used
51 // in a separate variable after the loop.
52 // b) Writing a separate breaking condition inside the
53 // loop for array overflow.
54 // After taking these steps we can do further processing using for() loops.
55
13
9) Array exercise 1:reversing an array within
1 //Array exercise 1: Reversing an array within
2 //These exercises are provided for self practice
3 //so UIY (Understand It Yourself)
4 #include<iostream>
5 #include<conio2.h>
6 using namespace std;
7 #define MAX 100
8 int main (void)
9 { // Variable declaration and definition
10 int num[MAX]={1,2,3,4,5,6,7,8,9,10};
11 int index, reverse_index, buffer, max_index=9;
12 // Displaying original array
13 cout<<"original array is:";
14 for(index=0;index<10;index++)
15 {
16 cout<<num[index]<<" ";
17 }
18 // Reversing loop
19 reverse_index=max_index;
20 for(index=0;index<=(max_index/2);index++)
21 {
22 // Swapping the top and bottom elements
23 buffer=num[index];
24 num[index]=num[reverse_index];
25 num[reverse_index]=buffer;
26 --reverse_index;
27 }
28 // Displaying reversed array
29 cout<<"\nthe reversed array is:";
30 for(index=0;index<10;index++)
31 {
32 cout<<num[index]<<" ";
33 }
34 return 0;
35 } 14
36
10) Array exercise 2:Inserting an element at specified location
1 ///Array exercise 2: Inserting an element at specified location
2 //These exercises are provided for self practice
3 //so UIY (Understand It Yourself)
4 #include<iostream>
5 #include<conio2.h>
6 using namespace std;
7 #define MAX 100
8 int main(void)
9 {
10 // variable definition
11 float temp[MAX]={ 1.0, 2.3, 4.8, -5.3, 6.6, 9.8, 0.5, 2.3, 1.0, 12.7};
12 int index_count, insert_index, max_index=9;
13 float insert_element;
14 // Displaying the original array
15 for(index_count=0;index_count<=max_index;index_count++)
16 {
17 cout<<"\nElement "<<index_count<<" = "<<temp[index_count];
18 }
19 // Asking user to enter element value and index to be inserted
20 cout<<"\n\nEnter value to be inserted (float number):";
21 cin>>insert_element;
22 cout<<"\n\nEnter location where value is to be inserted:";
23 cin>>insert_index;
24
25 // Inserting
26 // Shifting all elements 1 location down to make space
27 // for new value (from insert_index to last)
28 for(index_count=max_index;index_count>=insert_index;index_count--)
29 {
30 temp[index_count+1]=temp[index_count];
31 }
32 temp[insert_index]=insert_element;// Now put the new value at specified index
33 max_index++; // Increasing max_index as array size increased
34
35 // Displaying the final, processed array
36 for(index_count=0;index_count<=max_index;index_count++)
37 {
38 cout<<"\nElement "<<index_count<<" = "<<temp[index_count];
39 }
40 getch();
41 return 0; 15
}
11) Array exercise 3: Deleting an element from specified location
1 //These exercises are provided for self practice
2 //so UIY (Understand It Yourself)
3 #include<iostream>
4 #include<conio2.h>
5 using namespace std;
6 #define MAX 100
7 int main(void)
8 {
9 // variable definition
10 float temp[MAX]={ 1.0, 2.3, 4.8, -5.3, 6.6, 9.8, 0.5, 2.3, 1.0, 12.7};
11 int index_count, delete_index, max_index=9;
12 // Displaying the original array
13 for(index_count=0;index_count<=max_index;index_count++)
14 {
15 cout<<"\nElement "<<index_count<<" = "<<temp[index_count];
16 }
17 // Asking user to enter element index to be deleted
18 cout<<"\n\nEnter location to be deleted:";
19 cin>>delete_index;
20
21 // Deleting
22 // Shifting all elements 1 location up (from delete_index to last)
23 for(index_count=delete_index;index_count<max_index;index_count++)
24 {
25 temp[index_count]=temp[index_count+1];
26 }
27 max_index--; // reducing total tally count as one element is deleted
28
29 // Displaying the final, processed array
30 for(index_count=0;index_count<=max_index;index_count++)
31 {
32 cout<<"\nElement "<<index_count<<" = "<<temp[index_count];
33 }
34 getch();
35 return 0;} 16
36
12) Array exercise 4: Shifting an array downward by given amount
1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4 #define MAX 100
5 int main (void)
6 {
7 int num[MAX]={1,2,3,4,5,6,7,8,9,0};
8 int index, downshift, max_index=9 ;
9 cout<<"original array is:";
10 for(index=0;index<=max_index;index++)
11 {
12 cout<<endl<<num[index];
13 }
14 // shifting inputs
15 cout<<"\nEnter the amount of down shift:";
16 cin>>downshift;
17 //*********Actual Shifting Takes Place Here***********
18 for(index=max_index;index>=downshift;index--)
19 {
20 num[index]=num[index-downshift];
21 }
22 // zero padding
23 for(index=0;index<downshift;index++)
24 {
25 num[index]=0;
26 }
27 // ********Shifting ends here**********************
28 // display the final output
29 cout<<"\n the shifted array is:";
30 for(index=0;index<10;index++)
31 {
32 cout<<endl<<num[index];
33 }
34 return 0;
35 } 17
36
12) Array exercise 4: Shifting an array downward by given amount
1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4 #define MAX 100
5 int main (void)
6 {
7 int num[MAX]={1,2,3,4,5,6,7,8,9,0};
8 int index, downshift, max_index=9 ;
9 cout<<"original array is:";
10 for(index=0;index<=max_index;index++)
11 {
12 cout<<endl<<num[index];
13 }
14 // shifting inputs
15 cout<<"\nEnter the amount of down shift:";
16 cin>>downshift;
17 //*********Actual Shifting Takes Place Here***********
18 for(index=max_index;index>=downshift;index--)
19 {
20 num[index]=num[index-downshift];
21 }
22 // zero padding
23 for(index=0;index<downshift;index++)
24 {
25 num[index]=0;
26 }
27 // ********Shifting ends here**********************
28 // display the final output
29 cout<<"\n the shifted array is:";
30 for(index=0;index<10;index++)
31 {
32 cout<<endl<<num[index];
33 }
34 return 0;
35 } 18
36
13) Sequential Search: Searching an element in array
1 #include<iostream>
2 #include<conio2.h>
3 #include<cmath>
4 using namespace std;
5 #define MAX 100
6 int main(void)
7 { //Variable Definition and Declaration
8 float num[MAX]={12.0,5.5,7.3,6.0,3.0,0.5,9.8,7.5,2.9,66.0};
9 int index,check_flag=0, max_index=9, search_index;
10 float search_value;
11 // Entering value to be searched
12 cout<<"Enter the number to search in the array:";
13 cin>>search_value;
14
15 // Searching location No. of the search_value
16 for(index=0;index<=max_index;index++)
17 {
18 if(fabs(num[index]-search_value)<0.0001) // num[index]==search_value
19 {
20 check_flag=1;
21 search_index=index;
22 break;
23 }
24 }
25
26 if(check_flag==1)
27 {
28 cout<<"\nsearch value "<<search_value<<" found at location:"<<search_index;
29 }
30 else
31 {
32 cout<<"\nNo search found ";
33 }
34 return 0;
35 } 19
14) Bubble sort (Exchange sort): Sorting an array in order
1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4 #define MAX 100
5
6 int main (void)
7 { // Variable definition and declaration
8 int num[MAX]={10,2,34,4,-5,6,77,18,9,0};
9 int pivot, moving_index, buffer, max_index=9;
10 //Displaying the original array
11 cout<<"original array is:";
12 for(pivot=0;pivot<=max_index;pivot++)
13 {
14 cout<<num[pivot]<<" ";
15 }
16 // sorting with Bubble Sort Algorithm
17 //Outer Loop: controls pivot 0 to (max_index-1)
18 for(pivot=0;pivot<max_index;pivot++)
19 {
20 //Inner Loop controls moving_index=pivot+1 to max_index
21
22 for(moving_index=pivot+1;moving_index<=max_index;moving_index++)
23 {
24 //if the following element is less than preceeding element
25 // then swap: the '<' can be replaced with '>' to sort in
26 // descending order
27 if(num[moving_index]<num[pivot])
28 {
29 buffer=num[moving_index];
30 num[moving_index]=num[pivot];
31 num[pivot]=buffer;
32 }
33 }
34 }
35 20
36 // display final array
37 cout<<"\nthe sorted array is:";
38 for(pivot=0;pivot<=max_index;pivot++)
39 {
40 cout<<num[pivot]<<" ";
41 }
42 return 0;
43 }

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 }

16) Passing arrays to functions: Checking for Palindromes


1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4 #define MAX 100
5
6 //Prototype 1:function to copy a char array into another
7 void copychararray(const char arr1[],char arr2[], int SIZE);
8
9 //Prototype 2:function to reverse a char array within itself
10 void reversechararray(char arr[],int start,int stop, int SIZE);
11
12 //Prototype 3:compare char arrays of same size, element by element
13 bool comparechararray(const char arr1[],const char arr2[],int SIZE);
14 24
15 int main (void)
16 {
17 // Variable definition and declaration
18 char word1[10]={'r','a','c','e','e','a','r'};
19 char word2[10];
20 cout<<"The first word is:";
21 for(int index=0;index<7;index++)
22 {
23 cout<<word1[index];
24 }
25 cout<<endl<<endl;
26 copychararray(word1,word2,7);
27 cout<<"The 2nd word is:";
28 for(int index=0;index<7;index++)
29 {
30 cout<<word2[index];
31 }
32 cout<<endl<<endl;
33 reversechararray(word2,0,6,10);
34 cout<<"The 2nd word, reversed is:";
35 for(int index=0;index<7;index++)
36 {
37 cout<<word2[index];
38 }
39 cout<<endl<<endl;
40 if(comparechararray(word1,word2,7)==1)
41 {
42 cout<<"word1 is a palindrome";
43 }
44 else
45 {
46 cout<<"word1 is not a palindrome";
47 }
48 return 0;
49 }
50
25
51 //Definition 1:
52 void copychararray(const char arr1[],char arr2[], int SIZE)
53 {
54 int index;
55 for(index=0;index<SIZE;index++)
56 {
57 arr2[index]=arr1[index];
58 }
59 }
60 //Definition 2:
61 void reversechararray(char arr[],int start,int stop, int SIZE)
62 {
63 int index, reverse_index=stop;
64 char temp;
65 if(start>=0 && start<stop && stop<SIZE )
66 {
67 for(index=0;index<(stop/2);index++)
68 {
69 // Swapping the top and bottom elements
70 temp=arr[index];
71 arr[index]=arr[reverse_index];
72 arr[reverse_index]=temp;
73 --reverse_index;
74 }
75 }
76 else
77 {
78 cout<<"\n\ncopy operation failed";
79 }
80 }
81 //Definition 3:
82 bool comparechararray(const char arr1[],const char arr2[], int SIZE)
83 {
84 for(int index=0;index<SIZE;index++)
85 {
86 if(arr1[index]!=arr2[index])
87 {
88 return 0;
89 }
90 }
91 return 1;
92 }
93 26
17) Application Program: Making Histogram for frequency distribution
1 #include <iostream>
2 #include <cstdlib>
3 #include <ctime>
4
5 using namespace std;
6
7 void buildrandomarray(int arr[], int size);
8
9 void clearintarray(int arr[], int size);
10
11 void displayintarray(int arr[], int size);
12
13 void histogram(int arr[], int size);
14
15
16 int main(void)
17 {
18 const int size = 10;
19 int numbers[size];
20 buildrandomarray(numbers, size);
21 cout << endl;
22 displayintarray(numbers, size);
23 cout << endl;
24 int distrib[size];
25 clearintarray(distrib, size);
26 for(int i = 0; i < size; ++i)
27 distrib[numbers[i]] += 1;
28 displayintarray(distrib,size);
29 cout << endl;
30 histogram(distrib, size);
31 cout << endl;
32 return 0;
33 }
34
35 27
36 void buildrandomarray(int arr[], int size)
37 {
38 srand(time(NULL));
39 for(int i = 0; i < size; ++i)
40 arr[i] = rand() % 10 + 0;
41 }
42
43 void clearintarray(int arr[], int size)
44 {
45 for(int i = 0; i < size; ++i)
46 arr[i] = 0;
47 }
48
49 void displayintarray(int arr[], int size)
50 {
51 for(int i = 0; i < size; ++i)
52 {
53 cout << i << ": " << arr[i]<<" ";
54 if((i+1)%5==0)
55 {
56 cout<<endl;
57 }
58 }
59
Output:
60 }
61
62 void histogram(int arr[], int size)
63 {
64 for(int i = 0; i < size; ++i) {
65 cout << i << ": ";
66 for(int j = 1; j <= arr[i]; ++j)
67 cout << "*";
68 cout << endl;
69 }
70 }
71
28
72
29
18) 2D Array Introduction: Using nested loop to manipulate 2D array
1 //2D Arrays Intro
2 #include<iostream>
3 #include<conio2.h>
4 using namespace std;
5
6 #define row 5
7 #define col 3
8
9 int main(void)
10 {
11 int i,j;
12 float num[row][col];
13 cout<<"Enter elements of array:";
14 //***************nested loop for scanning**************
15 for(i=0;i<row;i++) // i controls rows
16 {
17 for(j=0;j<col;j++) // j controls columns
18 {
19 cout<<"\nEnter location "<<i<<","<<j<<":";
20 cin>>num[i][j];
21 }
22 }
23 cout<<"\n \n";
24 //***************nested loop for printing**************
25 for(i=0;i<row;i++) // i controls rows
26 {
27 for(j=0;j<col;j++) // j controls columns
28 {
29 cout<<i<<","<<j<<"="<<num[i][j]<<" ";
30 }
31 cout<<"\n";
32 }
33 getch();
34 return 0;
35 } 30
19) 2D Array Introduction: Part 2
1 //2D Arrays Intro:Part 2
2 #include<iostream>
3 #include<conio2.h>
4 using namespace std;
5 int main(void)
6 {
7 const int row=5,col=5;
8 int i,j;
9 //2D float array initialization
10 float num[row][col]={{2,6,23},{43,6,18},{1,5,9}};
11 //2D char array initialization
12 char animals[row][col]={{'c','a','t'},{'b','a','t'},{'r','a','t'}};
13 //***************nested loop for printing**************
14 for(i=0;i<row;i++) // i controls rows
15 {
16 for(j=0;j<col;j++) // j controls columns
17 {
18 cout<<i<<","<<j<<"="<<num[i][j]<<" ";
19 }
20 cout<<"\n"; 31
21 }
22 cout<<"\n\n";
23 //***************nested loop for printing**************
24 for(i=0;i<row;i++) // i controls rows
25 {
26 for(j=0;j<col;j++) // j controls columns
27 {
28 cout<<i<<","<<j<<"="<<animals[i][j]<<" ";
29 }
30 cout<<"\n";
31 }
32 cout<<"\n\n";
33 //another way to print 2D char array
34 //*********this method prints one row at once**************
35 for(i=0;i<row;i++) // i controls rows
36 {
37 cout<<animals[i]<<endl;
38 }
39 getch();
40 return 0;
41 }

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 }

21) 2D array to functions


1 #include<iostream>
2 #include<conio2.h>
3 using namespace std;
4 #define ROW 3
5 #define COL 3
6 //Prototype for square-matrix addition function
7 void matadd(double a[][COL],double b[][COL],double c[][COL],int dimension);
8
9 //Prototype for square-matrix subtraction function
10 void matsub(double a[][COL],double b[][COL],double c[][COL],int dimension);
11
12 //Prototype for square-matrix multiplication function
13 void matmul(double a[][COL],double b[][COL],double c[][COL],int dimension);
14
15 int main(void)
16 {
17 // A[][] and B[][] arrays for input, C[][] for output. All are initially 0.
18 double A[ROW][COL],B[ROW][COL],C[ROW][COL];
19 int index_row,index_col,k;
34
20 char option;
21 for(int c = 0; c < cols; ++c)
22 {
23 cout << "Test " << c+1 << ": ";
24 for(int r = 0; r < rows; ++r)
25 {
26 cout << grades[r][c] << " ";
27 total += grades[r][c];
28 }
29 average = total / rows;
30 cout << "Average: " << average << endl;
31 total = 0;
32 average = 0.0;
33 }
34 return 0;
35 }
36
37 //****************Enter contents in A[][]***********************
38 cout<<"Enter the contents of matrix A";
39 for(index_row=0;index_row<ROW;index_row++)
40 {
41 for(index_col=0;index_col<COL;index_col++)
42 {
43 cout<<"\nEnter element "<<index_row<<","<<index_col<<":";
44 cin>>A[index_row][index_col];
45 }
46 }
47
48 //***************Enter contents in B[][]************************
49 cout<<"\n\nEnter the contents of matrix B";
50 for(index_row=0;index_row<ROW;index_row++)
51 {
52 for(index_col=0;index_col<COL;index_col++)
53 {
54 cout<<"\nEnter element "<<index_row<<","<<index_col<<":";
55 cin>>B[index_row][index_col];
56 }
35
57 }
58 cout<<"\n\nWhat operation do you need to perform?";
59 cout<<"\nEnter +, - or *:";
60 option=getche();
61
62 switch(option)
63 {
64 case '+':
65 matadd(A,B,C,3);
66 break;
67 case '-':
68 matsub(A,B,C,3);
69 break;
70 case '*':
71 matmul(A,B,C,3);
72 break;
73 default:
74 cout<<"\nInvalid Operator.";
75 return 0;
76 }
77 cout<<"\n\n";
78 // ***************display result ***********************
79 for(index_row=0;index_row<ROW;index_row++)
80 {
81 for(index_col=0;index_col<COL;index_col++)
82 {
83
84 cout<<index_row<<","<<index_col<<":"<<C[index_row][index_col]<<" ";
85 }
86 cout<<"\n";
87 }
88 return 0;
89 }
90
91 //definition for square-matrix addition function
92 void matadd(double a[][COL],double b[][COL],double c[][COL],int dimension)
93 {
36
94
95 for(int index_row=0;index_row<dimension;index_row++)
96 {
97 for(int index_col=0;index_col<dimension;index_col++)
98 {
99
100 c[index_row][index_col]=a[index_row][index_col]
101 +b[index_row][index_col];
102 }
103 }
104 }
105
106 //Prototype for square-matrix subtraction function
107 void matsub(double a[][COL],double b[][COL],double c[][COL],int dimension)
108 {
109 for(int index_row=0;index_row<dimension;index_row++)
110 {
111 for(int index_col=0;index_col<dimension;index_col++)
112 {
113 c[index_row][index_col]=a[index_row][index_col]
114 -b[index_row][index_col];
115 }
116 }
117 }
118
119 //Prototype for square-matrix multiplication function
120 void matmul(double a[][COL],double b[][COL],double c[][COL],int dimension)
121 {
122 for(int index_row=0;index_row<dimension;index_row++)
123 {
124 for(int index_col=0;index_col<dimension;index_col++)
125 {
126 c[index_row][index_col]=0.0;
127 for(int k=0;k<dimension;k++) // loop for running sum
128 {
129 c[index_row][index_col]=c[index_row][index_col]
130 +(a[index_row][k]*b[k][index_col]);
131 }
132 }
133 }
134 }

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

Task: Declare pointer to char, bool, double, float data types.

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

Relationship Between Array and Pointers


les_09_code_04.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. array[i] = (i + 2)/.512;
9. }
10. cout<<"Printing Array Directly"<<endl;
11. for(int i=0; i<10;i++)
12. {
13. cout<<"\n Element "<<i<<" : "<<array[i];
14. }
15. cout<<"\nPrinting array via pointer\n";
16. for(int i = 0; i<10; i++)
17. {
18. cout<<"\n Element "<<i<<" : "<<*(array + i);
19. }
20. return 0;
21. }

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

You might also like