C++ Program Structure and Basics
C++ Program Structure and Basics
2
Chapter 1
§ 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
ü [Link] 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 localtime(), clock(), difftime() etc.
time manipulations in C++.
Contain function prototypes that test the type of
toupper(ch), tolower(ch), isalpha(ch),
characters (digit, alphabet, etc.). It also has
cctype isalnum(ch), isupper(ch), isdigit(ch),
prototypes that are used to convert between
uppercase and lowercase islower()
This header file includes function prototypes for
cstring strcpy (), strcat(), strcmp() etc.
C/C++-style string-processing functions.
Function as prototypes for functions that
fstream perform input/output from/to files on disk are open(), close(), put(), read(), write() etc.
included in fstream header.
CHAR_MIN, CHAR_MAX, INT_MIN,
This header file has the integral size limits of the
climits INT_MAX, UINT_MAX, LONG_MIN
system.
LONG_MAX
FLT_DIG, DBL_DIG, LDBL_DIG,
This header file contains the size limits for
cfloat FLT_MANT_DIG, DBL_MANT_DIG,
floating-point numbers on the system.
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
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
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 ([Link]) 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
fill(char ch)
be 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) [Link]
73
74