2. • C++ Program Structure
• The basic structure of a C++ program consists of the following parts:
• Header file inclusion section: This is the section where we include all
required header files whose functions we are going to use in the
program.
• Namespace section: This is the section where we use the namespace.
• The main() section: In this section, we write our main code. The
main() function is an entry point of any C++ programming code from
where the program's execution starts.
3. #include <iostream>
using namespace std;
// main() is where program execution begins.
int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
4. • The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is needed.
• iostream is used the import the input output stream library
• The line using namespace std; tells the compiler to use the std namespace. Namespaces are
a relatively recent addition to C++.
• The std namespace in C++ contains many standard library components, including data
types, functions, and objects. When you write using namespace std;, you're essentially
telling the compiler to consider all the names in the std namespace as if they're in the
global namespace.
• The next line '// main() is where program execution begins.' is a single-line comment
available in C++. Single-line comments begin with // and stop at the end of the line.
• The line int main() is the main function where program execution begins.
• The next line cout << "Hello World"; causes the message "Hello World" to be displayed on
the screen.
• The next line return 0; terminates main() function and causes it to return the value 0 to the
calling process.
• NOTE: In C++, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
5. • C++ Identifiers
• A C++ identifier is a name used to identify a variable, function, class,
module, or any other user-defined item. An identifier starts with a
letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
• C++ does not allow punctuation characters such as @, $, and % within
identifiers. C++ is a case-sensitive programming language. Thus,
Manpower and manpower are two different identifiers in C++.
• Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
6. • Rules for Identifiers
• It must begin with a letter (uppercase "A-Z" or lowercase "a-z") or an underscore
(_) but cannot start with a digit.
• After the first character, subsequent characters can be letters, digits (0-9), or
underscores.
• Identifiers are case-sensitive (myVar and myvar are different).
• It cannot be a keyword (reserved word in C++), for example, int, bool, return, and
while, etc.
• It must be unique within their namespace.
• Use meaningful names that reflect the purpose of the identifier (e.g, totalCount,
calculateArea).
• In common practices, generally use camelCase or snake_case for readability.
• There is generally no strict limit on the length, but avoid long names as they make
code harder to read and understand.
7. • Example of Invalid Identifiers
• 2ndValue (as it starts with a digit)
• first-name (it contains a hyphen)
• @username (begins with a special character)
• my variable (contains a space)
• float (uses a reserved keyword)
8. • C++ Keywords
• In C++, keywords are reserved words that have special meanings to the
compiler.The following list shows the reserved words in C++. These reserved
words may not be used as constant or variable or any other identifier names.
asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template
9. • C++ Comments
• Program comments are explanatory statements that you can include in the C++
code. These comments help anyone reading the source code. All programming
languages allow for some form of comments.
• Types of C++ Comments
• C++ supports two types of comments: single-line comments and multi-line
comments. All characters available inside any comment are ignored by the C++
compiler.
• 1. C++ Single-line Comments
• A single-line comment starts with //, extending to the end of the line. These
comments can last only till the end of the line, and the next line leads to a new
comment.
• Syntax
• // Text to be commented
10. • 2. C++ Multi-line Comments
• Multi-line comments start with /* and end with */. Any text in between these symbols
is treated as a comment only.
• Syntax
• /* This is a comment */
• /*
• C++ comments can also
• span multiple lines
• */
• Comments within Statements
• We can also comment-out specific statements within a code block inside a C++
program. This is done using both types of comments.
11. • Purpose of Comments
• Comments are used for various purposes in C++. Some of the main areas of
application of comments are given as follows:
• To represent a short and concise step in the program for users to understand
better.
• To explain a step in a detailed way that is not expressed explicitly in the code.
• To leave different hints for users to grab in the code itself.
• To leave comments for fun or recreation.
• To temporarily disable part of the code for debugging purposes.
• To add metadata to the code for future purposes.
• To create documentation for the code, for example, in Github pages.
12. • C++ Constants/Literals
• Constants refer to fixed values that the program may not alter and they are called
literals.
• Constants can be of any of the basic data types and can be divided into Integer
Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
• Again, constants are treated just like regular variables except that their values
cannot be modified after their definition.
• Defining Constants
• There are two simple ways in C++ to define constants −
• Using #define preprocessor.
• Using const keyword.
13. • The #define Preprocessor
• Following is the form to use #define preprocessor to define a constant
−
• #define identifier value
• e.g: #define LENGTH 10
• The const Keyword
• You can use const prefix to declare constants with a specific type as
follows −
• const type variable = value;
• e.g: const int LENGTH = 10;
14. • C++ Data Types
• C++ offers the programmer a rich assortment of built-in as well as user
defined data types. We have primitive (basic) datatype and user-defined
datatype. Following table lists down seven basic C++ data types −
• Type Keyword
• Boolean bool
• Character char
• Integer int
• Floating point float
• Double floating point double
• Valueless void
• Wide character wchar_t
15. • C++ Variable
• A variable provides us with named storage that our programs can manipulate. Each
variable in C++ has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
• C++ Variable Naming
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C++ is case-sensitive.
• Some other rules for variable naming conventions in C++ −
• Keywords cannot be used as variable names.
• The variable name cannot contain spaces.
• Hyphen (-) cannot be used within the variable names.
• Variable names must not start with special characters and numbers. It should be either
an uppercase or lowercase character or an underscore (_).
16. • Variable Definition in C++
• A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type, and contains a list of one or more
variables of that type as follows −
• Syntax
• type variable_list;
• Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or
any user-defined object, etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
• int i, j, k;
• char c, ch;
• float f, salary;
• double d;
• The line int i, j, k; both declares and defines the variables i, j and k; which instructs the
compiler to create variables named i, j and k of type int.
17. • Variable Initialization in C++
• Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows −
• Syntax
• type variable_name = value;
• Example:
• extern int d = 3, f = 5; // declaration of d and f.
• int d = 3, f = 5; // definition and initializing d and f.
• char x = 'x'; // the variable x has the value 'x'.
• For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables is undefined.
18. • Variable Scope in C++
• A scope is a region of the program and broadly speaking there are three places,
where variables can be declared −
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal parameters.
• Outside of all functions which is called global variables.
• C++ variables scopes are categorized mainly two parts −
• Local Variables
• Global Variables
19. • 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.
• 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.
20. • Local and Global Variables with Same Names
• A program can have same name for local and global variables but value of local
variable inside a function will take preference.
• Accessing Global Variable
• You can access a global variable when there is a local variable with the same
name by using the SRO (Scope Resolution Operator) :: before the name of that
variable.
21. • C++ Basic Input/ Output
• C++ I/O occurs in streams, which are sequences of bytes. If bytes flow
from a device like a keyboard, a disk drive, or a network connection
etc. to main memory, this is called input operation and if bytes flow
from main memory to a device like a display screen, a printer, a disk
drive, or a network connection, etc., this is called output operation.
• I/O Library Header Files
• There are following header files important to C++ programs −
22. Sr.No Header File & Function and Description
1
<iostream>
This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output
stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.
2
<iomanip>
This file declares services useful for performing formatted I/O with
so-called parameterized stream manipulators, such
as setw and setprecision.
3
<fstream>
This file declares services for user-controlled file processing. We will
discuss about it in detail in File and Stream related chapter.
4
<bits/stdc++.h>
This header file includes most of the standard C++ libraries, which
adds a wide range of functionalities without the need to specify
each library individually. This is particularly helpful during coding
contests.
23. • The Standard Output Stream (cout)
• The predefined object cout is an instance of ostream class. The cout
object is said to be "connected to" the standard output device, which
usually is the display screen. The cout is used in conjunction with the
stream insertion operator, which is written as << which are two less
than signs as shown in the following example.
• Example:
• cout << "Value of str is : " << str << endl;
24. • The Standard Input Stream (cin)
• The predefined object cin is an instance of istream class. The cin
object is said to be attached to the standard input device, which
usually is the keyboard. The cin is used in conjunction with the stream
extraction operator, which is written as >> which are two greater than
signs as shown in the following example.
• Example
cout << "Please enter your name: ";
cin >> name;
25. • Storage Classes in C++
• A storage class defines the scope (visibility) and life-time of variables
and/or functions within a C++ Program. These specifiers precede the
type that they modify. There are following storage classes, which can
be used in a C++ Program
• auto
• register
• static
• extern
• mutable
26. • The auto Storage Class
• The auto storage class is the default storage class for all local variables.
• The register Storage Class
• The register storage class is used to define local variables that should be stored in
a register instead of RAM. This means that the variable has a maximum size equal
to the register size (usually one word) and can't have the unary '&' operator
applied to it (as it does not have a memory location).
27. • The static Storage Class
• The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each
time it comes into and goes out of scope. Therefore, making local variables static
allows them to maintain their values between function calls.
• The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
• In C++, when static is used on a class data member, it causes only one copy of
that member to be shared by all objects of its class.
28. • The extern Storage Class
• The extern storage class is used to give a reference of a global variable that is
visible to ALL the program files. When you use 'extern' the variable cannot be
initialized as all it does is point the variable name at a storage location that has
been previously defined.
• When you have multiple files and you define a global variable or function, which
will be used in other files also, then extern will be used in another file to give
reference of defined variable or function. Just for understanding extern is used to
declare a global variable or function in another file.
• The extern modifier is most commonly used when there are two or more files
sharing the same global variables or functions
29. • The mutable Storage Class
• The mutable specifier applies only to class objects. It allows a member of an
object to override const member function. That is, a mutable member can be
modified by a const member function.
30. • Operators in C++
• An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulations. C++ is rich in built-in operators and provide the following
types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
31. • Arithmetic Operators
• Arithmetic operators in C++ are the basic operators, which are used for basic mathematical or arithmetical
operations on operands. These operators are essential for performing calculations and manipulating data
within a program.
• There are following arithmetic operators supported by C++ language −
• Assume variable A holds 10 and variable B holds 20, then −
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
%
Modulus Operator and remainder of after
an integer division
B % A will give 0
++ Increment operator, increases integer
value by one
A++ will give 11
--
Decrement operator, decreases integer
value by one
A-- will give 9
32. #include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c <<
endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c
<< endl;
c = a * b;
cout << "Line 3 - Value of c is :" << c <<
endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c
c = a % b;
cout << "Line 5 - Value of c is :" << c
<< endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c <<
endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c
<< endl ;
return 0;
}
33. #include <iostream>
using namespace std;
main() {
int a;
int b;
int c ;
//input values
cout<<“Input value a:”;
cin>>a;
c = a + b;
cout << "Line 1 - Value of c is :" << c <<
endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c
<< endl;
c = a * b;
cout << "Line 3 - Value of c is :" << c <<
endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c
<< endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c <<
endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c
<< endl ;
return 0;
}
34. • Relational Operators
• Relational operators are used to compare two values or expressions. These
operators return a boolean value − true if the comparison is correct, and else
false.
• They are essential for making decisions and controlling the flow of a program
based on conditions.
• There are following relational operators supported by C++ language
• Assume variable A holds 10 and variable B holds 20, then −
35. Operator Description Example
==
Checks if the values of two operands are equal or
not, if yes then condition becomes true. (A == B) is not true.
!=
Checks if the values of two operands are equal or
not, if values are not equal then condition
becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than
the value of right operand, if yes then condition
becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less than the
value of right operand, if yes then condition
becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than
or equal to the value of right operand, if yes then
condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or
equal to the value of right operand, if yes then
condition becomes true.
(A <= B) is true.
36. #include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
cout << "Line 1 - a is equal to b" << endl ;
} else {
cout << "Line 1 - a is not equal to b" << endl ;
}
if( a < b ) {
cout << "Line 2 - a is less than b" << endl ;
} else {
cout << "Line 2 - a is not less than b" << endl ;
}
if( a > b ) {
cout << "Line 3 - a is greater than b" << endl ;
} else {
cout << "Line 3 - a is not greater than b" << endl ;
}
/* Let's change the values of a and b */
a = 5;
b = 20;
if( a <= b ) {
cout << "Line 4 - a is either less than or equal to b" <<
endl ;
}
if( b >= a ) {
cout << "Line 5 - b is either greater than or equal to b" <<
endl ;
}
return 0;
}
37. • Logical Operators
• Logical operators are used to perform logical operations on boolean values (true
or false). These operators are essential for controlling the flow of a program
based on conditions. There are three primary logical operators in C++ as
mentioned below −
• There are following logical operators supported by C++ language.
• Assume variable A holds 1 and variable B holds 0, then −
38. Operator Description Example
&& Called Logical AND operator. If both the operands are
non-zero, then condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two
operands is non-zero, then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the
logical state of its operand. If a condition is true, then
Logical NOT operator will make false.
!(A && B) is true.
39. #include <iostream>
using namespace std;
main() {
int a = 5;
int b = 20;
int c ;
if(a && b) {
cout << "Line 1 - Condition is true"<< endl ;
}
if(a || b) {
cout << "Line 2 - Condition is true"<< endl ;
}
/* Let's change the values of a and b */
a = 0;
b = 10;
if(a && b) {
cout << "Line 3 - Condition is true"<< endl ;
} else {
cout << "Line 4 - Condition is not true"<< endl ;
}
if(!(a && b)) {
cout << "Line 5 - Condition is true"<< endl ;
}
return 0;
}
40. • Bitwise Operators
• Bitwise operators are used to perform operations at the bit level on integer data
types. These operations work on direct manipulation of bits, such as low-level
programming, graphics, and cryptography.
• Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
41. Operator Description Example
&
Binary AND Operator copies a bit to the result if it exists
in both operands.
(A & B) will give 12 which is 0000
1100
|
Binary OR Operator copies a bit if it exists in either
operand.
(A | B) will give 61 which is 0011
1101
^
Binary XOR Operator copies the bit if it is set in one
operand but not both.
(A ^ B) will give 49 which is 0011
0001
~
Binary Ones Complement Operator is unary and has the
effect of 'flipping' bits.
(~A ) will give -61 which is 1100
0011 in 2's complement form due
to a signed binary number.
<<
Binary Left Shift Operator. The left operands value is
moved left by the number of bits specified by the right
operand.
A << 2 will give 240 which is 1111
0000
>>
Binary Right Shift Operator. The left operands value is
moved right by the number of bits specified by the right
operand.
A >> 2 will give 15 which is 0000
1111
42. • Assignment Operators
• Assignment operators are used to assign values to variables. These operators
allow you to set or update the value stored in a variable.
• There are following assignment operators supported by C++ language −
Operat
or
Description Example
= Simple assignment operator, Assigns values from right side
operands to left side operand.
C = A + B will assign value
of A + B into C
+=
Add AND assignment operator, It adds right operand to the left
operand and assign the result to left operand.
C += A is equivalent to C =
C + A
-=
Subtract AND assignment operator, It subtracts right operand
from the left operand and assign the result to left operand.
C -= A is equivalent to C =
C - A
*=
Multiply AND assignment operator, It multiplies right operand
with the left operand and assign the result to left operand.
C *= A is equivalent to C =
C * A
43. /=
Divide AND assignment operator, It divides left
operand with the right operand and assign the
result to left operand.
C /= A is equivalent to C =
C / A
%=
Modulus AND assignment operator, It takes
modulus using two operands and assign the
result to left operand.
C %= A is equivalent to C
= C % A
<<= Left shift AND assignment operator.
C <<= 2 is same as C = C
<< 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C
>> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C &
2
^= Bitwise exclusive OR and assignment operator.
C ^= 2 is same as C = C ^
2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C |
2
44. #include <iostream>
using namespace std;
main() {
int a = 21;
int c ;
c = a;
cout << "Line 1 - = Operator, Value of c = : " <<c<< endl ;
c += a;
cout << "Line 2 - += Operator, Value of c = : " <<c<< endl ;
c -= a;
cout << "Line 3 - -= Operator, Value of c = : " <<c<< endl ;
c *= a;
cout << "Line 4 - *= Operator, Value of c = : " <<c<< endl ;
c /= a;
cout << "Line 5 - /= Operator, Value of c = : " <<c<< endl ;
c = 200;
c %= a;
cout << "Line 6 - %= Operator, Value of c = : " <<c<< endl ;
c <<= 2;
cout << "Line 7 - <<= Operator, Value of c = : " <<c<< endl ;
c >>= 2;
cout << "Line 8 - >>= Operator, Value of c = : " <<c<< endl ;
c &= 2;
cout << "Line 9 - &= Operator, Value of c = : " <<c<< endl ;
c ^= 2;
cout << "Line 10 - ^= Operator, Value of c = : " <<c<< endl ;
c |= 2;
cout << "Line 11 - |= Operator, Value of c = : " <<c<< endl ;
return 0;
}
45. • Misc Operators
• Miscellaneous operators, often abbreviated as "misc operators", include a variety
of operators that don’t fit neatly into other categories like arithmetic or logical
operators. Here are some common miscellaneous operators and their definitions
−
• The following table lists some other operators that C++ supports.
46. Sr.No Operator & Description
1
sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.
2
Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise
returns value of Y.
3
,
Comma operator causes a sequence of operations to be performed. The value of
the entire comma expression is the value of the last expression of the comma-
separated list.
4
. (dot) and -> (arrow)
Member operators are used to reference individual members of classes,
structures, and unions.
5
Cast
Casting operators convert one data type to another. For example, int(2.2000)
would return 2.
6
&
Pointer operator & returns the address of a variable. For example &a; will give
actual address of the variable.
7
*
Pointer operator * is pointer to a variable. For example *var; will pointer to a
variable var.
47. • Operators Precedence in C++
• Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has higher precedence than
the addition operator −
• For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3*2 and then adds into
7.
• Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
48. Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment
= += -= *= /= %=>>= <<= &= ^=
|= Right to left
Comma , Left to right
49. #include <iostream>
using namespace std;
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
cout << "Value of (a + b) * c / d is :" << e << endl ;
e = ((a + b) * c) / d; // (30 * 15 ) / 5
cout << "Value of ((a + b) * c) / d is :" << e << endl ;
e = (a + b) * (c / d); // (30) * (15/5)
cout << "Value of (a + b) * (c / d) is :" << e << endl ;
e = a + (b * c) / d; // 20 + (150/5)
cout << "Value of a + (b * c) / d is :" << e << endl ;
return 0;
}
50. Classwork
• Write a C++ program to convert Fahrenheit to Celsius and vice versa