0% found this document useful (0 votes)
2 views11 pages

CPP Core Notes Perfect Layout From File5

Uploaded by

Soumadip Karan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

CPP Core Notes Perfect Layout From File5

Uploaded by

Soumadip Karan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 01: CORE BASICS & SYNTACTIC STRUCTURE

📙 1. Boilerplate Code

Boilerplate code refers to standard template sections that must be included as a structural baseline in
almost every program before writing custom user logic.

In C++, the semicolon ( ; ) functions as a statement terminator, instructing the compiler that an
independent command line has reached completion.

• SOURCE TEMPLATE

#include<iostream>
using namespace std;
int main() {
return 0; // Statement ends with a semicolon terminator
}

📙 2. Code Compilation and Execution Lifecycle

Computers cannot interpret high-level language directly. The text files containing code must undergo
translation through software called a Compiler to generate an executable binary file composed of 0s and
1s.

The Compilation Pipeline:

• source code ([Link]): The core human-readable file written by us.

• Compiler: The background parsing software system.

• executable file ([Link]): The machine code output consisting of 0s and 1s.

• Output ("Hello"): The final rendered terminal print line.

• Windows OS: Produces executable files with a .exe file extension.

• macOS/Linux OS: Produces executable files with a .out file extension.

Error Detection: Syntax or compile-time violations contained within source records are identified and
halted by the compiler during this pipeline stage before building an executable.

C++ Core Programming Concepts Page 1


📙 3. Preprocessor Directives & Header Files

A Directive provides specific guidance instructions to the compiler. A Preprocessor Directive is a


specialized command executed before the actual program compilation begins.

