Fundamentals of Programming
Fundamentals of Programming
Semester: 1
Author
Credits
Centre for Distance and Online Education,
Parul University,
391760.
Website: https://paruluniversity.ac.in/
Disclaimer
This content is protected by CDOE, Parul University. It is sold under the stipulation that it cannot be
lent, resold, hired out, or otherwise circulated without obtaining prior written consent from the
publisher. The content should remain in the same binding or cover as it was initially published, and this
requirement should also extend to any subsequent purchaser. Furthermore, it is important to note that,
in compliance with the copyright protections outlined above, no part of this publication may be
reproduced, stored in a retrieval system, or transmitted through any means (including electronic,
Mechanical, photocopying, recording, or otherwise) without obtaining the
prior written permission from both the copyright owner and the publisher of
this content.
Note to Students
These course notes are intended for the exclusive use of students enrolled in
Online MCA. They are not to be shared or distributed without explicit
permission from the University. Any unauthorized sharing or distribution of
these materials may result in academic and legal consequences.
Table of Content
1.1 FEATURES & STRUCTURE OF C PROGRAMMING
1.2 ALGORITHM AND FLOWCHART
1.3 TYPES OF ERRORS, DEBUGGING, STEPWISE EXECUTION OF PROGRAM
2.1 ELEMENTS OF C: CHARACTER SET, C TOKENS
2.2 KEYWORDS, IDENTIFIERS, CONSTANT, VARIABLES
2.3 DATA TYPES, COMMENTS
2.4 C PROGRAMMING APPLICATIONS AND IMPORTANCE
3.1 OPERATORS: WHAT IS OPERATOR? TYPES OF OPERATORS
3.2 ARITHMETIC OPERATORS
3.3 RELATIONAL OPERATORS & LOGICAL OPERATORS
3.5 TERNARY OPERATORS & OTHER OPERATORS
3.6 TYPE CONVERSIONS IN EXPRESSIONS, OPERATOR PRECEDENCE AND ASSOCIATIVITY.
SUB LESSON 4.1
if & if else statement
SUB LESSON 4.2
NESTED IF STATEMENT
SUB LESSON 4.3
SWITCH STATEMENT
SUB LESSON 5.1
WHILE , DO WHILE
SUB LESSON 5.2
FOR AND NESTED FOR
BASIC OF C PROGRAMMING
2
SUB LESSON 7.2
WRITING STRINGS TO SCREEN, ARITHMETIC OPERATIONS ON CHARACTERS
SUB LESSON 8.1
CONCEPTS OF USER DEFINED FUNCTION &PROTOTYPES
SUB LESSON 8.2
DEFINITION OF FUNCTION
8.3 PARAMETERS, PARAMETERS PASSING
8.4 CALLING A FUNCTION, RECURSIVE FUNCTION
8.5 MACROS , PRE-PROCESSING
SUB LESSON 9.1
BASICS OF POINTERS, POINTER TO POINTER, POINTER AND ARRAY
SUB LESSON 9.2
POINTER TO ARRAY, ARRAY OF POINTERS
SUB LESSON 9.3
FUNCTIONS RETURNING A POINTER
10.1 PROCEDURE ORIENTED PROGRAMMING, OBJECT ORIENTED
PROGRAMMING, PURPOSE OF OBJECT-ORIENTED PROGRAMMING
10.2 PROCEDURAL VS OBJECT ORIENTED PROGRAMMING
10.3 PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING. BENEFITS AND APPLICATIONS OF OOP.
11.1 OVERVIEW OF C++, PROGRAM STRUCTURE
11.2 NAMESPACE & IDENTIFIERS
11.3 DATA TYPE IN C++, VARIABLE, CONSTANT
11.4 OPERATORS-1
11.5 OPERATORS-2
11.6 TYPECASTING IN C++
11.7 CONTROL STRUCTURES
12.1 BASIC OF FUNCTION, PARAMETER PASSING MECHANISM
12.2 INLINE FUNCTION
12.3 MACRO VS INLINE
12.4 FUNCTION OVERLOADING, DEFAULT ARGUMENTS
13.1 OBJECT AND CLASS IN C++, ACCESS SPECIFIERS
13.2 STATIC DATA MEMBER AND STATIC MEMBER FUNCTION
13.3 CONSTRUCTOR AND DESTRUCTOR
13.4 FRIEND FUNCTION, OPERATOR OVERLOADING
13.5 TYPECASTING IN C++
BASIC OF C PROGRAMMING
3
1.1 FEATURES & STRUCTURE OF C PROGRAMMING
HISTORY OF C PROGRAMMING
BASIC OF C PROGRAMMING
4
Table 1: History of C
FEATURES OF C LANGUAGE
1. Simple and Efficient: The basic syntax style of implementing C language is very
simple and easy to learn. This makes the language easily comprehensible and
enables a programmer to redesign or create a new application.
2. Fast: Statically typed programming languages are faster than dynamic ones. C is a
statically typed programming language, which gives it an edge over other dynamic
languages.
3. Portability: C programs are machine-independent which means that you can run the
fraction of a code created in C on various machines with none or some machine-
specific changes.
4. Extensibility: You can easily (and quickly) extend a C program. This means that if a
code is already written, you can add new features to it with a few alterations.
Basically, it allows adding new features, functionalities, and operations to an existing
C program.
5. Function-Rich Libraries: C comes with an extensive set of libraries with several built-
in functions that make the life of a programmer easy.
6. Dynamic Memory Management: One of the most significant features of C language
is its support for dynamic memory management (DMA). It means that you can utilize
and manage the size of the data structure in C during runtime.
7. Modularity with Structured Language: C is a general-purpose structured language.
This feature of C language allows you to break a code into different parts using
functions which can be stored in the form of libraries for future use and reusability.
8. Mid-Level Programming Language: Although C was initially developed to do only
low-level programming, it now also supports the features and functionalities of high-
level programming, making it a mid-level language.
9. Pointers: With the use of pointers in C, you can directly interact with memory.
BASIC OF C PROGRAMMING
5
10. Recursion: C language provides the feature of recursion. Recursion means that you
can create a function that can call itself multiple times until a given condition is true,
just like the loops.
STRUCTURE OF C PROGRAMMING
1. Documentation Section
2. Pre-processor Section / Link Section
3. Definition Section
4. Global Declaration Section
5. Main ( ) Function Section
6. Sub Programs Section
1. DOCUMENTATION SECTION
The documentation section in C language refers to the comments that are written in a
program to explain the code and make it more understandable. It is important to include
BASIC OF C PROGRAMMING
6
comments in your code so that other programmers who read your code can understand
what it does and how it does it.
Comments in C language start with the /* characters and end with the */ characters.
Everything between these characters is considered a comment and is ignored by the
compiler.
The pre-processor is a section in the C programming language that processes the source
code before it is compiled. It mainly consists of pre-processor directives, which are special
commands that begin with a '#' symbol. These directives are executed before the actual
compilation process begins, and they are used to include header files, define constants, and
perform other text manipulations in the source code.
Example:
#include <stdio.h>
#include <math.h>
3. DEFINITION SECTION
Pre-processors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and execution of the
program. Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used
to create a constant throughout the program. Whenever this name is encountered by the
compiler, it is replaced by the actual piece of defined code.
Example:
#define pi 3.14
The global declaration section is a part of the program where variables and functions can be
declared outside of any function or block, making them accessible to the entire program.
Example:
BASIC OF C PROGRAMMING
7
The main function is the starting point of a C program. The main function is where the
program begins execution, and it's the function that the operating system calls when the
program is executed.
Example:
void main ()
OR
int main ()
A sub program is a self-contained block of code that can be called from another part of the
program. This can help make code more organized, modular, and easier to read and
maintain.
Sub programs are implemented using functions. Functions can be defined anywhere in the
program, but are typically defined at the top of the program before the main function.
Example:
int sum (int x, int y)
{
return x+y;
}
KEY TAKEAWAYS
○ Documentation Section
○ Pre-processor Section / Link Section
○ Definition Section
○ Global Declaration Section
○ Main ( ) Function Section
○ Sub Programs Section
● Features of C Language
○ Fast ○ Extensibility
BASIC OF C PROGRAMMING
8
○ Function-Rich Libraries ○ Mid-Level Programming
Language
○ Dynamic Memory
Management ○ Pointers
BASIC OF C PROGRAMMING
9
1. BASIC OF C PROGRAMMING
Instructions are written in the natural language. It is also called step by step solution.
ADVANTAGES OF ALGORITHMS:
DISADVANTAGES OF ALGORITHMS:
Example 1:
Step 1: Start
Step 3: Add num1 and num2 and store the result in sum
Step 5: Stop
Example 2
BASIC OF C PROGRAMMING
2
Step 1: Start
Step 2: Read the length of one side of the square (side) from the user
Step 3: Compute the area of the square using the formula area = side * side
Step 5: Stop
Example 3
Step 5: stop
Step 7: stop
FLOWCHART
BASIC OF C PROGRAMMING
3
Flowcharts are graphical representations of the steps or processes involved in solving a
problem or completing a task. In the context of programming, flowcharts are often used to
visually illustrate the flow of control in a program or algorithm.
Overall, flowcharts can be a useful tool in C programming for designing, understanding, and
communicating the structure and logic of a program.
BASIC OF C PROGRAMMING
4
ADVANTAGES OF FLOWCHART
DISADVANTAGES OF FLOWCHART
Example 4
BASIC OF C PROGRAMMING
5
Design a flowchart for adding two numbers entered Design a flowchart for adding two
numbers entered by the user.by the user.
KEY TAKEAWAYS
BASIC OF C PROGRAMMING
6
● Effective analysis of logical programs can be easily done with the help of a related
flowchart.
● A flowchart is a better way of communicating the logic of a program.
BASIC OF C PROGRAMMING
7
1. BASIC OF C PROGRAMMING
In any programming language errors are common. If we miss any syntax like parenthesis or
semicolon then we get syntax errors. Apart from this we also get run time errors during the
execution of code.
Syntax Errors
Runtime Errors
Logical Errors
Linked Errors
Semantic Errors
1. SYNTAX ERRORS
These are also referred to as compile-time errors. These errors have occurred when the rule
of C writing techniques or syntaxes has been broken. These types of errors are typically
flagged by the compiler prior to compilation.
Example: In the below program we are getting an error because of a missing semicolon at
the end of the output statement (printf()) called syntax error.
#include <stdio.h>
int main()
{ // missing semicolon
return 0;
2. RUNTIME ERRORS
This type of error occurs while the program is running. Because this is not a compilation
error, the compilation will be completed successfully. These errors occur due to
BASIC OF C PROGRAMMING
2
segmentation fault when a number is divided by division operator or modulo division
operator.
Example: Let us consider an array of length 5 i.e. array[5], but during runtime, if we try to
access 10 elements i.e array[10] then we get segmentation fault errors called runtime
errors. Giving only an array length of 5
#include <stdio.h>
int main()
int array[5];
printf("%d", array[10]);
return 0;
Output: -621007737
But in output trying to access more than 5 i.e if we try to access array[10] during runtime
then the program will throw an error or will show an abnormal behavior and print any
garbage value.
3. LOGICAL ERRORS
Even if the syntax and other factors are correct, we may not get the desired results due to
logical issues. These are referred to as logical errors. We sometimes put a semicolon after a
loop, which is syntactically correct but results in one blank loop. In that case, it will display
the desired output.
Example: In the below example, the for loop iterates 5 times but the output will be
displayed only one time due to the semicolon at the end of for loop. This kind of error is
called a logical error.
#include <stdio.h>
BASIC OF C PROGRAMMING
3
int main()
int i;
printf("Hello World");
return 0;
4. LINKER ERRORS
When the program is successfully compiled and attempting to link the different object files
with the main object file, errors will occur. When this error occurs, the executable is not
generated. This could be due to incorrect function prototyping, an incorrect header file, or
other factors. If main() is written as Main(), a linked error will be generated.
#include <stdio.h>
int Main()
printf("Hello World");
return 0; }
5. SEMANTIC ERRORS
When a sentence is syntactically correct but has no meaning, semantic errors occur. This is
similar to grammatical errors. If an expression is entered on the left side of the assignment
operator, a semantic error may occur.
BASIC OF C PROGRAMMING
4
Example: Below is the C program to show semantic error.
#include <stdio.h>
int main()
int x = 10;
b = 20, c;
x + y = c;
printf("%d", c);
return 0;
DEBUGGING
We can define a bug as an error or a fault in a program because which program does not
work the usual way.
Debugging can be defined as the process of finding a bug and fixing it.
BASIC OF C PROGRAMMING
5
There are many ways of debugging an issue. It depends on the problem. Majorly, debugging
consists of 3 stages:
1. Print statements:
We can use print statements like printf, to figure out the value of variables. But, this process
can be risky as we may forget to remove the print statements after debugging an issue. Print
statements in the code will be printed to an application's console.
2. Logging:
The console of an application would not be accessible every time. For example, we cannot
access the console to view print statements in a production environment. Logging can be
used in these cases. Using logging, we can configure whether print statements in the code
are written to a file or printed to the console. This is the significant difference between
logging and print statements.
3. Interactive debugger:
Technologies like C, C++, and many high-level languages support an interactive way of
debugging. The interactive way means we can pause program execution and spectate
variables. Breakpoints are the lines where the program will pause during execution. This
way, we need not add too many print statements to debug and remove them after
debugging.
This method significantly reduces the effort of debugging as we need to start the debugger
and place breakpoints to debug.
C code:
When you first write the code in the C language, that source code is sent to the
Preprocessing section.
Preprocessing:
BASIC OF C PROGRAMMING
6
In this section our source code is attached to the preprocessor file. Different types of header
files are used like the stdio.h, math.h, etc. Our C source code is attached to these types of
files and the final C Source generates. (Some of the preprocessor directives are #include,
#define). After generating the pre-processed C source code, the C source code is sent to the
compiler section.
Compiler:
The preprocessed source code moves to the compiler, and an assembly-level code is
generated by the compiler after the compilation of the whole C source code program. All
the different files which have the C program must be saved with the.c extension. For the
compiler to understand whether the program file is a C program file or not, it is necessary to
have the '.c' extension. For a program file named first.c, the compiler searches for any error
and stores the file as an.obj file of the same name, which is termed as the object file. After
the compilation, the process is continued by the assembler section.
Assembler:
BASIC OF C PROGRAMMING
7
This part usually generates the Object code, after taking the assembly-level code from the
compiler. This object code is quite similar to the machine code or the set of binary digits.
After this assembler part, The Linker continues the process, producing an executable.exe file
at the end.
Linker:
The library functions are part of the C software, but not of any C program. The linker does
this task by linking the object file to the library functions so that the programme can be run
as an executable file (.exe). This process creates the first.exe file, which is in an executable
format.
Loader:
Whenever the command is given for the execution of a particular program, The loader plays
an important role. With the help of the loader, the .exe file is loaded in the RAM and the
CPU is informed of the starting point of the address of the program where it is loaded.
KEY TAKEAWAYS
● 5 Types of Errors.
● Debugging consists of 3 stages:
● Stepwise Execution of C Program.
BASIC OF C PROGRAMMING
8
2. BASIC CONSTANTS,
VARIABLES AND DATA TYPES
2.1 ELEMENTS OF C: CHARACTER SET, C TOKENS
CHARACTER SET
The character set is a collection of all the valid characters that may be used in the source
code to create words, expressions, and numbers.
It defines the set of letters, digits, special characters, whitespace characters, and control
characters that can be used to write a C program.
TYPES OF CHARACTERS
Lowercase a to z a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w,
Alphabets x, y, z
Uppercase A to Z A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U,
Alphabets V, W, X, Y, Z
Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
⮚ Each character set used in the C programming language has a corresponding ASCII value.
The ASCII value stands for American Standard Code for Information Interchange. It
consists of less than 256 characters, and we can represent these in 8 bits or even less.
⮚ The majority of ANSI-compatible C compilers support these ASCII characters for both the
source and execution character sets. Each ASCII character will have a unique numerical
value.
⮚ The ASCII values for uppercase letters (A-Z) of the English alphabet range from 65 to 90.
⮚ The ASCII values for lowercase letters (a-z) of the English alphabet range from 97 to 122.
C TOKENS
⮚ Tokens are the smallest elements or the building blocks used to construct a C program.
⮚ C Tokens are of 6 types, and they are classified as: Identifiers, Keywords, Constants,
Operators, Special Characters and Strings.
USES OF TOKENS
⮚ Tokens in C are building blocks which means a program can’t be created without tokens.
⮚ Tokens are classified into several significant subcategories, such as identifiers, which are
used to provide a variable identification, keywords, which may be used to predefine
things, operators, which can be used to conduct operations, and so on.
⮚ Tokens like strings and special symbols play a major role in dealing with problems as
strings are required to define something, and special symbols are used as a part of the
syntax and many more.
KEY TAKEAWAYS
● The ASCII value stands for American Standard Code for Information Interchange.
● Each character set used in the C programming language has a corresponding ASCII
value.
● Tokens are the smallest elements or the building blocks used to construct a C
program.
● C Tokens are of 6 types: Identifiers, Keywords, Constants, Operators, Special
Characters and Strings.
● Tokens in C are building blocks which means a program can’t be created without
tokens.
KEYWORDS
Keywords in C language are the collection of pre-defined or reserved words. These are case-
sensitive and written in lower cases. Their meaning and functionality are already known to
the compiler.
We can't use these keywords as variable names or function names because by doing so, we
are trying to assign a new meaning to the keyword, which is not allowed in C language.
There are a total of 32 keywords supported by the C language.
Table 1 : Keywords in C
Identifiers in C are short and informative names that uniquely identify variables or function
names.
These are user-defined words used for naming of functions, variables, structures, unions,
arrays etc. These can be composed of lowercase letters, uppercase letters, underscore or
digits, but the first character should be either an underscore or an alphabet.
Examples:
1. count
2. num_1
3. sumOfNumbers
4. _temp
5. MAX_SIZE
Constants are the variables whose values are fixed and cannot be modified during the
execution of a program once they are defined.
Constants are used to assign a specific value to a variable or to define a value that is used
throughout the program.
Constants are useful in programming because they provide a way to give meaningful names
to values that are used repeatedly in the program, making the code more readable and
easier to maintain.
Types of Constants:
⮚ Numeric Constants: These are the values used to represent numbers, such as integers or
floating-point numbers. Numeric constants can be represented in different formats,
such as decimal, hexadecimal, or octal.
Example: 5, 1.0, -2, -7.1.
⮚ Character Constants: These are the values used to represent characters, such as letters,
digits, or special symbols. Character constants are enclosed in single quotes, such as 'a',
'1', or '$'.
Example: ‘A’, ‘t’, ‘$’.
In addition, C also has predefined constants, such as the value of Pi, which are declared in
the standard library header files. These constants can be used in the program without
defining them explicitly.
Variables are containers for storing data values, like numbers and characters.
We can store different types of data in the variable and reuse the same variable for storing
some other data any number of times.
For using a variable in C, we have to first define it to tell the compiler about its existence so
that compiler can allocate the required memory to it.
⮚ Syntax:
o data_type variable_name = value; // defining single variable
o data_type variable_name1, variable_name2; // defining multiple variable
TYPES OF VARIABLES
1. Local Variables: These are variables declared inside a function or block and have
local scope. They are only accessible within the function or block in which they are
declared. Once the function or block exits, the memory allocated for the local
variable is released.
Variable declaration in C tells the compiler about the existence of the variable with
the given name and data type. No memory is allocated to a variable in the
declaration.
2. Variable Definition:
In the definition of a C variable, the compiler allocates some memory and some
value to it. A defined variable will contain some random garbage value till it is not
initialized.
3. Variable Initialization:
Initialization of a variable is the process where the user assigns some meaningful
value to the variable.
KEY TAKEAWAYS
● Constants are the variables whose values are fixed and cannot be modified during
the execution of a program once they are defined.
● Variables are containers for storing data values, like numbers and characters.
● We can store different types of data in the variable and reuse the same variable for
storing some other data any number of times.
DATA TYPES
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. It specifies the
type of data that the variable can store like integer, character, floating, double, etc.
The data type is a collection of data with values having fixed values, meaning as well as its
characteristics.
INTEGER TYPES
The integer data type in C is used to store the whole numbers without decimal values. Octal
values, hexadecimal values, and decimal values can be stored in int data type in C.
CHARACTER TYPES
Character data type allows its variable to store only a single character. The storage size of
the character is 1. It is the most basic data type in C. It stores a single character and requires
a single byte of memory in almost all compilers.
FLOATING-POINT TYPES
Float in C is used to store decimal and exponential values. It is used to store decimal
numbers (numbers with floating point values) with single precision.
DOUBLE TYPES
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C.
Double data type is basically a precision sort of data type that is capable of holding 64 bits of
decimal numbers or floating points. Since double has more precision as compared to that
float then it is much more obvious that it occupies twice the memory as occupied by the
The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller. It has no values and no operations. It is used to represent nothing.
Void is used in multiple ways as function return type, function arguments as void, and
pointers to void.
● Below is a list of ranges along with the memory requirement and format specifiers:
Table 1
COMMENTS
SINGLE-LINE COMMENT
Example:
MULTI-LINE COMMENT
Example:
KEY TAKEAWAYS
● The data type is a collection of data with values having fixed values, meaning as well
as its characteristics.
● Each data type requires different amounts of memory and has some specific
operations which can be performed over it. It specifies the type of data that the
variable can store like integer, character, floating, double, etc.
● Comments can be used to explain code, and to make it more readable. It can also be
used to prevent execution when testing alternative code.
C PROGRAMMING LANGUAGE
APPLICATIONS OF C LANGUAGE
1. Operating Systems: C is the primary language used to develop operating systems like
Windows, Linux, and UNIX.
IMPORTANCE OF C LANGUAGE
The core features of a programming language describe its ability and uniqueness and how
beneficial it can be in developing a website or software. Listed below are some of the
significant features of C language:
FEATURES OF C LANGUAGE
1. Simple and Efficient: The basic syntax style of implementing C language is very
simple and easy to learn. This makes the language easily comprehensible and
enables a programmer to redesign or create a new application.
2. Fast: Statically typed programming languages are faster than dynamic ones. C is a
statically typed programming language, which gives it an edge over other dynamic
languages.
3. Portability: C programs are machine-independent which means that you can run the
fraction of a code created in C on various machines with none or some machine-
specific changes.
4. Extensibility: You can easily (and quickly) extend a C program. This means that if a
code is already written, you can add new features to it with a few alterations.
KEY TAKEAWAYS
● C is the primary language used to develop operating systems like Windows, Linux,
and UNIX and also used to develop system software such as compilers, assemblers,
and device drivers.
● Features of C Language
○ Portability
OPERATOR 1
3.1 OPERATORS: WHAT IS OPERATOR? TYPES OF OPERATORS
OPERATORS IN C
Operators are the foundation of any programming language. We can define operators as symbols that
help us to perform specific mathematical and logical computations on operands. In other words, we can
say that an operator operates the operands.
c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands.
The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
The functionality of the C programming language is incomplete without the use of operators.
1. Arithmetic Operators
2. Relational Operator
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary Operator
7. Other Operators
OPERATOR 2
(Figure1: Operators)
KEY TAKEAWAYS
- Various types of operators have various types of usage.
- Arithmetic Operator performs mathematical operations.
- Relational Operator check relationship between operands.
- Increment / Decrement operator performs increment and decrement by 1.
- 2 Types of Increment / Decrement operators are
o Prefix Operator
o Postfix Operator
- Actually operator types are unary, binary and ternary
OPERATOR 3
3. OPERATOR
OPERATOR
3.2 ARITHMETIC OPERATORS
ARITHMETIC OPERATORS
b) Binary Operators:
A) UNARY OPERATORS:
Operators that operate or work with a single operand are unary operators. For example:
Increment(++) and Decrement(–) Operators
int val = 5;
cout<<++val; // 6
OPERATOR
B) BINARY OPERATORS:
Operators that operate or work with two operands are binary operators. For example:
Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
OPERATOR
HOW DOES ONE PREFIX THE — AND ++ OPERATORS?
The operator — always decrements the available value of the variable, while the ++ increments
the value. Knowing this, we can consider the following statement:
var = A = B++;
In this case, if the value of the available variable is 17, then you must know that it will be 18
after we perform the ++ operation. So, what is the original value of the variable now- 17 or 18?
Generally speaking, we read the math equations of the C language from left to right. On the
basis of this rule, the value of the variable preceding the execution of the statement is 17, and
the current value of the variable is 18.
When we place the — or the ++ operator after a given variable, then it is known as post-
decrementing and post-incrementing, respectively. In case we want to decrement or increment
the given value of the variable before we use it, then we place the — or ++ before we place the
name of the variable. For instance:
a = ++b;
Here, we can witness that there is an increment in the value of b, and then it gets assigned to
the variable a.
a = ++b++;
We would get no output. It is because the ++var++ results in an error in the code. So we can
ignore this condition.
Go through the following example to understand how all the arithmetic operators function in
the C program:
OPERATOR
#include <stdio.h>
main() {
int p = 21;
int q = 10;
int r ;
r = p + q;
r = p – q;
r = p * q;
r = p / q;
r = p % q;
r = p++;
r = p–;
Once you have completed compiling and executing the program mentioned above, it will
produce the results as follows:
OPERATOR
Line 3 – The value of r is 210
KEY TAKEAWAYS
ARITHMETIC OPERATORS
a) Unary Operators
Operators that operate or work with a single operand are unary operators. For example:
Increment(++) and Decrement(–) Operators
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example:
Addition(+), Subtraction(-), multiplication(*), Division(/) operators
OPERATOR
3. OPERATOR
OPERATOR 10
3.3 RELATIONAL OPERATORS & LOGICAL OPERATORS
These are used for the comparison of the values of two operands. For example, checking if one
operand is equal to the other operand or not, whether an operand is greater than the other
operand or not, etc. Some of the relational operators are (==, >=, <=).Here is a list of all the
relational operators used in the C language:
● Equal to
● Not equal to
● Less than
● Greater than
● Less than or equal to
● Greater than or equal to
EQUAL TO OPERATOR
The function of the equal to operator (==) is to check if two of the available operands are equal
to each other or not. If it is so, then it returns to be true, or else it returns false. For instance,
3==3 will return to be true. On the other hand, 2==3 will return to be false.
The function of the not equal to operator (!=) is to check if two of the available operands are
equal to each other or not. If it is not equal, then it returns to be true, or else it returns false.
For instance, 3!=3 will return to be false. On the other hand, 3!=4 will return to be true.
The function of the less than operator (<) is to check if the first available operand is lesser than
the second one. If it is so, then it returns to be true, or else it returns false. For instance, 5<4
will return to be false. On the other hand, 6<8 will return to be true.
OPERATOR 11
GREATER THAN OPERATOR
The function of the greater than operator (>) is to check if the first available operand is greater
than the second one. If it is so, then it returns to be true, or else it returns false. For instance,
5>4 will return to be true. On the other hand, 7>8 will return to be false.
The function of the less than or equal to operator (<=) is to check if the first available operand is
equal to or less than the second one. If it is so, then it returns to be true, or else it returns false.
For instance, 9<=9 and 6<=9 will return to be true. On the other hand, 9<=8 will return to be
false.
The function of the greater than or equal to operator (>=) is to check if the first available
operand is equal to or greater than the second one. If it is so, then it returns to be true, or else
it returns false. For instance, 2>=2 and 4>=2 will return to be true. On the other hand, 3>=4 will
return to be false.
For example, the logical AND represented as the ‘&&’ operator in C returns true when both the
conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b
returns true when both a and b are true (i.e. non-zero)
OPERATOR 12
LOGICAL NOT (!) OPERATOR
This type of operator returns true whenever the conditions that are under condition are not at
all satisfied. In any other case, it is bound to return false. For instance, the !p will return true if p
is false, meaning, when p = 0.
For example –
We can write the statement “A student can enroll in my program, if they are not enrolled
yet” programmatically as –
if (!enrolled)
This type of operator returns true even when both or even one of the conditions that are under
consideration are satisfied. In any other case, it is bound to return false. For instance, the p || q
will return true when both or one of p and q are true (non-zero). It also returns to be true when
p and q are true.
For example –
// It is a holiday
OPERATOR 13
LOGICAL AND (&&) OPERATOR
This type of operator returns true when both the conditions that are under consideration
happen to be satisfied. In any other case, it is bound to return false. For instance, the p && q
will return true when both- p and q are true (non-zero).
For example–
Note – Do not confuse the bitwise AND & with the logical AND &&.
KEY TAKEAWAYS
Relational Operators
● Equal to
● Not equal to
● Less than
● Greater than
● Less than or equal to
● Greater than or equal to
Logical Operators
OPERATOR 14
3. OPERATOR
OPERATOR 15
3.5 TERNARY OPERATORS & OTHER OPERATORS
TERNARY OPERATORS:
where expr1 is a logical expression, logical expression can be TRUE or FALSE. expr2 and expr3
are expressions.
expr1 is evaluated first, and depending on its value, either expr2 or expr3 is evaluated. If expr1
is TRUE, then expr2 is executed, otherwise expr3 is executed.
Example: -
#include <stdio.h>
main()
int x,y,max,min;
scanf("%d %d",&x,&y);
OPERATOR 16
Output
-------------------------------------------------------------------------------
--------------------------
36
maximum of 3 and 6 is = 6
minimum of 3 and 6 is = 3
OTHER OPERATORS:
Apart from the above operators, there are some other operators available in C used to perform
some specific tasks. Some of them are discussed here:
A. SIZE OF OPERATOR
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable.
B. COMMA OPERATOR
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
OPERATOR 17
Comma acts as both operator and separator.
C. CONDITIONAL OPERATOR
Here, Expression1 is the condition to be evaluated. If the condition (Expression1) is True then
we will execute and return the result of Expression2 otherwise if the condition (Expression1) is
false then we will execute and return the result of Expression3.
Member operators are used to reference individual members of classes, structures, and unions.
E. CAST OPERATOR
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
A cast is a special operator that forces one data type to be converted into another.
The most general cast supported by most of the C compilers is as follows − [ (type) expression
].
F. &, * OPERATOR
Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable var.
OPERATOR 18
KEY TAKEAWAYS
A. SIZE OF OPERATOR
B. COMMA OPERATOR
C. CONDITIONAL OPERATOR
E. CAST OPERATOR
F. &,* OPERATOR
Pointer operator & returns the address of a variable. For example &a; will give the
actual address of the variable.
Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
OPERATOR 19
3. OPERATOR
OPERATOR 1
3.6 TYPE CONVERSIONS IN EXPRESSIONS, OPERATOR PRECEDENCE AND
ASSOCIATIVITY.
TYPE CONVERSION IN C
Type conversion in C is the process of converting one data type to another. The type conversion
is only performed to those data types where conversion is possible. Type conversion is
performed by a compiler. In type conversion, the destination data type can’t be smaller than
the source data type. Type conversion is done at compile time and it is also called widening
conversion because the destination data type can’t be smaller than the source data type. There
are two types of Conversion:
A. Done by the compiler on its own, without any external trigger from the user.
B. Generally takes place when in an expression more than one data type is present. In such
conditions type conversion (type promotion) takes place to avoid loss of data.
C. All the data types of the variables are upgraded to the data type of the variable with the
largest data type.
OPERATOR 2
D. It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Implicit type conversion is also called automatic type conversion. Some of its few occurrences
are mentioned below:
● Conversion Rank
● Conversions in Assignment Expressions
● Conversion in other Binary Expressions
● Promotion
● Demotion
OPERATOR 3
2. EXPLICIT TYPE CONVERSION
This process is also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type. The syntax in C Programming:
(type) expression
Type indicated the data type to which the final result is converted.
Exampe:
#include<stdio.h>
int main()
double x = 1.2;
return 0;
OPERATOR 4
Output
sum = 2
The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.
OPERATOR 5
Precedence Operator Description Associativity
OPERATOR 6
Precedence Operator Description Associativity
* Dereference right-to-left
OPERATOR 7
Precedence Operator Description Associativity
12 || Logical OR left-to-right
= Assignment right-to-left
OPERATOR 8
Precedence Operator Description Associativity
KEY TAKEAWAYS
TYPE CONVERSION IN C
A. Done by the compiler on its own, without any external trigger from the user.
B. Generally takes place when in an expression more than one data type is present.
In such conditions type conversion (type promotion) takes place to avoid loss of
data.
C. All the data types of the variables are upgraded to the data type of the variable
with the largest data type.
OPERATOR 9
This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type. The syntax in C Programming:
(type) expression
Type indicated the data type to which the final result is converted.
OPERATOR 10
4. IF & IF ELSE STATEMENT
There come situations in real life when we need to make some decisions and based on these
decisions, we decide what we should do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the next
block of code.
For example, in C if x occurs then execute y else execute z. There can also be multiple
conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute
r. This condition of C else-if is one of the many ways of importing multiple conditions. The
Decision Making Statements are used to evaluate the one or more conditions and make the
decision whether to execute set of statement or not.
Example:
If Ram can having 100 GeekBits then he can redeem these GeekBits and get the GFG T-shirt.
if (condition)
statement1;
statement2;
#include <stdio.h>
int main()
int i = 10;
if (i > 15) {
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is not
executed.
2. IF-ELSE IN C
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else if the condition is
false. Here comes the C else statement. We can use the else statement with the if statement to
execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
FLOWCHART:
KEY TAKEAWAYS
NESTED IF STATEMENT 8
SUB LESSON 4.2
NESTED IF STATEMENT
NESTED IF IN C LANGUAGE
Nested If in C Programming is placing If Statement inside another IF Statement. Nested If in C is
helpful if you want to check the condition inside a condtion. If Else Statement prints different
statements based on the expression result (TRUE, FALSE). Sometimes we have to check even
further when the condition is TRUE. In these situations, we can use these C Nested IF
statements, but be careful while using it.
For example, every person is eligible to work if he is 18 years old or above else he is not eligible.
However, companies will not give a job to every person. So, we use another IF Statement, also
called as Nested If Statement in C, to check his education qualifications or any specific company
requirements.
NESTED IF IN C SYNTAX
if ( test condition 1)
//If the test condition 1 is TRUE then these it will check for test condition 2
if ( test condition 2)
NESTED IF STATEMENT 9
}
else
else
//If the test condition 1 is FALSE then these statements will be executed
NESTED IF STATEMENT 10
Flow Chart for Nested if in C
Programming
If the Test Condition1 is FALSE, STATEMENT3 will execute. When Test Condition1 is TRUE,
then C Programming will check for the Test Condition2. If it is TRUE, STATEMENT1 will execute
else STATEMENT2. Please refer to If Else and IF Condition articles.
In this Nested If in c program, User can enter his age, and we are going to store it in the variable
age. If the age is less than 18, we are going to print two statements.
If the condition fails, we will check one more expression (Nested If), and if it succeeds, we print
something. When the nested If the expression evaluates to fails, we print some other thing.
#include <stdio.h>
int main()
NESTED IF STATEMENT 11
int age;
scanf("%d",&age);
if ( age < 18 )
else
else
NESTED IF STATEMENT 12
printf("You are too old to work as per the Government rules\n");
return 0;
Within this example, If the age of a person is less than 18, he is not eligible to work. If the age is
greater than or equal to 18, then the first condition fails, it will check the else statement.
In the Else statement, there is another if condition called Nested If in C to check further.
• In this example, the Nested IF Statement checks the person’s age greater than or
equal to 18 and less than or equal to 60. When the condition is TRUE, then he
can apply for the job.
• If the condition is FALSE, then the statement – he is too old to work as per the
government.
• OUTPUT 1: Enter the age = 14. It means First If condition is TRUE
KEY TAKEAWAYS
• Nested If in C Programming is placing If Statement inside another IF Statement.
NESTED IF STATEMENT 13
4.3 SWITCH STATEMENT
SWITCH STATEMENT 14
SUB LESSON 4.3
SWITCH STATEMENT
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case.
SYNTAX
switch (expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
SWITCH STATEMENT 15
FLOW DIAGRAM
EXAMPLE
#include <stdio.h>
int main () {
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
SWITCH STATEMENT 16
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
KEY TAKEAWAYS
• A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for
each switch case.
SWITCH STATEMENT 17
5. WHILE, DO WHILE
WHILE, DO WHILE 18
SUB LESSON 5.1
WHILE , DO WHILE
In programming, loops are used to repeat a block of code until a specified condition is met.
while loop
do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will learn about
do…while and loop.
while loop
while (testExpression) {
// the body of the loop
}
To learn more about test expressions (when testExpression is evaluated to true and false), check
out relational and logical operators.
WHILE, DO WHILE 19
Flowchart of while loop
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
Run Code
Output
WHILE, DO WHILE 20
1
2
3
4
5
1. When i=1 the test expression i<=5 is true. Hence, the body of the while loop is executed.
This prints 1 on the screen and the value of I is increased to 2.
2. Now i=2, the test expression i<=5 is again true. The body of the while loop is executed
again. This prints 2 on the screen and the value of i is increased to 3.
3. This process goes on until i becomes 6. Then, the test expression i<=5 will be false and
the loop terminates.
do...while loop
The do…while loop is similar to t while loop with one important difference. The body of
do…while loop is executed at least once. Only then, the test expression is evaluated.
do {
// the body of the loop
}
while (testExpression);
1. The body of do…while loop is executed once. Only then, the testExpression is evaluated.
2. If testExpression is true, the body of the loop is executed again and
testExpression is evaluated once more.
3. This process goes on until testExpression becomes false.
4. If testExpression is false, the loop ends.
KEY TAKEAWAYS
- While loop is called as entry controlled loop.
- Do…While loop is called as exit controlled loop.
WHILE, DO WHILE 21
5. FOR AND NESTED FOR
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
SYNTAX
EXAMPLE
Live Demo
#include <stdio.h>
int main () {
int a;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of
statements inside another loop. Let's observe an example of nesting loops in C.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining
any number of loops. The nesting level can be defined at n times. You can define any type of
loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or
'do-while' loop.
The nested for loop means any type of loop which is defined inside the 'for' loop.
1. #include <stdio.h>
2. int main()
3. {
4. int n;// variable declaration
5. printf("Enter the value of n :");
6. // Displaying the n tables.
7. for(int i=1;i<=n;i++) // outer loop
8. {
9. for(int j=1;j<=10;j++) // inner loop
10. {
11. printf("%d\t",(i*j)); // printing the value.
12. }
13. printf("\n");
14. }
o First, the 'i' variable is initialized to 1 and then program control passes to the
i<=n.
o The program checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of
the outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked
again, i.e., i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.
Output:
● A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
STATEMENT
In C programming language, there are control statements which do not need any condition to control
the flow of execution of a program. Such statements are known as unconditional control statements.
The unconditional control statements provided by C are:
● break statement
● continue statement
● goto statement
Break Statement:
This is used for two important purposes:
● The break statement is used to terminate the switch case statement.
● It is used to terminate the looping statements like for, while and do-while.
Goto statement:
● This is a kind of jump statement which can take control of the program from
anywhere to anywhere within a function.
When a break statement is found inside the switch case statement, the execution control moves out of
the switch statement.
Example:
#include <stdio.h>
void print_name( int roll_number)
{
switch(roll_number)
{
case 1:
printf("\n Name is A");
break;
case 2:
Name is A
continue statement:
It is similar to break statement, the only difference lies that break statement terminates the loop
whereas continue statement, forces the control to reach for the next iteration of the loop that is to the
beginning of the loop.
When we use continue statement with while and do-while statements the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
Diag-2: The break statement execution is as shown in the following figure.
Example:
It prints 0 to 10 except 5 as it goes to the beginning of the loop because of the continue statement.
int main()
{
for (int i = 0 ;i <=10; i ++) {
if (i == 5)
continue;
printf("%d ", i);
}
}
Output:
0 1 2 3 4 6 7 8 9 10
goto statement:
The goto statement is used to jump from one line to another in the program.
Simple C program to illustrate the concept of goto statement
#include <stdio.h>
void print_name( int roll_number)
{
switch(roll_number)
{
case 1:
printf("\n Name is A");
goto jump;
int main()
{
int roll_number = 1;
print_name(roll_number);
return 0;
}
OUTPUT:
Name is A
I am in jump
Note:
● Instead of “jump” we can use any name/label.
● break, goto, switch, case, if, else, if, all these are keywords in C.
KEY TAKEAWAYS
- Break will stop the current iteration of the loop.
- Continue will iterate the current iteration of the loop.
- Switch statement can be used for checking multiple if conditions. Just like else if ladder.
ARRAYS
SUB LESSON 6.1
DECLARATION ,INITIALIZATION , ACCESS OF ONE DIMENSIONAL & TWO
DIMENSIONAL ARRAYS
• In general array is a group of similar datatypes (primary) or in other words a collection
of similar datatypes which are stored consecutively in the main memory.
Declaration:
ARRAYS
int arr[2][4][5];//a multi-dimensional array with each having 4 rows and 5 columns and that too
twice
INITIALIZATION:
• Initializing is nothing but the process of assigning the value to the variable at the time of
declaration i.e. the before the program is executed .
o Method - 1
int arr1[5]={1,2,3,4,5};
In the above example the values in the { } brackets cannot be more than the number
written in the [] which is the size of the array .
o Method - 2
int arr2[]={1,2,3,4,5,6,7};
In the above example we can have as many values as we want to have in the array as
the size of the array is not defined by default , the size will be defined according to the
values we give in the { } brackets.
Index : 0 1 2 3 4
1 2 3 4 5
ARRAYS
Figure 6.1.1(1-D array Representation)
o We can access the one dimensional array every programming languages along with the
C language by the index number it is assigned .
o The index number starts from 0 and goes upto size of array -1.
o Example – 1
int arr1[5]={1,2,3,4,5};
ARRAYS
o Example – 2(Using Loops)
int arr2[5]={1,2,3,4,5};
for(int i=0;i<5;i++)
{
printf(“%d”,arr2[i]);//prints all the array elements one by one from index 0 to 5
}
We can also use other loops like while loop and do while loop to make accessing of the
elements in an easy way
i=0;
while(i!=5)
{
printf(“%d”,arr2[i]);
i++;
Index : 00 01 02 03 04
1 2 3 4 5
5 6 7 8 9
10 11 12 13 14
ARRAYS
Figure 6.1.2(2-D array Representation)
o In C language the two dimensional array requires two parameters to access its elements
which are the row you want to access and the column you want to access in that
particular row.
o Let us suppose we have an array A[10][20], and we want to access the element
at 4th row and 5th column. Since we are using 0-based indexing, I th row will be present
at (i−1) &(j−1).
o To access an element at position (i, j), we use array_name[i - 1][j - 1]. Thus the element
at the 4th row and 5th column will be accessed by A[3][4].
o Example -1
int arr1[2][3]={{1,2,3},{4,5,6}};
ARRAYS
o Example – 2( Using Loops)
int arr1[2][3]={{1,2,3},{4,5,6}};
In the above example the Ith loop is running from row index 0 to 1 and the jth loop is
running from column index 0 to 2 for each row.
KEY TAKEWAYS
• An arrangement of objects, pictures, or numbers in rows and columns is called an array
• The initializer for an array is a comma-separated list of constant expressions enclosed
in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to
initialize all elements in an array.
• A One-Dimensional Array is the simplest form of an Array in which the elements are
stored linearly and can be accessed individually by specifying the index value of each
element stored in the array.
• Accessing two-dimensional arrays can be done using row index value and column index
value. Name_of_the arrays[row_index][column_index];
ARRAYS
6. Array
ARRAYS 1
SUB LESSON 6.2
PROGRAM – 1
#include<stdio.h>
int main()
int arr[5]={1,2,3,4,5};
printf("%d",arr[0]);
printf("%d",arr[1]);
printf("%d",arr[2]);
printf("%d",arr[3]);
printf("%d",arr[4]);
return 0;
Explanation:
In the above program an array is initialized with 5 elements in it . The index number is used to
access each elements of the array .
ARRAYS 2
OutPut:
12345
#include<stdio.h>
int main()
int arr[5];
for(int i=0;i<5;i++)
scanf(“%d”,&arr[i]);
for(i=0;i<5;i++)
printf("\t%d",arr[i]);
return 0;
ARRAYS 3
Explanation :
In the above code we have used the loops which makes the accessing of the array elements
much easier than the previous one.
1 2 3 4 5
#include<stdio.h>
int main()
int arr[5],i=0;
while(i!=5)
ARRAYS 4
printf("Enter Element %d",i+1);
scanf("%d",&arr[i]);
i++;
i=0;
while(i!=5)
printf("\t%d",arr[i]);
i++;
return 0;
Explanation :
1 2 3 4 5
ARRAYS 5
LOOP EXECUTION (1-D)
1 2 3 4 5
1 2 3 4 5
ARRAYS 6
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
PROGRAM - 1
#include<stdio.h>
ARRAYS 7
int main()
int arr[2][2],i=0;
arr[0][0]=1;
arr[0][1]=2;
arr[1][0]=3;
arr[1][1]=4;
printf("%d",arr[0][0]);
printf("%d",arr[0][1]);
printf("\n");
printf("%d",arr[1][0]);
printf("%d",arr[1][1]);
return 0;
Explanation:
While accessing 2-d array we require two parameter which are the row index and the column
index.
ARRAYS 8
Output:
1 2
3 4
#include<stdio.h>
int main()
int arr[2][3],i=0,j=0;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&arr[i][j]);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
ARRAYS 9
printf("\t%d",arr[i]);
printf("\n");
return 0;
Explanation:
In the above code we have used loops for accessing the elements in the array
The j th loop is running from index 0 to total column-1 for each row
1 2 3
4 5 6
ARRAYS 10
↓
1 2 3
4 5 6
1 2 3
4 5 6
1 2 3
ARRAYS 11
4 5 6
1 2 3
4 5 6
1 2 3
4 5 6
ARRAYS 12
6TH LOOP EXECUTION (I=1,J=2)
1 2 3
4 5 6
KEY TAKEAWAYS
- There are 2 types of arrays are there 1D and 2D.
- Index position will start from 0th Index Position only.
- Array is normally used to store homogeneous elements in one variable.
ARRAYS 13
6. Arrays
ARRAYS
SUB LESSON 6.3
TRANSPOSING MATRICES : SORTING & SEARCH METHODS
SORTING:
int main()
int i, key, j;
key = arr[i];
j = i - 1;
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
ARRAYS
}
int i;
return 0;
Execution :
(initial)
11 2 20 14
i=1 , j = 0 , key =2
Swap
↓ ↓
ARRAYS
2 11 20 14
↓ ↓
2 11 20 14
↓ ↓
2 11 20 14
ARRAYS
up to 2nd index
↓ ↓
2 11 14 20
SEARCHING :
#include <stdio.h>
int main()
int arr[4]={11,3,15,25};
scanf("%d", &toSearch);
flag = 0;
ARRAYS
{
if (arr[i] == toSearch)
flag = 1;
break;
if (flag == 1)
else
return 0;
EXPLANATION :
ARRAYS
When a search is found the flag is set to 1 and break is used to exit the loop
If the flag is 1 the program will print the location of the element we were looking for.
Execution :
11 3 15 25
Search for 15
i=0 ,flag=0
11 3 15 25
i=1 ,flag=0
ARRAYS
11 3 15 25
11 3 15 25
KEY TAKEAWAYS
- Linear Search and Binary Search are the searching technique which are there in C
language.
- Compare to Binary Search Linear Search is slower
- Linear search takes much more time compare to binary search for searching an element
from an array.
- Binary search is faster than linear search.
ARRAYS
7. STRING
STRING
SUB LESSON 7.1
Declaration of Strings
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax
for declaring a string.
STRING
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used to
define the length of the string, i.e the number of characters strings will store.
Note: There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character arrays. When
a Sequence of characters enclosed in the double quotation marks is encountered by the
compiler, a null character ‘\0’ is appended at the end of the string by default.
When strings are declared as character arrays, they are stored like other types of arrays in C.
For example, if str[] is an auto variable then the string is stored in stack segment, if it’s a global
or static variable then stored in data segment, etc.
When a string value is directly assigned to a pointer, in most of the compilers, it’s stored in a
read-only block (generally in data segment) that is shared among functions.
STRING
Example:
In the above line “GfG” is stored in a shared read-only location, but pointer str is stored in read-
write memory. You can change str to point something else but cannot change value at present
str. So this kind of string should only be used when we don’t want to modify the string at a later
stage in the program.
Strings are stored like other dynamically allocated things in C and can be shared among
functions.
KEY TAKEAWAYS
• String in C programming is a sequence of characters terminated with a null character
‘\0’.
• Strings are defined as an array of characters.
• The difference between a character array and a string is the string is terminated with a
unique character ‘\0’.
• When a string value is directly assigned to a pointer, in most of the compilers, it’s stored
in a read-only block (generally in data segment) that is shared among functions.
• Strings are stored like other dynamically allocated things in C and can be shared among
functions.
STRING
7. STRINGS
STRING
SUB LESSON 7.2
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
puts(str);
return 0;
}
Output:-
Enter a string: Know Program@999
Know Program@999
STRING
int main()
{
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
fputs(str, stdout);
return 0;
}
Output:-
Enter a string: KnowProgram 2355>{}
KnowProgram 2355>{}
The puts() and fputs() return an EOF if an error occur. It will return a positive number upon success.
Thus, they are sometimes called string-to-line output functions.
Character arithmetic in C
As already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind
while doing character arithmetic.
int main()
{
STRING
char ch1 = 125, ch2 = 10;
ch1 = ch1 + ch2;
printf("%d\n", ch1);
printf("%c\n", ch1 - ch2 - 4);
return 0;
}
Output
-121
y
So %d specifier causes an integer value to be printed and %c specifier causes a character value to
printed. But care has to taken that while using %c specifier the integer value should not exceed 127.
Example no 2
#include <stdio.h>
// driver code
int main(void)
{
char value1 = 'a';
char value2 = 'b';
char value3 = 'z';
// perform character arithmetic
char num1 = value1 + 3;
char num2 = value2 - 1;
char num3 = value3 + 2;
// print value
printf("numerical value=%d\n", num1);
printf("numerical value=%d\n", num2);
printf("numerical value=%d\n", num3);
STRING
return 0;
}
Output:
numerical value=100
numerical value=97
numerical value=124
Example no 3
#include <stdio.h>
int main() {
char a = 'A';
char b = 'B';
return 0;
}
Explanation
• In this program, two character variables a and b are declared and assigned the values ‘A’ and
‘B’, respectively. The program then adds a and b using character arithmetic, which results in
the value ‘C’. The result is then printed using the printf function.
• Note that in character arithmetic, the characters are treated as integers based on their ASCII
code values. For example, the ASCII code for ‘A’ is 65 and for ‘B’ is 66, so adding ‘A’ and ‘B’
results in 65 + 66 = 131, which is the ASCII code for ‘C’.
KEY TAKEAWAYS
• Character arithmetic is used to implement arithmetic operations like addition, subtraction
,multiplication ,division on characters in C language.
• In character arithmetic character converts into integer value to perform task. For this ASCII
value is used.
STRING
• It is used to perform action the strings.
STRING
8.1 CONCEPTS OF USER DEFINED
FUNCTIONS
User-defined functions in C language are defined by the programmer to perform specific operations.
They are also known as “tailor-made functions” which are built only to satisfy the given condition. We
can classify functions into call by value or call by reference.
Here return_type of the function is an integer and the name of the function is sum() which has two
arguments of type int passed to the function.
Function Definition
Once the function has been called, the function definition contains the actual block of code that
will be executed. The four components of a function definition are as follows:
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the brackets.
There are two types of function calls i.e, Call by value and Call by reference.
Syntax:
Example:
add(10,14);
A. Call by value
In call by value, a copy of the value is passed to the function and changes that are made to the
function are not reflected back to the values. Actual and formal arguments are created in
different memory locations.
B. Call by Reference
In a call by Reference, the address of the argument is passed to the function, and changes that
are made to the function are reflected back to the values.
Return Statement
Return Statement is used to return value from the function. It basically terminates the
execution of the function and the control of the program is returned to its caller. After the
Syntax:
return (Expression)
Example:
return x+y;
KEY TAKEAWAYS
DEFINITION OF FUNCTION
Function Definition
Once the function has been called, the function definition contains the actual block of code that
will be executed. The four components of a function definition are as follows:
Function Calling
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the brackets.
There are two types of function calls i.e, Call by value and Call by reference.
Syntax:
Example:
add(10,14);
A. Call by value
In call by value, a copy of the value is passed to the function and changes that are made to the
function are not reflected back to the values. Actual and formal arguments are created in
different memory locations.
Example:
// call by value
int temp = a;
a = b;
b = temp;
int main()
swap(x, y);
return 0;
Output:
Note:
Values aren’t changed in the call by value since they aren’t passed by reference.
In a call by Reference, the address of the argument is passed to the function, and changes that
are made to the function are reflected back to the values.
Example
// Call by Reference
#include <stdio.h>
*a = *b;
*b = temp;
// Driver code
int main()
swap(&x, &y);
return 0;
Return Statement
Return Statement is used to return value from the function. It basically terminates the
execution of the function and the control of the program is returned to its caller. After the
function call, the execution starts immediately. The return data type must match the defined
data type in the function declaration and definition.
Syntax:
return (Expression)
Example:
return x+y;
KEY TAKEAWAYS
• Once the function has been called, the function definition contains the actual block of
code that will be executed. The four components of a function definition are as follows:
o The return type of the function
o Function Name
o Function parameters
o Body of function
• In order to transfer control to a user-defined function, we need to call it. Functions are
called using their names followed by round brackets. Their arguments are passed inside
the brackets. There are two types of function calls i.e, Call by value and Call by
reference.
• Syntax:
function_name(arg1, arg2, ... argN);
Call by value
• In a call by Reference, the address of the argument is passed to the function, and
changes that are made to the function are reflected back to the values.
KEY TAKEAWAYS
- Function is used to perform specific task in a programming language.
- Another name of function is UDF (User Defined Functions)
- There are various types of functions available in C language they are:
o Function without argument without return value
o Function with argument but no return value
o Function with argument with return value
Example: Suppose a sum () function is needed to be called with two numbers to add. These two
numbers are referred to as the arguments and are passed to the sum () when it called from
somewhere else.
Parameters
The parameter is referred to as the variables that are defined during a function declaration or
definition. These variables are used to receive the arguments that are passed during a function call.
These parameters within the function prototype are used during the execution of the function for
which it is defined. These are also called Formal arguments or Formal Parameters.
Example: Suppose a Mult() function is needed to be defined to multiply two numbers. These two
numbers are referred to as the parameters and are defined while defining the function Mult().
Argument Parameter
When a function is called, the values The values which are defined at the time of the
that are passed during the call are function prototype or definition of the function are
called as arguments. called as parameters.
BASIC OF C PROGRAMMING
2
Argument Parameter
They are also called Actual Parameters They are also called Formal Parameters
Example:
BASIC OF C PROGRAMMING
3
(Figure 1: Functions )
EXAMPLE:
// call by value
#include <stdio.h>
BASIC OF C PROGRAMMING
4
the formal parameter are reflected in the actual parameter in the calling environment as formal
parameter receives a reference (or pointer) to the actual data. This method is also called as call by
reference. This method is efficient in both time and space.
(Figure 2: Functions )
// C program to illustrate
// call by reference
#include <stdio.h>
int main(void)
{
int a = 10, b = 20;
// passing parameters
swapnum(&a, &b);
BASIC OF C PROGRAMMING
5
printf("a is %d and b is %d\n", a, b);
return 0;
}
Output:
a is 20 and b is 10
C and C++ both support call by value as well as call by reference whereas Java doesn’t support call by
reference.
Shortcomings:
● Many potential scenarios can occur
● Programs are difficult to understand sometimes
KEY TAKEAWAYS
● An argument is referred to the values that are passed within a function when the function
is called.
● The parameter is referred to as the variables that are defined during a function declaration
or definition
● Any modifications to the formal parameter variable inside the called function or method
affect only the separate storage location and will not be reflected in the actual parameter
in the calling environment. This method is also called as call by value.
● Any changes to the formal parameter are reflected in the actual parameter in the calling
environment as formal parameter receives a reference (or pointer) to the actual data. This
method is also called as call by reference.
BASIC OF C PROGRAMMING
6
CALLING A FUNCTION,
RECURSIVE FUNCTION
8.4 CALLING A FUNCTION, RECURSIVE FUNCTION
Important methods of Parameter Passing
1. CALL BY VALUE:
This method uses in-mode semantics. Changes made to formal parameter do not get transmitted
back to the caller. Any modifications to the formal parameter variable inside the called function or
method affect only the separate storage location and will not be reflected in the actual parameter
in the calling environment.
(Figure 1: Functions )
EXAMPLE:
// call by value
#include <stdio.h>
BASIC OF C PROGRAMMING
2
printf("In main, x = %d y = %d\n", x, y);
return 0;
}
Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
Shortcomings:
● Inefficiency in storage allocation
● For objects and arrays, the copy semantics are costly
2. CALL BY REFRENCE : This technique uses in/out-mode semantics. Changes made to formal
parameter do get transmitted back to the caller through parameter passing. Any changes to the
formal parameter are reflected in the actual parameter in the calling environment as formal
parameter receives a reference (or pointer) to the actual data. This method is efficient in both time
and space.
(Figure 2: Functions )
// call by reference
#include <stdio.h>
BASIC OF C PROGRAMMING
3
*j = temp;
}
int main(void)
{
int a = 10, b = 20;
// passing parameters
swapnum(&a, &b);
Output:
a is 20 and b is 10
C and C++ both support call by value as well as call by reference whereas Java doesn’t support call by
reference.
Shortcomings:
● Many potential scenarios can occur
● Programs are difficult to understand sometimes
Recursive Functions:
In programming terms, a recursive function can be defined as a routine that calls itself directly or
BASIC OF C PROGRAMMING
4
indirectly.
Using the recursive algorithm, certain problems can be solved quite easily. Towers of Hanoi (TOH) is
one such programming exercise. Try to write an iterative algorithm for TOH. Moreover, every
recursive program can be written using iterative methods.
Mathematically, recursion helps to solve a few puzzles easily.
Base Case:
One critical requirement of recursive functions is the termination point or base case. Every recursive
program must have a base case to make sure that the function will terminate. Missing base case
results in unexpected behavior.
● Any modifications to the formal parameter variable inside the called function or method
affect only the separate storage location and will not be reflected in the actual parameter
in the calling environment. This method is also called as call by value.
● Any changes to the formal parameter are reflected in the actual parameter in the calling
environment as formal parameter receives a reference (or pointer) to the actual data. This
method is also called as call by reference.
BASIC OF C PROGRAMMING
5
MACROS , PRE-PROCCESING
8.5 MACROS , PRE-PROCESSING
Macros and Pre-processors in C
In a C program, all lines that start with # are processed by preprocessor which is a special program
invoked by the compiler. by this we mean to say that the ‘#’ symbol is used to process the
functionality prior than other statements in the program, that is, which means it processes some
code before run-time or say during the compile-time. In a very basic term, preprocessor takes a C
program and produces another C program without any #.
The following are some interesting facts about preprocessors in C.
1) When we use include directive, the contents of included header file (after preprocessing) are
copied to the current file.
Angular brackets < and > instruct the preprocessor to look in the standard folder where all header
files are held. Double quotes “and “instruct the preprocessor to look into the current folder
(current directory).
2) When we use define for a constant, the preprocessor produces a C program where the defined
constant is searched and matching tokens are replaced with the given expression. For example in
the following program max is defined as 100.
EXAMPLE:
#include <stdio.h>
#define max 100
int main()
{
printf("max is %d", max);
return 0;
}Easy to Extend
3) The macros can take function like arguments, the arguments are not checked for data type. For
example, the following macro INCREMENT(x) can be used for x of any data type.
#include <stdio.h>
#define INCREMENT(x) ++x
int main()
{
char* ptr = "GeeksQuiz";
int x = 10;
printf("%s ", INCREMENT(ptr));
printf("%d", INCREMENT(x));
return 0;
}
Output:
eeksQuiz 11
4) The macro arguments are not evaluated before macro expansion. For example, consider the
following program
BASIC OF C PROGRAMMING
2
#include <stdio.h>
#define MULTIPLY(a, b) a* b
int main()
{
// The macro is expanded as 2 + 3 * 3 + 5, not as 5*8
printf("%d", MULTIPLY(2 + 3, 3 + 5));
return 0;
}
// Output: 16
Output:
16
#include <stdio.h>
// here, instead of writing a*a we write (a)*(b)
#define MULTIPLY(a, b) (a) * (b)
int main()
{
// The macro is expanded as (2 + 3) * (3 + 5), as 5*8
printf("%d", MULTIPLY(2 + 3, 3 + 5));
return 0;
}
// This code is contributed by Santanu
Output:
40
5) The tokens passed to macros can be concatenated using operator ## called Token-Pasting
operator.
#include <stdio.h>
#define merge(a, b) a##b
int main() { printf("%d ", merge(12, 34)); }
Output:
1234
6) A token passed to macro can be converted to a string literal by using # before it.
BASIC OF C PROGRAMMING
3
#include <stdio.h>
#define get(a) #a
int main()
{
// GeeksQuiz is changed to "GeeksQuiz"
printf("%s", get(GeeksQuiz));
}
Output:
GeeksQuiz
7) The macros can be written in multiple lines using ‘\’. The last line doesn’t need to have ‘\’.
8) The macros with arguments should be avoided as they cause problems sometimes. And Inline
functions should be preferred as there is type checking parameter evaluation in inline functions.
C99 onward, inline functions are supported by C language also.
For example consider the following program. From first look the output seems to be 1, but it
produces 36 as output.
C
#include <stdio.h>
#define square(x) x* x
int main()
{
// Expanded as 36/6*6
int x = 36 / square(6);
printf("%d", x);
return 0;
}
Output
36
But we can write this code as follows to get the expected result i.e. 1:
#include <stdio.h>
#define square(x) (x * x)
int main()
{
// Expanded as 36/(6*6)
int x = 36 / square(6);
printf("%d", x);
BASIC OF C PROGRAMMING
4
return 0;
}
Output
1
If we use inline functions, we get the expected output. Also, the program given in point 4 above can
be corrected using inline functions.
#include <stdio.h>
Output:
1
9) Preprocessors also support if-else directives which are typically used for conditional compilation.
int main()
{
#if VERBOSE >= 2
printf("Trace Message");
#endif
}
Output:
No Output
10) A header file may be included more than one time directly or indirectly, this leads to problems of
redeclaration of same variables/functions. To avoid this problem, directives
like defined, ifdef and ifndef are used
11) There are some standard macros which can be used to print program file (__FILE__), Date of
compilation (__DATE__), Time of compilation (__TIME__) and Line Number in C code (__LINE__)
BASIC OF C PROGRAMMING
5
KEY TAKEAWAYS
- In a C program, all lines that start with # are processed by preprocessor which is a special
program invoked by the compiler.
- By this we mean to say that the ‘#’ symbol is used to process the functionality prior than
other statements in the program, that is, which means it processes some code before run-
time or say during the compile-time
BASIC OF C PROGRAMMING
6
9.1 POINTERS
POINTER
SUB LESSON 9.1
(Figure 6: Pointers)
POINTER
• Define a pointer variable
• Assigning the address of a variable to a pointer using the unary operator (&) which
returns the address of that variable.
• Accessing the value stored in the address using unary operator (*) which returns the
value of the variable located at the address specified by its operand.
The reason we associate data type with a pointer is that it knows how many bytes the data is
stored in. When we increment a pointer, we increase the pointer by the size of the data type to
which it points.
Pointers variables are also known as address data types because they are used to store the
address of another variable. The address is the memory location that is assigned to the variable.
It doesn’t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language.
The operations are slightly different from the ones that we generally use for mathematical
calculations. The operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers of the same type
Passing the pointers to the function means the memory location of the variables is passed to
the parameters in the function, and then the operations are performed. The function definition
accepts these addresses using pointers, addresses are stored using pointers.
When we pass arguments without pointers the changes made by the function would be
done to the local variables of the function.
POINTER
Below is the C program to pass arguments to function without a pointer:
KEY TAKEAWAYS
• Pointers in C are used to store the address of variables or a memory location. This
variable can be of any data type i.e, int, char, function, array, or any other pointer. The
pointer of type void is called Void pointer or Generic pointer.
• Void pointer can hold address of any type of variable. The size of the pointer depends
on the computer architecture like 16-bit, 32-bit, and 64-bit.
• Pointers variables are also known as address data types because they are used to store
the address of another variable. The address is the memory location that is assigned to
the variable. It doesn’t store any value.
POINTER
9. POINTERS
POINTER
SUB LESSON 9.2
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also
declare a pointer that can point to whole array instead of only one element of the array. This pointer is
useful when talking about multidimensional arrays.
Syntax:
data_type (*var_name)[size_of_array];
Example:
int (*ptr)[10];
Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer
name inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the
whole array are totally different.
POINTER
(Figure 7: Array to pointers)
Array of Pointers in C
data_type (array_name)[sizeof_array];
Example :
int arr[10];
data_type (*array_name)[sizeof_array];
Example :
int *ptr[10];
We are using * operator to define that the ptr array is an array of pointers.
POINTER
An application of an array of pointers is that it becomes easy to store strings in a char pointer
array and it also reduces the memory consumption. Let us look at the C Program to understand
the array of pointers in a char array.
EXAMPLE
#include <stdio.h>
int main()
printf("%s\n", fruits[i]);
return 0;
Output:
apple
banana
mango
grapes
orange
POINTER
Explanation :
• We have declared and initialized an array of pointers named fruits. It can contain
addresses of char type variables only. Array representation and comparison of
simple char array with char pointers array in the memory :
• We are printing the strings pointed by the pointers in the array using
the printf() statement.
KEY TAKEAWAYS
• Array name generally acts as a pointer to the array and contains the starting address of
the array.
• Array elements can be accessed and manipulated using a pointer containing the starting
address of the array.
• Syntax for representation of 2-D arrays elements in terms of pointers is *(*(arr + i) +
j) (arr[i][j]) and for 3-D arrays elements is *(*(*(arr + i) + j) + k) (arr[i][j][k]).
• Array of pointers are used to store multiple address values and are very useful in case of
storing various string values.
POINTER
9. POINTERS
// Driver Code
int main()
{
// Declare a pointer
int* p;
// Function call
p = fun();
printf("%p\n", p);
printf("%d\n", *p);
POINTER
return 0;
}
Program 1:
The below program will give segmentation fault since ‘A’ was local to the function:
EXPLANATION:
The main reason behind this scenario is that compiler always make a stack for a function call.
As soon as the function exits the function stack also gets removed which causes the local
variables of functions goes out of scope.
Static Variables have a property of preserving their value even after they are out of their
scope. So to execute the concept of returning a pointer from function in C you must define the
local variable as a static variable.
POINTER
(Figure 9: Functions returning a pointer)
Program 2:
#include <stdio.h>
int* fun()
POINTER
// Declare a static integer
return (&A);
// Driver Code
int main()
// Declare a pointer
int* p;
// Function call
p = fun();
// Print Address
printf("%p\n", p);
printf("%d\n", *p);
return 0;
Output:
0x601038
POINTER
10
KEY TAKEAWAYS
• Pointers in C programming language is a variable which is used to store the memory
address of another variable.
• We can pass pointers to the function as well as return pointer from a function. But it is
not recommended to return the address of a local variable outside the function as it
goes out of scope after function returns.
POINTER
10. C++ PROGRAMMING
10.1 PROCEDURE ORIENTED PROGRAMMING, OBJECT
ORIENTED PROGRAMMING, PURPOSE OF OBJECT-ORIENTED
PROGRAMMING
Emphasis on Procedures: The focus is on dividing the program into smaller, self-contained
procedures that perform specific tasks. Each procedure performs a particular operation and
can be reused in different parts of the program.
Top-Down Design: The program is designed in a top-down manner, starting with a main
procedure that calls other procedures to perform tasks. This approach provides a clear
structure and allows for step-by-step refinement of the program.
Shared Data: Data is often shared between procedures using parameters or global variables.
Procedures can modify global variables, which can impact the behaviour of other
procedures. However, excessive reliance on global data can lead to potential issues, such as
data coupling and code maintenance problems.
Focus on Algorithms: POP places a strong emphasis on algorithms and the step-by-step
instructions required to solve a problem. It is well-suited for tasks that can be decomposed
into a series of procedural steps.
C++ PROGRAMMING
2
Procedure-oriented programming has been widely used in early programming languages like
Fortran and C. While it still has its place in certain scenarios, many modern programming
languages and paradigms, such as object-oriented programming and functional
programming, provide more advanced techniques for organizing and managing code
complexity.
C++ PROGRAMMING
3
Here are some key concepts and features of object-oriented programming:
Classes and Objects: A class is a user-defined data type that defines a set of properties and
behaviours. Objects are instances of classes that can hold data and perform actions based
on the class's defined methods.
Encapsulation: Encapsulation is the practice of bundling data and methods together within
a class, hiding internal implementation details and exposing only the necessary interfaces to
interact with the object. This concept helps in achieving data security and code modularity.
Inheritance: Inheritance allows classes to inherit properties and behaviours from other
classes, forming a hierarchical relationship. The derived class (subclass) can inherit
attributes and methods from a base class (superclass) and can also add its own unique
characteristics.
Object-oriented programming languages like Java, C++, Python, and C# provide built-in
support for OOP concepts. OOP promotes code reusability, maintainability, and modularity,
making it widely used in software development for creating complex systems and
applications.
C++ PROGRAMMING
4
Modularity: OOP allows for the modular organization of code by encapsulating data and
behaviour within objects. Objects can be created, modified, and reused independently,
providing a way to break down complex problems into manageable units. This promotes
code organization, readability, and easier maintenance.
Reusability: OOP promotes code reuse through the concept of classes and inheritance.
Classes serve as blueprints or templates for creating objects. By defining common attributes
and behaviour in a class, multiple objects can be created based on that class, reducing the
need to rewrite code. Inheritance allows new classes to inherit properties and behaviour
from existing classes, enabling the reuse of code and promoting code extensibility.
Maintainability: OOP helps in writing code that is easier to maintain and modify.
Encapsulation allows for hiding the internal details of objects, providing a clear interface for
interacting with them. This abstraction of implementation details makes it easier to update
or modify the internal workings of objects without affecting other parts of the codebase.
Extensibility: OOP provides mechanisms like inheritance and polymorphism that enable the
creation of new classes that extend or specialize the functionality of existing classes. This
allows for code extension without modifying the existing codebase, promoting scalability
and adaptability.
C++ PROGRAMMING
5
KEY TAKEAWAYS
- There are 2 types of programming languages are there
o Procedural Oriented Programming Language
▪ Focuses on Functionality / Function
▪ Shortly known as UDF (User Defined Functions)
o Object Oriented Programming Language (OOP)
▪ Focuses on Objects
C++ PROGRAMMING
6
10. C++ PROGRAMMING
10.2 PROCEDURAL VS OBJECT ORIENTED PROGRAMMING
Procedural programming (PP) and object-oriented programming (OOP) are two different
programming paradigms with distinct approaches to organizing and structuring code. Here's
a comparison between procedural programming and object-oriented programming:
1) Approach:
C++ PROGRAMMING
2
Procedural Programming: PP focuses on procedures or functions that manipulate data. It
follows a top-down approach, dividing the program into smaller procedures that execute
sequentially.
2) Code Structure:
Procedural Programming: PP uses procedures or functions as the main building blocks. Data
and functions are typically separated, and data is shared between functions using
parameters or global variables.
Object-Oriented Programming: OOP organizes code around objects that combine data and
behaviour. Objects are instances of classes, and they interact through methods. OOP
promotes encapsulation, where objects hide internal details and provide well-defined
interfaces for interaction.
3) Reusability:
Procedural Programming: PP allows for the reuse of functions or procedures by calling them
from different parts of the program. However, reusing code may require passing data
through parameters, making it less modular.
4) Data Security:
Procedural Programming: In PP, data is often accessed globally or passed between
functions using parameters or global variables. This can lead to potential issues with data
security and integrity.
C++ PROGRAMMING
3
5) Real-World Modelling:
Procedural Programming: PP does not provide explicit mechanisms for modelling real-world
entities and relationships.
Object-Oriented Programming: OOP allows for modelling real-world entities using objects
and their interactions, providing a closer alignment between the code and the problem
domain. It facilitates the modelling of relationships, inheritance, and polymorphism.
Both paradigms have their strengths and are suitable for different scenarios. Procedural
programming is often used for small programs or performance-critical applications, while
object-oriented programming is widely used for larger systems where code modularity,
reusability, and maintainability are important. Many programming languages, such as C++,
Java, and Python, support both paradigms, allowing developers to choose the most
appropriate approach for their specific needs.
KEY TAKEAWAYS
- POP focuses on Procedures
- OOP focuses on Objects
- Example of POP in Library Application various functionalities that can be carried out
are :
o Issuing Book
o Returning Book
o Fine Calculation
- Example of OOP in Library Application various objects can be :
o Student
o Book
o Librarian
C++ PROGRAMMING
4
10. C++ PROGRAMMING
10.3 PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING. BENEFITS AND
APPLICATIONS OF OOP.
Object
An object means anything from real world like as person, computer, bench etc...
An object is a component of a program that knows how to interact with other pieces of the
program.
Figure 1: Object
Class
“An Object is an instance of a Class. When a class is defined, there is no memory allocation
but when it is instantiated (i.e., an object is created) memory is allocated.”
It has the data and its associated function wrapped in it. Classes can also be known as a
collection of similar objects or objects of the same type. In the OOPs concept the variables
which are declared inside a class are known as "Data Members" and the functions declared
are known as "Member Functions".
C++ PROGRAMMING
2
Figure 2: Class
Data Abstraction
The functions which operate on these data are known as: member functions or methods.
Encapsulation
It is used as a binding agent to binding the data and the functions that operate on them in
Object-Oriented Programming.
Functions wrapped together within a single unit only can access the data.
Inheritance
“The capability of a class to derive properties and characteristics from another class is called
Inheritance.”
C++ PROGRAMMING
3
Inheritance is one of the most key features of Object-Oriented Programming.
Sub Class: “It is the class that inherits properties from another class. It is also known as
Derived Class.”
Super Class: “The class whose properties are inherited by sub class is called Base Class or
Super class.”
Reusability: Reusability is used in inheritance, i.e., when we want to create a new class and
there is already a class that includes some of the code that we want, we can derive our new
class from the existing class.
Figure 3: Inheritance
Polymorphism
The word polymorphism means having various forms. In simple words, we can define it as
the ability of a message to be displayed in more than one way.
For E.g., A person at the same time can have different characteristic. Like a man at the same
time is a father, a husband, an employee. So, the same person possesses different
behaviour in different situations. This is called polymorphism.
Its advantage is that it helps to reduce complexity by allowing one interface to specify a
general class of action. It is the compiler’s job to select the specific action as it applies to
each situation.
C++ PROGRAMMING
4
Figure 4: Polymorphism
Function Overloading: “Using a single function name to perform different types of tasks is
known as Function overloading. Polymorphism is extensively used in implementing
inheritance.”
Header File
It is also known as late binding, as it will not bind the code until the time of call at run time.
In short, we can say that properties of the variables are determined at runtimes.
C++ PROGRAMMING
5
It has association with polymorphism and inheritance.
Compilers should match function calls with the correct definition at the run time.
Message Passing
Objects communicate with one another by sending and receiving information to each other.
A message for an object is a request for execution of a procedure and therefore it will
invoke a function in the receiving object that generates the desired results.
It involves specifying the name of the object, the name of the function and the information
to be sent
Message passing needs the object name, function name and the information which is to be
sent.
C++ PROGRAMMING
6
Figure 7: Message Passing
Object-oriented programming (OOP) offers several benefits and has numerous applications
across various domains. Here are some of the key benefits and applications of OOP:
Benefits of OOP:
Modularity and Code Reusability: OOP encourages the creation of modular code by dividing
complex systems into smaller, self-contained objects. These objects can be reused in
different parts of the program or in other projects, reducing redundant code and promoting
code reusability.
Encapsulation and Information Hiding: OOP allows the encapsulation of data and methods
within objects, hiding the internal implementation details. This enhances data security and
prevents direct access to internal states, ensuring that the object's behaviour is controlled
through well-defined interfaces.
Maintainability and Scalability: OOP promotes code maintainability and scalability. With
encapsulation, changes made to the internal implementation of an object have minimal
impact on other parts of the code. Additionally, OOP's modular nature makes it easier to
extend and enhance existing code by adding new objects or modifying existing ones.
Flexibility and Adaptability: OOP enables the creation of flexible and adaptable code
structures. Through concepts like polymorphism and inheritance, objects can be designed to
respond differently to the same method call based on the context. This flexibility allows for
dynamic behaviour and makes it easier to introduce changes without affecting the overall
system.
C++ PROGRAMMING
7
Collaboration and Teamwork: OOP supports collaboration and teamwork in software
development. Different developers can work on different objects or classes simultaneously,
allowing for parallel development. OOP's clear separation of responsibilities and well-
defined interfaces facilitate easier integration and collaboration among team members.
Applications of OOP:
Graphical User Interfaces (GUI): OOP is well-suited for designing graphical user interfaces.
GUI frameworks and libraries often leverage OOP principles to represent GUI elements as
objects, enabling interaction, event handling, and providing a modular approach to building
user-friendly applications.
Game Development: OOP is prevalent in game development due to its ability to represent
game objects, behaviours, and interactions. Game engines and frameworks utilize OOP
concepts to create game entities, implement game logic, and handle user inputs, enabling
the creation of complex and interactive games.
Object Databases: OOP is closely aligned with object databases, which store data as objects
rather than traditional tables and rows. Object-oriented databases leverage OOP principles
to provide a natural and efficient way to persist, retrieve, and manipulate objects,
simplifying data management.
Web Development: OOP is utilized in web development frameworks and technologies. For
example, in web application development, OOP can be employed to design and organize
components such as models, views, and controllers. OOP concepts like encapsulation and
inheritance facilitate code organization and maintenance in web applications.
These are just a few examples of the many areas where OOP finds applications. The
versatility and benefits of OOP make it a widely adopted programming paradigm in various
industries.
KEY TAKEAWAYS
- C++ is an object oriented programming language.
- Common characteristics of OOP programming languages are Class, Object,
Inheritance, Datahiding, Databinding, Encapsulation, Polymorphism.
C++ PROGRAMMING
8
11. C++ BASIC
C++ BASICS 9
11.1 OVERVIEW OF C++, PROGRAM STRUCTURE
OVERVIEW OF C++
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey,
as an enhancement to the C language and originally named C with Classes but later it was
renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Note − A programming language is said to use static typing when type checking is performed
during compile-time as opposed to run-time.
C++ BASICS 10
OBJECT-ORIENTED PROGRAMMING
C++ fully supports object-oriented programming, including the four pillars of object-oriented
development –
• Encapsulation
• Data hiding
• Inheritance
• Polymorphism
STANDARD LIBRARIES
• The core language giving all the building blocks including variables, data types and
literals, etc.
• The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.
• The Standard Template Library (STL) giving a rich set of methods manipulating data
structures, etc.
THE ANSI STANDARD
The ANSI standard is an attempt to ensure that C++ is portable; that code you write for
Microsoft's compiler will compile without errors, using a compiler on a Mac, UNIX, a Windows
box, or an Alpha.
The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers
support the ANSI standard.
LEARNING C++
The purpose of learning a programming language is to become a better programmer; that is, to
become more effective at designing and implementing new systems and at maintaining old
ones.
C++ supports a variety of programming styles. You can write in the style of Fortran, C, Smalltalk,
etc., in any language. Each style can achieve its aims effectively while maintaining runtime and
space efficiency.
USE OF C++
C++ BASICS 11
C++ is used by hundreds of thousands of programmers in essentially every application domain.
C++ is being highly used to write device drivers and other software that rely on direct
manipulation of hardware under realtime constraints.
C++ is widely used for teaching and research because it is clean enough for successful teaching
of basic concepts.
Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used
C++ because the primary user interfaces of these systems are written in C++.
The C++ program is written using a specific template structure. The structure of the program
written in C++ language is as follows:
DOCUMENTATION SECTION:
• This section comes first and is used to document the logic of the program that the
programmer going to code.
• It can be also used to write for purpose of the program.
• Whatever written in the documentation section is the comment and is not compiled
by the compiler.
• Documentation Section is optional since the program can execute without them.
Below is the snippet of the same:
factorial of a number
C++ BASICS 12
The basic requirement for writing this
*/
LINKING SECTION:
HEADER FILES:
• Generally, a program includes various programming elements like built-in functions,
classes, keywords, constants, operators, etc. that are already defined in the standard
C++ library.
• In order to use such pre-defined elements in a program, an appropriate header must
be included in the program.
• Standard headers are specified in a program through the preprocessor directive
#include. In Figure, the iostream header is used. When the compiler processes the
instruction #include<iostream>, it includes the contents of the stream in the
program. This enables the programmer to use standard input, output, and error
facilities that are provided only through the standard streams defined in <iostream>.
These standard streams process data as a stream of characters, that is, data is read
and displayed in a continuous flow. The standard streams defined in <iostream> are
listed here.
#include<iostream>
NAMESPACES:
• A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
• Any user can create separate namespaces of its own and can use them in any other
program.
• In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
using namespace std;
• Namespaces can be accessed in multiple ways:
o using namespace std;
C++ BASICS 13
o using std :: cout;
DEFINITION SECTION:
• It is used to declare some constants and assign them some value.
• In this section, anyone can define your own datatype using primitive data types.
• In #define is a compiler directive which tells the compiler whenever the message is
found to replace it with “Factorial\n”.
• typedef int INTEGER; this statement tells the compiler that whenever you will
encounter INTEGER replace it by int and as you have declared INTEGER as datatype
you cannot use it as an identifier.
GLOBAL DECLARATION SECTION:
• Here, the variables and the class definitions which are going to be used in the
program are declared to make them global.
• The scope of the variable declared in this section lasts until the entire program
terminates.
• These variables are accessible within the user-defined functions also.
// num to one
fact *= i;
C++ BASICS 14
// Return the factorial calculated
return fact;
MAIN FUNCTION:
• The main function tells the compiler where to start the execution of the program.
The execution of the program starts with the main function.
• All the statements that are to be executed are written in the main function.
• The compiler executes all the instructions which are written in the curly braces {}
which encloses the body of the main function.
• Once all instructions from the main function are executed, control comes out of the
main function and the program terminates and no further execution occur.
KEY TAKEAWAYS:
• A programming language is said to use static typing when type checking is performed
during compile-time as opposed to run-time.
• C++ is used by hundreds of thousands of programmers in essentially every application
domain.
• A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
C++ BASICS 15
11. C++ BASICS
C++ BASICS 16
11.2 NAMESPACE & IDENTIFIERS
NAMESPACE
• Namespace provide the space where we can define or declare identifier i.e.
variable, method, classes.
• Using namespace, you can define the space or context in which identifiers
are defined i.e. Variable, method, classes. In essence, a namespace defines a
scope.
C++ BASICS 17
DEFINING A NAMESPACE:
• A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
Namespace namespace_name
namespace namespace_name1
// code declarations
namespace namespace_name2
C++ BASICS 18
{
// code declarations
In the above statements if you are using namespace_name1, then it will make
elements of namespace_name2 available in the scope as follows:
#include <iostream>
Namespace first_space
void func()
namespace second_space
C++ BASICS 19
{
void func()
Int main ()
func();
return 0;
Output
Inside second_space
C++ BASICS 20
• Multiple namespace blocks with the same name are allowed. All declarations within
those blocks are declared in the named scope.
A namespace definition begins with the keyword namespace followed by the namespace
name as follows:
namespace namespace_name
{
int x, y; // code declarations where
// x and y are declared in
// namespace_name's scope
}
• Namespace declarations appear only at global scope.
• Namespace declarations can be nested within another namespace.
• Namespace declarations don’t have access specifiers (Public or Private).
• No need to give a semicolon after the closing brace of the definition of namespace.
• We can split the definition of namespace over several units.
For example, you might be writing some code that has a function called xyz() and there is
another library available in your code which also has the same function xyz(). Now the
compiler has no way of knowing which version of xyz() function you are referring to within
your code.
A namespace is designed to overcome this difficulty and is used as additional information to
differentiate similar functions, classes, variables, etc. with the same name available in
different libraries.
The best example of namespace scope is the C++ standard library (std), where all the classes,
methods and templates are declared. Hence, while writing a C++ program, we usually include
the directive
IDENTIFIERS
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or
other user-defined data types created by the programmer. They are the basic requirement of
any language. Every language has its own rules for naming the identifiers.
C++ BASICS 21
In short, we can say that the C++ identifiers represent the essential elements in a program
which are given below:
• Constants
• Variables
• Functions
• Labels
• Defined data types
Some naming rules are common in both C and C++. They are as follows:
For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in
second. Therefore, it proves that identifiers are case-sensitive.
VALID IDENTIFIERS
The following are the examples of valid identifiers are:
1. Result
2. Test2
3. _sum
4. power
INVALID IDENTIFIERS
The following are the examples of invalid identifiers:
C++ BASICS 22
3. break // use of a keyword.
Note: Identifiers cannot be used as the keywords. It may not conflict with the keywords, but it
is highly recommended that the keywords should not be used as the identifier name. You
should always use a consistent way to name the identifiers so that your code will be more
readable and maintainable.
KEY TAKEAWAYS
• Namespace provide the space where we can define or declare identifier i.e.
variable, method, classes.
• Namespaces allow us to group named entities that otherwise would have global
scope into narrower scopes, giving them namespace scope. This allows organizing the
elements of programs into different logical scopes referred to by names.
• C++ identifiers in a program are used to refer to the name of the variables, functions,
arrays, or other user-defined data types created by the programmer. They are the basic
requirement of any language. Every language has its own rules for naming the
identifiers.
C++ BASICS 23
11. C++ BASICS
C++ BASICS 24
11.3 DATA TYPE IN C++, VARIABLE, CONSTANT
All variables use data type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data they can
store. Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data type with which it is declared. Every data type requires a different
amount of memory.
C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application. Data types specify the size and types of values to
be stored. However, storage representation and machine instructions to manipulate each data
type differ from machine to machine, although C++ instructions are identical on all machines.
C++ BASICS 25
Data Types in C++ are Mainly Divided into 3 Types:
These data types are built-in or predefined data types and can be used directly by the user to
declare variables.
• Integer
• Character
• Boolean
• Floating Point
• Double Floating Point
• Valueless or Void
• Wide Character
2. DERIVED DATA TYPES
Derived data types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types.
• Function
• Array
• Pointer
• Reference
3. ABSTRACT OR USER-DEFINED DATA TYPES
Abstract or User-Defined data types are defined by the user itself. Like, defining a class in C++
or a structure.
• Class
• Structure
• Union
• Enumeration
• Typedef defined Datatype
C++ BASICS 26
PRIMITIVE DATA TYPES
• Integer: The keyword used for integer data types is int. Integers typically require 4 bytes
of memory space and range from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. The keyword used for the
character data type is char. Characters typically require 1 byte of memory space and
range from -128 to 127 or 0 to 255.
• Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean
variable can store either true or false. The keyword used for the Boolean data type is
bool.
• Floating Point: Floating Point data type is used for storing single-precision floating-point
values or decimal values. The keyword used for the floating-point data type is float.
Float variables typically require 4 bytes of memory space.
• Double Floating Point: Double Floating Point data type is used for storing double-
precision floating-point values or decimal values. The keyword used for the double
floating-point data type is double. Double variables typically require 8 bytes of memory
space.
• Void: Void means without any value. void data type represents a valueless entity. A void
data type is used for those function which does not return a value.
• Wide Character: Wide character data type is also a character data type but this data
type has a size greater than the normal 8-bit data type. Represented by wchar_t. It is
generally 2 or 4 bytes long.
• sizeof() operator: sizeof() operator is used to find the number of bytes occupied by a
variable/data type in computer memory.
Example:
int m , x[50];
cout<<sizeof(x); //returns 200 which is the number of bytes occupied by the integer
array variable “x”.
Advantages:
• Data types provide a way to categorize and organize data in a program, making it easier
to understand and manage.
• Each data type has a specific range of values it can hold, allowing for more precise
control over the type of data being stored.
C++ BASICS 27
• Data types help prevent errors and bugs in a program by enforcing strict rules about
how data can be used and manipulated.
• C++ provides a wide range of data types, allowing developers to choose the best type
for a specific task.
Disadvantages:
• Using the wrong data type can result in unexpected behavior and errors in a program.
• Some data types, such as long doubles or char arrays, can take up a large amount of
memory and impact performance if used excessively.
• C++’s complex type system can make it difficult for beginners to learn and use the
language effectively.
• The use of data types can add additional complexity and verbosity to a program, making
it harder to read and understand.
VARIABLE IN C++
Variables in C++ is a name given to a memory location. It is the basic unit of storage in a
program.
type variable_name;
A variable name can consist of alphabets (both upper and lower case), numbers, and the
underscore ‘_’ character.
C++ BASICS 28
(Figure 2: Variable in C++)
Examples:
float simpleInterest;
char var;
C++ BASICS 29
We can also provide values while declaring the variables as given below:
The variable declaration refers to the part where a variable is first declared or introduced
before its first use. A variable definition is a part where the variable is assigned a memory
location and a value. Most of the time, variable declaration and definition are done together.
TYPES OF VARIABLES
C++ BASICS 30
There are three types of variables based on the scope of variables in C++
• Local Variables
• Instance Variables
• Static Variables
2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor, or block.
C++ BASICS 31
o As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
o Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier then the default access specifier will be used.
o Initialization of Instance Variable is not Mandatory.
o Instance Variable can be accessed only by creating objects.
• Each object will have its own copy of the instance variable whereas We can only have
one copy of a static variable per class irrespective of how many objects we create.
• Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of the instance variable. In the case of static,
changes will be reflected in other objects as static variables are common to all objects of
a class.
• We can access instance variables through object references and Static Variables can be
accessed directly using the class name.
• The syntax for static and instance variables:
class Example
C++ BASICS 32
static int a; // static variable
CONSTANT IN C++
The constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program. The type of constant can be an integer constant, a floating pointer
constant, a string constant, or a character constant. In C language, the const keyword is used to
define the constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is declared in
the program. We can not make any change in the value of the constant variables after they are
defined.
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
TYPES OF CONSTANTS IN C
C++ BASICS 33
The type of the constant is the same as the data type of the variables. Following is the list of the
types of constants
• Integer Constant
• Character Constant
• Floating Point Constant
• Double Precision Floating Point Constant
• Array Constant
• Structure Constant
We just have to add the const keyword at the start of the variable declaration.
PROPERTIES OF CONSTANT IN C
The important properties of constant variables in C defined using the const keyword are as
follows:
We can only initialize the constant variable in C at the time of its declaration. Otherwise,
it will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized
only once in the whole program. After that, we cannot modify the value stored inside
that variable.
KEY TAKEAWAYS
• All variables use data type during declaration to restrict the type of data to be stored.
There are three types of variables based on the scope of variables in C++
• Local Variables
• Instance Variables
• Static Variables
The constants in C are the read-only variables whose values cannot be modified once they
are declared in the C program.
C++ BASICS 34
11. C++ BASICS
C++ BASICS
11.4 OPERATORS-1
OPERATORS
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
C++ BASICS
1. ARITHMETIC OPERATORS
These operators are used to perform arithmetic or mathematical operations on the operands.
For example, ‘+’ is used for addition, ‘-’ is used for subtraction ‘*’ is used for multiplication, etc.
A) Unary Operators: These operators operate or work with a single operand. For example:
Increment (++) and Decrement (–) Operators.
Note: ++a and a++, both are increment operators, however, both are slightly different.
In ++a, the value of the variable is incremented first and then It is used in the program. In a++,
the value of the variable is assigned first and then it is incremented. Similarly happens for the
decrement operator.
B) Binary Operators: These operators operate or work with two operands. For example:
Addition (+), Subtraction (-), etc.
C++ BASICS
Name Symbol Description Example
int a = 3, b = 6;
Addition + Adds two operands
int c = a+b; // c = 9
int a = 9, b = 6;
Subtracts second operand from the
Subtraction –
first int c = a-b; // c = 3
int a = 3, b = 6;
Multiplication * Multiplies two operands
int c = a*b; // c = 18
int a = 12, b = 6;
Divides first operand by the second
Division /
operand int c = a/b; // c = 2
int a = 8, b = 6;
Modulo Returns the remainder an integer
%
Operation division int c = a%b; // c = 2
Note: The modulo operator (%) operator should only be used with integers.
2. RELATIONAL OPERATORS
These operators are used for the comparison of the values of two operands. For example, ‘>’
checks if one operand is greater than the other operand or not, etc. The result returns a
Boolean value, i.e., true or false.
int a = 3, b = 6;
C++ BASICS
Name Symbol Description Example
int a = 3, b = 6;
Checks if first operand is greater than a>b;
Greater Than >
the second operand
// returns false
int a = 3, b = 6;
Greater Than Checks if first operand is greater than a>=b;
>=
or Equal To or equal to the second operand
// returns false
int a = 3, b = 6;
Checks if first operand is lesser than a<b;
Less Than <
the second operand
// returns true
int a = 3, b = 6;
Less Than or Checks if first operand is lesser than a<=b;
<=
Equal To or equal to the second operand
// returns true
int a = 3, b = 6;
Checks if both operands are not a!=b;
Not Equal To !=
equal
// returns true
3. LOGICAL OPERATORS
These operators are used to combine two or more conditions or constraints or to complement
the evaluation of the original condition in consideration. The result returns a Boolean value, i.e.,
true or false.
C++ BASICS
Name Symbol Description Example
int a = 3, b = 6;
Returns true only if all the operands are a&&b;
Logical AND &&
true or non-zero
// returns true
int a = 3, b = 6;
Returns true if either of the operands is a||b;
Logical OR ||
true or non-zero
// returns true
int a = 3;
Returns true if the operand is false or !a;
Logical NOT !
zero
// returns false
KEY TAKEAWAYS
• An operator is a symbol that operates on a value to perform specific mathematical or
logical computations.
• Arithmetic operators are used to perform arithmetic or mathematical operations on the
operands. For example, ‘+’ is used for addition, ‘-’ is used for subtraction ‘*’ is used for
multiplication, etc.
• Relational operators are used for the comparison of the values of two operands. For
example, ‘>’ checks if one operand is greater than the other operand or not, etc. The
result returns a Boolean value, i.e., true or false.
• Logical operators are used to combine two or more conditions or constraints or to
complement the evaluation of the original condition in consideration. The result returns
a Boolean value, i.e., true or false.
C++ BASICS
11. C++ BASICS
C++ BASICS
11.5 OPERATORS-2
OPERATORS
4. BITWISE OPERATORS
These operators are used to perform bit-level operations on the operands. The operators are
first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing.
int a = 2, b = 3;
Copies a bit to the evaluated result if it exists
Binary AND & (a & b);
in both operands
//returns 2
int a = 2, b = 3;
Copies a bit to the evaluated result if it exists (a | b);
Binary OR |
in any of the operand
//returns 3
int a = 2, b = 3;
Copies the bit to the evaluated result if it is
Binary XOR ^ present in either of the operands but not (a ^ b);
both //returns 1
int a = 2, b = 3;
Shifts the value to left by the number of bits
Left Shift << (a << 1);
specified by the right operand.
//returns 4
int a = 2, b = 3;
Shifts the value to right by the number of
Right Shift >> (a >> 1);
bits specified by the right operand.
//returns 1
C++ BASICS
Name Symbol Description Example
int b = 3;
One’s (~b);
~ Changes binary digits 1 to 0 and 0 to 1
Complement
//returns -4
Note: Only char and int data types can be used with Bitwise Operators.
5. ASSIGNMENT OPERATORS
These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The
value on the right side must be of the same data type as the variable on the left side otherwise
the compiler will raise an error.
int a = 2;
Assignment Assigns the value on the right to the
=
Operator variable on the left // a = 2
C++ BASICS
Name Symbol Description Example
The ternary operator determines the answer on the basis of the evaluation of Expression1. If it
is true, then Expression2 gets evaluated and is used as the answer for the expression. If
Expression1 is false, then Expression3 gets evaluated and is used as the answer for the
expression.
There are some other common operators available in C++ besides the operators discussed
above. Following is a list of these operators discussed in detail:
A) sizeof Operator
This unary operator is used to compute the size of its operand or variable.
sizeof(char); // returns 1
C++ BASICS
C) -> Operator
This operator is used to access the variables of classes or structures.
cout<<emp->first_name;
D) Cast Operator
This unary operator is used to convert one data type into another.
float a = 11.567;
E) Dot Operator
This operator is used to access members of structure variables or class objects in C++.
F) & Operator
This is a pointer operator and is used to represent the memory address of an operand.
G) * Operator
This is an Indirection Operator
KEY TAKEAWAY
• Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. Mathematical operations such as addition, subtraction, multiplication, etc.
can be performed at the bit level for faster processing.
• Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator
is a value. The value on the right side must be of the same data type as the variable on
the left side otherwise the compiler will raise an error.
• The ternary operator determines the answer on the basis of the evaluation of
Expression1. If it is true, then Expression2 gets evaluated and is used as the answer for
the expression. If Expression1 is false, then Expression3 gets evaluated and is used as
the answer for the expression.
This operator takes three operands, therefore it is known as a Ternary Operator.
C++ BASICS
11. C++ BASICS
C++ BASICS 46
TYPECASTING IN C++
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
• Done by the compiler on its own, without any external trigger from the user.
• Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
• All the data types of the variables are upgraded to the data type of the variable with
largest data type.
bool -> char -> short int -> int ->
• It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).
Example of Type Implicit Conversion:
#include <iostream>
int main()
// value of 'a' is 97
C++ BASICS 47
x = x + y;
float z = x + 1.0;
return 0;
Output:
x = 107
y=a
z = 108
This process is also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type.
(type) expression
where type indicates the data type to which the final result is converted.
Example:
C++ BASICS 48
#include <iostream>
int main()
double x = 1.2;
return 0;
Output:
Sum = 2
• Conversion using Cast operator: A Cast operator is an unary operator which forces
one data type to be converted into another data type.
C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Example:
#include <iostream>
int main()
float f = 3.5;
C++ BASICS 49
// using cast operator
int b = static_cast<int>(f);
cout << b;
OUTPUT:
KEY TAKEAWAYS
• A type cast is basically a conversion from one type to another.
• Implicit Type Conversion also known as ‘automatic type conversion’.
• Explicit Type Conversion process is also called type casting and it is user-defined. Here
the user can typecast the result to make it of a particular data type.
C++ BASICS 50
11. C++ Basics
C++ BASICS 2
C++ BASICS 3
Example of if in C++
#include <iostream>
int main ()
int i = 10;
if (i > 15)
Output
I am Not in if
C++ BASICS 4
LOOP STATEMENTS
C++ programming language provides the following type of loops to handle looping
requirements.
while loop
1
Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop
body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
C++ BASICS 5
Example of For Loop in C++
#include <iostream>
int main ()
return 0;
Output
Hello World
Hello World
Hello World
Hello World
Hello World
KEY TAKEAWAYS
● Looping Statements like while loop, do while loop & for loop.
C++ BASICS 6
12. FUNCTIONS
FUNCTIONS
12.1 BASIC OF FUNCTION, PARAMETER PASSING MECHANISM
FUNCTION IN C++
A function is a set of statements that take inputs, do some specific computation, and produce
output. The idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different inputs, we can
call the function.
In simple terms, a function is a block of code that only runs when it is called.
Syntax:
FUNCTIONS
FUNCTION DECLARATION
A function declaration tells the compiler about the number of parameters function takes data-
types of parameters, and returns the type of function. Putting parameter names in the function
declaration is optional in the function declaration, but it is necessary to put them in the
definition. Below are an example of function declarations. (Parameter names are not there in
the below declarations)
TYPES OF FUNCTIONS
FUNCTIONS
USER DEFINED FUNCTION
LIBRARY FUNCTION
Library functions are also called “builtin Functions“. These functions are a part of a compiler
package that is already defined and consists of a special function with special and different
meanings. Builtin Function gives us an edge as we can directly use them without defining them
whereas in the user-defined function we have to declare and define a function before using
them.
The parameters passed to function are called actual parameters. For example, in the program
below, 5 and 10 are actual parameters.
The parameters received by the function are called formal parameters. For example, in the
below program x and y are formal parameters.
FUNCTIONS
(Figure 4: Formal Parameter and Actual Parameter)
1. Pass by Value: In this parameter passing method, values of actual parameters are copied
to the function’s formal parameters and the two types of parameters are stored in
different memory locations. So any changes made inside functions are not reflected in
the actual parameters of the caller.
2. Pass by Reference: Both actual and formal parameters refer to the same locations, so
any changes made inside the function are actually reflected in the actual parameters of
the caller.
Function Definition:
Pass by value is used where the value of x is not modified using the function fun().
The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies
the value at the address ptr. The dereference operator * is used to access the value at an
address. In the statement ‘*ptr = 30’, the value at address ptr is changed to 30. The address
operator & is used to get the address of a variable of any data type. In the function call
statement ‘fun(&x)’, the address of x is passed so that x can be modified using its address.
A copy of value is passed to the function An address of value is passed to the function
Actual and formal arguments will be created Actual and formal arguments will be created
in in
different memory location same memory location.
FUNCTIONS
Points to Remember About Functions in C++
1. Most C++ program has a function called main() that is called by the operating system
when a user runs the program.
2. Every function has a return type. If a function doesn’t return any value, then void is used
as a return type. Moreover, if the return type of the function is void, we still can use the
return statement in the body of the function definition by not specifying any constant,
variable, etc. with it, by only mentioning the ‘return;’ statement which would symbolize
the termination of the function as shown below:
void function name(int a)
3. To declare a function that can only be called without any parameter, we should use
“void fun(void)“. As a side note, in C++, an empty list means a function can only be
called without any parameter. In C++, both void fun() and void fun(void) are same.
MAIN FUNCTION
The main function is a special function. Every C++ program must contain a function named
main. It serves as the entry point for the program. The computer will start running the code
from the beginning of the main function.
1. Without parameters
// Without Parameters
2. With parameters:
// With Parameters
FUNCTIONS
The reason for having the parameter option for the main function is to allow input from the
command line. When you use the main function with parameters, it saves every group of
characters (separated by a space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return
statement in the code. The number that is returned is used to inform the calling program what
the result of the program’s execution was. Returning 0 signals that there were no problems.
KEY TAKEAWAYS
• A function is a set of statements that take inputs, do some specific computation, and
produce output. The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and again for
different inputs, we can call the function.
• A function declaration tells the compiler about the number of parameters function takes
data-types of parameters, and returns the type of function.
• The main function is a special function. Every C++ program must contain a function
named main. It serves as the entry point for the program.
FUNCTIONS
12. FUNCTIONS
FUNCTIONS 14
12.2 INLINE FUNCTION
INLINE FUNCTION
C++ provides inline functions to reduce the function call overhead. An inline function is a
function that is expanded in line when it is called. When the inline function is called whole code
of the inline function gets inserted or substituted at the point of the inline function call. This
substitution is performed by the C++ compiler at compile time. An inline function may increase
efficiency if it is small.
Syntax:
// function code
FUNCTIONS 15
Remember, inlining is only a request to the compiler, not a command. The compiler can ignore
the request for inlining.
When the program executes the function call instruction the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack,
and finally transfers control to the specified function. The CPU then executes the function code,
stores the function return value in a predefined memory location/register, and returns control
to the calling function. This can become overhead if the execution time of the function is less
than the switching time from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of the function call is
usually insignificant compared to the amount of time the function takes to run. However, for
small, commonly-used functions, the time needed to make the function call is often a lot more
than the time needed to actually execute the function’s code. This overhead occurs for small
functions because the execution time of a small function is less than the switching time.
FUNCTIONS 16
1. The added variables from the inlined function consume additional registers, After the in-
lining function if the variable number which is going to use the register increases then
they may create overhead on register variable resource utilization. This means that
when the inline function body is substituted at the point of the function call, the total
number of variables used by the function also gets inserted. So the number of registers
going to be used for the variables will also get increased. So if after function inlining
variable numbers increase drastically then it would surely cause overhead on register
utilization.
2. If you use too many inline functions then the size of the binary executable file will be
large, because of the duplication of the same code.
3. Too much inlining can also reduce your instruction cache hit rate, thus reducing the
speed of instruction fetch from that of cache memory to that of primary memory.
4. The inline function may increase compile time overhead if someone changes the code
inside the inline function then all the calling location has to be recompiled because the
compiler would be required to replace all the code once again to reflect the changes,
otherwise it will continue with old functionality.
5. Inline functions may not be useful for many embedded systems. Because in embedded
systems code size is more important than speed.
6. Inline functions might cause thrashing because inlining might increase the size of the
binary executable file. Thrashing in memory causes the performance of the computer to
degrade.
INLINE FUNCTION AND CLASSES
It is also possible to define the inline function inside the class. In fact, all the functions defined
inside the class are implicitly inline. Thus, all the restrictions of inline functions are also applied
here. If you need to explicitly declare an inline function in the class then just declare the
function inside the class and define it outside the class using the inline keyword.
Syntax:
class S
public:
FUNCTIONS 17
// function body
};
The above style is considered a bad programming style. The best programming style is to just
write the prototype of the function inside the class and specify it as an inline in the function
definition.
KEY TAKEAWAYS
• C++ provides inline functions to reduce the function call overhead. An inline function is a
function that is expanded in line when it is called.
• It is also possible to define the inline function inside the class. In fact, all the functions
defined inside the class are implicitly inline. Thus, all the restrictions of inline functions
are also applied here.
FUNCTIONS 18
12. FUNCTIONS
FUNCTIONS
12.3 MACRO VS INLINE
1. INLINE
An inline function is a normal function that is defined by the inline keyword. An inline function
is a short function that is expanded by the compiler. And its arguments are evaluated only once.
An inline functions are the short length functions that are automatically made the inline
functions without using the inline keyword inside the class.
#include <iostream>
// Inline function
return (a > b) ? a : b;
int main()
cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;
cout << "Max (20, 0): " << Maximum(20, 0) << endl;
FUNCTIONS
return 0;
Output:
2. MACRO
It is also called preprocessors directive. The macros are defined by the #define keyword. Before
the program compilation, the preprocessor examines the program whenever the preprocessor
detects the macros then preprocessor replaces the macro by the macro definition.
Syntax of Macro:
Example of Macro:
#include <iostream>
int main()
FUNCTIONS
return 0;
Output:
Through inline function, the class’s data Whereas macro can’t access the class’s data
2.
members can be accessed. members.
In the case of inline function, the Whereas in the case of macros, the program
3.
program can be easily debugged. can’t be easily debugged.
In C++, inline may be defined either Whereas the macro is all the time defined at
5.
inside the class or outside the class. the beginning of the program.
FUNCTIONS
S.NO Inline Macro
7. Inline is not as widely used as macros. While the macro is widely used.
Inline is not used in competitive While the macro is very much used in
8.
programming. competitive programming.
Inline function is terminated by the While the macro is not terminated by any
9.
curly brace at the end. symbol, it is terminated by a new line.
KEY TAKEAWAYS
• An inline function is a normal function that is defined by the inline keyword. An inline
function is a short function that is expanded by the compiler.
• Macro is also called preprocessors directive. The macros are defined by the #define
keyword. Before the program compilation, the preprocessor examines the program
whenever the preprocessor detects the macros then preprocessor replaces the macro
by the macro definition.
FUNCTIONS
12. FUNCTIONS
FUNCTIONS 24
12.4 FUNCTION OVERLOADING, DEFAULT ARGUMENTS
FUNCTION OVERLOADING
If multiple functions having same name but parameters of the functions should be different is
known as Function Overloading.
If we have to perform only one operation and having same name of the functions increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the function such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you to understand the behavior of the function
because its name differs.
The parameters should follow any one or more than one of the following conditions for
Function overloading:
add(int a, int b)
add(double a, double b)
FUNCTIONS 25
• ELSE ERROR
1. Function overloading and return type
2. Functions that cannot be overloaded in C++
3. Function overloading and const keyword
4. Function Overloading vs Function Overriding in C++
DEFAULT ARGUMENT IN C++
1) The following is a simple C++ example to demonstrate the use of default arguments.
Here, we don’t have to write 3 sum functions; only one function works by using the
default values for 3rd and 4th arguments.
// CPP Program to demonstrate Default Arguments
#include <iostream>
return (x + y + z + w);
// Driver Code
int main()
// Statement 1
FUNCTIONS 26
// Statement 2
// Statement 3
return 0;
Output:
25
50
80
Explanation: In statement 1, only two values are passed, hence the variables z and w
take the default values of 0. In statement 2, three values are passed, so the value of z is
overridden with 25. In statement 3, four values are passed, so the values of z and w are
overridden with 25 and 30 respectively.
2) If function overloading is done containing the default arguments, then we need to make
sure it is not ambiguous to the compiler, otherwise it will throw an error. The following
is the modified version of the above program:
// CPP Program to demonstrate Function overloading in
// Default Arguments
#include <iostream>
return (x + y + z + w);
FUNCTIONS 27
}
return (x + y + z + w);
// Driver Code
int main()
return 0;
Error:
FUNCTIONS 28
int sum(int, int, float, float)
3) A constructor can contain default parameters as well. A default constructor can either
have no parameters or parameters with default arguments.
// CPP code to demonstrate use of default arguments in
// Constructors
#include <iostream>
class A {
private:
int var = 0;
public:
return;
int getVar(){
};
int main(){
FUNCTIONS 29
A a(1);
a.setVar(2);
/* ANOTHER APPROACH:
A *a = new A(1);
a->setVar(2);
*/
KEY POINTS:
• Default arguments are different from constant arguments as constant arguments can’t
be changed whereas default arguments can be overwritten if required.
• Default arguments are overwritten when the calling function provides values for them.
For example, calling the function sum(10, 15, 25, 30) overwrites the values of z and w to
25 and 30 respectively.
• When a function is called, the arguments are copied from the calling function to the
called function in the order left to right. Therefore, sum(10, 15, 25) will assign 10, 15,
and 25 to x, y, and z respectively, which means that only the default value of w is used.
• Once a default value is used for an argument in the function definition, all subsequent
arguments to it must have a default value as well. It can also be stated that the default
arguments are assigned from right to left. For example, the following function definition
is invalid as the subsequent argument of the default variable z is not default.
// Invalid because z has default value, but w after it doesn't have a default value
FUNCTIONS 30
• It helps in reducing the size of a program.
• It provides a simple and effective programming approach.
• Default arguments improve the consistency of a program.
FUNCTIONS 31
13.1 OBJECTS AND CLASSES
Class in C++ is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A C++ class is like a blueprint for an
object. For Example: Consider the Class of Cars. There may be many cars with different names
and brands but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, and
mileage are their properties.
• A Class is a user-defined data type that has data members and member functions.
• Data members are the data variables and member functions are the functions used to
manipulate these variables together, these data members and member functions define
the properties and behavior of the objects in a Class.
• In the above example of class Car, the data member will be speed limit, mileage, etc,
and member functions can be applying brakes, increasing speed, etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated.
A class is defined in C++ using the keyword class followed by the name of the class. The body of
the class is defined inside the curly brackets and terminated by a semicolon at the end.
Declaring Objects:
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName;
KEY TAKEAWAYS
• Class in C++ is the building block that leads to Object-Oriented programming.
• It is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class.
• A Class is a user-defined data type that has data members and member functions.
• An Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
• When a class is defined, only the specification for the object is defined; no memory or
storage is allocated.
Static data members are class members that are declared using static keywords. A static
member has certain special characteristics which are as follows:
• Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
• It is initialized before any object of this class is created, even before the main starts.
• It is visible only within the class, but its lifetime is the entire program.
Syntax:
Below is the C++ program to demonstrate the working of static data members:
#include <iostream>
class A {
public:
A()
endl;
};
static A a;
public:
B()
endl;
};
// Driver code
int main()
B b;
return 0;
• Static members are only declared in a class declaration, not defined. They must be
explicitly defined outside the class using the scope resolution operator.
As told earlier, the static members are only declared in the class declaration. If we try to access
the static data member without an explicit definition, the compiler will give an error.
Below is the C++ program to show when static member ‘a’ is accessed without explicit
definition:
#include <iostream>
class A {
int x;
public:
A()
endl;
};
class B {
static A a;
public:
B()
endl;
static A getA()
return a;
};
int main()
B b;
A a = b.getA();
return 0;
Explanation: Here static member ‘a’ is accessed without explicit definition. If we add the
definition, the program will work fine and call A’s constructor.
To access the static data member of any class we have to define it first.
Below is the C++ program to show how to resolve the above error:
#include <iostream>
class A {
int x;
public:
A()
endl;
};
static A a;
public:
B()
endl;
static A getA()
return a;
};
// Definition of a
A B::a;
// Driver code
int main()
A a = b1.getA();
return 0;
NOTE: Static data members can only be defined globally in C++. The only exception to this are
static const data members of integral type which can be initialized in the class declaration.
We can access any static member without any object by using the scope resolution operator
directly with the class name.
Below is the C++ program to show access to the static member without an object:
// C++ Program to demonstrate static members can be accessed without any object
#include <iostream>
class A {
int x;
public:
A()
endl;
};
class B {
public:
B()
endl;
static A getA()
return a;
};
// Definition of a
A B::a;
// Driver code
int main()
A a = B::getA();
return 0;
CONSTRUCTOR
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor in
C++ has the same name as the class or structure. Constructor is invoked at the time of object
creation. It constructs the values i.e. provides data for the object which is why it is known as
constructors.
• Constructor is a member function of a class, whose name is same as the class name.
• Constructor is a special type of member function that is used to initialize the data
members for an object of a class automatically, when an object of the same class is
created.
• Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
• Constructor do not return value, hence they do not have a return type.
The prototype of the constructor looks like
<class-name> (list-of-parameters);
Constructor can be defined inside the class declaration or outside the class declaration
//constructor definition
//constructor definition
TYPES OF CONSTRUCTOR
• Default constructor
• Parameterized constructor
• Overloaded constructor
• Constructor with default value
• Copy constructor
• Inline constructor
A constructor is different from normal functions in following ways:
Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the
options? The first one you go to a shop and say give me a marker. So just saying give me a
marker mean that you did not set which brand name and which color, you didn’t mention
anything just say you want a marker. So when we said just I want a marker so whatever the
frequently sold marker is there in the market or in his shop he will simply hand over that. And
this is what a default constructor is! The second method is you go to a shop and say I want a
marker a red in color and XYZ brand. So you are mentioning this and he will give you that
marker. So in this case you have given the parameters. And this is what a parameterized
constructor is! Then the third one you go to a shop and say I want a marker like this (a physical
marker on your hand). So the shopkeeper will see that marker. Okay, and he will give a new
marker for you. So copy of that marker. And that’s what a copy constructor is!
TYPES OF CONSTRUCTORS
1. Default Constructors: Default constructor is the constructor which doesn’t take any
argument. It has no parameters. It is also called a zero-argument constructor.
Student s;
3. Copy Constructor:
A copy constructor is a member function that initializes an object using another object
of the same class. A detailed article on Copy Constructor.
Sample(Sample &t)
id=t.id;
DESTRUCTOR
A destructor is also a special member function as a constructor. Destructor destroys the class
objects created by the constructor. Destructor has the same name as their class name preceded
by a tilde (~) symbol. It is not possible to define more than one destructor. The destructor is
only one way to destroy the object created by the constructor. Hence destructor can-not be
overloaded. Destructor neither requires any argument nor returns any value. It is automatically
called when the object goes out of scope. Destructors release memory space occupied by the
objects created by the constructor. In destructor, objects are destroyed in the reverse of object
creation.
~ <class-name>()
<class-name>: : ~ <class-name>(){}
CHARACTERISTICS OF A DESTRUCTOR
1. Destructor is invoked automatically by the compiler when its corresponding constructor
goes out of scope and releases the memory space that is no longer required by the
program.
2. Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.
KEY TAKEWAYS
• Constructor is a member function of a class, whose name is same as the class name.
• Constructors are mostly declared in the public section of the class though it can be
declared in the private section of the class.
• A destructor is also a special member function as a constructor. Destructor destroys the
class objects created by the constructor. Destructor has the same name as their class
name preceded by a tilde (~) symbol.
OPERATOR OVERLOADING
C++ provides a special function to change the current functionality of some operators within its
class which is often called as operator overloading. Operator Overloading is the method by
which we can change the function of some specific operators to do some different tasks.
Syntax:
Function Body
Here,
1. In the case of a non-static member function, the binary operator should have only one
argument and the unary should not have an argument.
2. In the case of a friend function, the binary operator should have only two arguments
and the unary should have only one argument.
3. All the class member objects should be public if operator overloading is implemented.
4. Operators that cannot be overloaded are .* :: ?:
5. Operators that cannot be overloaded when declaring that function as friend function
are = () [] ->.
Let us consider overloading (-) unary operator. In the unary operator function, no arguments
should be passed. It works only with one class object. It is the overloading of an operator
operating on a single operand.
Example: Assume that class Distance takes two member objects i.e. feet and inches, and
creates a function by which the Distance object should decrement the value of feet and inches
by 1 (having a single operand of Distance Type).
In the binary operator overloading function, there should be one argument to be passed. It is
the overloading of an operator operating on two operands. Below is the C++ program to show
the overloading of the binary operator (+) using a class Distance with two distant objects.
Example: Below is the C++ program to show binary operator overloading using a friend
function.
#include <iostream>
class Distance {
public:
Distance()
this->feet = 0;
this->inch = 0;
Distance(int f, int i)
this->feet = f;
this->inch = i;
Distance&);
};
// Call by reference
Distance& d2)
Distance d3;
return d3;
// Driver Code
int main()
Distance d3;
d3 = d1 + d2;
return 0;
Explanation: The operator function is implemented outside of the class scope by declaring that
function as the friend function.
In these ways, an operator can be overloaded to perform certain tasks by changing the
functionality of operators.
KEY TAKEAWAYS
• C++ provides a special function to change the current functionality of some operators
within its class which is often called as operator overloading.
• In the unary operator function, no arguments should be passed. It works only with one
class object. It is the overloading of an operator operating on a single operand.
• In the binary operator overloading function, there should be one argument to be
passed. It is the overloading of an operator operating on two operands.
• . All the working and implementation would same as the binary operator function
except this function will be implemented outside the class scope.
C++ BASICS 1
13.5 TYPECASTING IN C++
TYPECASTING IN C++
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
• Done by the compiler on its own, without any external trigger from the user.
• Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
• All the data types of the variables are upgraded to the data type of the variable with
largest data type.
• It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).
#include <iostream>
int main()
C++ BASICS 2
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
float z = x + 1.0;
return 0;
Output:
x = 107
y=a
z = 108
This process is also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
C++ BASICS 3
Example:
#include <iostream>
int main()
double x = 1.2;
return 0;
Output:
Sum = 2
• Conversion using Cast operator: A Cast operator is an unary operator which forces
one data type to be converted into another data type.
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
Example:
#include <iostream>
C++ BASICS 4
using namespace std;
int main()
float f = 3.5;
int b = static_cast<int>(f);
cout << b;
OUTPUT:
KEY TAKEAWAYS
C++ BASICS 5