SlideShare a Scribd company logo
Using
C++
Programming Fundamentals
Lecturer 2
Today’s Lecture
 Software Categories
 System Software
 Application Software
 Introduction to ‘C’ Language
 History
 Evolution
 Justification
 Development Environment of ‘C’
There are two main categories of software
 System software
 Application Software
TWAIN
Technology Without An Interesting Name
ANSI C
American National standard Institute (ANSI)
Tools of the trade
 Editor
 Interpreter and Compilers
 Debuggers
Integrated Development Environment
(IDE)
It contains
 Editor
 Compilers
 Debugger
 Linkers
 Loaders
Preprocessor program
processes the code.
Loader puts program in
memory.
CPU takes each
instruction and executes it,
possibly storing new data
values as the program executes.
Compiler creates object code and
stores
it on disk.
Linker links the object
code with the libraries
Loader
Primary Memory
Compiler
Editor
Preprocessor
Linker
Primary Memory
.
.
.
.
.
.
.
.
.
.
.
.
Disk
Disk
Disk
CPU
Disk
Disk
Program is created in the editor and
stored on disk.
#include <iostream>
using namespace std;
void main ( )
{
cout << “ Welcome to UET TAXILA”;
}
The Parts of a C++ Program
// sample C++ program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, there!";
return 0;
}
preprocessor directive
comment
which namespace to use
beginning of function named main
beginning of block for main
output statement
end of block for main
string literal
send 0 to operating system
Structure of a C++ program
Source code
1. // my first program in C++
2. # include <iostream>
3.
4. int main ()
5. {
6. std::cout<<“Hello Word!”;
7. }
Output
Hello Word!
Components of a C++ program
 Line 1: // my first program in C++
 Lines beginning with two slash signs (//) are
comments by the programmer and have no effect on
the behavior of the program.
 Programmers use them to include short
explanations or observations concerning the code or
program. In this case, it is a brief introductory
description of the program.
Comments
 Comments are for the reader, not the compiler
 Two types:
 Single line
// This is a C++ program. It prints the sentence:
// Welcome to C++ Programming.
 Multiple line
/*
You can include comments that can
occupy several lines.
*/
Single-Line Comments
Begin with // through to the end of line:
int length = 12; // length in inches
int width = 15; // width in inches
int area; // calculated area
// calculate rectangle area
area = length * width;
Multi-Line Comments
 Begin with /*, end with */
 Can span multiple lines:
/* this is a multi-line
comment
*/
 Can begin and end on the same line:
int area; /* calculated area */
Components of a C++ program (Cont.)
 Line 2: #include <iostream>
 Lines beginning with a hash sign (#) are directives
read and interpreted by what is known as the
preprocessor.
 In this case, the directive #include <iostream>,
instructs the preprocessor to include a section of
standard C++ code, known as header iostream, that
allows to perform standard input and output
operations.
The #include Directive
 Inserts the contents of another file into the program
 This is a preprocessor directive, not part of C++
language
 #include lines not seen by compiler
 Do not place a semicolon at end of #include line
Preprocessor Directives
 C++ has a small number of operations
 Many functions and symbols needed to run a C++
program are provided as collection of libraries
 Every library has a name and is referred to by a
header file
 Preprocessor directives are commands supplied to
the preprocessor
 All preprocessor commands begin with #
Preprocessor Directives (continued)
 Syntax to include a header file:
 For example:
#include <iostream>
 Causes the preprocessor to include the header file iostream
in the program
namespace and Using cin and cout in a
Program
 cin and cout are declared in the header file
iostream, but within std namespace
 To use cin and cout in a program, use the following
two statements:
#include <iostream>
using namespace std;
 Line 3: A blank line.
 Blank lines have no effect on a program. They simply
improve readability.
Components of a C++ program (Cont.)
 Line 4: int main ( )
 This line initiates the declaration of a function.
Essentially, a function is a group of code statements
which are given a name: in this case, this gives the
name "main" to the group of code statements that
follow.
 The execution of all C++ programs begins with
the main function regardless of where the function is
actually located within the code.
Components of a C++ program (Cont.)
Whitespaces
 Every C++ program contains whitespaces
 Include blanks, tabs, and newline characters
 Used to separate special symbols, reserved words,
and identifiers
 Proper utilization of whitespaces is important
 Can be used to make the program readable
 Line 6: std::cout << "Hello World!";
 This statement has three parts: First, std::cout,
which identifies the standard character output
device (usually, this is the computer screen).
 Second, the insertion operator (<<), which
indicates that what follows is inserted into std::cout.
 Finally, a sentence within quotes ("Hello world!"), is
the content inserted into the standard output.
Components of a C++ program (Cont.)
 Stream manipulator std::endl
 Outputs a newline.
 Flushes the output buffer.
 The notation std::cout specifies that we are using a
name (cout ) that belongs to a “namespace” (std).
The Basics of a C++ Program
 Function: collection of statements; when executed,
accomplishes something
 May be predefined or standard
 Syntax: rules that specify which statements
(instructions) are legal
 Programming language: a set of rules, symbols, and
special words
 Semantic rule: meaning of the instruction
The cout Object
 Displays output on the computer screen
 You use the stream insertion operator << to send
output to cout:
cout << "Programming is fun!";
The cout Object
 Can be used to send more than one item to cout:
cout << "Hello " << "there!";
Or:
cout << "Hello ";
cout << "there!";
The cout Object
 This produces one line of output:
cout << "Programming is ";
cout << "fun!";
cout << “Hello…”
VariableInsertion
operator
Object
Hello…
Output in C++
The endl Manipulator
 You can use the endl manipulator to start a new line
of output. This will produce two lines of output:
cout << "Programming is" << endl;
cout << "fun!";
Manipulator
 Manipulators are the operators in C++ for
formatting the output.
 The data is manipulated according to the desired
output.
The endl Manipulator
cout << "Programming is" << endl;
cout << "fun!";
Programming is
fun!
The endl Manipulator
 You do NOT put quotation marks around endl
 The last character in endl is a lowercase L, not the
number 1.
endl This is a lowercase L
Escape Sequence
 The backslash is called the escape character.
 An escape sequence is a series of characters that represents a special character
 An escape sequence begins with a backslash character (), which indicates that
the character(s) that follow should be treated in a special way.
 It tells the compiler that the next character is “escaping”.
 Escape Sequence are special character used in control string to modify the
format of output.
Escape Sequence
The n Escape Sequence
 You can also use the n escape sequence to start a
new line of output. This will produce two lines of
output:
cout << "Programming isn";
cout << "fun!";
Notice that the n is INSIDE
the string.
The n Escape Sequence
cout << "Programming isn";
cout << "fun!";
Programming is
fun!
Keywords / Reserve Words:
 The predefined words of the C++ that are used for
special purposes in the source program.
 Also known as reserved words
 Always written in lowercase
 There are 63 keywords in c++.
Tokens:
 In C++, a source program consists of keywords,
variables (or identifiers), constants, operators,
punctuators.
 These elements of a c++ program are called tokens.
C++ Key Words
You cannot use any of the C++ key words as an
identifier. These words have reserved meaning.
Identifier:
 The unique names used in the program to represent
the variables, constants, functions, and labels etc. are
called identifiers.
 The name of identifier may be 31 characters long. If
the name is more than 31 characters long , then first
31 characters will be used by the compiler.
An identifier Rules
 consist of alphabets, digits, and underscore.
 The first character of identifier name must be an alphabetic
letter or underscore.
 The keywords cannot be used as identifier name.
Types of identifiers:
 Standard Identifier
 There are also predefined identifiers in c++
 The predefined identifiers that are used for special
purposes in the source program are called the standard
identifiers.
 E.g cin, cout
 User-defined identifier
 the identifiers defined by the user in the program are
called user-defined identifers.
 E.g variables, user-defined functions, labels
Valid and Invalid Identifiers
IDENTIFIER VALID? REASON IF INVALID
totalSales Yes
total_Sales Yes
total.Sales No Cannot contain .
4thQtrSales No Cannot begin with digit
totalSale$ No Cannot contain $
Variable
Variable X
Variable
 Pic of the memory
 25
 10323
name
of the
variable
Variable
Variable starts with
1. Character
2. Underscore _ (Not Recommended)
Variable Names
 A variable name should represent the purpose of the
variable. For example:
itemsOrdered
The purpose of this variable is to hold the number of
items ordered.
Variable
 Small post box
X
Variable
Variable is the name of a location in
the memory
e.g. x= 2;
Variable Definition in Program
Variable Definition
Variable
In a program a variable has:
1. Name
2. Type
3. Size
4. Value
Assignment Operator
=
x = 2
X
2
Assignment Operator
L.H.S = R.H.S.
X+ 3 = y + 4 Wrong
Z = x +4
x +4 = Z Wrong
X = 10 ;
X = 30 ;
X 10
X 30
X = X + 1;
10 + 1
=
X
11
Data type
 int i ; ->
Declaration line
i
#include <iostream>
using namespace std;
int main ( )
{
int x ;
int y ;
int z ;
x = 10 ;
y = 20 ;
z = x + y ;
cout << " x = " ;
cout << x ;
cout << " y = " ;
cout << y ;
cout << " z =x + y = " ;
cout << z ;
return 0;
}
int x, y, z ;
int x; int y; int z ;
The cin Object
 Standard input object
 Like cout, requires iostream file
 Used to read input from keyboard
 Information retrieved from cin with >>
 Input is stored in one or more variables
Input in C++
>> 45
Object
Extraction
Operator
myVariable

cin
The cin Object in Program
The cin Object
 cin converts data to the type that matches the
variable:
int height;
cout << "How tall is the room? ";
cin >> height;
Displaying a Prompt
 A prompt is a message that instructs the user to
enter data.
 You should always use cout to display a prompt
before each cin statement.
cout << "How tall is the room? ";
cin >> height;
The cin Object
 Can be used to input more than one value:
cin >> height >> width;
 Multiple values from keyboard must be separated
by spaces
 Order is important: first value entered goes to first
variable, etc.
The cin Object Gathers Multiple Values in Program
The cin Object Reads Different
Data Types in Program
Standard Input/Output
C++ Data Types
C++ DataTypes
DerivedTypes
Array
Function
Pointer
Reference
Userdefined
Types
Structure
Union
Class
Enumeration
Built InTypes
EmptyType Floating TypesIntegral Types
Int char float doublevoid
C++ Primitive Data Types
Primitive types
integral floating
char short int long bool float double long double
unsigned
Data Types
1. int
2. short
3. long
4. float
5. double
6. char
C++ Data Type
A type defines a set of values and a
set of operations that can be applied on
those values. The set of values for each
type is known as the domain for the type.
C++ contains 5 standard types:
void int char float bool
Standard
Data Types
void
The void type has no values and no
operations. In other words, both the set
of values and the set of operations are
empty. Although this might seem unusual,
we will see later that it is a very
useful data type.
Integer
An integer type is a number without a
fractional part. It is also known as an
integral number. C++ supports three different
sizes of the integer data type: short int, int
and long int.
sizeof(short int)<= sizeof(int)<= sizeof(long int)
Short int
int
long int
Integer Data Types
• Integer variables can hold whole numbers such
as 12, 7, and -99.
Defining Variables
 Variables of the same type can be defined
- On separate lines:
int length;
int width;
unsigned int area;
- On the same line:
int length, width;
unsigned int area;
 Variables of different types must be in different definitions
Integer Types in Program
This program has three variables: checking,
miles, and days
Literals
 Literal: a value that is written into a program’s code.
"hello, there" (string literal)
12 (integer literal)
Integer Literal in Program
20 is an integer literal
Integer Literals
 An integer literal is an integer value that is typed into
a program’s code. For example:
itemsOrdered = 15;
In this code, 15 is an integer literal.
Integer Literals in Program
Integer Literals
Integer Literals
 Integer literals are stored in memory as int by
default
 To store an integer constant in a long memory
location, put ‘L’ at the end of the number: 1234L
 Constants that begin with ‘0’ (zero) are base 8: 075
 Constants that begin with ‘0x’ are base 16: 0x75A
The char Data Type
 Used to hold characters or very small integer values
 Usually 1 byte of memory
 Numeric value of character from the character set is
stored in memory:
CODE:
char letter;
letter = 'C';
MEMORY:
letter
67
The ‘char’ data type:
 Used to store a single character such as ‘a’, ‘$’ etc.
 When the character is stored into a variable, the
ASCII value is stored into the variable.
 The ASCII value of ‘A’ is 65 and ‘a’ is 97.
 By default the character data type is unsigned
because the ASCII values are positive.
 The range for unsigned ‘char’ data type is from 0 to
255.
 For signed ‘char’ its -128 to 127
 ASCII stands for American Standard Code for
Information Interchange
char Data Type
 The smallest integral data type
 Used for characters: letters, digits, and special
symbols
 Each character is enclosed in single quotes
 'A', 'a', '0', '*', '+', '$', '&'
 A blank space is a character and is written ' ',
with a space left between the single quotes
Character Literals
 Character literals must be enclosed in single quote
marks. Example:
'A'
Character Literals in Program
Character Strings
 A series of characters in consecutive memory
locations:
"Hello"
 Stored with the null terminator, 0, at the end:
 Comprised of the characters between the " "
H e l l o 0
string Type
 Programmer-defined type supplied in
ANSI/ISO Standard C++ library
 Sequence of zero or more characters
 Enclosed in double quotation marks
 Null: a string with no characters
 Each character has relative position in string
 Position of first character is 0 (zero)
 Length of a string is number of characters in it
 Example: length of "William Jacob" is 13
The C++ string Class
 Special data type supports working with strings
 #include <string>
 Can define string variables in programs:
string firstName, lastName;
 Can receive values with assignment operator:
firstName = “Kristen";
lastName = “Stewart";
 Can be displayed via cout
cout << firstName << " " << lastName;
The string class in Program
String Literals in Program
These are string literals
Floating Point
A floating-point type is a number with a
fractional part, such as 43.32. The C++
language supports three different sizes of
floating-point: float, double and long double.
sizeof(float)<= sizeof(double)<= sizeof(long double)
float
double
long double
Floating-Point Data Types
 The floating-point data types are:
float
double
long double
 They can hold real numbers such as:
12.45 -3.8
 Stored in a form similar to scientific notation
 All floating-point numbers are signed
Floating-Point Data Types
Floating-Point Data Types (continued)
 Maximum number of significant digits (decimal
places) for float values is 7
 Maximum number of significant digits for double is
15
 Precision: maximum number of significant digits
 Float values are called single precision
 Double values are called double precision
Floating-Point Literals
 Can be represented in
 Fixed point (decimal) notation:
31.4159 0.0000625
 E notation:
3.14159E1 6.25E-5
 Are double by default
 Can be forced to be float (3.14159f) or long double
(0.0000625L)
Floating-Point Data Types in Program
The bool Data Type
 Represents values that are true or false
 bool variables are stored as small integers
 false is represented by 0, true by 1:
bool allDone = true;
bool finished = false;
allDone finished
1 0
Boolean Variables in Program
Determining the Size of a Data Type
The sizeof operator gives the size of any data type
or variable:
double amount;
cout << "A double is stored in "
<< sizeof(double) << "bytesn";
cout << "Variable amount is stored in
"
<< sizeof(amount)
<< "bytesn";
Overflow and Underflow:
 An overflow occurs when the value assigned to a
variable is more than the maximum allowable
limit.
 An underflow occurs when the value assigned to
a variable is less then the minimum allowable
limit.
Variable Assignments and Initialization
 An assignment statement uses the = operator to
store a value in a variable.
item = 12;
 This statement assigns the value 12 to the item
variable.
Assignment
 The variable receiving the value must appear on the
left side of the = operator.
 This will NOT work:
// ERROR!
12 = item;
Variable Initialization
 To initialize a variable means to assign it a value
when it is defined:
int length = 12;
 Can initialize some or all variables:
int length = 12, width = 5, area;
Variable Initialization in Program
Scope
 The scope of a variable: the part of the program in
which the variable can be accessed
 A variable cannot be used before it is defined
Variable Out of Scope in Program
Local Variables
 Variables that are declared inside a function or block
are local variables. They can be used only by
statements that are inside that function or block of
code.
 Local variables are not known to functions outside
their own.
Local Variables
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b; int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
 Global variables are defined outside of all the
functions, usually on top of the program. The global
variables will hold their value throughout the life-
time of your program.
 A global variable can be accessed by any function.
That is, a global variable is available for use
throughout your entire program after its declaration.
Global Variables
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but
value of local variable inside a function will take preference. For example:
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
} // Output of Program g = 10
Initializing Local and Global Variables
 When a local variable is defined, it is not initialized
by the system, you must initialize it yourself. Global
variables are initialized automatically by the system
when you define them as follows
Data Type Initializer
int 0
char '0'
float 0.0
double 0.0
pointer NULL
Arithmetic Operators
 Used for performing numeric calculations
 C++ has unary, binary, and ternary operators:
 unary (1 operand) -5
 binary (2 operands) 13 - 7
 ternary (3 operands) exp1 ? exp2 : exp3
Arithmetic operators
Plus +
Minus -
Multiply *
Divide /
Modulus %
Arithmetic operators
i + j
x * y
a / b
a % b
Binary Arithmetic Operators
SYMBOL OPERATION EXAMPLE VALUE OF
Ans
+ addition ans = 7 + 3; 10
- subtraction ans = 7 - 3; 4
* multiplication ans = 7 * 3; 21
/ division ans = 7 / 3; 2
% modulus ans = 7 % 3; 1
x = 2 + 4 ;
= 6 ;
Memory
x
6
Memory
x = a + b ;
a b
x
#include <iostream>
void main ( )
{
int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10 ;
int TotalAge ;
int AverageAge ;
cout << “ Please enter the age of student 1: “ ;
cin >> age1 ;
cout << “ Please enter the age of student 2: “ ;
cin >> age2 ;
:
:
TotalAge = age1+ age2 + age3+ age4+ age5+age6+ age7+ age8+age9 + age10 ;
AverageAge = TotalAge / 10 ;
cout<< “The average age of the class is :” << AverageAge ;
}
Quadratic Equation
 In algebra
y = ax2 + bx + c
 In C
y = a*x*x + b*x + c
a*b%c +d
a*(b%c) = a*b%c
Discriminant
b2 - 2a
= b*b - 4*a*c /2 *a Incorrect answer
Solution
= (b*b - 4*a*c) /(2 *a) Correct answer
4c
 No expression on the left hand side
of the assignment
 Integer division truncates
fractional part
 Liberal use of
brackets/parenthesis
A Closer Look at the / Operator
 / (division) operator performs integer division if
both operands are integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
 If either operand is floating point, the result is
floating point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
A Closer Look at the % Operator
 % (modulus) operator computes the remainder
resulting from integer division
cout << 13 % 5; // displays 3
 % requires integers for both operands
cout << 13 % 5.0; // error
% = Remainder
5 % 2 = 1
2 % 2 = 0
4 / 2 = 2
5 / 2 = ?
Precedence
 Highest: ( )
 Next: * , / , %
 Lowest: + , -
operator=
Compound Assignment Operators
 counter += 3 ;
same as
 counter = counter + 3 ;
+=
 counter -= 5 ;
same as
 counter = counter – 5 ;
-=
x*=2
x = x * 2
*=
x /= 2
x = x / 2
/=
 x %= 2 ;
Same As
 x = x % 2 ;
%=
Precedence
Operators Associativity
(), ++postfix, -- postfix Left to right
++ prefix, ++prefix Left to right
*,/,% Left to right
+,- Left to right
=,+=,-=,*=,/= Right to left
Expressions
 If all operands are integers
 Expression is called an integral expression
 Yields an integral result
 Example: 2 + 3 * 5
 If all operands are floating-point
 Expression is called a floating-point expression
 Yields a floating-point result
 Example: 12.8 * 17.5 - 34.50
Mixed Expressions
 Mixed expression:
 Has operands of different data types
 Contains integers and floating-point
 Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
Mixed Expressions (continued)
 Evaluation rules:
 If operator has same types of operands
 Evaluated according to the type of the operands
 If operator has both types of operands
 Integer is changed to floating-point
 Operator is evaluated
 Result is floating-point
 Entire expression is evaluated according to precedence rules
Rules for Division
 C++ treats integers differently from decimal
numbers.
 100 is an int type.
 100.0 , 100.0000, and 100. are double type.
 The general rule for division of int and double
types is:
 double/double -> double (normal)
 double/int -> double (normal)
 int/double -> double (normal)
 int/int -> int (note: the decimal part is discarded)
Rules for Division
 Examples:
 220. / 100.0 double/double -> double result is 2.2
 220. / 100 double/int -> double result is 2.2
 220 / 100.0 int/double -> double result is 2.2
 220 / 100 int/int -> int result is 2
 Summary: division is normal unless both the
numerator and denominator are int, then the result is
an int (the decimal part is discarded).
Assignment Conversions
 A decimal number assigned to an int type variable is
truncated.
 An integer assigned to a double type variable is
converted to a decimal number.
 Example 1:
double yy = 2.7;
int i = 15;
int j = 10;
i = yy; // i is now 2
yy = j; // yy is now 10.0
Assignment Conversions
 Example 2:
int m, n;
double xx;
m = 7;
n = 2.5;
xx = m / n;
n = xx + m / 2;
// What is the value of n?
Assignment Conversions
 Example 2:
int m, n;
double xx;
m = 7;
n = 2.5; // 2.5 converted to 2 and assigned to n
xx = m/n; // 7/2=3 converted to 3.0 and assigned to xx
n = xx+m/2;
// m/2=3 : integer division
// xx+m/2 : double addition because xx is double
// convert result of m/2 to double (i.e. 3.0)
// xx+m/2=6.0
// convert result of xx+m/2 to int (i.e. 6)
// because n is int
Forcing a Type Change
 You can change the type of an expression with a cast
operation.
 Syntax:
variable1 = type(variable2);
variable1 = type(expression);
 Example:
int x=1, y=2;
double result1 = x/y; // result1 is 0.0
double result2 = double(x)/y; // result2 is 0.5
double result3 = x/double(y); // result3 is 0.5
double result4 = double(x)/double(y);// result4 is 0.5
double result5 = double(x/y); // result5 is 0.0
int cents = int(result4*100); // cents is 50
When You Mix Apples with Oranges: Type
Conversion
 Operations are performed between operands of the
same type.
 If not of the same type, C++ will convert one to be
the type of the other
 This can impact the results of calculations.
Hierarchy of Types
Highest:
Lowest:
Ranked by largest number they can hold
long double
double
float
unsigned long
long
unsigned int
int
Type Coercion
 Type Coercion: automatic conversion of an operand
to another data type
 Promotion: convert to a higher type
 Demotion: convert to a lower type
Coercion Rules
1) char, short, unsigned short automatically
promoted to int
2) When operating on values of different data types,
the lower one is promoted to the type of the higher
one.
3) When using the = operator, the type of expression
on right will be converted to type of variable on left
Type Casting
 Used for manual data type conversion
 Useful for floating point division using int:
