Chapter 2 - Basic Programming Constructors
Chapter 2 - Basic Programming Constructors
Computer
Programming
Chapter Two
Basic Programming
Constructors
Outline
Compilation Process and running programs:
Compiling, Debugging and Linking
Structure (Anatomy) of C++ program
Preprocessor and library functions
main() function
Statement and Block
Why C++ programming language
2
Chapter 1
Outline
Basic Elements of program (Syntax and Semantics)
Input/output standards
Variables and Data types
Constants
Operators and expression
Debugging and Programming Errors
Error types
Debugging errors
Formatting Program
Comment, braces, Indentation and White space
Formatted Input-Output
3
Chapter 1
Anatomy of C++ program
string literal
return 0; send 0 to operating system Output
Hello, there!
Blocks
Also called compound statement
A group of statements surrounded by braces { }.
All the statements inside the block are treated as one unit.
There is no need to put a semi-colon after the closing brace to end
a complex statement
E.ge main() function
5
Chapter 1
Structure of C++ Program (cont’d)
main () function
It is where program execution starts in C++
Every C++ must contain main () function
The main () function can be made to return a value to the
operating system (the caller)
The return type is specified by Data type where as the return value
is mentioned by with return keyword.
The main () function must followed by block i.e. { }
Note
Instead of using numeric value of zero and non-zero, you can
also use EXIT_SUCESS or EXIT_FAILURE, which is defined in the
cstdlib header (i.e., you need to "#include <cstdlib>".
6
Chapter 1
I/O Streams
Data stream refers to the flow of data between program and it’s
environment particularly input/output devices.
Data stream typically exist in the form of characters or numbers
Syntax: cout<<data;
The insertion operator "<<" inserts data into cout
cout is an output stream sending data to the monitor
data refers to data to be printed which can be literal,
variable, expression or constant.
More than one data separated by insertion operator can be
sent to screen with single cout output stream.
8
Chapter 1
I/O Streams (cont’d)
C++ standard INPUT Stream (cin)
cin (console input) is the object to read data typed at the
keyboard in C++.
Syntax: cin>>variable;
cin is an input stream bringing data from the keyboard
The extraction operator (>>) removes data to be used
variable refers to memory location where the data will be stored.
More than one variable separated by extraction operator can
be used to capture data from keyboard with single cin input
stream.
9
Chapter 1
I/O Streams (cont’d)
Sample program to demonstrate the standard Input/output stream
10
Chapter 1
C/C++ Library Functions and preprocessor
Library functions also called “built-in” functions
This are functions that are implemented in C/C++ and ready to be directly
incorporated in our program as per our requirements
Library functions in C/C++ are declared and defined in special files called
“Header Files” which we can reference in our C/C++ programs using the
“include” directive.
Some of C/C++ library header files are tabularized as below
Headers Description Functions
This header contains the prototype
iostream for standard input and output cin, cout, cerror, get(), getline() etc.
functions used in C++
sqrt(), pow(base,exponent), exp(x),
This is the header containing
cmath/math fabs(x), log(x), log 10(x), sin(x), cos(x),
various math library functions.
tan(x), asin(x), acos(x), atan(x) etc.
This header contains stream
setw (int n), setfill(char c),
iomanip manipulator functions that allow setprecision(int n) etc.
us to format the stream of data.
11
Chapter 1
C/C++ Library Functions (cont’d)
Headers Description Functions
contains various functions related to conversion abs(x), atof(const char* str), atoi(const
cstdlib between text and numbers, random numbers, char* str), atol(const char* str),
and other utility functions. atoll(const char* str) etc.
Contains function prototypes related to date and
ctime time manipulations in C++. localtime(), clock(), difftime() etc.
Contain function prototypes that test the type of toupper(ch), tolower(ch), isalpha(ch),
characters (digit, alphabet, etc.). It also has
cctype prototypes that are used to convert between isalnum(ch), isupper(ch), isdigit(ch),
uppercase and lowercase islower()
This header file includes function prototypes for
cstring C/C++-style string-processing functions. strcpy (), strcat(), strcmp() etc.
Function as prototypes for functions that open(), close(), put(), read(), write()
fstream perform input/output from/to files on disk are
included in fstream header. etc.
CHAR_MIN, CHAR_MAX, INT_MIN,
This header file has the integral size limits of the
climits system.
INT_MAX, UINT_MAX, LONG_MIN
LONG_MAX
FLT_DIG, DBL_DIG, LDBL_DIG,
This header file contains the size limits for
cfloat floating-point numbers on the system.
FLT_MANT_DIG, DBL_MANT_DIG,
LDBL_MANT_DIG
12
Chapter 1
C/C++ Library Functions (cont’d)
Namespace: using namespace std;
Namespace designed to overcome a difficulty of like the below
Sometimes a developer might be writing some code that has a
function called xyz() and there is another library available which is
also having same function xyz().
The compiler has no way of knowing which version of xyz() function
you are referring to within your code.
14
Chapter 1
Preprocessor Directives (cont’d)
A file preprocessor
#include <filename> versus #include “/path/filename.h”
#include <filename>
• Looks in the IDE C++ devloper tools standard include directories that
were created at install time for the file.
#include “/path/filename.h”
• Looks for the filename.h file in the /path/ directory path.
• Used when you are creating your own files (we will learn later how to
do) OR when you have downloaded some 3rd party non-standard C++
header files.
15
Chapter 1
Comments
• Used to document parts of the program
• Are ignored by the compiler
• Type of comments -- Single comment and Multi line comment
18
Chapter 1
Translation and Execution process (2/4)
Compiler Interpreter
Compiler scans the whole program in one go Translates program one statement at a time.
As it scans the code in one go, the errors (if Considering it scans code one line at a time,
any) are shown at the end together. errors are shown line by line.
Converts the source code into object code. does not convert source code into object code
19
Chapter 1
Translation and Execution process (3/4)
20
Chapter 1
Translation and Execution process (4/4)
21
Chapter 1
Variables and Data types
Variables
A primary goal of computer program is data processing
Variable is a named reserved place (storage location) in memory,
which stores a piece of data of a particular data type.
As a result it can be used in various computations in a program
All variables have three important components
Data Types
Identifier
Value
22
Chapter 1
Variables and Data types (cont’d)
Data Types
Describes the property of the data and the size of the reserved
memory.
Established when the variable is defined
Data types supported by C++ can be classified as follow
23
Chapter 1
Variables and Data types (cont’d)
25
Chapter 1
Variables and Data types (cont’d)
Data types size and range of value
26
Chapter 1
Variables and Data types (cont’d)
The program below prints the size of C++ primitive data types
27
Chapter 1
Variables and Data types (cont’d)
Signed Vs. Unsigned
+ve – 0 bit
-ve ---> 1 bit
By default
integer Data types are Signed where as char data types are Unsigned
float, double, long double is also Signed, and cannot restricted to be Unsigned
28
Chapter 1
Variables and Data types (cont’d)
29
Chapter 1
Variables and Data types (cont’d)
30
Chapter 1
Variables Naming Conventions
An identifiers refers to the name of variable that needed to
uniquely identify each variable, so as to store a value to the
variable and retrieve the value stored
33
Chapter 1
Variables declaration and Initialization
Variable Declaration
Variable must first be declared (defined) before they can be
used.
Variables can be created in a process known as declaration
which instructs the computer to reserve a memory location
with the name and size
Declaration syntax:
DataType Identifier;
Declaration Examples:
• float moon_distance;
• double average, m_score, total_score;
• int age, num_students;
• Assigning a value: age=14;
34
Chapter 1
Variables declaration and Initialization
(cont’d)
Variable Initialization
When a variable is assigned a value at the time of declaration
Example:
int length = 12;
double width = 26.3, area = 0.0;
int length (12), width (5);
36
Chapter 1
Scope of Variables
Variables in a program can be declared just about anywhere.
However, the accessibility, visibility and length of life of a variable depend
on where the variable is declared.
Scope of a variable is the boundary or block in a program where a
variable can be accessed
Global Variable
referred/accessed
anywhere in the
code
Local Variable
Accessed only in side
a block within which
they are declared
37
Chapter 1
Scope of Variables (cont’d)
Sample program to demonstrate scope of variable
38
Chapter 1
Constants and literals (1/8)
Constant
Like a variable a data storage locations in the computer memory
that has a fixed value and that do not change their content during
the execution of a program.
Must be initialized when they are created by the program,
The programmer can’t assign a new value to a constant later.
Usually defined for values that will be used more than once in a
program but not changed
E.g., PI = 3.14, Sun_Seed = 3*10^8
40
Chapter 1
Constants and literals (3/8)
Literals
are data used for representing fixed values.
They can be used directly in the code.
For example: 1, 2.5, 'c' etc.
41
Chapter 1
Constants and literals (4/8)
Sample program
42
Chapter 1
Constants and literals (5/8)
C++ Escape characters
43
Chapter 1
Constants and literals (6/8)
Special characters
44
Chapter 1
Constants and literals (7/8)
Enumerated Constant
Use to declare multiple integer constants using single line with
different features.
Cannot take any other data type than integer
enum types can be used to set up collections of named integer
constants.
Enables programmers to define variables and restrict the value of
that variable to a set of possible values which are integer.
Use the keyword enum is short for ``enumerated''.
Syntax: enum identifier {enumerated list};
45
Chapter 1
Constants and literals (8/8)
enum sample program
46
Chapter 1
Operators and expression (1/ 17)
Operators
A symbol that tells the computer to perform certain mathematical
(or) logical manipulations (makes the machine to take an action).
Based on the number of the operands the operators act on, operators are
grouped as
48
Chapter 1
Operators and expression (3/17)
Expression
A combination of operators and operands (variables or literal values),
that can be evaluated to yield a single value of a certain type.
It can also be viewed as any statement that evaluates to a value (returns
a value)
Examples:
• x=3.2; returns the value 3.2
• x = a + b;
49
Chapter 1
Operators and expression (4/17)
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
Points to be considered
Arithmetic expression
Mixed type operations - two operands belong to different types
Type casting – implicitly type casting
Overflow/Under Flow – what happen if the computation result
exceed the storage capacity of the result variable 50
Chapter 1
Operators and expression (5/17)
Overflow/Underflow and wrapping around
Arithmetic overflow/underflow happens when an arithmetic operation
results in a value that is outside the range of values representable by the
given data type
Wrapping around unsigned integers - when the program runs out of positive
number, the program moves into the largest negative number and then
counts back to zero
Wrapping around signed integers - when the program runs out of positive
number, the program moves into the largest negative number and then
counts back to smallest negative value
51
Chapter 1
Operators and expression (6/17)
Exercise
52
Chapter 1
Operators and expression (7/17)
Assignment Operators
Copy/put the value/content (of RHS) ----> to a variable (of LHS)
Evaluates an expression (of RHS) and assign the resultant value to a
variable (of LHS)
Single assignment operators
Compound assignment
operators
Multiple assignment
a = b = c = 36
53
Chapter 1
Operators and expression (8/17)
Relation (Comparison) Operators
Evaluated to true/false
Used to compare two operands that must evaluated to numeric
Characters and Boolean are valid operands as they are represented
by numeric. Character can be evaluated by their ASCII value
54
Chapter 1
Operators and expression (9/17)
Logical Operators
Evaluated to true/false
Used to compare two logical statements
any non-zero value can be used to represent the logical true, whereas
only zero represents the logical false
Exercise:
• Given the year, month (1-12), and day (1-31), write a Boolean expression which
returns true for dates before October 15, 1582 (G.C. cut over date)
55
Chapter 1
Operators and expression (10/17)
Bitwise Operators
It refers to the testing, setting or shifting of actual bits in a
byte or word.
There are bitwise operators
56
Chapter 1
Operators and expression (11/17)
Increment/Decrement Operators (++/--)
Used to automatically increment and decrement the value of a
variable by 1
Provide a convenient way of, respectively, adding and subtracting 1
from a numeric variable
main() {
int a = 21, c ;
main() {
int a = 21, c ;
a++; //postfix increment
c = a;
cout<<"Value of c after assigned a++ is :"<<c<<endl;
cout<<“Value of a is after a++:" << a << endl ;
Output:
i = 10 j = 5
10>=5? 10: 5
The larger
number is 10 60
Chapter 1
Operators and expression (15/17)
Miscellaneous Operators
Type casting operator (using bracket)
61
Chapter 1
Operators and expression (16/17)
/* Test Type Casting (TestTypeCast.cpp) double d1 = 5.5, d2 = 6.6;
*/ cout << (int)d1 / i2 << endl; // 0
#include <iostream> cout << (int)(d1 / i2) << endl; // 0
#include <iomanip>
using namespace std; // Test implict type casting
d1 = i1; // int implicitly casts to double
int main() { cout << d1 << endl; // 4.0
// Print floating-point number in fixed
format with 1 decimal place // double truncates to int! (Warning?)
cout << fixed << setprecision(1); i2 = d2;
cout << i2 << endl; // 6
// Test explicit type casting }
int i1 = 4, i2 = 8;
cout << i1 / i2 << endl; // 0
cout << (double)i1 / i2 << endl; // 0.5
cout << i1 / (double)i2 << endl; // 0.5
cout << (double)(i1 / i2) << endl; // 0.0
62
Chapter 1
Operator precedence (17/17)
Refers to the order an expression that contain more than one
operators will be evaluated
63
Chapter 1
Debugging program Errors (1/2)
Errors
The problems or the faults that occur in the program, which
makes the behavior of the program abnormal
Also known as the bugs or faults
Detected either during the time of compilation or execution
Debugging
The process of removing program bugs and correcting it
Types of errors
The are three major errors in programming namely
1. Syntax errors – also include semantics error
2. Logical errors
3. Run-time errors
64
Chapter 1
Debugging program Errors (2/2)
Syntax errors
When there is the violation of the grammatical (Syntax) rule.
Detected at the compilation time.
e.g. missing of semicolon, Identifier not declared
Logical Errors:
Produced due to wrong logic of program. Tough to identify and even
tougher to remove.
Variables are used before initialized/assigned value
Misunderstanding of priority and associativity of operators
Runtime Errors:
Generated during execution phase due to mathematical or some
operation generated at the run time.
Division by zero,
Square root of negative number,
File not found, Trying to write a read only file 65
Chapter 1
Formatted Input/output (1/2)
Formatted console input/output functions are used for performing input/output
operations at console and the resulting data is formatted and transformed.
Functions Description
Using this function, we can specify the width of a value to be displayed
width(int width)
in the output at the console.
Using this function, we can fill the unused white spaces in a value(to be
fill(char ch)
printed at the console), with a character of our choice.
Using this function, we can set the flags, which allow us to display a
setf(arg1, arg2)
value in a particular format.
The function returns the next character from input stream, without
peek()
removing it from the stream.
The function skips over a number of characters, when taking an input
ignore(int num)
from the user at console.
This function appends a character(which was last read by get()
putback(char ch)
function) back to the input stream.
Using this function, we can specify the number of
precision(int num_of_digts) digits(num_of_digits) to the right of decimal, to be printed in the
output.
66
Chapter 1
Formatted Input/output (2/2)
67
Chapter 1
Formatting codes (1/1)
Proper commenting
Avoid improper/unnecessary and over comments
Comment your codes liberally
Braces
Place the beginning brace at the end of the line, and align the ending
brace with the start of the statement
Indentation and whitespace
Indent the body of a block by an extra 3 (or 4 spaces), according to its
level and provide enough space/newline between statements, operators,
operands/variables and other programming elements
Naming (Identifiers)
Use self-contained identifier (variable naming)
e.g., row, col, size, xMax, numStudents.
Avoid using single-alphabet and meaningless names, such as a, b, c, d
except common one like i, j, x, y
68
Chapter 1
Summary of C++ Statements (1/1)
Prep-processor statements
Declarative Statements
Variable declaration
Variable Initialization
Constant definition
Executable statements
Input/output statements
Assignment statements
Expression
Selection statements
Loop statements
Special Statements (break, continue, return, exit)
69
Chapter 1
Exercise
1. Identify which of the following are valid and invalid identifiers?
Justify your answer.
a) Identifier f) 2by2
b) seven_11 g) Default
c) _unique_ h) average_weight_of_large_pizza
d) gross-income i) variable
e) gross$income j) object.oriented
74