• All preprocessor directives start strictly with a hash symbol ( # ).

• The directive #include <iostream> requests the preprocessor to load the contents of the iostream
Header File into our program prior to compilation.

• Header Files (e.g., <iostream> , <vector> , <stack> ) house pre-written utility configurations. For
instance, the predefined definitions driving input/output operations like cout and cin are embedded
inside the iostream file.

📙 4. Macros

Preprocessor directives are also used to define Macros, which are symbolic constants. The preprocessor
replaces all instances of a macro name with its defined value throughout the source file before
compilation begins.

• MACRO REPLACEMENT EXAMPLE

#include<iostream>
#define PI 3.14 // Defining a symbolic constant macro named PI
using namespace std;

int main() {
cout << PI; // Replaced by 3.14 prior to compiling. Output: 3.14
return 0;
}

📙 5. Escape Sequences & Stream Manipulators

When formatting output streams, plain text strings are often insufficient. C++ provides built-in
mechanisms to format output visually and handle text layouts across the terminal display interface.

C++ Core Programming Concepts Page 2


A. Escape Sequences

These are special backslash character constants embedded directly within text literals. The compiler
intercepts them to trigger specific formatting actions rather than printing them literally.

Escape Sequence Description / Action Example Output Mapping

Newline: Shifts the output cursor directly to the "Hello\nWorld" → Splits


\n
start of the next line. onto two lines.

Horizontal Tab: Shifts cursor forward by a


"A\tB" → Inserts structured
\t standard horizontal spacing gap (usually 4 or 8
column spacing.
spaces).

Double Quote: Forces a literal double-quote "He said \"Hi\"" → He


\"
character to display inside a string literal. said "Hi"

Backslash: Prints a single literal backslash "C:\\Program" → C:


\\
symbol safely. \Program

📙 B. Stream Manipulators & The Critical Contrast (endl vs '\n')

These are special helper functions plugged directly into output redirection pipelines to alter output
formatting behaviors dynamically.

• endl: Inserts a newline character into the output stream and immediately forces an explicit buffer flush,
instantly synchronizing physical output with the terminal display screen.

• setw(int w): Set width helper imported via the <iomanip> header file. It establishes an exact character
width window for the next printed parameter item, filling unused space with default blank padding for
clear data alignments.

Structural Comparison (endl vs '\n'):

• Use '\n' when printing frequent lines of text (e.g., in loops or high-performance Competitive
Programming). It only inserts a line break without interrupting program execution to clean memory.

💡 Conceptually Critical Note:

Use endl when immediate output rendering is mandatory (e.g., debugging circuit data logs or user-
facing prompts) because its buffer flushing mechanism ensures that text is printed live on screen
immediately, though at a slight execution performance cost.

C++ Core Programming Concepts Page 3


• FORMATTING & MANIPULATOR DEMO

#include<iostream>
#include<iomanip> // Required to use stream manipulators like setw
using namespace std;

int main() {
cout << "Line A" << endl; // Breaks line & flushes buffer
cout << "Col1" << "\t" << "Col2\n"; // Tab spacing and newline sequence
cout << setw(10) << 45 << endl; // Right-aligns '45' inside a 10-char space
return 0;
}

📙 6. The Main Function Entry Point

The expression int main() defines the primary structural function of a C++ application. It acts as the
mandatory entry point where runtime code execution initiates.

• Every operational C++ executable must contain exactly one main() function block.

• The prefix keyword int indicates that the function returns an integer numerical status upon
completion.

• Curly braces ( {} ) delimit the code block, explicitly defining where the execution scope starts and ends.

• The ending command statement return 0; terminates the main() function execution.

• Returning a value of 0 conventionally signifies that the program executed successfully without any
runtime faults. Any non-zero integer return value indicates a structural failure or anomalous exit code.

📙 7. Namespaces & Scope Management

A Namespace provides a declarative scope to organize code and prevent identifier naming conflicts when
dealing with large codebases or multiple external libraries.

• The official standard C++ library namespace is named std .

• Standard components like cout and cin are physically defined inside the <iostream> file header,
but their identifying names are officially registered inside the std namespace.

C++ Core Programming Concepts Page 4


• To avoid prefixing std:: before every standard object, we add using namespace std; at the top of
the file.

📙 8. Basic Output Pattern Demonstration

This program uses cascading stream outputs to print a basic descending star shape directly to the user
display console terminal.

• PATTERN CODE BLOCK

#include<iostream>
using namespace std;

int main() {
cout << "*****";
cout << "***";
cout << "**";
cout << "*";
return 0;
}

C++ Core Programming Concepts Page 5


CHAPTER 02: VARIABLES AND DATA TYPES

📙 1. Variables & Identifiers

A variable is a named memory location assigned to a value that can change during program execution. It
can be thought of as a named container that holds data in the RAM.

An identifier is a unique name used to identify program elements like variables, functions, objects, and
classes. Variable names are a specific type of identifier and should always be meaningful.

A literal is a fixed value represented directly within the source code (e.g., 10, 'A'). Unlike variables, literals
do not point to changing memory locations; they represent the constant value itself.

📙 2. Core Structural Contrast: Keyword vs. Identifier

Understanding the strict differences between predefined core assets and programmer-defined markers is
fundamental to code compilation diagnostics.

• Keywords: These are reserved tokens that have specific fixed meanings pre-programmed into the C++
compiler engine (e.g., int , float , double , return , const ). They cannot be reassigned,
repurposed, or altered by the developer.

• Identifiers: These are entirely custom strings defined dynamically by the software developer to identify
structural storage references (such as variable labels, structural class naming, or custom function
names). They must strictly observe the system naming syntax rules.

📙 3. Identifier Naming Conventions & Rules

When defining identifiers (variable names, function signatures, class descriptors) in C++, developers must
adhere strictly to the following architectural compiler rules:

• Rule 1: An identifier name must start with a letter (either uppercase or lowercase) or an underscore
symbol ( _ ). It cannot begin with a numerical digit.

• Rule 2: The body of the identifier can only contain alphanumeric characters (letters and numbers 0-9)
and underscores ( _ ). No spaces or special characters are allowed.

• Rule 3: Identifiers must not match any reserved keywords, as these words possess explicit built-in
operational definitions designated by the compiler.

C++ Core Programming Concepts Page 6


📙 4. Variable Lifecycle: Declaration vs. Initialization

Allocating and managing random access memory blocks requires a clear, step-by-step approach to
variable setup.

A. Variable Declaration

This operation alerts the compiler that an identifier tracking label is now registered, alongside the target
variable data type. No value assignment occurs here; it simply reserves space based on the size of the
data type.

int marks; // Declaration: Reserves 4 bytes in RAM, value is currently garbage.

B. Variable Initialization

This step assigns a concrete initial value to a variable at the exact same moment it is declared in the code.

int age = 21; // Initialization: Declared and bounded immediately to value 21.

C. Multiple Variable Initialization

C++ provides a clean syntax to declare or initialize multiple variables of the same data type in a single
statement, separating them with commas.

• MULTI-VARIABLE PATTERNS

int x = 10, y = 20, z = 30; // Initializes multiple distinct variables


int a, b, c; // Declares multiple variables simultaneously

D. Default Initialization

What happens when a declared primitive variable isn't assigned an explicit value? Its starting state
depends entirely on its structural storage environment:

• Local Variables (Inside Functions): They are not initialized to zero automatically. They are left holding
whatever residual data was already left in that memory address, resulting in a Garbage Value.

• Global / Static Variables (Outside Functions): The compiler automatically applies Default
Initialization, safely setting numerical primitives directly to zero (0 or 0.0).

C++ Core Programming Concepts Page 7


📙 5. Constant Variables (The const Keyword)

While macros ( #define ) perform raw text replacement before code compiles, modern C++ type-safety
guidelines recommend using the const keyword to lock variable values.

• Adding const before a variable data type makes its assigned value strictly read-only across the entire
application runtime scope.

• Rule: A constant variable must be initialized immediately upon declaration. Attempting to declare a
constant without an initial value, or trying to modify its value later, will trigger a compile-time error.

• CONSTANT SCOPE RESTRICTIONS

const double EARTH_GRAVITY = 9.81; // Type-safe read-only variable


// EARTH_GRAVITY = 10.0; // COMPILER ERROR! Cannot reassign a constant variable
// const int MAX_SPEED; // COMPILER ERROR! Must be initialized instantly

📙 6. Data Types

A data type defines the type and size of value a variable is allowed to store. Statically typed languages like
C++ require explicitly declaring the data type of every variable before usage.

Data types are broadly categorized into two types:

• Primitive Data Types: Built-in types directly supported by the compiler.


◦ int (Integer): Stores whole numbers. Size: 4 Bytes

◦ char (Character): Stores single characters inside single quotes. Size: 1 Byte

◦ bool (Boolean): Stores true (1) or false (0). Size: 1 Byte

C++ Core Programming Concepts Page 8


• ...Continued Primitive Data Types:
◦ float (Floating Point): Stores decimal values. Size: 4 Bytes

◦ double (Double Precision): Stores higher-precision decimals. Size: 8 Bytes

• Non-Primitive Data Types: User-defined or derived types like Strings and Arrays.

📙 7. Garbage Values

When a local variable is declared without an initial value, C++ does not automatically reset it to zero.
Instead, it retains whatever residual bit pattern was already present in that RAM sector. This unpredictable
data is referred to as a Garbage Value.

• GARBAGE VERIFICATION OUTPUT

#include<iostream>
using namespace std;

int main() {
int a; // Uninitialized local variable
cout << "a = " << a << endl;
// Output prints an unpredictable system number, e.g., a = 4201051
return 0;
}

📙 8. Comments

Comments are descriptive annotations added inside a program to help developers understand the
codebase. They are completely ignored by the compiler during execution.

• Single-Line Comments: Denoted by double forward slashes ( // ).

• Multi-Line Comments: Enclosed within /* and */ blocks.

📙 9. Stream Input (cin)

The cin object (character input) belongs to the std namespace and is used to read data from the
standard input device (terminal keyboard) using the extraction operator ( >> ).

C++ Core Programming Concepts Page 9


📙 10. Application: Sum and Product Program

• ARITHMETIC PROGRAM LOGIC

#include<iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter a number a: ";
cin >> a;
cout << "Enter a number b: ";
cin >> b;

int sum = a + b;
int product = a * b;

cout << "Sum of two numbers: " << sum << endl;
cout << "Product of two numbers: " << product << endl;
return 0;
}

📙 11. Application: Average of Marks Program

• FLOATING POINT PROCESSING

#include<iostream>
using namespace std;

int main() {
float science_marks, english_marks, math_marks;
cout << "Enter marks for Science, English and Math: ";
cin >> science_marks >> english_marks >> math_marks;

float average = (science_marks + english_marks + math_marks) / 3.0f;


cout << "Average of the subjects is " << average << endl;
return 0;
}

C++ Core Programming Concepts Page 10


📙 12. Chapter Practice Problems

🎯 Question 1: Area of a Square

• PRACTICE PROBLEM 1

#include<iostream>
using namespace std;

int main() {
int side;
cin >> side;
cout << "area = " << side * side << endl;
return 0;
}

🎯 Question 2: Total Cost with 18% GST

• PRACTICE PROBLEM 2

#include<iostream>
using namespace std;

int main() {
float penCost, pencilCost, eraserCost;
cin >> penCost >> pencilCost >> eraserCost;

float totCost = penCost + pencilCost + eraserCost;


cout << "total = " << totCost << endl;
cout << "total with GST = " << (totCost + (0.18f * totCost)) << endl;
return 0;
}

C++ Core Programming Concepts Page 11

You might also like