double m;
m = static_cast<double>(y2-y1)
/(x2-x1);
 Useful to see int value of a char variable:
char ch = 'C';
cout << ch << " is "
<< static_cast<int>(ch);
Type Casting in Program
C-Style and Prestandard Type Cast Expressions
 C-Style cast: data type name in ()
cout << ch << " is " << (int)ch;
 Prestandard C++ cast: value in ()
cout << ch << " is " << int(ch);
 Both are still supported in C++, although
static_cast is preferred
Interesting Problem
Given a four-digit integer,
separate and print the digits on
the screen
Analysis
 Number = 1234
 Take the remainder of the above number after dividing by 10
Eg 1234 / 10 gives remainder 4
1234 % 10 = 4
 Remove last digit
 1234/10 = 123.4
 123 (Truncation due to Integer Division)
 123 %10 gives 3
 Remove last digit
 123/10 = 12.3
 12 (Truncation due to Integer Division)
 12 % 10 gives remainder 2
 Remove last digit
 12/10 = 1.2
 1 (Truncation due to Integer Division)
 Final digit remains
Code
#include <iostream>
void main ( )
{
int number;
int digit;
cout << “Please enter a 4 digit integer : ”;
cin >> number; 1234
digit = number %10; 4
cout <<“The digit is: “ << digit << ‘n’; // first digit; and then << ‘n’
number = number / 10; 123
digit = number % 10; 3
cout <<“The digit is: “ << digit << ‘n’;
number = number / 10; 12
digit = number % 10 ; 2
cout <<“The digit is: “ << digit << ‘n’;
number = number / 10; 1
digit = number % 10;
cout <<“The digit is: “ << digit;
}
Named Constants
 Named constant (constant variable): variable whose
