Chapter 2 Computer Programming Fresh Man
Chapter 2 Computer Programming Fresh Man
Computer programming
Chapter Two
C++ Basics
Structure of C++ Program
A C++ program has the following structure
Comments:- single line and multiple line comment
Preprocessor directives:- All the preprocessor directives in C++ start
with the # (hash) symbol
Global variable declarations:-A global variable can be accessed from
anywhere in the entire program. It is usually declared at the top or
start of the program outside of all blocks and functions of the
program.
Prototypes of functions:-A function prototype begins with the
keyword function, then lists the function name, its parameters (if
any), and return value (if any).
Definitions of functions:-A function is a block of code which only runs
when it is called.
C++ Integrated Development
Environment(IDE)
An Integrated Development Environment (IDE) is a software suite that
combines tools needed for software development, such as a code editor,
debugger, and build automation tools, into one user-friendly interface.
It often includes features like code completion and version control
integration.
The complete development cycle in C++ is: Write the program, compile the
source code, link the program, and run it.
•Writing: Using a text editor to create C++ source files (.cpp).
•Compiling: Using a C++ compiler to translate source code into object files.
•Linking: Combining object files into an executable program.
•Running: Executing the program to see its output or behavior.
Cont.…
Writing a Program
To write a source code, your compiler may have its own built-in text editor, or you
may be using a commercial text editor or word processor that can produce text
files.
The important thing is that whatever you write your program in, it must save
simple, plain-text files, with no word processing commands embedded in the text.
Simple editors like Notepad (on Windows) or TextEdit (on macOS).
Specialized editors like Visual Studio Code, Code::Blocks, Dev C++,
NetBeans, Quincy, Sublime Text, or Atom.
The files you create with your editor are called source files, and for C++ they
typically are named with the extension .CPP.
For example, you might create a file named hello.cpp.
Cont.…
Compiling
Your source code file can't be executed, or run, as a program can.
To turn your source code into a program, you use a compiler.
How you invoke your compiler, and how you tell it where to find your
source code, will vary from compiler to compiler.
In Borland's Turbo C++ you pick the RUN menu command or type tc
<filename>
from the command line, where <filename> is the name of your source
code file (for example, test.cpp).
Other compilers may do things slightly differently.
After your source code is compiled, an object file is produced.
This file is often named with the extension .OBJ.
This is still not an executable program, however,to turn this into an
executable program, you must run your linker.
Cont.…
• Linking
• C++ programs are typically created by linking together one or more
OBJ files with one or more libraries.
• A library is a collection of linkable files that were supplied with your
compiler, that you purchased separately, or that you created and
compiled.
• All C++ compilers come with a library of useful functions (or
procedures) and classes that you can include in your program.
• A function is a block of code that performs a service, such as adding
two numbers or printing to the screen.
• A class is a collection of data and related functions.
Cont.…
Summary
The steps to create an executable file are
1. Create a source code file, with a .CPP extension.
2. Compile the source code into a file with the .OBJ extension.
3. Link your OBJ file with any needed libraries to produce an executable program.
However, this is a fairly technical distinction, and for practical purposes you are advised
to treat main, cin, and cout as if they were reserved as well.
Syntax of an identifier
Identifiers
An identifier is name associated with a function or data object and used to refer to that
function or data object. Letter
An identifier must: Letter
Start with a letter or underscore - Digit
Consist only of letters, the digits 0-9, or the underscore symbol _ -
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
Cont.…
• An assignment operation is itself an expression whose value is the value
stored in its left operand.
• An assignment operation can therefore be used as the right operand of
another assignment operation.
• Any number of assignments can be concatenated in this fashion to form
one expression. For example:
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
• This is equally applicable to other forms of assignment. For example:
m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);
Cont.…
Arithmetic Operators
• C++ provides five basic arithmetic operators.
• Except for remainder (%) all other arithmetic operators can accept a mix of integer and
real operands.
• Generally, if both operands are integers then the result will be an integer.
• However, if one or both of the operands are reals then the result will be a real (or double
to be exact).
• When both operands of the division operator (/)
are integers then the division is performed as an
Operator Name Example
+ Addition 12 + 4.9 // gives 16.9 integer division and not the normal division we
- Subtraction 3.98 - 4 // gives -0.02 are used to.
Multiplicatio
* n 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5 • Integer division always results in an integer
13 % 3 //gives 1
% Remainder // gives 1 outcome (i.e., the result is always rounded down).
Arithmetic operators.
For example: 9/2 // gives 4, not 4.5!
(representing the true outcome) or 0 > Greater Than 5 > 5.5 // gives 0
• Logical negation is a unary operator, which negates the logical value of its single
operand. If its operand is nonzero it produces 0, and if it is 0 it produces 1.
• Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it
produces 1.
• Logical or produces 0 if both of its operands evaluate to 0. Otherwise, it
produces 1.
Cont.…
• Note that here we talk of zero and nonzero operands (not zero and 1).
• In general, any nonzero value can be used to represent the logical
true, whereas only zero represents the logical false.
• The following are, therefore, all valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
• C++ does not have a built-in boolean type.
• It is customary to use the type int for this purpose instead. For example:
int sorted = 0; // false
int balanced = 1; // true
Cont.…
Bitwise Operators
C++ provides six bitwise operators for manipulating the individual bits in an integer quantity.
Operator Description Example
Binary AND Operator copies a bit to the result if it exists in both
& operands. (A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
Binary XOR Operator copies the bit if it is set in one operand but
^ not both. (A ^ B) will give 49 which is 0011 0001
Binary Ones Complement Operator is unary and has the effect of (~A ) will give -61 which is 1100 0011 in 2's
~ 'flipping' bits. complement form due to a signed binary number.
Binary Left Shift Operator. The left operands value is moved left by
<< the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
Binary Right Shift Operator. The left operands value is moved right
>> by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111
Cont.…
• Bitwise operators expect their operands to be integer quantities and
treat them as bit sequences.
• Bitwise negation is a unary operator which reverses the bits in its
operands.
• Bitwise and compares the corresponding bits of its operands and
produces a 1 when both bits are 1, and 0 otherwise.
• Bitwise or compares the corresponding bits of its operands and
produces a 0 when both bits are 0, and 1 otherwise.
• Bitwise exclusive or compares the corresponding bits of its operands
and produces a 0 when both bits are 1 or both bits are 0, and 1
otherwise.
Cont.…
• Bitwise left shift operator and bitwise right shift operator both take
a bit sequence as their left operand and a positive integer quantity n
as their right operand.
• The former produces a bit sequence equal to the left operand but
which has been shifted n bit positions to the left.
• The latter produces a bit sequence equal to the left operand but
which has been shifted n bit positions to the right. Vacated bits at
either end are set to 0.
Cont.…
• To avoid worrying about the sign bit (which is machine dependent), it is common to
declare a bit sequence as an unsigned quantity:
unsigned char x = '\011';
unsigned char y = '\027';
• Table below illustrates how the bits are calculated.
• To calculate the bit sequence for the given values of
unsigned char, we need to understand the values in
both octal and binary notation.
Example Octal Value Bit Sequence
x 011 0 0 0 0 1 0 0 1 Step-by-Step Conversion
y 027 0 0 0 1 0 1 1 1 1.Values in Octal:
~x 366 1 1 1 1 0 1 1 0 •\011 in octal
x&y 001 0 0 0 0 0 0 0 1 •\027 in octal
x|y 037 0 0 0 1 1 1 1 1 2.Convert Octal to Decimal:
x^y 036 0 0 0 1 1 1 1 0 •\011 (octal) = 1*8^1 + 1*8^0 = 8 + 1 = 9
x << 2 044 0 0 1 0 0 1 0 0
x >> 2 002 0 0 0 0 0 0 1 0 (decimal)
•\027 (octal) = 2*8^1 + 7*8^0 = 16 + 7 =
23 (decimal)
3.Convert Decimal to Binary:
•9 (decimal) = 00001001 (binary) (8-bit
representation)
•23 (decimal) = 00010111 (binary) (8-bit
representation)
Cont.…
Increment/decrement Operators
• The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable.
• These are summarized in the following table. The examples assume the following
variable definition: int k = 5;
Operator Name Example
++ Auto Increment (prefix) ++k + 10 // gives 16
++ Auto Increment (postfix) k++ + 10 // gives 15
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) k-- + 10 // gives 15
Increment and decrement operators
• Both operators can be used in prefix and postfix form. The difference is significant.
• When used in prefix form, the operator is first applied and the outcome is then used in the
expression.
• When used in the postfix form, the expression is evaluated first and then the operator applied.
• Both operators may be applied to integer as well as real variables, although in practice real
Cont.…
#include <iostream.h>
int main() {
int num1 = 10, num2 = 5;
float decimal1 = 3.5, decimal2 = 2.0;
// Arithmetic Operators
cout << "Arithmetic Operations:" << endl;
cout << "num1 + num2 = " << num1 + num2 << endl;
cout << "num1 - num2 = " << num1 - num2 << endl;
cout << "num1 * num2 = " << num1 * num2 << endl;
cout << "num1 / num2 = " << num1 / num2 << endl;
cout << "num1 % num2 = " << num1 % num2 << endl; // Modulo
(remainder)
// Logical Operators
cout << "nLogical Operations:" << endl;
cout << "(num1 > 10) && (num2 < 10): " << ((num1 > 10) && (num2 < 10))
<< endl;
cout << "(num1 > 10) || (num2 < 10): " << ((num1 > 10) || (num2 < 10)) <<
endl;
cout << "!(num1 > 10): " << (!(num1 > 10)) << endl;
Cont.…
// Relational Operators
cout << "nRelational Operations:" << endl;
cout << "num1 == num2: " << (num1 == num2) << endl; cout << "num1 !=
num2: " << (num1 != num2) << endl; cout << "num1 > num2: " << (num1 >
num2) << endl;
cout << "num1 < num2: " << (num1 < num2) << endl;
cout << "num1 >= num2: " << (num1 >= num2) << endl; cout << "num1 <=
num2: " <<Operators
// Bitwise (num1 <=(assuming
num2) << endl;
integers)
cout << "nBitwise Operations (integers):" << endl;
cout << "num1 & num2: " << (num1 & num2) << endl; // Bitwise AND
cout << "num1 | num2: " << (num1 | num2) << endl; // Bitwise OR
cout << "num1 ^ num2: " << (num1 ^ num2) << endl; // Bitwise XOR
cout << "~num1: " << (~num1) << endl; // Bitwise NOT
cout << "num1 << 2: " << (num1 << 2) << endl; // Left shift
cout << "num2 >> 1: " << (num2 >> 1) << endl; // Right shift
Cont.…
// Assignment Operators
cout << "nAssignment Operations:" << endl;
int result = num1; cout << "result = num1: " << result << endl;
result += num2; // result = result + num2
cout << "result += num2: " << result << endl; result -= num2; // result = result - num2
cout << "result -= num2: " << result << endl; result *= num2; // result = result *
num2
cout << "result *= num2: " << result << endl; result /= num2; // result = result /
num2
cout << "result /= num2: " << result << endl; result %= num2; // result = result %
num2
cout << "result %= num2: " << result << endl;
Cont.…
// Increment/Decrement Operators
cout << "nIncrement/Decrement Operations:" << endl;
int counter = 5;
cout << "counter (before): " << counter << endl;
cout << "counter++ (post-increment): " << counter++ << endl;
cout << "counter (after): " << counter << endl;
cout << "++counter (pre-increment): " << ++counter << endl; cout << "counter
(after): " << counter << endl;
cout << "counter-- (post-decrement): " << counter-- << endl;
cout << "counter (after): " << counter << endl;
cout << "--counter (pre-decrement): " << --counter << endl;
cout << "counter (after): " << counter << endl;
return 0; }
Cont.…
• **Output:**
Logical Operations: Assignment Operations:
Arithmetic Operations:
(num1 > 10) && (num2 < 10): 0 result = num1: 10
num1 + num2 = 15 (num1 > 10) || (num2 < 10): 1 result += num2: 15
num1 - num2 = 5 !(num1 > 10): 1 result -= num2: 10
num1 * num2 = 50 Relational Operations: result *= num2: 50
num1 == num2: 0 result /= num2: 10
num1 / num2 = 2 num1 != num2: 1 result %= num2: 0
num1 % num2 = 0 num1 > num2: 1
num1 < num2: 0
Bitwise Operations (integers): num1 >= num2: 1 Increment/Decrement Operations:
num1 & num2: 0 num1 <= num2: 0 counter (before): 5
num1 | num2: 15 counter++ (post-increment): 5
num1 ^ num2: 15 counter (after): 6 ++counter (pre-increment): 7
~num1: -11 counter (after): 7
num1 << 2: 40 counter-- (post-decrement): 7
num2 >> 1: 2 counter (after): 6
--counter (pre-decrement): 5 counter (after): 5
Cont.…
Precedence of Operators
The order in which operators are evaluated in an expression is
significant and is determined by precedence rules.
These rules divide the C++ operators into a number of precedence
levels.
Operators in higher levels take precedence over operators in lower
levels.
Cont.…
• For example, in a == b + c * d
• c * d is evaluated first because * has a higher precedence than + and ==.
• The result is then added to b because + has a higher precedence than ==,
and then == is evaluated.
• Precedence rules can be overridden using brackets. For example, rewriting
the above expression as a == (b + c) * d causes + to be evaluated before *.
• Operators with the same precedence level are evaluated in the order
specified by the last column of Table 2.7.
• For example, in a = b += c the evaluation order is right to left, so first b +=
c is evaluated, followed by a = b.
Level Operator Kind Order
*
+ ++ ! new
- -- ~ & delete sizeof() Unary Right to Left
^=
= += *= &= <<=
-= /= %= |= >>= Binary Right to Left