C++ Program Structure
- A typical C++ program has a structure as shown below:
---------------------------------- | | | Header Files | | Class Declaration | | Member Function Definition | | Main Function | | | ----------------------------------
Example
#include //Header Files using namespace std;
class employee //Class declaration with class name employee { char name[30]; //Class data initialization int age; public: void getdata(); // Member function definition void display(); };
void employee : getdata() //Function Definition { cout << "Enter the name and age :: "; cin >> name >> age; }
void employee : display() { cout << "Name = " << name <<"\n Age = " << age; }
int main() //Main Function { employee e; e.getdata(); e.display(); return 0; }
Character Set and Tokens
Character Set
- Character set is the any acceptable alphabet, digit, symbol, etc that represent information in a program which together forms tokens.
- The valid character set of C++ are:
1. Alphabets (a - z, A - Z)
2. Digits (0 - 9)
3. Special Symbols (+, -, *, /, =, {, }, etc)
4. White space (blank, new line, tab, etc)
Tokens
- Tokens are the smallest individual units of a program formed by the combination of character sets.
- The tokens in C++ are:
1. Keyword
2. Identifier
3. Constant
4. Operator
5. Punctuation
Keyword
- Keywords are the reserved words in C++ that have some special functioning.
- They can not be defined by user for any other purposes.
- They should be in lower case letters.
- Eg: int, auto, private, default, char, switch, if, for, etc.
Identifier
- Identifiers are the name of variables, function, array, class and so on created by the users.
- The rules for naming identifiers are as follows:
1. Only alphabets, digits and underscore are permitted.
2. Name can not start with digits.
3. Uppercase and lowercase letters are distinct.
4. Keywords can not be used.
5. No limits on the length of the name.
Constants / Literals
- Constants represent the fixed values that can not be altered during the program execution.
- It is classified as:
1. String constant
2. Numeric constant
3. Character constant
- Numeric constants are further divided into:
1. Integer
2. Float
3. Octal
4. Hex
Operator
- Operators are the special symbols used to perform mathematical or logical operations.
- The various operators used are as follows:
1. Arithmetic (+, -, *, /, %)
2. Assignment (=)
3. Self Assignment (++, --)
4. Arithmetic Assignment (+= , -=, *=, /=, %=)
5. Relational (>, <, >=, <=)
6. Equality (==, !=)
7. Logical (&&, ||, !)
8. Bitwise (>>, <<, ~, ^, |)
9. Other (?, :, ::, ( ), [ ], ->, etc)
Punctuator
- They are the special symbols which act as a punctuation marks.
- Eg: Parenthesis ( ), Braces { }, Comma ',', Semicolon :
Precedence and Associativity
Precedence Operators Associativity ------------------------------------------------------------------------------------------------------ 1 (), [ ], ->, ., postfix (++, --) Left to right 2 ++, --, !, ~, size of(), unary(+, -), & Right to left 3 *, /, % Left to right 4 +, - Left to right 5 <<, >> Left to right 6 <, <=, >, >= Left to right 7 ==, != Left to right 8 & Left to right 9 ^ Left to right 10 | Left to right 11 && Left to right 12 || Left to right 13 ?: Right to left 14 Assignment Right to left 15 , Left to right
Variable Declaration and Expression
- Variables are the entities that holds values which may alter during the program execution.
- Every variable must be declared.
Syntax: data_type variable_name_1, variable_name_2, ..............., variable_name_n;
- Expressions are the combination of variable, constant, function call, operators and so on.
- Eg: x = a + b
Statements and Data Types
Statement
- A statement carries out some action.
- Expression statement consists of any valid C++ expressions followed by a semicolon.
Eg: x = a + b;
- Compound statement is a group of C++ expression written wihin { and }.
Example: { a = b + c; x = y; }
- Control statement is used to control the flow of program under the given conditions.
Example: if (a > b) {
}
Data Type
- A data type defines a set of values that a variable can store and a set of operations that can be performed on that variable.
- It is of two types: Basic and Derived data types.
- Basic data types includes:
1. char
2. int
3. float, double
4. bool
- Derived data types includes:
1. array
2. structure
3. union
4. class
5. pointer
6. reference
Type Conversion and Promotion Rules
- Type conversion is the process of conversion of one data type into another type.
- It is of two types:
1. Implicit conversion
2. Explicit conversion
Implicit Conversion
- While evaluating expression containing mixed data types, one data type is automatically converted to higher type.
- The basic rule is:
char --> short --> int --> long --> float --> double --> long double
Explicit Conversion
- It is done by programmers as per their needs.
- The basic syntax is:
(data_type) expression;
- Eg:
int x;
(float) x;``
Preprocessor Directives
- The line beginning with # sign are called preprocessor directives.
- Eg:
#include
#define N 100
Namespace
- Namespace is the process of logically grouping of program elements.
- It is used to localize the name of identifiers to remove naming conflicts across different modules designed by different programmers.
Syntax: namespace namespace_name { //Declarations of variables, classes, functions }
- In other to include the already defined namespace into our scope, keyword 'using' is added.
- Syntax : using namespace namespace_name
User Defined Constant
- The keyword 'const' added before variable declaration indicates that the variable value does not alter during program execution.
Example: const float pi = 3.17 const int max = 255
Input/Output Streams and Manipulators
Input/Output Stream
-Stream is a sequence of characters from source to destination.
- Output stream is a sequence of characters from computer to output device.
- Input stream is a sequence of characters from input device to computer.
- 'cout' is used for output and 'cin' for input.
#include int main() { char name[30]; int age; cout << "Enter name and age:"; cin >> name >> age; cout << "Name = " << name << "Age = " << age; return 0; }
Manipulators
- Manipulators are instruction to i/o stream that modify the output in various ways.
- The header file must be included to use manipulators.
endl Manipulator
- It causes a line feed to be inserted into the stream so that the subsequent text is displayed on new line.
- Eg: cout << "Subject : C++";
cout << endl << "Total :" << marks;
setw Manipulator
- It causes the number or string that follows it in the stream to be printed within a field specified in the argument.
- Syntax : cout << setw(n) << variable_name;
C++ Example using Manipulators
#include //Header Files #include
int main() { float mark1 = 99, mark2 = 74; cout << setw(5) << "Names" << setw(7) << "Marks" << endl; cout << setw(5) << "Suraj" << setw(7) << mark1 << endl; cout << setw(5) << "Anil" << setw(7) << mark2 << endl; return 0; }
Output: Names Marks Suraj 99 Anil 74
DMA with new and delete
Dynamic Memory Allocation
- It is the process of allocating memory during run time as per the need.
- 'new' operator is used for allocation and 'delete' operator is used for deallocation.
New
- It obtains memory at run time from memory heap of operating system and returns the address of obtained memory.
- Syntax:
data_type *data_type_pointer;
data_type_pointer = new data_type; //Allocate for single variable
data_type_pointer = new data_type[size]; //Allocate an array
Delete
- It releases the memory allocated by 'new' back to operating system memory heap.
- Syntax:
delete data_type_ptr;
delete [ ] data_type_ptr;
Illustration of DMA in C++
#include //Header Files
int main() { int n, i, *arr, tot=0; float avg; cout << "How many numbers:"; cin >> n; arr = new int[n]; cout << "Enter elements"; for (i = 0; i < n; i++) { cin >> arr[i]; tot += arr[i]; } avg = tot / n; cout << endl << "Total = " << tot; cout << endl << "Average = " << avg; delete []arr; return 0; }
Condition and Looping
1. Sequential
2. Selective (if, if_else, switch, ?:)
3. Repetitive (while, do_while, for)
Syntax:
if statement
if (test_exp) statement;
if_else statement
if (test_exp) statement1; else statement2;
nested if_else
if (exp1) if (exp2) statement 1; else statement 2; else statement3;
switch statement
switch (exp) { case val_1: statement1; break; case val_2: statement2; break; .......... .......... default: default_statement; }
Conditional operator
exp1 ? true_statement : false_statement;
while loop
while (test_exp) statement;
do_while loop
do { statement; } while (test_exp);
for loop
for (initialize; test_exp; exp3) statement;
Functions
- Functions is a group of statements in a single unit to perform some specific task.
- It helps in code reusability.
Function Prototype
- A function header specified before function call.
- Syntax:
return_type function_name (parameter_list);
Function Definition
Syntax:
return_type function_name (parameter_list)
{
//body of function
}
Function Call
- Syntax:
function_name (argument_list);
Illustration of Function in C++
#include //Header Files
float calc(int, int, float); //Function prototype
int main() { int p, t; float r, i; cout << "Enter the value for p, t and r :"; cin >> p >> t >> r; i = calc(p, t, r); //Function call cout << "The interest is : " << i; return 0; }
//Function Definition float calc(int p, int t, float r) { return (p * t * r / 100); }
Function Overloading
- It is a logical method of calling several functions with different arguments and data types which performs identical actions by the same function name.
- Eg:
void display(); //No argument
void display(int); //one int argument
void display(int, char); //one int and one char argument
- The advantages of function overloading are as follows:
1. Eliminates the use of different function name for same operation.
2. Easy to understand and debug.
3. Easy to maintain code.
4. Better real world problem analysis.
- It is categorized as:
1. type of argument
2. number of argument
3. type and number of arguments
Type of Argument:
#include //Header Files
void display(char); void display(int);
int main() { char ch = 's'; int num = 20; cout << "Character : "; display(ch); cout << "Integer : "; display(num); return 0; }
void display(char c) { cout << c; }
void display(int n) { cout << n; }
Number of Argument:
#include //Header Files
void display(int); void display(int, int);
int main() { int ch = 10; int num = 20; cout << "One argument : "; display(ch); cout << "Two argument : "; display(ch, num); return 0; }
void display(int c) { cout << c; }
void display(int c, int n) { cout << c << n; }
Type and Number of Arguments:
#include //Header Files
void display(int); void display(char, int);
int main() { int ch = 's'; int num = 20; cout << "One argument of integer type : "; display(num); cout << "Two argument of integer and character type: "; display(ch, num); return 0; }
void display(int c) { cout << c; }
void display(char c, int n) { cout << c << n; }
Inline Function
- The function in which the code is copied in the called location is known as inline function.
- Syntax : inline return_type function_name (parameters)
- In ordinary function, when function is called, the control is passed to the calling function and after execution of the function, the control is passed back to the called function.
- In case of inline function, on function call, the code of called function is copied at the place of the call and compiled at the calling function without flow of control from calling to called function and back to calling function.
- This helps to minimize the execution time.
#include //Header Files
inline void display(int c) { cout << c; }
int main() { int num = 20; cout << "Inline function output : "; display(num); return 0; }
Default Argument
- During function call, less number of arguments can be passed than the actual number of arguments needed.
- This mechanism is possible by providing default argument.
- It helps in easy development and maintenance of the code.
#include //Header Files
inline void display(int c = 10, int d = 20) { int total; total = c + d; cout << total; }
int main() { display(); //Total = 30 display(30); //Total = 30 + 20 = 50 display(5, 5); //Total = 5 + 5 = 10 return 0; }
Pass by Reference
- On passing arguments by reference, the formal arguments in called function became aliases to actual arguments in the calling function.
- It is necessary when changes in called function is also important for the original arguments.
#include
void swap(int&, int&);
int main() { int a = 4, b = 6; cout << "Before swapping" << a << "and" << b; swap(a, b); cout << "After swapping" << a << "and" << b; return 0; }
void swap(int &x, int &y) { int temp; temp = x; x = y; y = temp; }
Return by Reference
- A function is able to return a variable by reference.
#include
int& max(int &x, int &y) { if (x > y) return x; else return y; }
int main() { int a = 5, b = 10; c = max(a, b); cout << c; return 0; }
Array, Pointer and String
Array
- It is a collection of similar data items.
- Each data item is called an element.
- Index starts with 0.
- 1D array declaration : type array_name[no_of_element];
- 2D array declaration : type array_name[row] [column];
Pointer
- It is a variable containing address of another variable.
- It is useful to return more than one value from the called function.
- It creates complex data structures.
- It is declared as:
data_type *variable_name;
- Eg: int *pnum;
String
- It is an array of characters.
- It is terminated by null character.
- It is declared as:
char string_name[no_of_characters];
Structure, Union and Enumeration
Structure
- It is the method of combining different data types.
- After defining a structure, a variable of its type can be declared.
Example: struct sudent { char name[30]; int age; }; student s1;
OR,
struct sudent
{
char name[30];
int age;
} s1;
Union
- It is similar to structure but differs in the way of storing and retrieving data.
- Union holds only one value for one data type.
- If a new assignment is done, the previous one is erased automatically.
Example: Union name { data_type mem1; data_type mem2; };
Enumeration
- Set of values represented by identifiers called enumeration constant.
Syntax: enum name { mem1; mem2; ........ mem n; };
Declaration:
enum name var1, var2, var3, ................ , varn;
-by SURAJ AWAL
Ⓒ Copyright ESign Technology 2019. A Product of ESign Technology. All Rights Reserved.