content cannot be changed during program
execution
 Used for representing constant values with
descriptive names:
const double TAX_RATE = 0.0675;
const int NUM_STATES = 50;
 Often named in uppercase letters
 Use #define preprocessor directive instead of const
definitions
Named Constants in Program
#define directive in Program
Difference between #define and const
‘#define’ directive ‘const’ Qualifier
Used as preprocessor directive Used as a statement
Not terminated with the ; Terminated with the ;
Data type of constant identifier
is not specified
Data type is specified
Postfix expressions
Two postfix operators: ++ (postfix increment)
-- (postfix decrement)
the effect of a++ is the same as a = a + 1
the effect of a-- is the same as a = a - 1
Prefix expressions
Two prefix operators: ++ (prefix increment)
-- (prefix decrement)
the effect of ++a is the same as a = a + 1
the effect of --a is the same as a = a - 1
163
Relational Operators and the Type char
 '0' through '9' have ASCII code values 48 through 57
'0' < '1' < . . . < '9'
 'A' through 'Z' have ASCII code values 65 through 90
'A' < 'B' < . . .< 'Z'
 'a' through 'z' have ASCII code values 97 through 122
'a' < 'b' < . . .< 'z'
C++ Standard
Library Header Files
C++ Standard
Library Header Files
C++ Standard
Library Header Files
C++ Standard
Library Header Files
Programming Style
 The visual organization of the source code
 Includes the use of spaces, tabs, and blank lines
 Does not affect the syntax of the program
 Affects the readability of the source code
Programming Style
Common elements to improve readability:
 Braces { } aligned vertically
 Indentation of statements within a set of braces
 Blank lines between declaration and other
statements
 Long statements wrapped over multiple lines with
aligned operators

More Related Content

What's hot

Access specifiers (Public Private Protected) C++
Access specifiers (Public Private  Protected) C++Access specifiers (Public Private  Protected) C++
Access specifiers (Public Private Protected) C++
vivekkumar2938
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Data types in c++
Data types in c++ Data types in c++
Data types in c++
RushikeshGaikwad28
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
Md. Ashraful Islam
 
Automata Theory
Automata TheoryAutomata Theory
This pointer
This pointerThis pointer
This pointer
Kamal Acharya
 
Function in c
Function in cFunction in c
Control statements
Control statementsControl statements
Control statements
Kanwalpreet Kaur
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsRanel Padon
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
Arun Sial
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Sikder Tahsin Al-Amin
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Binary parallel adder
Binary parallel adderBinary parallel adder
Binary parallel adder
anu surya
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
vampugani
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 

What's hot (20)

Access specifiers (Public Private Protected) C++
Access specifiers (Public Private  Protected) C++Access specifiers (Public Private  Protected) C++
Access specifiers (Public Private Protected) C++
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Data types in c++
Data types in c++ Data types in c++
Data types in c++
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Automata Theory
Automata TheoryAutomata Theory
Automata Theory
 
This pointer
This pointerThis pointer
This pointer
 
Function in c
Function in cFunction in c
Function in c
 
Control statements
Control statementsControl statements
Control statements
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Binary parallel adder
Binary parallel adderBinary parallel adder
Binary parallel adder
 
Break and continue
Break and continueBreak and continue
Break and continue
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 

Similar to C++ AND CATEGORIES OF SOFTWARE

C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
sajjad ali khan
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
DineshDhuri4
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
valerie5142000
 
C++ basics
C++ basicsC++ basics
C++ basics
AllsoftSolutions
 
Chapter3
Chapter3Chapter3
Chapter3
Kamran
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
PushkarNiroula1
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
cpjcollege
 
lecture1 pf.pptx
lecture1 pf.pptxlecture1 pf.pptx
lecture1 pf.pptx
MalikMFalakShairUnkn
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
JosephAlex21
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
Qrembiezs Intruder
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
Mohammad Golyani
 
C programming
C programmingC programming
C programming
PralhadKhanal1
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
20EUEE018DEEPAKM
 
(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt
atulchaudhary821
 

Similar to C++ AND CATEGORIES OF SOFTWARE (20)

C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
C++ basics
C++ basicsC++ basics
C++ basics
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Chapter2
Chapter2Chapter2
Chapter2
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
Chapter3
Chapter3Chapter3
Chapter3
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
lecture1 pf.pptx
lecture1 pf.pptxlecture1 pf.pptx
lecture1 pf.pptx
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 
C programming
C programmingC programming
C programming
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt
 

More from UNIVERSITY OF ENGINEERING AND TECHNOLOGY TAXILA

FET TRANSISTOR
FET TRANSISTOR FET TRANSISTOR
C++ IF STATMENT AND ITS TYPE
C++ IF STATMENT AND ITS TYPEC++ IF STATMENT AND ITS TYPE
Energy slides
Energy slidesEnergy slides
TOURISM IN PAKISTAN
TOURISM IN PAKISTANTOURISM IN PAKISTAN
Pak China SEPEC
Pak China SEPECPak China SEPEC
SIR SAYED AHMAD KHAN
SIR SAYED AHMAD KHANSIR SAYED AHMAD KHAN
WRITING AND TEACHING ISSUE
WRITING AND TEACHING ISSUEWRITING AND TEACHING ISSUE
ENGLISH QUIZ PARAGRAPH
ENGLISH QUIZ PARAGRAPHENGLISH QUIZ PARAGRAPH
ENGLISH QUIZ PARAGRAPH 2
ENGLISH QUIZ PARAGRAPH 2ENGLISH QUIZ PARAGRAPH 2
PELTON WHEEL
PELTON WHEEL PELTON WHEEL
ARTIFICAL INTELLIGENCE
ARTIFICAL INTELLIGENCEARTIFICAL INTELLIGENCE
Capacitors and Inductors
Capacitors and InductorsCapacitors and Inductors
JFET TRANSISTER with reference,working and conclusion
JFET TRANSISTER with reference,working and conclusionJFET TRANSISTER with reference,working and conclusion
JFET TRANSISTER with reference,working and conclusion
UNIVERSITY OF ENGINEERING AND TECHNOLOGY TAXILA
 

More from UNIVERSITY OF ENGINEERING AND TECHNOLOGY TAXILA (14)

FET TRANSISTOR
FET TRANSISTOR FET TRANSISTOR
FET TRANSISTOR
 
C++ IF STATMENT AND ITS TYPE
C++ IF STATMENT AND ITS TYPEC++ IF STATMENT AND ITS TYPE
C++ IF STATMENT AND ITS TYPE
 
Energy slides
Energy slidesEnergy slides
Energy slides
 
TOURISM IN PAKISTAN
TOURISM IN PAKISTANTOURISM IN PAKISTAN
TOURISM IN PAKISTAN
 
Pak China SEPEC
Pak China SEPECPak China SEPEC
Pak China SEPEC
 
SIR SAYED AHMAD KHAN
SIR SAYED AHMAD KHANSIR SAYED AHMAD KHAN
SIR SAYED AHMAD KHAN
 
WRITING AND TEACHING ISSUE
WRITING AND TEACHING ISSUEWRITING AND TEACHING ISSUE
WRITING AND TEACHING ISSUE
 
ENGLISH QUIZ PARAGRAPH
ENGLISH QUIZ PARAGRAPHENGLISH QUIZ PARAGRAPH
ENGLISH QUIZ PARAGRAPH
 
ENGLISH QUIZ PARAGRAPH 2
ENGLISH QUIZ PARAGRAPH 2ENGLISH QUIZ PARAGRAPH 2
ENGLISH QUIZ PARAGRAPH 2
 
PELTON WHEEL
PELTON WHEEL PELTON WHEEL
PELTON WHEEL
 
ARTIFICAL INTELLIGENCE
ARTIFICAL INTELLIGENCEARTIFICAL INTELLIGENCE
ARTIFICAL INTELLIGENCE
 
Capacitors and Inductors
Capacitors and InductorsCapacitors and Inductors
Capacitors and Inductors
 
RLC circuit
 RLC  circuit RLC  circuit
RLC circuit
 
JFET TRANSISTER with reference,working and conclusion
JFET TRANSISTER with reference,working and conclusionJFET TRANSISTER with reference,working and conclusion
JFET TRANSISTER with reference,working and conclusion
 

Recently uploaded

Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 

Recently uploaded (20)

Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 

C++ AND CATEGORIES OF SOFTWARE

  • 2. Today’s Lecture  Software Categories  System Software  Application Software  Introduction to ‘C’ Language  History  Evolution  Justification  Development Environment of ‘C’
  • 3. There are two main categories of software  System software  Application Software
  • 4. TWAIN Technology Without An Interesting Name
  • 5. ANSI C American National standard Institute (ANSI)
  • 6. Tools of the trade  Editor  Interpreter and Compilers  Debuggers
  • 7. Integrated Development Environment (IDE) It contains  Editor  Compilers  Debugger  Linkers  Loaders
  • 8. Preprocessor program processes the code. Loader puts program in memory. CPU takes each instruction and executes it, possibly storing new data values as the program executes. Compiler creates object code and stores it on disk. Linker links the object code with the libraries Loader Primary Memory Compiler Editor Preprocessor Linker Primary Memory . . . . . . . . . . . . Disk Disk Disk CPU Disk Disk Program is created in the editor and stored on disk.
  • 9. #include <iostream> using namespace std; void main ( ) { cout << “ Welcome to UET TAXILA”; }
  • 10. The Parts of a C++ Program // sample C++ program #include <iostream> using namespace std; int main() { cout << "Hello, there!"; return 0; } preprocessor directive comment which namespace to use beginning of function named main beginning of block for main output statement end of block for main string literal send 0 to operating system
  • 11. Structure of a C++ program Source code 1. // my first program in C++ 2. # include <iostream> 3. 4. int main () 5. { 6. std::cout<<“Hello Word!”; 7. } Output Hello Word!
  • 12. Components of a C++ program  Line 1: // my first program in C++  Lines beginning with two slash signs (//) are comments by the programmer and have no effect on the behavior of the program.  Programmers use them to include short explanations or observations concerning the code or program. In this case, it is a brief introductory description of the program.
  • 13. Comments  Comments are for the reader, not the compiler  Two types:  Single line // This is a C++ program. It prints the sentence: // Welcome to C++ Programming.  Multiple line /* You can include comments that can occupy several lines. */
  • 14. Single-Line Comments Begin with // through to the end of line: int length = 12; // length in inches int width = 15; // width in inches int area; // calculated area // calculate rectangle area area = length * width;
  • 15. Multi-Line Comments  Begin with /*, end with */  Can span multiple lines: /* this is a multi-line comment */  Can begin and end on the same line: int area; /* calculated area */
  • 16. Components of a C++ program (Cont.)  Line 2: #include <iostream>  Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor.  In this case, the directive #include <iostream>, instructs the preprocessor to include a section of standard C++ code, known as header iostream, that allows to perform standard input and output operations.
  • 17. The #include Directive  Inserts the contents of another file into the program  This is a preprocessor directive, not part of C++ language  #include lines not seen by compiler  Do not place a semicolon at end of #include line
  • 18. Preprocessor Directives  C++ has a small number of operations  Many functions and symbols needed to run a C++ program are provided as collection of libraries  Every library has a name and is referred to by a header file  Preprocessor directives are commands supplied to the preprocessor  All preprocessor commands begin with #
  • 19. Preprocessor Directives (continued)  Syntax to include a header file:  For example: #include <iostream>  Causes the preprocessor to include the header file iostream in the program
  • 20. namespace and Using cin and cout in a Program  cin and cout are declared in the header file iostream, but within std namespace  To use cin and cout in a program, use the following two statements: #include <iostream> using namespace std;
  • 21.  Line 3: A blank line.  Blank lines have no effect on a program. They simply improve readability. Components of a C++ program (Cont.)
  • 22.  Line 4: int main ( )  This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name: in this case, this gives the name "main" to the group of code statements that follow.  The execution of all C++ programs begins with the main function regardless of where the function is actually located within the code. Components of a C++ program (Cont.)
  • 23. Whitespaces  Every C++ program contains whitespaces  Include blanks, tabs, and newline characters  Used to separate special symbols, reserved words, and identifiers  Proper utilization of whitespaces is important  Can be used to make the program readable
  • 24.  Line 6: std::cout << "Hello World!";  This statement has three parts: First, std::cout, which identifies the standard character output device (usually, this is the computer screen).  Second, the insertion operator (<<), which indicates that what follows is inserted into std::cout.  Finally, a sentence within quotes ("Hello world!"), is the content inserted into the standard output. Components of a C++ program (Cont.)
  • 25.  Stream manipulator std::endl  Outputs a newline.  Flushes the output buffer.  The notation std::cout specifies that we are using a name (cout ) that belongs to a “namespace” (std).
  • 26. The Basics of a C++ Program  Function: collection of statements; when executed, accomplishes something  May be predefined or standard  Syntax: rules that specify which statements (instructions) are legal  Programming language: a set of rules, symbols, and special words  Semantic rule: meaning of the instruction
  • 27. The cout Object  Displays output on the computer screen  You use the stream insertion operator << to send output to cout: cout << "Programming is fun!";
  • 28. The cout Object  Can be used to send more than one item to cout: cout << "Hello " << "there!"; Or: cout << "Hello "; cout << "there!";
  • 29. The cout Object  This produces one line of output: cout << "Programming is "; cout << "fun!";
  • 31. The endl Manipulator  You can use the endl manipulator to start a new line of output. This will produce two lines of output: cout << "Programming is" << endl; cout << "fun!";
  • 32. Manipulator  Manipulators are the operators in C++ for formatting the output.  The data is manipulated according to the desired output.
  • 33. The endl Manipulator cout << "Programming is" << endl; cout << "fun!"; Programming is fun!
  • 34. The endl Manipulator  You do NOT put quotation marks around endl  The last character in endl is a lowercase L, not the number 1. endl This is a lowercase L
  • 35. Escape Sequence  The backslash is called the escape character.  An escape sequence is a series of characters that represents a special character  An escape sequence begins with a backslash character (), which indicates that the character(s) that follow should be treated in a special way.  It tells the compiler that the next character is “escaping”.  Escape Sequence are special character used in control string to modify the format of output.
  • 37. The n Escape Sequence  You can also use the n escape sequence to start a new line of output. This will produce two lines of output: cout << "Programming isn"; cout << "fun!"; Notice that the n is INSIDE the string.
  • 38. The n Escape Sequence cout << "Programming isn"; cout << "fun!"; Programming is fun!
  • 39. Keywords / Reserve Words:  The predefined words of the C++ that are used for special purposes in the source program.  Also known as reserved words  Always written in lowercase  There are 63 keywords in c++. Tokens:  In C++, a source program consists of keywords, variables (or identifiers), constants, operators, punctuators.  These elements of a c++ program are called tokens.
  • 40. C++ Key Words You cannot use any of the C++ key words as an identifier. These words have reserved meaning.
  • 41. Identifier:  The unique names used in the program to represent the variables, constants, functions, and labels etc. are called identifiers.  The name of identifier may be 31 characters long. If the name is more than 31 characters long , then first 31 characters will be used by the compiler. An identifier Rules  consist of alphabets, digits, and underscore.  The first character of identifier name must be an alphabetic letter or underscore.  The keywords cannot be used as identifier name.
  • 42. Types of identifiers:  Standard Identifier  There are also predefined identifiers in c++  The predefined identifiers that are used for special purposes in the source program are called the standard identifiers.  E.g cin, cout  User-defined identifier  the identifiers defined by the user in the program are called user-defined identifers.  E.g variables, user-defined functions, labels
  • 43. Valid and Invalid Identifiers IDENTIFIER VALID? REASON IF INVALID totalSales Yes total_Sales Yes total.Sales No Cannot contain . 4thQtrSales No Cannot begin with digit totalSale$ No Cannot contain $
  • 45. Variable  Pic of the memory  25  10323 name of the variable
  • 46. Variable Variable starts with 1. Character 2. Underscore _ (Not Recommended)
  • 47. Variable Names  A variable name should represent the purpose of the variable. For example: itemsOrdered The purpose of this variable is to hold the number of items ordered.
  • 49. Variable Variable is the name of a location in the memory e.g. x= 2;
  • 50. Variable Definition in Program Variable Definition
  • 51. Variable In a program a variable has: 1. Name 2. Type 3. Size 4. Value
  • 53. Assignment Operator L.H.S = R.H.S. X+ 3 = y + 4 Wrong Z = x +4 x +4 = Z Wrong
  • 54. X = 10 ; X = 30 ; X 10 X 30
  • 55. X = X + 1; 10 + 1 = X 11
  • 56. Data type  int i ; -> Declaration line i
  • 57. #include <iostream> using namespace std; int main ( ) { int x ; int y ; int z ; x = 10 ; y = 20 ; z = x + y ; cout << " x = " ; cout << x ; cout << " y = " ; cout << y ; cout << " z =x + y = " ; cout << z ; return 0; }
  • 58. int x, y, z ; int x; int y; int z ;
  • 59. The cin Object  Standard input object  Like cout, requires iostream file  Used to read input from keyboard  Information retrieved from cin with >>  Input is stored in one or more variables
  • 60. Input in C++ >> 45 Object Extraction Operator myVariable  cin
  • 61. The cin Object in Program
  • 62. The cin Object  cin converts data to the type that matches the variable: int height; cout << "How tall is the room? "; cin >> height;
  • 63. Displaying a Prompt  A prompt is a message that instructs the user to enter data.  You should always use cout to display a prompt before each cin statement. cout << "How tall is the room? "; cin >> height;
  • 64. The cin Object  Can be used to input more than one value: cin >> height >> width;  Multiple values from keyboard must be separated by spaces  Order is important: first value entered goes to first variable, etc.
  • 65. The cin Object Gathers Multiple Values in Program
  • 66. The cin Object Reads Different Data Types in Program
  • 68. C++ Data Types C++ DataTypes DerivedTypes Array Function Pointer Reference Userdefined Types Structure Union Class Enumeration Built InTypes EmptyType Floating TypesIntegral Types Int char float doublevoid
  • 69. C++ Primitive Data Types Primitive types integral floating char short int long bool float double long double unsigned
  • 70. Data Types 1. int 2. short 3. long 4. float 5. double 6. char
  • 71. C++ Data Type A type defines a set of values and a set of operations that can be applied on those values. The set of values for each type is known as the domain for the type. C++ contains 5 standard types: void int char float bool Standard Data Types
  • 72. void The void type has no values and no operations. In other words, both the set of values and the set of operations are empty. Although this might seem unusual, we will see later that it is a very useful data type.
  • 73. Integer An integer type is a number without a fractional part. It is also known as an integral number. C++ supports three different sizes of the integer data type: short int, int and long int. sizeof(short int)<= sizeof(int)<= sizeof(long int) Short int int long int
  • 74. Integer Data Types • Integer variables can hold whole numbers such as 12, 7, and -99.
  • 75. Defining Variables  Variables of the same type can be defined - On separate lines: int length; int width; unsigned int area; - On the same line: int length, width; unsigned int area;  Variables of different types must be in different definitions
  • 76. Integer Types in Program This program has three variables: checking, miles, and days
  • 77. Literals  Literal: a value that is written into a program’s code. "hello, there" (string literal) 12 (integer literal)
  • 78. Integer Literal in Program 20 is an integer literal
  • 79. Integer Literals  An integer literal is an integer value that is typed into a program’s code. For example: itemsOrdered = 15; In this code, 15 is an integer literal.
  • 80. Integer Literals in Program Integer Literals
  • 81. Integer Literals  Integer literals are stored in memory as int by default  To store an integer constant in a long memory location, put ‘L’ at the end of the number: 1234L  Constants that begin with ‘0’ (zero) are base 8: 075  Constants that begin with ‘0x’ are base 16: 0x75A
  • 82. The char Data Type  Used to hold characters or very small integer values  Usually 1 byte of memory  Numeric value of character from the character set is stored in memory: CODE: char letter; letter = 'C'; MEMORY: letter 67
  • 83. The ‘char’ data type:  Used to store a single character such as ‘a’, ‘$’ etc.  When the character is stored into a variable, the ASCII value is stored into the variable.  The ASCII value of ‘A’ is 65 and ‘a’ is 97.  By default the character data type is unsigned because the ASCII values are positive.  The range for unsigned ‘char’ data type is from 0 to 255.  For signed ‘char’ its -128 to 127  ASCII stands for American Standard Code for Information Interchange
  • 84. char Data Type  The smallest integral data type  Used for characters: letters, digits, and special symbols  Each character is enclosed in single quotes  'A', 'a', '0', '*', '+', '$', '&'  A blank space is a character and is written ' ', with a space left between the single quotes
  • 85. Character Literals  Character literals must be enclosed in single quote marks. Example: 'A'
  • 87. Character Strings  A series of characters in consecutive memory locations: "Hello"  Stored with the null terminator, 0, at the end:  Comprised of the characters between the " " H e l l o 0
  • 88. string Type  Programmer-defined type supplied in ANSI/ISO Standard C++ library  Sequence of zero or more characters  Enclosed in double quotation marks  Null: a string with no characters  Each character has relative position in string  Position of first character is 0 (zero)  Length of a string is number of characters in it  Example: length of "William Jacob" is 13
  • 89. The C++ string Class  Special data type supports working with strings  #include <string>  Can define string variables in programs: string firstName, lastName;  Can receive values with assignment operator: firstName = “Kristen"; lastName = “Stewart";  Can be displayed via cout cout << firstName << " " << lastName;
  • 90. The string class in Program
  • 91. String Literals in Program These are string literals
  • 92. Floating Point A floating-point type is a number with a fractional part, such as 43.32. The C++ language supports three different sizes of floating-point: float, double and long double. sizeof(float)<= sizeof(double)<= sizeof(long double) float double long double
  • 93. Floating-Point Data Types  The floating-point data types are: float double long double  They can hold real numbers such as: 12.45 -3.8  Stored in a form similar to scientific notation  All floating-point numbers are signed
  • 95. Floating-Point Data Types (continued)  Maximum number of significant digits (decimal places) for float values is 7  Maximum number of significant digits for double is 15  Precision: maximum number of significant digits  Float values are called single precision  Double values are called double precision
  • 96. Floating-Point Literals  Can be represented in  Fixed point (decimal) notation: 31.4159 0.0000625  E notation: 3.14159E1 6.25E-5  Are double by default  Can be forced to be float (3.14159f) or long double (0.0000625L)
  • 98. The bool Data Type  Represents values that are true or false  bool variables are stored as small integers  false is represented by 0, true by 1: bool allDone = true; bool finished = false; allDone finished 1 0
  • 100. Determining the Size of a Data Type The sizeof operator gives the size of any data type or variable: double amount; cout << "A double is stored in " << sizeof(double) << "bytesn"; cout << "Variable amount is stored in " << sizeof(amount) << "bytesn";
  • 101. Overflow and Underflow:  An overflow occurs when the value assigned to a variable is more than the maximum allowable limit.  An underflow occurs when the value assigned to a variable is less then the minimum allowable limit.
  • 102. Variable Assignments and Initialization  An assignment statement uses the = operator to store a value in a variable. item = 12;  This statement assigns the value 12 to the item variable.
  • 103. Assignment  The variable receiving the value must appear on the left side of the = operator.  This will NOT work: // ERROR! 12 = item;
  • 104. Variable Initialization  To initialize a variable means to assign it a value when it is defined: int length = 12;  Can initialize some or all variables: int length = 12, width = 5, area;
  • 106. Scope  The scope of a variable: the part of the program in which the variable can be accessed  A variable cannot be used before it is defined
  • 107. Variable Out of Scope in Program
  • 108. Local Variables  Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code.  Local variables are not known to functions outside their own.
  • 109. Local Variables #include <iostream> using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; }
  • 110. Global Variables  Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life- time of your program.  A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
  • 111. Global Variables #include <iostream> using namespace std; // Global variable declaration: int g; int main () { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; }
  • 112. A program can have same name for local and global variables but value of local variable inside a function will take preference. For example: #include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; } // Output of Program g = 10
  • 113. Initializing Local and Global Variables  When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows Data Type Initializer int 0 char '0' float 0.0 double 0.0 pointer NULL
  • 114. Arithmetic Operators  Used for performing numeric calculations  C++ has unary, binary, and ternary operators:  unary (1 operand) -5  binary (2 operands) 13 - 7  ternary (3 operands) exp1 ? exp2 : exp3
  • 115. Arithmetic operators Plus + Minus - Multiply * Divide / Modulus %
  • 116. Arithmetic operators i + j x * y a / b a % b
  • 117. Binary Arithmetic Operators SYMBOL OPERATION EXAMPLE VALUE OF Ans + addition ans = 7 + 3; 10 - subtraction ans = 7 - 3; 4 * multiplication ans = 7 * 3; 21 / division ans = 7 / 3; 2 % modulus ans = 7 % 3; 1
  • 118. x = 2 + 4 ; = 6 ; Memory x 6
  • 119. Memory x = a + b ; a b x
  • 120. #include <iostream> void main ( ) { int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10 ; int TotalAge ; int AverageAge ; cout << “ Please enter the age of student 1: “ ; cin >> age1 ; cout << “ Please enter the age of student 2: “ ; cin >> age2 ; : : TotalAge = age1+ age2 + age3+ age4+ age5+age6+ age7+ age8+age9 + age10 ; AverageAge = TotalAge / 10 ; cout<< “The average age of the class is :” << AverageAge ; }
  • 121. Quadratic Equation  In algebra y = ax2 + bx + c  In C y = a*x*x + b*x + c
  • 124. Discriminant b2 - 2a = b*b - 4*a*c /2 *a Incorrect answer Solution = (b*b - 4*a*c) /(2 *a) Correct answer 4c
  • 125.  No expression on the left hand side of the assignment  Integer division truncates fractional part  Liberal use of brackets/parenthesis
  • 126. A Closer Look at the / Operator  / (division) operator performs integer division if both operands are integers cout << 13 / 5; // displays 2 cout << 91 / 7; // displays 13  If either operand is floating point, the result is floating point cout << 13 / 5.0; // displays 2.6 cout << 91.0 / 7; // displays 13.0
  • 127. A Closer Look at the % Operator  % (modulus) operator computes the remainder resulting from integer division cout << 13 % 5; // displays 3  % requires integers for both operands cout << 13 % 5.0; // error
  • 128. % = Remainder 5 % 2 = 1 2 % 2 = 0
  • 129. 4 / 2 = 2 5 / 2 = ?
  • 130. Precedence  Highest: ( )  Next: * , / , %  Lowest: + , -
  • 132.  counter += 3 ; same as  counter = counter + 3 ; +=
  • 133.  counter -= 5 ; same as  counter = counter – 5 ; -=
  • 134. x*=2 x = x * 2 *=
  • 135. x /= 2 x = x / 2 /=
  • 136.  x %= 2 ; Same As  x = x % 2 ; %=
  • 137. Precedence Operators Associativity (), ++postfix, -- postfix Left to right ++ prefix, ++prefix Left to right *,/,% Left to right +,- Left to right =,+=,-=,*=,/= Right to left
  • 138. Expressions  If all operands are integers  Expression is called an integral expression  Yields an integral result  Example: 2 + 3 * 5  If all operands are floating-point  Expression is called a floating-point expression  Yields a floating-point result  Example: 12.8 * 17.5 - 34.50
  • 139. Mixed Expressions  Mixed expression:  Has operands of different data types  Contains integers and floating-point  Examples of mixed expressions: 2 + 3.5 6 / 4 + 3.9 5.4 * 2 – 13.6 + 18 / 2
  • 140. Mixed Expressions (continued)  Evaluation rules:  If operator has same types of operands  Evaluated according to the type of the operands  If operator has both types of operands  Integer is changed to floating-point  Operator is evaluated  Result is floating-point  Entire expression is evaluated according to precedence rules
  • 141. Rules for Division  C++ treats integers differently from decimal numbers.  100 is an int type.  100.0 , 100.0000, and 100. are double type.  The general rule for division of int and double types is:  double/double -> double (normal)  double/int -> double (normal)  int/double -> double (normal)  int/int -> int (note: the decimal part is discarded)
  • 142. Rules for Division  Examples:  220. / 100.0 double/double -> double result is 2.2  220. / 100 double/int -> double result is 2.2  220 / 100.0 int/double -> double result is 2.2  220 / 100 int/int -> int result is 2  Summary: division is normal unless both the numerator and denominator are int, then the result is an int (the decimal part is discarded).
  • 143. Assignment Conversions  A decimal number assigned to an int type variable is truncated.  An integer assigned to a double type variable is converted to a decimal number.  Example 1: double yy = 2.7; int i = 15; int j = 10; i = yy; // i is now 2 yy = j; // yy is now 10.0
  • 144. Assignment Conversions  Example 2: int m, n; double xx; m = 7; n = 2.5; xx = m / n; n = xx + m / 2; // What is the value of n?
  • 145. Assignment Conversions  Example 2: int m, n; double xx; m = 7; n = 2.5; // 2.5 converted to 2 and assigned to n xx = m/n; // 7/2=3 converted to 3.0 and assigned to xx n = xx+m/2; // m/2=3 : integer division // xx+m/2 : double addition because xx is double // convert result of m/2 to double (i.e. 3.0) // xx+m/2=6.0 // convert result of xx+m/2 to int (i.e. 6) // because n is int
  • 146. Forcing a Type Change  You can change the type of an expression with a cast operation.  Syntax: variable1 = type(variable2); variable1 = type(expression);  Example: int x=1, y=2; double result1 = x/y; // result1 is 0.0 double result2 = double(x)/y; // result2 is 0.5 double result3 = x/double(y); // result3 is 0.5 double result4 = double(x)/double(y);// result4 is 0.5 double result5 = double(x/y); // result5 is 0.0 int cents = int(result4*100); // cents is 50
  • 147. When You Mix Apples with Oranges: Type Conversion  Operations are performed between operands of the same type.  If not of the same type, C++ will convert one to be the type of the other  This can impact the results of calculations.
  • 148. Hierarchy of Types Highest: Lowest: Ranked by largest number they can hold long double double float unsigned long long unsigned int int
  • 149. Type Coercion  Type Coercion: automatic conversion of an operand to another data type  Promotion: convert to a higher type  Demotion: convert to a lower type
  • 150. Coercion Rules 1) char, short, unsigned short automatically promoted to int 2) When operating on values of different data types, the lower one is promoted to the type of the higher one. 3) When using the = operator, the type of expression on right will be converted to type of variable on left
  • 151. Type Casting  Used for manual data type conversion  Useful for floating point division using int: double m; m = static_cast<double>(y2-y1) /(x2-x1);  Useful to see int value of a char variable: char ch = 'C'; cout << ch << " is " << static_cast<int>(ch);
  • 152. Type Casting in Program
  • 153. C-Style and Prestandard Type Cast Expressions  C-Style cast: data type name in () cout << ch << " is " << (int)ch;  Prestandard C++ cast: value in () cout << ch << " is " << int(ch);  Both are still supported in C++, although static_cast is preferred
  • 154. Interesting Problem Given a four-digit integer, separate and print the digits on the screen
  • 155. Analysis  Number = 1234  Take the remainder of the above number after dividing by 10 Eg 1234 / 10 gives remainder 4 1234 % 10 = 4  Remove last digit  1234/10 = 123.4  123 (Truncation due to Integer Division)  123 %10 gives 3  Remove last digit  123/10 = 12.3  12 (Truncation due to Integer Division)  12 % 10 gives remainder 2  Remove last digit  12/10 = 1.2  1 (Truncation due to Integer Division)  Final digit remains
  • 156. Code #include <iostream> void main ( ) { int number; int digit; cout << “Please enter a 4 digit integer : ”; cin >> number; 1234 digit = number %10; 4 cout <<“The digit is: “ << digit << ‘n’; // first digit; and then << ‘n’ number = number / 10; 123 digit = number % 10; 3 cout <<“The digit is: “ << digit << ‘n’; number = number / 10; 12 digit = number % 10 ; 2 cout <<“The digit is: “ << digit << ‘n’; number = number / 10; 1 digit = number % 10; cout <<“The digit is: “ << digit; }
  • 157. Named Constants  Named constant (constant variable): variable whose content cannot be changed during program execution  Used for representing constant values with descriptive names: const double TAX_RATE = 0.0675; const int NUM_STATES = 50;  Often named in uppercase letters  Use #define preprocessor directive instead of const definitions
  • 158. Named Constants in Program
  • 160. Difference between #define and const ‘#define’ directive ‘const’ Qualifier Used as preprocessor directive Used as a statement Not terminated with the ; Terminated with the ; Data type of constant identifier is not specified Data type is specified
  • 161. Postfix expressions Two postfix operators: ++ (postfix increment) -- (postfix decrement) the effect of a++ is the same as a = a + 1 the effect of a-- is the same as a = a - 1
  • 162. Prefix expressions Two prefix operators: ++ (prefix increment) -- (prefix decrement) the effect of ++a is the same as a = a + 1 the effect of --a is the same as a = a - 1
  • 163. 163 Relational Operators and the Type char  '0' through '9' have ASCII code values 48 through 57 '0' < '1' < . . . < '9'  'A' through 'Z' have ASCII code values 65 through 90 'A' < 'B' < . . .< 'Z'  'a' through 'z' have ASCII code values 97 through 122 'a' < 'b' < . . .< 'z'
  • 168. Programming Style  The visual organization of the source code  Includes the use of spaces, tabs, and blank lines  Does not affect the syntax of the program  Affects the readability of the source code
  • 169. Programming Style Common elements to improve readability:  Braces { } aligned vertically  Indentation of statements within a set of braces  Blank lines between declaration and other statements  Long statements wrapped over multiple lines with aligned operators