Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Fundamentals of Programming

The document outlines the Fundamentals of Programming course for the Online MCA Program at Parul University, authored by Dr. Pratik Patel. It covers key topics such as the features and structure of C programming, algorithms, flowcharts, and various programming concepts including data types, operators, control structures, and memory management. Additionally, it emphasizes the importance of documentation, modularity, and the historical context of the C programming language.

Uploaded by

TYBCA 2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Fundamentals of Programming

The document outlines the Fundamentals of Programming course for the Online MCA Program at Parul University, authored by Dr. Pratik Patel. It covers key topics such as the features and structure of C programming, algorithms, flowcharts, and various programming concepts including data types, operators, control structures, and memory management. Additionally, it emphasizes the importance of documentation, modularity, and the historical context of the C programming language.

Uploaded by

TYBCA 2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 309

FUNDAMENTALS OF PROGRAMMING

Centre for Distance and Online Education


Online MCA Program
Fundamentals of Programming

Semester: 1

Author

Dr. Pratik Patel, Assistant Professor, Online Degree-CDOE,


Parul University

Credits
Centre for Distance and Online Education,
Parul University,

Post Limda, Waghodia,

Vadodara, Gujarat, India

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

SUB LESSON 5.3


BREAK CONTINUE GO TO STATEMENT

SUB LESSON 6.1


DECLARATION ,INITIALIZATION , ACCESS OF ONE DIMENSIONAL & TWO
DIMENSIONAL ARRAYS
SUB LESSON 6.2
PROGRAMS USING ONE DIMENSIONAL AND TWO DIMENSIONAL ARRAY
SUB LESSON 6.3
TRANSPOSING MATRICES : SORTING & SEARCH METHODS
SUB LESSON 7.1
STRING & STRING STORAGE

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

⮚ C programming language was developed in 1972 by Dennis Ritchie at Bell laboratories of


AT&T (American Telephone & Telegraph), located in the U.S.A.
⮚ Dennis Ritchie is known as the founder of the c language.
⮚ It was developed to overcome the problems of previous languages such as B, BCPL, etc.
⮚ Initially, C language was developed to be used in the UNIX operating system. It inherits
many features of previous languages such as B and BCPL.
⮚ The language was named “C” because its features were derived from “B”, which
according to Ken Thompson was a stripped-down version of the type less BCPL
programming language.
⮚ In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C (The C Programming Language), now known as the K&R standard. Both
of them added lots of features to the language “C”.
⮚ Until the early 1980s, although compilers existed for a variety of machine architectures
and operating systems, the language was almost exclusively associated with Unix
⮚ In 1989 the American National Standards Institute (ANSI) committee published a
standard for C (generally called “ANSI C”)
⮚ Today, the UNIX operating system, the C compiler, and essentially all UNIX applications
programs have been written in C

Language Year Developed By

ALGOL 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

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

Figure 1: Structure of C Programming

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.

Example: /* This program calculates the sum of two numbers */

2. PREPROCESSOR SECTION / LINK SECTION

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

4. GLOBAL DECLARATION SECTION

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:

int num = 18;

5. MAIN () FUNCTION SECTION

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 ()

6. SUB PROGRAMS SECTION

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

● C programming language was developed in 1972 by Dennis Ritchie at Bell


Laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A.
● Structure of C Programming consist of

○ Documentation Section
○ Pre-processor Section / Link Section
○ Definition Section
○ Global Declaration Section
○ Main ( ) Function Section
○ Sub Programs Section

● Features of C Language

○ Simple and Efficient ○ Portability

○ Fast ○ Extensibility

BASIC OF C PROGRAMMING
8
○ Function-Rich Libraries ○ Mid-Level Programming
Language
○ Dynamic Memory
Management ○ Pointers

○ Modularity with Structured ○ Recursion


Language

BASIC OF C PROGRAMMING
9
1. BASIC OF C PROGRAMMING

1.2 ALGORITHM AND FLOWCHART


ALGORITHM

Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in


a certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language.

Instructions are written in the natural language. It is also called step by step solution.

ADVANTAGES OF ALGORITHMS:

1. It is a step-wise representation of a solution to a given problem, which makes it easy


to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps hence, it
is easier for programmer to convert it into an actual program.

DISADVANTAGES OF ALGORITHMS:

1. Algorithms is Time consuming.


2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms

Example 1:

Write an algorithm to find out sum of two numbers.

Step 1: Start

Step 2: Read num1 and num2 from the user

Step 3: Add num1 and num2 and store the result in sum

Step 4: Print the value of sum

Step 5: Stop

Example 2

Write an algorithm to find out area of square.

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 4: Print the value of area

Step 5: Stop

Example 3

Write an algorithm to find out minimum from three numbers.

Step 1: Input three numbers: a, b, c

Step 2: if a < b then go to next step otherwise (else) go to step 8

Step 3: if a < c then go to next step else go to step 6

Step 4: print “minimum =”, a

Step 5: stop

Step 6: print “minimum =”, c

Step 7: stop

Step 8: if b < c then go to next step else go to step 11

Step 9: print “minimum =”, b

Step 10: stop

Step 11: print “minimum =”, c

Step 12: 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.

In C language, flowcharts can be used to represent the control structures used in


programming such as loops, conditional statements, and function calls. For example, a
flowchart can be used to represent the steps involved in a "for" loop or an "if-else"
statement.

Flowcharts typically use standard symbols to represent different types of operations or


steps, such as rectangles for processes, diamonds for decision points, and arrows for
directional flow. By following the flowchart, a programmer can easily visualize the logic of
the program and identify potential errors or inefficiencies in the design.

Overall, flowcharts can be a useful tool in C programming for designing, understanding, and
communicating the structure and logic of a program.

Figure 1 : Flowchart symbols

BASIC OF C PROGRAMMING
4
ADVANTAGES OF FLOWCHART

Following are the various advantages of flowchart:

1. Communication: A flowchart is a better way of communicating the logic of a


program.
2. Synthesis: Flowchart is used as working models in designing new programs and
software systems.
3. Efficient Coding: Flowcharts act as a guide for a programmer in writing the actual
code in a high-level language.
4. Proper Debugging: Flowcharts help in the debugging process.
5. Effective Analysis: Effective analysis of logical programs can be easily done with the
help of a related flowchart.
6. Proper Documentation: Flowchart provides better and proper documentation. It
consists of various activities such as collecting, organizing, storing, and maintaining
all related program records.
7. Testing: A flowchart helps in the testing process.
8. Efficient program maintenance: The maintenance of the program becomes easy
with the help of a flowchart.

DISADVANTAGES OF FLOWCHART

Following are the various disadvantages of flowchart:

1. Time-consuming: Designing a flowchart is a very time-consuming process.


2. Complex: It isn't easy to draw a flowchart for large and complex programs.
3. There is no standard in the flowchart; there is no standard to determine the
quantity of detail.
4. Difficult to modify: It is very difficult to modify the existing 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.

Figure 2: Flowchart for Adding Two Numbers

KEY TAKEAWAYS

● Algorithm is a step-by-step procedure, which defines a set of instructions to be


executed in a certain order to get the desired output.
● It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
● Every step in an algorithm has its own logical sequence so it is easy to debug.
● Flowcharts are graphical representations of the steps or processes involved in
solving a problem or completing a task.

● 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
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

1.3 TYPES OF ERRORS, DEBUGGING, STEPWISE EXECUTION OF


PROGRAM
TYPES OF ERRORS

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.

There are 5 types of error in C:

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.

// C program to demonstrate a syntax error due to missing semi colon

#include <stdio.h>

int main()

{ // missing semicolon

printf("Geeks for geeks!")

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

// C program to demonstrate a runtime error

#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.

// C program to demonstrate a logical error

#include <stdio.h>

BASIC OF C PROGRAMMING
3
int main()

int i;

for(i = 0; i <= 5; i++);

printf("Hello World");

return 0;

Output: Hello World

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.

Example: Below is the C program to show the linker error.

// C program to demonstrate a linker error

#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.

// C program to demonstrate a 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. Understand in what scenarios the bug in a program is happening

2. Inspect the value of variables at different stages of a program

3. Figure out if a part of the code is executed or not.

Following are the common ways of debugging a bug in C:

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.

STEPWISE EXECUTION OF PROGRAM

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.

(Figure 1: Execution of Program)

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.

Let us look at the image syntax of the steps of execution of C program.

(Figure 2: Steps of Execution of Program)

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

Type of Character Description 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

Special Characters – `~@!$#^*%&()[]{}<>+=_–|/\;:‘“,.?

White Spaces – Blank Spaces, Carriage Return, Tab, New Line

Table 1 : Types of Characters

BASIC CONSTANTS, VARIABLES AND DATA TYPES


2
ASCII VALUES

⮚ 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

BASIC CONSTANTS, VARIABLES AND DATA TYPES


3
● 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.

● 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.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


4
BASIC CONSTANTS, VARIABLES
AND DATA TYPES
2.2 KEYWORDS, IDENTIFIERS, CONSTANT, VARIABLES

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.

auto break case char

const continue default do

double else enum extern

float for goto if

int long register return

short signed sizeof static

struct switch typedef union

unsigned void volatile while

Table 1 : Keywords in C

BASIC CONSTANTS, VARIABLES AND DATA TYPES


2
IDENTIFIERS

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.

⮚ There are some defined rules in C language for declaring identifiers:


1. Identifiers shouldn't begin with any numerical digit and hence, the first character
must be either an underscore or an alphabet.
2. Identifiers are case-sensitive and hence, both lowercase and uppercase letters are
distinct.
3. The length of identifiers shouldn't be more than 31 characters.
4. Commas and blank spaces are not allowed while declaring an identifier.
5. Also, the most important rule is that we can't use keywords as identifiers because
keywords in C language are reserved words for special purposes only.

Examples:

1. count
2. num_1
3. sumOfNumbers
4. _temp
5. MAX_SIZE

It's important to note that C is a case-sensitive language, so identifiers with different


capitalization are considered different identifiers. For example, "count" and "Count" would
be treated as two different identifiers

BASIC CONSTANTS, VARIABLES AND DATA TYPES


3
CONSTANTS

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.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


4
VARIABLES

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

⮚ Rules for defining variables:


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with
a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

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.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


5
2. Global Variables: These are variables declared outside any function or block and
have global scope. They can be accessed from anywhere in the program. Global
variables are initialized only once when the program starts, and they retain their
value throughout the program's execution.

⮚ There are 3 aspects of defining a variable:


1. Variable Declaration:

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.

Figure 1: Initialization of Variable

KEY TAKEAWAYS

BASIC CONSTANTS, VARIABLES AND DATA TYPES


6
● 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.

● There are a total of 32 keywords supported by the C language.

● Identifiers 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.

● 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.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


7
2. BASIC CONSTANTS,
VARIABLES AND DATA TYPES
2.3 DATA TYPES, COMMENTS

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.

● The data types in C can be classified as follows:

Figure 1 : Data Types in C

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.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


2
We can determine the size of the int data type by using the size of operator in C.

● Range: -2,147,483,648 to 2,147,483,647


● Size: 2 bytes or 4 bytes
● Format Specifier: %d

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.

● Range: (-128 to 127)


● Size: 1 byte
● Format Specifier: %c

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.

● Range: 1.2E-38 to 3.4E+38


● Size: 4 bytes
● Format Specifier: %f

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

BASIC CONSTANTS, VARIABLES AND DATA TYPES


3
floating-point type. It can easily accommodate about 16 to 17 digits after or before a
decimal point.

● Range: 1.7E-308 to 1.7E+308


● Size: 8 bytes
● Format Specifier: %lf

VOID DATA TYPES

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:

Data Type Memory (bytes) Range Format Specifier

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

signed char 1 -128 to 127 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

Table 1

COMMENTS

BASIC CONSTANTS, VARIABLES AND DATA TYPES


4
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.

Comments can be singled-lined or multi-lined.

SINGLE-LINE COMMENT

⮚ Single-line comments start with two forward slashes (//).


⮚ Any text between // and the end of the line is ignored by the compiler (will not be
executed).

Example:

// This is a single line comment

MULTI-LINE COMMENT

⮚ Multi-line comments start with /* and ends with */.


⮚ Any text between /* and */ will be ignored by the compiler.

Example:

/* this is a multi-line comment,

and it will be ignored by the compiler*/

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.

● Comments are of two types Single lined and Multi lined

BASIC CONSTANTS, VARIABLES AND DATA TYPES


5
● Single-line comments start with two forward slashes (//).

● Multi-line comments start with /* and ends with */.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


6
2.BASIC CONSTANTS,
VARIABLES AND DATA TYPES
2.4 C PROGRAMMING APPLICATIONS AND IMPORTANCE

C PROGRAMMING LANGUAGE

⮚ The C language is a high-level, general-purpose programming language. It provides a


straightforward, consistent, powerful interface for programming systems. That's why
the C language is widely used for developing system software, application software,
and embedded systems.
⮚ The C programming language has been highly influential, and many other languages
have been derived from it. For example, C++ and Java are two popular modern
dialects of C.
⮚ It was developed to overcome the challenges of BASIC, B, and BPCL programming
languages. It had both high-level functionality and detailed features required to
program an operating system.

APPLICATIONS OF C LANGUAGE

1. Operating Systems: C is the primary language used to develop operating systems like
Windows, Linux, and UNIX.

2. System Programming: C is used to develop system software such as compilers,


assemblers, and device drivers.

3. Embedded Systems: C is used to develop software for embedded systems such as


cell phones, routers, and microcontrollers.

4. Gaming: C is widely used in game development to create high-performance games.

5. Networking: C is used to develop networking protocols, such as TCP/IP, which are


used to connect computers and other devices on a network.

6. Artificial Intelligence: C is used to develop AI applications, such as natural language


processing and machine learning.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


2
7. Graphics: C is used to develop graphics libraries and applications, such as OpenGL
and DirectX, which are used to create high-performance graphics in video games,
simulations, and other applications.

8. Database Systems: C is used to develop database management systems, such as


MySQL and PostgreSQL, which are used to store and manage large amounts of data.

9. Web Development: C is used in web development to create server-side scripts that


handle the back-end processing of web applications.

10. Security: C is used in developing security-related software such as firewalls and


encryption software.

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.

BASIC CONSTANTS, VARIABLES AND DATA TYPES


3
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.
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.

KEY TAKEAWAYS

● The C language is a high-level, general-purpose programming language. It provides a


straightforward, consistent, powerful interface for programming systems.

● 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

○ Simple and Efficient ○ Extensibility

○ Fast ○ Function-Rich Libraries

○ Portability

BASIC CONSTANTS, VARIABLES AND DATA TYPES


4
○ Dynamic Memory ○ Mid-Level Programming
Management Language

○ Modularity with Structured ○ Pointers


Language
○ Recursion

BASIC CONSTANTS, VARIABLES AND DATA TYPES


5
3. OPERATOR

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.

For example, ‘+’ is an operator used for addition, as shown below:

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.

C has many built-in operators and can be classified into 4 types:

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

These operators are used to perform arithmetic/mathematical operations on operands.


Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:

a) Unary 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 Description Example

— Decrease of the integer value by var = A–


the decrement operator by one

++ Increase of the integer value by the var = A++


increment operator by one

– Unary minus var = -A

+ Unary plus var = +A

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 Description Example

– Subtraction of the second variable var = A – B = -5


from the first one

+ Addition of two operands var = A + B = 15

/ Division of the numerator by the de- var = B / A = 2


numerator

* Multiplication of both the operands var = A * B = 50

% The modulus operator and the var = B % A = 0


remainder after the division of an
integer

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.

WHAT COMES FIRST IN OPERATION — THE = OR THE ++?

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.

Also, what if a complex condition occurs, such as:

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.

EXAMPLES OF ARITHMETIC OPERATORS

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;

printf(“Line 1 – Value of r is %d\n”, r );

r = p – q;

printf(“Line 1 – Value of r is %d\n”, r );

r = p * q;

printf(“Line 1 – Value of r is %d\n”, r );

r = p / q;

printf(“Line 1 – Value of r is %d\n”, r );

r = p % q;

printf(“Line 1 – Value of r is %d\n”, r );

r = p++;

printf(“Line 1 – Value of r is %d\n”, r );

r = p–;

printf(“Line 1 – Value of r is %d\n”, r );

Once you have completed compiling and executing the program mentioned above, it will
produce the results as follows:

Line 1 – The value of r is 31

Line 2 – The value of r is 11

OPERATOR
Line 3 – The value of r is 210

Line 4 – The value of r is 2

Line 5 – The value of r is 1

Line 6 – The value of r is 21

Line 7 – The value of r is 22

KEY TAKEAWAYS

ARITHMETIC OPERATORS

These operators are used to perform arithmetic/mathematical operations on operands.


Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:

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

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.

NOT EQUAL TO OPERATOR

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.

LESS THAN OPERATOR

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.

Less than or equal to Operator

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.

GREATER THAN OR EQUAL TO OPERATOR

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.

Logical Operators are used to combine two or more conditions/constraints or to complement


the evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or 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)

TYPES OF LOGICAL OPERATORS IN C

We have three major logical operators in the C language:

● Logical NOT (!)


● Logical OR (||)
● Logical AND (&&)

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)

// Enroll the student

LOGICAL OR (||) OPERATOR

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 –

We can write the statement “It is a holiday, if it is Sunday or Saturday” programmatically as –

if (today == Sunday || today == Saturday)

// It is a holiday

Note – Don’t confuse bitwise OR | with logical OR ||.

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–

We can write the statement, “He is a handsome guy” programmatically as –

if (skill == ‘C’ && experience >= 2)

//He is a handsome guy

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

● Logical NOT (!)


● Logical OR (||)
● Logical AND (&&)

OPERATOR 14
3. OPERATOR

OPERATOR 15
3.5 TERNARY OPERATORS & OTHER OPERATORS

TERNARY OPERATORS:

‘C’ language provides? operator as a conditional operator. It is also known as a ternary


operator. It is used as shown below.

expr1? expr2: expr3;

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;

printf("Give two integer numbers\n");

scanf("%d %d",&x,&y);

max = (x>y) ? x: y; /* x>y is a logical expression */

min = (x<y) ? x: y; /* x<y is a logical expression */

printf("maximum of %d and %d is = %d\n",x,y,max);

printf("minimum of %d and %d is = %d\n",x,y,min);

OPERATOR 16
Output

-------------------------------------------------------------------------------

--------------------------

Give two integer numbers

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

Size of is much used in the C programming language.

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).

The comma operator has the lowest precedence of any C operator.

OPERATOR 17
Comma acts as both operator and separator.

C. CONDITIONAL OPERATOR

The conditional operator is of the form Expression1? Expression2: Expression3

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.

We may replace the use of if..else statements with conditional operators.

D. DOT (.) AND ARROW (->) OPERATORS

Member operators are used to reference individual members of classes, structures, and unions.

The dot operator is applied to the actual object.

The arrow operator is used with a pointer to an object.

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

D. DOT (.) AND ARROW (->) OPERATORS

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:

1. IMPLICIT TYPE CONVERSION

Implicit type conversion also known as ‘automatic type 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.

bool -> char -> short int -> int ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double

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).

Occurrences of Implicit Type Conversion in C

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

(Figure1: Type conversion)

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:

// C program to demonstrate explicit type casting

#include<stdio.h>

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;

OPERATOR 4
Output

sum = 2

(Figure1: Type conversion)

OPERATOR PRECEDENCE CHART

The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.

Precedence Operator Description Associativity

OPERATOR 5
Precedence Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

. Member selection via object name left-to-right

-> Member selection via a pointer left-to-right

1 a++/a– Postfix increment/decrement (a is a variable) left-to-right

++a/–a Prefix increment/decrement (a is a variable) right-to-left

+/- Unary plus/minus right-to-left

!~ Logical negation/bitwise complement right-to-left

2 (type) Cast (convert value to temporary value of type) right-to-left

OPERATOR 6
Precedence Operator Description Associativity

* Dereference right-to-left

& Address (of operand) right-to-left

sizeof Determine size in bytes on this implementation right-to-left

3 *,/,% Multiplication/division/modulus left-to-right

4 +/- Addition/subtraction left-to-right

5 << , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right

6 > , >= Relational greater than/greater than or equal to left-to-right

7 == , != Relational is equal to/is not equal to left-to-right

OPERATOR 7
Precedence Operator Description Associativity

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

= Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left

14 *= , /= Multiplication/division assignment right-to-left

OPERATOR 8
Precedence Operator Description Associativity

%= , &= Modulus/bitwise AND assignment right-to-left

^= , |= Bitwise exclusive/inclusive OR assignment right-to-left

<>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right

KEY TAKEAWAYS

TYPE CONVERSION IN C

1. IMPLICIT TYPE 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.

2. EXPLICIT TYPE CONVERSION

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

IF & IF ELSE STATEMENT 1


SUB LESSON 4.1

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.

(Figure 1: If Else Statement)

IF & IF ELSE STATEMENT 2


Decision-making statements in programming languages decide the direction of the flow of
program execution. Decision-making statements available in C or C++ are:
1.if statement
2.if-else statements
3.nested if statements
4.if-else-if ladder
5.switch statements
6.Jump Statements:
● break
● continue
● goto
● return
1. IF STATEMENT IN C/C++
if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement accepts boolean
values – if the value is true then it will execute the block of statements below it otherwise not.
If we do not provide the curly braces ‘{‘and ‘}’ after if(condition) then by default if statement
will consider the first immediately below statement to be inside its block.

Example:
If Ram can having 100 GeekBits then he can redeem these GeekBits and get the GFG T-shirt.
if (condition)
statement1;
statement2;

IF & IF ELSE STATEMENT 3


(Figure 1: If Else Statement)

// C program to illustrate If statement

#include <stdio.h>

int main()

int i = 10;

if (i > 15) {

IF & IF ELSE STATEMENT 4


printf("10 is greater than 15");

printf("I am Not in if");

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:

IF & IF ELSE STATEMENT 5


(Figure 1: If Else Statement)

KEY TAKEAWAYS

● Decision-making statements in programming languages decide the direction of the flow


of program execution.
● If statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not i.e if a certain
condition is true then a block of statement is executed otherwise not.

IF & IF ELSE STATEMENT 6


● 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.

IF & IF ELSE STATEMENT 7


4. NESTED IF STATEMENT

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

The Nested If in C Programming language Syntax is

if ( test condition 1)

//If the test condition 1 is TRUE then these it will check for test condition 2

if ( test condition 2)

//If the test condition 2 is TRUE, these statements execute

Test condition 2 True statements;

NESTED IF STATEMENT 9
}

else

//If the c test condition 2 is FALSE, then these statements execute

Test condition 2 False statements;

else

//If the test condition 1 is FALSE then these statements will be executed

Test condition 1 False statements;

NESTED IF STATEMENT 10
Flow Chart for Nested if in C

Programming

(Figure 1: flowchart for nested if)

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.

NESTED IF IN C PROGRAMMING EXAMPLE

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;

printf("Please Enter Your Age Here:\n");

scanf("%d",&age);

if ( age < 18 )

printf("You are Minor.\n");

printf("Not Eligible to Work");

else

if (age >= 18 && age <= 60 )

printf("You are Eligible to Work \n");

printf("Please fill in your details and apply\n");

else

NESTED IF STATEMENT 12
printf("You are too old to work as per the Government rules\n");

printf("Please Collect your pension! \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

The syntax for a switch statement in C programming language is as follows −

switch (expression) {

case constant-expression :
statement(s);
break; /* optional */

case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}
The following rules apply to a switch statement −
• The expression used in a switch statement must have an integral or enumerated
type, or be of a class type in which the class has a single conversion function to
an integral or enumerated type.
• You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in
the switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.

SWITCH STATEMENT 15
FLOW DIAGRAM

(Figure 2: switch Statement)

EXAMPLE
#include <stdio.h>

int main () {

/* local variable definition */


char grade = 'B';

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" );
}

printf("Your grade is %c\n", grade );

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.

C programming has two types of loops.

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

The syntax of the while loop is:

while (testExpression) {
// the body of the loop
}

(Figure 3: while loop)

How while loop works?

• The while loop evaluates the testExpression inside the parentheses ()


• If testExpression is true, statements inside the body of while loop are executed. Then,
testExpression is evaluated again.
• The process goes on until testExpression is evaluated to false.
• If testExpression is false, the loop terminates (ends).

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

Working of while loop

(Figure 4: Flowchart of while loop)

Example 1: while loop

// Print numbers from 1 to 5

#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

Here, we have initialized i to 1.

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.

The syntax of the do…while loop is:

do {
// the body of the loop
}
while (testExpression);

(Figure 5: do…while loop)

How do...while loop works?

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 AND NESTED FOR 1


SUB LESSON 5.2

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

The syntax of a for loop in C programming language is −


for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a 'for' loop −
● The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
● Next, the condition is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute and the flow of control jumps to
the next statement just after the 'for' loop.
● After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.
● The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates
● Flow Diagram

FOR AND NESTED FOR 2


(Figure 1: Flow chart of for loop)

EXAMPLE
Live Demo

#include <stdio.h>

int main () {

int a;

/* for loop execution */


for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", 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

FOR AND NESTED FOR 3


value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Nested for

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.

Syntax of Nested 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.

Nested for loop

The nested for loop means any type of loop which is defined inside the 'for' loop.

1. for (initialization; condition; update)


2. {
3. for(initialization; condition; update)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.

FOR AND NESTED FOR 4


8. }

Example of nested 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. }

Explanation of the above code

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:

FOR AND NESTED FOR 5


KEY TAKEAWAYS

● 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.

FOR AND NESTED FOR 6


5.3 BREAK CONTINUE GOTO

STATEMENT

BREAK CONTINUE GOTO STATEMENT 1


SUB LESSON 5.3

BREAK CONTINUE GO TO 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.

● It is also referred to as an unconditional jump statement.

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:

printf("\n Name is B");


break;
case 3:
printf("\n Name is C");
break;
default:
printf("\n Name is D");

BREAK CONTINUE GOTO STATEMENT 2


break;
}
}
int main()
{
int roll_number = 1;
print_name(roll_number);
return 0;
}
Output:

Name is A

Diag-1:The break statement execution is as shown in the following figure.

(Figure 1: Goto statement)

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.

BREAK CONTINUE GOTO STATEMENT 3


(Figure 2: Continue statement)

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;

BREAK CONTINUE GOTO STATEMENT 4


break;
default:
printf("\n Name is D");
break;
}
jump:
printf("\n I am in 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.

● Avoid using them for general purposes like naming a variable.

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.

BREAK CONTINUE GOTO STATEMENT 5


6. Arrays

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:

The general syntax to define an array is :

Data_type array_name [array_size];//1-D array

Data_type array_name [array_row_size][array_column_size];//2-D array

TO UNDERSTAND IN A BETTER LETS GO THROUGH SOME EXAMPLES

int arr1[5]; //an array of 5 integer

char arr2[5]; // an array of 5 character

float arr2[5]; //an array of 5 float values

int arr[2][4];//a 2-d array of 2 rows with each having 4 columns

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 .

To understand in a better lets go through some examples

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)

ACCESSING OF ONE DIMENSIONAL ARRAY

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.

Let’s go through some examples

o Example – 1

int arr1[5]={1,2,3,4,5};

int val1=arr1[0]//the first element of the array

int val2=arr1[1]//the second element of the array

int val3=arr1[2]//the third element of the array

int val4=arr1[4]//the fourth element of the array

int val5=arr1[5]//the fifth element of the array

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)

ACCESSING OF TWO DIMENSIONAL ARRAY

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].

Let’s go through some examples

o Example -1

int arr1[2][3]={{1,2,3},{4,5,6}};

int val1=arr1[0][0];//value at row 0 and column 0

int val2=arr1[0][1];//value at row 0 and column 1

int val3=arr1[0][2];//value at row 0 and column 2

int val4=arr1[1][0];//value at row 1 and column 0

int val5=arr1[1][1];//value at row 1 and column 1

int val6=arr1[1][2];//value at row 1 and column 2

ARRAYS
o Example – 2( Using Loops)

int arr1[2][3]={{1,2,3},{4,5,6}};

for( int i=0;i<2;i++)


{
for(int j=0;j<3;j++)
{
Printf(“%d”,arr1[i]);
}
}

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

PROGRAMS USING ONE DIMENSIONAL AND TWO DIMENSIONAL ARRAY

ONE DIMENSIONAL ARRAY

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

PROGRAM – 2(USING FOR LOOP)

#include<stdio.h>

int main()

int arr[5];

for(int i=0;i<5;i++)

printf(“Enter Element %d",i+1);

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.

The i loop runs from index to 4(length of array -1)

Output (assuming the input was 1,2,3,4,5):

1 2 3 4 5

PROGRAM – 3(USING WHILE LOOP)

#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 :

Same as the program 2 but with while loop being used

Result(assuming the input was 1,2,3,4,5):

1 2 3 4 5

ARRAYS 5
LOOP EXECUTION (1-D)

1st Loop execution (i=0)

1 2 3 4 5

2nd Loop execution (i=1)

1 2 3 4 5

3srd Loop execution (i=2)

ARRAYS 6
1 2 3 4 5

4th Loop execution (i=3)

1 2 3 4 5

5st Loop execution (i=4)

1 2 3 4 5

TWO DIMENSIONAL ARRAY

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

Program – 2(Using For Loop)

#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++)

printf("Enter Element %d %d"i+1,j+1);

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 i th loop is running from index 0 to total row-1

The j th loop is running from index 0 to total column-1 for each row

Output((assuming the input was 1,2,3,4,5,6)

1 2 3

4 5 6

LOOP EXECUTION (2-D ARRAY)

1ST LOOP EXECUTION (I=0,J=0)

ARRAYS 10

1 2 3

4 5 6

2ND LOOP EXECUTION (I=0,J=1)

1 2 3

4 5 6

3RD LOOP EXECUTION (I=0,J=2)

1 2 3

ARRAYS 11
4 5 6

4ST LOOP EXECUTION (I=1,J=0)

1 2 3

4 5 6

5TH LOOP EXECUTION (I=1,J=1)

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:

o Method – 1(Insertion Sort)


▪ This algorithm is one of the simplest algorithm with simple implementation
▪ Basically, Insertion sort is efficient for small data values
Program
#include <stdio.h>

int main()

int arr[4] = {11,2, 20,14};

int i, key, j;

for (i = 1; i < n; i++)

key = arr[i];

j = i - 1;

while (j >= 0 && arr[j] > key)

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

ARRAYS
}

int i;

for (i = 0; i < n; i++)

printf("\t%d ", arr[i]);

return 0;

Execution :

(initial)

11 2 20 14

i=1 , j = 0 , key =2

Swap

↓ ↓

ARRAYS
2 11 20 14

i=2 , j = 1 , key =20

↓ ↓

2 11 20 14

i=2 , j = 0 , key =20

↓ ↓

2 11 20 14

i=3 , j = 2,1,0 , key =14

ARRAYS
up to 2nd index

↓ ↓

2 11 14 20

SEARCHING :

#include <stdio.h>

int main()

int arr[4]={11,3,15,25};

int i, toSearch, flag;

printf("\nEnter element to search: ");

scanf("%d", &toSearch);

flag = 0;

for (i = 0; i < size; i++)

ARRAYS
{

if (arr[i] == toSearch)

flag = 1;

break;

if (flag == 1)

printf("\n%d is found at position %d", toSearch, i + 1);

else

printf("\n%d is not found in the array", toSearch);

return 0;

EXPLANATION :

Flag indicates whether the element is found or not

The i loop runs from index 0 to length -1 of the array

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 :

i=0 , flag =0 (initial)

11 3 15 25

Search for 15

i=0 ,flag=0

11 3 15 25

i=1 ,flag=0

ARRAYS
11 3 15 25

i=2 ,flag=1 (Element Found)

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

STRING & STRING STORAGE


Strings in C

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’.
Example of C String:

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.

Fours Ways to Initialize a String in C

1. Assigning a string literal without size:


2. Assigning a string literal with a predefined size:
3. Assigning character by character with size:
4. Assigning character by character without size.

Storage for Strings in C

Strings as character arrays

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.

Strings using character pointers


Using character pointer strings can be stored in two ways:

1) Read only string in a shared segment.

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:

char *str = "GfG";

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.

2) Dynamically allocated in heap segment.

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

WRITING STRINGS TO SCREEN, ARITHMETIC OPERATIONS ON


CHARACTERS

Writing Strings to Screen


Display string in C using puts() or fputs()
The library function puts()/fputs() writes a line of output to the standard output or a file. It terminates
the line with a new line, ‘\n’.
The puts() function change ‘\0’ to a new line but fputs() function doesn’t change it. So, using puts()
function control came to next line as printf(“\n”) do, but using fputs() control remains in same line. The
declarations for these functions are:-
int puts(const char* strptr);
int fputs(const char* strptr, FILE* stream);

Demonstrating puts() function

#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

Demonstrating fputs() function


#include<stdio.h>

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.

WHAT IS CHARACTER ARITHMETIC ?


Character arithmetic is used to implement arithmetic operations like addition, subtraction
,multiplication ,division on characters in C and C++ language.
In character arithmetic character converts into integer value to perform task. For this ASCII value is
used.
It is used to perform action the strings.
To understand better let’s take an example.
Example no 1
C

// C program to demonstrate character arithmetic.


#include <stdio.h>

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.

let’s take one more example.

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';

printf("a = %c\n", a);


printf("b = %c\n", b);
printf("a + b = %c\n", a + 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

SUB LESSON 8.1

CONCEPTS OF USER DEFINED FUNCTIONS 32


CONCEPTS OF USER DEFINED FUNCTION &PROTOTYPES
User-Defined Function in C

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.

Advantages of using functions in the program are:


• One can avoid duplication of code in the programs by using functions. Code can be written more
quickly and be more readable as a result.
• Code can be divided and conquered using functions. This process is known as Divide and
Conquer. It is difficult to write large amounts of code within the main function, as well as testing
and debugging. Our one task can be divided into several smaller sub-tasks by using functions,
thus reducing the overall complexity.
• For example, when using pow, sqrt, etc. in C without knowing how it is implemented, one can
hide implementation details with functions.
• With little to no modifications, functions developed in one program can be used in another,
reducing the development time.

Elements of User-Defined Function in C


Function Prototype
A function prototype is also known as a function declaration which specifies the function’s name,
function parameters, and return type. The function prototype does not contain the body of the
function. It is basically used to inform the compiler about the user-defined function which can be used
in the later part of the program.
Syntax:
return_type function_name(type1 arg1, type2 arg2, … typeN argN);

CONCEPTS OF USER DEFINED FUNCTIONS 33


Example:
int sum( int x, int y);

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:

• The return type of the function


• Function Name
• Function parameters
• Body of function
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:

function_name(arg1, arg2, ... argN);

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

CONCEPTS OF USER DEFINED FUNCTIONS 34


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

• 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.

• A function prototype is also known as a function declaration which specifies


the function’s name, function parameters, and return type. The function prototype
does not contain the body of the function. It is basically used to inform the compiler
about the user-defined function which can be used in the later part of the program.
• 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.
• 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.
• 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 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.

CONCEPTS OF USER DEFINED FUNCTIONS 35


8. CONCEPTS OF USER DEFINED
FUNCTIONS

CONCEPTS OF USER DEFINED FUNCTIONS


SUB LESSON 8.2

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:

• The return type of the function


• Function Name
• Function parameters
• Body of function

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:

function_name(arg1, arg2, ... argN);

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

CONCEPTS OF USER DEFINED FUNCTIONS


#include <stdio.h>

void swap(int a, int b)

int temp = a;

a = b;

b = temp;

int main()

int x = 10, y = 20;

printf("Values of x and y before swap are: %d, %d\n", x, y);

swap(x, y);

printf("Values of x and y after swap are: %d, %d", x, y);

return 0;

Output:

Values of x and y before swap are: 10, 20

Values of x and y after swap are: 10, 20

Note:

Values aren’t changed in the call by value since they aren’t passed by reference.

CONCEPTS OF USER DEFINED FUNCTIONS


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.

Example

// Call by Reference

#include <stdio.h>

void swap(int* a, int* b)

int temp = *a;

*a = *b;

*b = temp;

// Driver code

int main()

int x = 10, y = 20;

printf("Values of x and y before swap are: %d, %d\n", x, y);

swap(&x, &y);

printf("Values of x and y after swap are: %d, %d", x, y);

return 0;

CONCEPTS OF USER DEFINED FUNCTIONS


Output:

Values of x and y before swap are: 10, 20

Values of x and y after swap are: 20, 10

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

CONCEPTS OF USER DEFINED FUNCTIONS


• 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.
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.
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

CONCEPTS OF USER DEFINED FUNCTIONS


PARAMETERS, PARAMETERS
PASSING
8.3 PARAMETERS, PARAMETERS PASSING
Argument
An argument is referred to the values that are passed within a function when the function is called.
These values are generally the source of the function that require the arguments during the
process of execution. These values are assigned to the variables in the definition of the function
that is called. The type of the values passed in the function is the same as that of the variables
defined in the function definition. These are also called Actual arguments or Actual Parameters.

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().

Difference between Argument and Parameter

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.

These are used in function call


statement to send value from the
calling function to the receiving These are used in function header of the called
function. function to receive the value from the arguments.

During the time of call each argument


is always assigned to the parameter in Parameters are local variables which are assigned
the function definition. value of the arguments when the function is called.

BASIC OF C PROGRAMMING
2
Argument Parameter

They are also called Actual Parameters They are also called Formal Parameters

Example:

int Call(int rnum)


Example:
{
int num = 20; printf("the num is %d", rnum);
Call(num) }

// num is argument // rnum is parameter

Parameter Passing Techniques in C


There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are
called formal arguments.
Terminology
● Formal Parameter : A variable and its type as they appear in the prototype of the function
or method.
● Actual Parameter : The variable or expression corresponding to a formal parameter that
appears in the function or method call in the calling environment.
● Modes:
● IN: Passes info from caller to callee.
● OUT: Callee writes values in caller.
● IN/OUT: Caller tells callee value of variable, which may be updated by callee.
Important methods of Parameter Passing
1. Pass 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. This method is also called as call by value.

BASIC OF C PROGRAMMING
3
(Figure 1: Functions )

EXAMPLE:
// call by value
#include <stdio.h>

void func(int a, int b)


{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7; // Passing parameters
func(x, y);
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. Pass by reference(aliasing): 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

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>

void swapnum(int* i, int* j)


{
int temp = *i;
*i = *j;
*j = temp;
}

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>

void func(int a, int b)


{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7; // Passing parameters
func(x, y);

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>

void swapnum(int* i, int* j)


{
int temp = *i;
*i = *j;

BASIC OF C PROGRAMMING
3
*j = temp;
}

int main(void)
{
int a = 10, b = 20;

// passing parameters
swapnum(&a, &b);

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

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.

Different Ways of Writing Recursive Functions


Function calling itself: (Direct way)
Most of us are aware of at least two different ways of writing recursive programs. Given below are
towers of the Hanoi code. It is an example of direct calling.

Recursion using mutual function call: (Indirect way)


Indirect calling. Though least practical, a function [funA()] can call another function [funB()] which in
turn calls [funA()] the former function. In this case, both the functions should have the base case.
Defensive Programming:
We can combine defensive coding techniques with recursion for the graceful functionality of the
application. Usually, recursive programming is not allowed in safety-critical applications, such as
flight controls, health monitoring, etc. However, one can use a static count technique to avoid
uncontrolled calls (NOT in safety-critical systems, but may be used in soft real-time systems).

Recursion using function pointers: (Indirect way)


Recursion can also implemented with function pointers. An example is a signal handler in POSIX
compliant systems. If the handler causes to trigger the same event due to which the handler being
called, the function will reenter.
KEY TAKEAWAYS

● 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

The previous problem can be solved using following program

#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>

static inline int square(int x) { return x * x; }


int main()
{
int x = 36 / square(6);
printf("%d", x);
return 0;
}

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__)

12) We can remove already defined macros using:


#undef MACRO_NAME

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

BASICS OF POINTERS, POINTER TO POINTER, POINTER AND


ARRAY
Pointers
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.
Syntax:
datatype *var_name;
Let pointer “ptr” holds the address of an integer variable or holds the address of memory
whose value(s) can be accessed as integer values through “ptr”. So to define “ptr” we can do it
in four ways, which are as following:
int *ptr;
int* ptr;
int * ptr;
int*ptr;

(Figure 6: Pointers)

How to use a pointer?

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.

References and Pointers


There are 3 ways to pass C arguments to a function:
• Call-By-Value
• Call-By-Reference with a Pointer Argument
• Call-By-Reference with a Reference Argument
Pointer Arithmetic’s in C with Examples

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 Pointers to Functions in C

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.

Arguments passing without pointer

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:

Arguments passing with pointers

A pointer to a function is passed in this example. As an argument, a pointer is passed instead of


a variable and its address is passed instead of its value. As a result, any change made by the
function using the pointer is permanently stored at the address of the passed variable. In C, this
is referred to as call by reference.

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

POINTER TO ARRAY, ARRAY OF POINTERS


Pointer to Array
Consider the following program:

#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

As we know, arrays are collections of elements stored in contiguous memory locations. An


array of pointers is similar to any other array in C Language. It is an array which contains
numerous pointer variables and these pointer variables can store address values of some other
variables having the same data type.

Syntax to declare a normal array :

data_type (array_name)[sizeof_array];

Example :

int arr[10];

Syntax to declare a pointer array :

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()

char *fruits[5] = {"apple", "banana", "mango", "grapes", "orange"}, i;

for(i = 0; i < 5; i++)

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 :

(Figure 8: Array to pointers)

• 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

SUB LESSON 9.3


POINTER
FUNCTIONS RETURNING A POINTER
How to return a Pointer from a Function in C
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.
Program 1:
The below program will give segmentation fault since ‘A’ was local to the function:

// C program to illustrate the concept of


// returning pointer from a function
#include <stdio.h>

// Function returning pointer


int* fun()
{
int A = 10;
return (&A);
}

// 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:

// C program to illustrate the concept of

// returning pointer from a function

#include <stdio.h>

// Function that returns pointer

int* fun()

POINTER
// Declare a static integer

static int A = 10;

return (&A);

// Driver Code

int main()

// Declare a pointer

int* p;

// Function call

p = fun();

// Print Address

printf("%p\n", p);

// Print value at the above address

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

PROCEDURE ORIENTED PROGRAMMING

Procedure-oriented programming (POP) is a programming paradigm that focuses on the


decomposition of a program into a collection of procedures or functions. It is a traditional
programming approach where the emphasis is on breaking down a problem into a series of
tasks or procedures, which are then executed in a linear fashion.

In procedure-oriented programming, the program is divided into a set of functions or


procedures, each responsible for performing a specific task. These procedures are organized
in a top-down manner, with the main procedure controlling the flow of execution by calling
other procedures as needed. Data is typically shared between procedures through
parameters or global variables.

Here are some key characteristics of procedure-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.

Limited Reusability: Procedure-oriented programming may lack the modularity and


reusability provided by other programming paradigms, such as object-oriented
programming (OOP). Functions or procedures are typically designed to solve specific
problems and may not be easily adaptable for other use cases.

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.

OBJECT ORIENTED PROGRAMMING

Object-oriented programming (OOP) is a programming paradigm that organizes software


design around objects that represent real-world entities. It provides a way to structure
programs by encapsulating data and behaviour within objects, allowing for modular and
reusable code.

In object-oriented programming, an object is an instance of a class, which serves as a


blueprint or template for creating objects. A class defines the properties (attributes or data)
and behaviours (methods or functions) that objects of that class can possess. Objects can
interact with each other by invoking methods and accessing each other's data.

Figure 1: Object Oriented Programming

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.

Polymorphism: Polymorphism allows objects of different classes to be treated as objects of


a common superclass. It enables the use of a single interface to represent multiple types,
making the code more flexible and extensible. Polymorphism is often achieved through
method overriding and method overloading.

Abstraction: Abstraction focuses on representing essential features and behaviours of an


object while hiding unnecessary details. It provides a simplified view of an object or a
system, allowing programmers to work with high-level concepts without worrying about
low-level implementation specifics.

Association, Aggregation, and Composition: These are relationships between objects.


Association represents a relationship where objects are loosely connected, aggregation
represents a "has-a" relationship (one object is composed of other objects), and
composition represents a strong "part-of" relationship (one object is composed of other
objects and has responsibility for their creation and destruction).

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.

PURPOSE OF OBJECT-ORIENTED PROGRAMMING

The purpose of object-oriented programming (OOP) is to provide a programming paradigm


that supports modular, reusable, and maintainable code. OOP achieves this through the use
of objects, classes, and related concepts. Here are the key purposes of OOP:

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.

Collaboration: OOP facilitates collaboration among developers working on large projects.


Different team members can work on different classes or objects independently, as long as
they adhere to the defined interfaces. This promotes parallel development and code
integration, leading to more efficient teamwork.

Modelling Real-World Entities: OOP allows developers to model real-world entities,


concepts, and relationships in a more natural and intuitive way. By mapping objects and
their interactions to real-world entities, OOP promotes a closer alignment between the
software and the problem domain it addresses, making the code easier to understand and
maintain.

Code Simplicity: OOP simplifies code by providing a higher level of abstraction. By


representing complex systems or problems using objects and their interactions, OOP allows
for a more intuitive and understandable representation of the code. This can lead to
reduced complexity and improved code quality.

Overall, the purpose of object-oriented programming is to enhance code organization,


reusability, maintainability, and collaboration, ultimately leading to more efficient and
robust software development.

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:

Figure 1: PROCEDURAL VS 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.

Object-Oriented Programming: OOP focuses on objects that encapsulate data and


behaviour. It emphasizes the interaction between objects through methods, and it follows a
bottom-up approach, building complex systems by combining and extending objects.

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.

Object-Oriented Programming: OOP promotes code reuse through inheritance and


composition. Inheritance allows the creation of new classes that inherit properties and
behaviours from existing classes, facilitating code extension. Composition allows objects to
be composed of other objects, promoting modular design.

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.

Object-Oriented Programming: OOP encapsulates data within objects, providing control


over data access and manipulation. Objects hide their internal state and expose only
necessary interfaces, improving data security and reducing the risk of unintended
modifications.

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.

PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING

Object

An object is an instance of a class.

An object means anything from real world like as person, computer, bench etc...

Every object has at least one unique identity.

An object is a component of a program that knows how to interact with other pieces of the
program.

An object is the variable of the type class.

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

It is considered as one of the most essential and important features of object-oriented


programming in C++. Abstraction can be defined as displaying only essential information
and hiding the details.

The functions which operate on these data are known as: member functions or methods.

It is implemented in class to provide data security.

Encapsulation

It can be understood as wrapping up of information and data as a single unit.

It is used as a binding agent to binding the data and the functions that operate on them in
Object-Oriented Programming.

In C++ the data is inaccessible to the outside world.

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.

It means ability of operators and functions to act differently in different situations.

C++ PROGRAMMING
4
Figure 4: Polymorphism

C++ also supports operator overloading and function overloading.

Operator overloading: “The process of making an operator to exhibit different behaviours in


different instances is known as operator overloading.”

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.”

Figure 5: Concept of Polymorphism

Header File

Dynamic Binding: It is linking a procedure call to the code which is to be executed in


response to the call.

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.

Figure 6: Header File

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

Create classes that define objects and their behaviour.

Create objects from class definition

Establish communication among objects.

Message passing needs the object name, function name and the information which is to be
sent.

C++ PROGRAMMING
6
Figure 7: Message Passing

BENEFITS AND APPLICATIONS OF OOP.

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:

Software Development: OOP is widely used in software development to build complex


systems and applications. It provides a structured approach to designing and organizing
code, making it easier to manage large projects and teams. Popular programming languages
like Java, C++, and Python extensively use OOP concepts.

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.

Modelling and Simulation: OOP is employed in modelling and simulation applications. It


allows developers to represent real-world entities as objects and simulate their interactions
and behaviours. OOP's modular and extensible nature aids in creating complex simulations
and modelling systems.

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++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming


language that supports procedural, object-oriented, and generic programming.

C++ is regarded as a middle-level language, as it comprises a combination of both high-level and


low-level language features.

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.

(Figure 1: Features of c++)

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

Standard C++ consists of three important parts –

• 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 most important thing while learning C++ is to focus on concepts.

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++.

PROGRAM STRUCTURE OF C++

The C++ program is written using a specific template structure. The structure of the program
written in C++ language is as follows:

(Figure 2: Structure of c++ )

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:

/* This is a C++ program to find the

factorial of a number

C++ BASICS 12
The basic requirement for writing this

program is to have knowledge of loops

To find the factorial of number

iterate over range from number to one

*/

LINKING SECTION:

The linking section contains two parts:

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.

FUNCTION DECLARATION SECTION:


• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined functions.
This part of the program can be written after the main function but for this, write the function
prototype in this section for the function which for you are going to write code after the main
function

// Function to implement the

// factorial of number num

INTEGER factorial(INTEGER num)

// Iterate over the loop from

// num to one

for (INTEGER i = 1; i <= num; i++) {

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.

FIGURE 1: NAMESPACE OF C++ PROGRAMMING

ADVANTAGE OF NAMESPACE TO AVOID NAME COLLISION.


• Example, you might be writing some code that has a function called xyz()
and there is another library available which is also having 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 using namespace std;

C++ BASICS 17
DEFINING A NAMESPACE:
• A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
Namespace namespace_name

// code declarations i.e. Variable (int a;)

method (void add();)

classes ( class student{};)

• It is to be noted that, there is no semicolon (;) after the closing brace.


• To call the namespace-enabled version of either function or variable,
prepend the namespace name as follows:
namespace_name: :code; // code could be variable , function or class.

THE USING DIRECTIVE:


• You can also avoid prepending of namespaces with the using namespace
directive. This directive tells the compiler that the subsequent code is
making use of names in the specified namespace.
• Names introduced in a using directive obey normal scope rules. The name is
visible from the point of the using directive to the end of the scope in which
the directive is found. Entities with the same name defined in an outer
scope are hidden.
NESTED NAMESPACES:
• Namespaces can be nested where you can define one namespace inside
another name space as follows:
Syntax:

namespace namespace_name1

// code declarations

namespace namespace_name2

C++ BASICS 18
{

// code declarations

You can access members of nested namespace by using resolution operators as


follows:

// to access members of namespace_name2

using namespace namespace_name1::namespace_name2;

// to access members of namespace_name1

using namespace namespace_name1;

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>

Using namespace std;

// first name space

Namespace first_space

void func()

cout << "inside first_space" << endl;

// second name space

namespace second_space

C++ BASICS 19
{

void func()

cout << "inside second_space" << endl;

Using namespace first_space::second_space;

Int main ()

// this calls function from second name space.

func();

return 0;

Output

Inside second_space

DEFINITION AND CREATION:


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. Namespaces provide the space
where we can define or declare identifiers i.e. names of variables, methods, classes, etc.
• A namespace is a feature added in C++ and is not present in C.
• A namespace is a declarative region that provides a scope to the identifiers (names of
functions, variables or other user-defined data types) inside it.

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.

NAMESPACE PROVIDES THE ADVANT AGE OF AVOIDING NAME COLLISION

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:

• Only alphabetic characters, digits, and underscores are allowed.


• The identifier name cannot start with a digit, i.e., the first letter should be
alphabetical. After the first letter, we can use letters, digits, or underscores.
• In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
• A declared keyword cannot be used as a variable name.

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:

1. Sum-1 // containing special character '-'.


2. 2data // the first letter is a digit.

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++ supports the following data types:

1. Primary or Built-in or Fundamental data type


2. Derived data types
3. User-defined data types

(Figure 10: Datatypes in c++)

C++ BASICS 25
Data Types in C++ are Mainly Divided into 3 Types:

1. PRIMITIVE DATA TYPES

These data types are built-in or predefined data types and can be used directly by the user to
declare variables.

Primitive data types available in C++ are:

• 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.

These can be of four types namely:

• 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.

C++ provides the following user-defined datatypes:

• 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(m); //returns 4 which is the number of bytes occupied by the integer


variable “m”.

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.

• The value stored in a variable can be changed during program execution.


• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In C++, all the variables must be declared before use.
How to Declare Variables?

A typical variable declaration is of the form:

// Declaring a single variable

type variable_name;

// Declaring multiple variables:

type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers, and the
underscore ‘_’ character.

However, the name must not start with a number.

C++ BASICS 28
(Figure 2: Variable in C++)

In the above diagram,

Data type: Type of data that can be stored in this variable.

Variable name: Name given to the variable.

Value: It is the initial value stored in the variable.

Examples:

// Declaring float variable

float simpleInterest;

// Declaring integer variable

int time, speed;

// Declaring character variable

char var;

C++ BASICS 29
We can also provide values while declaring the variables as given below:

int a=50,b=100; //declaring 2 variable of integer type

float f=50.8; //declaring 1 variable of float type

char c='Z'; //declaring 1 variable of char type

RULES FOR DECLARING VARIABLE


• The name of the variable contains letters, digits, and underscores.
• The name of the variable is case sensitive (ex Arr and arr both are different variables).
• The name of the variable does not contain any whitespace and special characters (ex
#,$,%,*, etc).
• All the variable names must begin with a letter of the alphabet or an underscore(_).
• We cannot used C++ keyword(ex float,double,class)as a variable name.

Valid variable names:

int x; //can be letters

int _yz; //can be underscores

int z40;//can be letters

Invalid variable names:

int 89; Should not be a number

int a b; //Should not contain any whitespace

int double;// C++ keyword CAN NOT BE USED

DIFFERENCE BETWEEN VARIABLE DECLARATION AND DEFINITION

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

(Figure 3: Types of Variable in C++)

Let us now learn about each one of these variables in detail.

1. Local Variables: A variable defined within a block or method or constructor is called a


local variable.
o These variables are created when entered into the block or the function is called
and destroyed after exiting from the block or when the call returns from the
function.
o The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access this variable only within that block.
o Initialization of Local Variable is Mandatory.

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.

3. Static Variables: Static variables are also known as Class variables.


o These variables are declared similarly as instance variables, the difference is that
static variables are declared using the static keyword within a class outside any
method constructor or block.
o Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
o Static variables are created at the start of program execution and destroyed
automatically when execution ends.
o Initialization of Static Variable is not Mandatory. Its default value is 0
o If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The
compiler will replace the object name with the class name automatically.
o If we access the static variable without the class name, the Compiler will
automatically append the class name.

Instance Variable Vs Static Variable:

• 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

int b; // instance 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.

How to define a constant in C?

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.

Syntax to Define Constant

const data_type var_name = value;

(Figure 4: constant in C++)

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:

1. Initialization with Declaration

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

An operator is a symbol that operates on a value to perform specific mathematical or logical


computations. They form the foundation of any programming language. In C++, we have built-in
operators to provide the required functionality.

An operator operates the operands. For example,

int c = a + b;

Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.

Operators in C++ can be classified into 6 types:

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators

(Figure 11: Operators in C++)

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.

Arithmetic Operators can be classified into 2 Types:

A) Unary Operators: These operators operate or work with a single operand. For example:
Increment (++) and Decrement (–) Operators.

Name Symbol Description Example

Increment Operator ++ Increases the integer value of int a = 5; a++; //


the variable by one returns 6

Decrement Operator -- Decreases the integer value int a = 5; a–; // returns


of the variable by one 4

(Table 1: Unary 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

(Table 2: Binary Operators)

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.

Name Symbol Description Example

int a = 3, b = 6;

Is Equal To == Checks if both operands are equal a==b;


// returns false

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

(Table 4: Relational Operators)

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

(Table 5: Logical Operators)

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.

Name Symbol Description Example

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

(Table 1: Bitwise Operator)

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.

Name Symbol Description Example

int a = 2;
Assignment Assigns the value on the right to the
=
Operator variable on the left // a = 2

First adds the current value of the variable


Add and int a = 2, b = 4;
on left to the value on the right and then
Assignment +=
assigns the result to the variable on the a+=b; // a = 6
Operator
left

First subtracts the value on the right from


Subtract and int a = 2, b = 4;
the current value of the variable on left
Assignment -=
and then assign the result to the variable a-=b; // a = -2
Operator
on the left

First multiplies the current value of the


Multiply and int a = 2, b = 4;
variable on left to the value on the right
Assignment *=
and then assign the result to the variable a*=b; // a = 8
Operator
on the left

C++ BASICS
Name Symbol Description Example

First divides the current value of the


Divide and int a = 4, b = 2;
variable on left by the value on the right
Assignment /=
and then assign the result to the variable a /=b; // a = 2
Operator
on the left

(Figure 2: Assignment Operator)

6. TERNARY OR CONDITIONAL OPERATORS

This operator returns the value based on the condition.

Expression1? Expression2: Expression3

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.

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

B) Comma Operator (,)


This binary operator (represented by the token) is used to evaluate its first operand and
discards the result, it then evaluates the second operand and returns this value (and
type). It is used to combine various expressions together.
int a = 6;
int b = (a+1, a-2, a+5); // b = 10

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

11.6 TYPECASTING IN C++

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:

1. IMPLICIT TYPE CONVERSION

Also known as ‘automatic 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 ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double

• 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:

// An example of implicit conversion

#include <iostream>

using namespace std;

int main()

int x = 10; // integer x

char y = 'a'; // character c

// y implicitly converted to int. ASCII

// value of 'a' is 97

C++ BASICS 47
x = x + y;

// x is implicitly converted to float

float z = x + 1.0;

cout << "x = " << x << endl

<< "y = " << y << endl

<< "z = " << z << endl;

return 0;

Output:

x = 107

y=a

z = 108

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.

In C++, it can be done by two ways:

• Converting by assignment: This is done by explicitly defining the required type in


front of the expression in parenthesis. This can be also considered as forceful
casting.
Syntax:

(type) expression

where type indicates the data type to which the final result is converted.

Example:

// C++ program to demonstrate

// explicit type casting

C++ BASICS 48
#include <iostream>

using namespace std;

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

cout << "Sum = " << sum;

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>

using namespace std;

int main()

float f = 3.5;

C++ BASICS 49
// using cast operator

int b = static_cast<int>(f);

cout << b;

OUTPUT:

ADVANTAGES OF TYPE CONVERSION


• This is done to take advantage of certain features of type hierarchies or type
representations.
• It helps to compute expressions containing variables of different data types.

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

11.7 CONTROL STRUCTURES

DECISION MAKING STATEMENTS


Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.

Fig. 1. Decision Making Statements

C++ programming language provides following types of decision-making statements.

C++ BASICS 2
C++ BASICS 3
Example of if in C++

#include <iostream>

using namespace std;

int main ()

int i = 10;

if (i > 15)

cout << "10 is greater than 15";

cout << "I am Not in if";

Output

I am Not in if

C++ BASICS 4
LOOP STATEMENTS

C++ programming language provides the following type of loops to handle looping
requirements.

Sr. No. Loop Type & Description

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>

using namespace std;

int main ()

for (int i = 1; i <= 5; i++) {

cout << "Hello World\n";

return 0;

Output

Hello World

Hello World

Hello World

Hello World

Hello World

KEY TAKEAWAYS

● Decision Making Statements like if statement, if else statement, switch statement,


nested if statement, nested switch statement.

● 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:

(Figure 1: Syntax of Function)

WHY DO WE NEED FUNCTIONS?


• Functions help us in reducing code redundancy. If
functionality is performed at multiple places in software, then rather than writing the
same code, again and again, we create a function and call it everywhere. This also helps
in maintenance as we have to change at one place if we make future changes to the
functionality.
• Functions make code modular. Consider a big file
having many lines of code. It becomes really simple to read and use the code if the code
is divided into functions.
• Functions provide abstraction. For example, we can
use library functions without worrying about their internal work.

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)

(Figure 2: Function declaration)

TYPES OF FUNCTIONS

(Figure 3: Types of Function in C++)

FUNCTIONS
USER DEFINED FUNCTION

User Defined functions are user/customer-defined blocks of code specially customized to


reduce the complexity of big programs. They are also commonly known as “tailor-made
functions” which are built only to satisfy the condition in which the user is facing issues
meanwhile reducing the complexity of the whole program.

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.

For Example: sqrt(), setw(), strcat(), etc.

Parameter Passing to Functions:

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)

There are two most popular ways to pass parameters:

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().

FUNCTIONS USING POINTERS:

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.

Difference between call by value and call by reference in C++

Call by value Call by reference

A copy of value is passed to the function An address of value is passed to the function

Changes made inside the function is


Changes made inside the function is not
reflected
reflected on other functions
outside the function also

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)

....... // Function Body

return; // Function execution would get terminated

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.

Types of Main Functions

1. Without parameters
// Without Parameters

int main() { ... return 0; }

2. With parameters:
// With Parameters

int main(int argc, char* const argv[]) { ... return 0; }

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:

inline return-type function-name(parameters)

// function code

(Figure 1: Inline Function)

FUNCTIONS 15
Remember, inlining is only a request to the compiler, not a command. The compiler can ignore
the request for inlining.

The compiler may not perform inlining in such circumstances as:

1. If a function contains a loop. (for, while and do-while)


2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement doesn’t exist in a
function body.
5. If a function contains a switch or goto statement.

WHY INLINE FUNCTIONS ARE USED?

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.

INLINE FUNCTIONS ADVANTAGES:


1. Function call overhead doesn’t occur.
2. It also saves the overhead of push/pop variables on the stack when a function is called.
3. It also saves the overhead of a return call from a function.
4. When you inline a function, you may enable the compiler to perform context-specific
optimization on the body of the function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of the
calling context and the called context.
5. An inline function may be useful (if it is small) for embedded systems because inline can
yield less code than the function called preamble and return.

INLINE FUNCTION DISADVANTAGES:

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:

inline int square(int s) // redundant use of inline

// this function is automatically inline

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.

Syntax of an Inline function:

inline return_type function_name ( parameters )

// inline function code

Example of an Inline function:

#include <iostream>

using namespace std;

// Inline function

inline int Maximum(int a, int b)

return (a > b) ? a : b;

// Main function for the program

int main()

cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;

cout << "Max (20, 0): " << Maximum(20, 0) << endl;

FUNCTIONS
return 0;

Output:

Max (100, 1000): 1000

Max (20, 0): 20

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:

#define MACRO_NAME Macro_definition

Example of Macro:

#include <iostream>

using namespace std;

// macro with parameter

#define MAXIMUM(a, b) (a > b) ? a : b

// Main function for the program

int main()

cout << "Max (100, 1000):";

int k = MAXIMUM(100, 1000);

cout << k << endl;

cout << "Max (20, 0):";

int k1 = MAXIMUM(20, 0);

cout << k1;

FUNCTIONS
return 0;

Output:

Max (100, 1000):1000

Max (20, 0):20

DIFFERENCE BETWEEN INLINE AND MACRO IN C++

S.NO Inline Macro

An inline function is defined by Whereas the macros are defined by


1.
the inline keyword. the #define keyword.

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.

Whereas in the case of macro, the arguments


In the case of inline, the arguments are
4. are evaluated every time whenever macro is
evaluated only once.
used in the program.

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.

In C++, inside the class, the short length


6. functions are automatically made the While the macro is specifically defined.
inline functions.

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

Function overloading is a feature of object-oriented programming where two or more functions


can have the same name but different parameters. When a function name is overloaded with
different jobs it is called Function Overloading. In Function Overloading “Function” name should
be the same and the arguments should be different. Function overloading can be considered as
an example of a polymorphism feature in C++.

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:

• Parameters should have a different type

add(int a, int b)

add(double a, double b)

How does Function Overloading work?

• Exact match:- (Function name and Parameter)


• If a not exact match is found:–
o ->Char, Unsigned char, and short are promoted to an int.
o ->Float is promoted to double
• If no match is found:
o ->C++ tries to find a match through the standard conversion.

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++

A default argument is a value provided in a function declaration that is automatically assigned


by the compiler if the calling function doesn’t provide a value for the argument. In case any
value is passed, the default value is overridden.

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>

using namespace std;

// A function with default arguments,

// it can be called with

// 2 arguments or 3 arguments or 4 arguments.

int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0

return (x + y + z + w);

// Driver Code

int main()

// Statement 1

cout << sum(10, 15) << endl;

FUNCTIONS 26
// Statement 2

cout << sum(10, 15, 25) << endl;

// Statement 3

cout << sum(10, 15, 25, 30) << endl;

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>

using namespace std;

// A function with default arguments, it can be called with

// 2 arguments or 3 arguments or 4 arguments.

int sum(int x, int y, int z = 0, int w = 0)

return (x + y + z + w);

FUNCTIONS 27
}

int sum(int x, int y, float z = 0, float w = 0)

return (x + y + z + w);

// Driver Code

int main()

cout << sum(10, 15) << endl;

cout << sum(10, 15, 25) << endl;

cout << sum(10, 15, 25, 30) << endl;

return 0;

Error:

prog.cpp: In function 'int main()':

prog.cpp:17:20: error: call of overloaded

'sum(int, int)' is ambiguous

cout << sum(10, 15) << endl;

prog.cpp:6:5: note: candidate:

int sum(int, int, int, int)

int sum(int x, int y, int z=0, int w=0)

prog.cpp:10:5: note: candidate:

FUNCTIONS 28
int sum(int, int, float, float)

int sum(int x, int y, float z=0, float w=0)

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>

using namespace std;

class A {

private:

int var = 0;

public:

A(int x = 0): var(x){}; // default constructor with one argument

// Note that var(x) is the syntax in c++ to do : "var = x"

void setVar(int s){

var = s; // OR => this->var = s;

return;

int getVar(){

return var; // OR => return this->var;

};

int main(){

FUNCTIONS 29
A a(1);

a.setVar(2);

cout << "var = " << a.getVar() << endl;

/* ANOTHER APPROACH:

A *a = new A(1);

a->setVar(2);

cout << "var = " << a->getVar() << endl;

*/

Explanation: Here, we see a default constructor with no arguments and a default


constructor with one default argument. The default constructor with argument has a
default parameter x, which has been assigned a value of 0.

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

int sum(int x, int y, int z = 0, int w).

ADVANTAGES OF DEFAULT ARGUMENTS:


• Default arguments are useful when we want to increase the capabilities of an existing
function as we can do it just by adding another default argument to the function.

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.

DISADVANTAGES OF DEFAULT ARGUMENTS:


• It increases the execution time as the compiler needs to replace the omitted arguments
by their default values in the function call.
KEY TAKEAWAYS
- Function overloading means when same name function has different parameters.
- Function will be invoked according to the parameter passed to the function.
- Priority of calling to the function calling will be given to the exact parameter first.

FUNCTIONS 31
13.1 OBJECTS AND CLASSES

OBJECTS AND CLASSES 32


13.1 OBJECT AND CLASS IN C++, ACCESS SPECIFIERS

OBJECT AND CLASS IN C++

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.

Defining Class and Declaring Objects:

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.

OBJECTS AND CLASSES 33


(Figure 1: Class and Object)

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.

OBJECTS AND CLASSES 34


13. OBJECTS AND CLASSES

OBJECTS AND CLASSES 35


13.2 STATIC DATA MEMBER AND STATIC MEMBER FUNCTION

STATIC DATA MEMBER

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:

static data_type data_member_name;

Below is the C++ program to demonstrate the working of static data members:

// C++ Program to demonstrate

// the working of static data member

#include <iostream>

using namespace std;

class A {

public:

A()

cout << "A's Constructor Called " <<

endl;

};

OBJECTS AND CLASSES 36


class B {

static A a;

public:

B()

cout << "B's Constructor Called " <<

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.

ACCESSING A STATIC MEMBER

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:

// C++ Program to demonstrate the Compilation Error occurred

// due to violation of Static Data Memeber Rule

#include <iostream>

OBJECTS AND CLASSES 37


using namespace std;

class A {

int x;

public:

A()

cout << "A's constructor called " <<

endl;

};

class B {

static A a;

public:

B()

cout << "B's constructor called " <<

endl;

static A getA()

return a;

};

OBJECTS AND CLASSES 38


// Driver code

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.

DEFINING STATIC DATA MEMBER

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:

// C++ program to access static data member with explicit definition

#include <iostream>

using namespace std;

class A {

int x;

public:

A()

cout << "A's constructor called " <<

endl;

};

OBJECTS AND CLASSES 39


class B {

static A a;

public:

B()

cout << "B's constructor called " <<

endl;

static A getA()

return a;

};

// Definition of a

A B::a;

// Driver code

int main()

B b1, b2, b3;

A a = b1.getA();

return 0;

OBJECTS AND CLASSES 40


Explanation: The above program calls B’s constructor 3 times for 3 objects (b1, b2, and b3), but
calls A’s constructor only once. The reason is that the static members are shared among all
objects. That is why they are also known as class members or class fields.

Also, static members can be accessed without any object.

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.

ACCESS STATIC MEMBERS WITHOUT ANY OBJECT

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>

using namespace std;

class A {

int x;

public:

A()

cout << "A's constructor called " <<

endl;

};

class B {

OBJECTS AND CLASSES 41


static A a;

public:

B()

cout << "B's constructor called " <<

endl;

static A getA()

return a;

};

// Definition of a

A B::a;

// Driver code

int main()

// static member 'a' is accessed

// without any object of B

A a = B::getA();

return 0;

OBJECTS AND CLASSES 42


KEY TAKEAWAYS
• Static data members are class members that are declared using static keywords.
• We can access any static member without any object by using the scope resolution
operator directly with the class name.

OBJECTS AND CLASSES 43


13. OBJECTS AND CLASSES

OBJECTS AND CLASSES 44


13.3 CONSTRUCTOR AND DESTRUCTOR

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

a. Syntax for defining the constructor within the class


<class-name>(list-of-parameters)

//constructor definition

b. Syntax for defining the constructor outside the class


<class-name>: :<class-name>(list-of-parameters)

//constructor definition

OBJECTS AND CLASSES 45


CHARACTERISTICS OF CONSTRUCTOR
• The name of the constructor is same as its 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.
• Constructors do not return values; hence they do not have a return type.
• A constructor gets called automatically when we create the object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
• Constructor cannot be inherited.
• Addresses of Constructor cannot be referred.
• Constructor make implicit calls to new and delete operators during memory allocation.

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:

• Constructor has same name as the class itself


• Default Constructors don’t have input argument however, Copy and Parameterized
Constructors have input arguments
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• It must be placed in public section of class.
• If we do not specify a constructor, C++ compiler generates a default constructor for
object (expects no parameters and has an empty body).

OBJECTS AND CLASSES 46


(Figure 1: CONSTRUCTOR in C++)

Let us understand the types of constructors in C++ by taking a real-world example.

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.

2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically,


these arguments help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other function.
When you define the constructor’s body, use the parameters to initialize the object.
Note: when the parameterized constructor is defined and no default constructor is
defined explicitly, the compiler will not implicitly call the default constructor and hence
creating a simple object as

Student s;

OBJECTS AND CLASSES 47


Will flash an error

• Uses of Parameterized constructor:


o It is used to initialize the various data elements of different objects with different
values when they are created.
o It is used to overload constructors.

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.

Whenever we define one or more non-default constructors (with parameters) for a


class, a default constructor (without parameters) should also be explicitly defined as the
compiler will not provide a default constructor in this case. However, it is not necessary
but it’s considered to be the best practice to always define a default constructor.

Copy constructor takes a reference to an object of the same class as an argument.

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.

The syntax for defining the destructor within the class

~ <class-name>()

OBJECTS AND CLASSES 48


{

The syntax for defining the destructor outside the class

<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.

OBJECTS AND CLASSES 49


13. OBJECTS AND CLASSES

OBJECTS AND CLASSES 50


13.4 FRIEND FUNCTION, OPERATOR OVERLOADING

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:

Return_Type classname :: operator op(Argument list)

Function Body

} // This can be done by declaring the function

Here,

• Return_Type is the value type to be returned to another object.


• operator op is the function where the operator is a keyword.
• op is the operator to be overloaded.

Operator Overloading can be done by using three approaches:

1. Overloading unary operator.


2. Overloading binary operator.
3. Overloading binary operator using a friend function.

Criteria/Rules to Define the Operator Function

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 = () [] ->.

OBJECTS AND CLASSES 51


6. The operator function must be either a non-static (member function) or a friend
function.

1. OVERLOADING UNARY OPERATOR

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).

2. OVERLOADING BINARY OPERATOR

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.

Pictorial View of working of Binary Operator

(Figure 12: Pictorial view of working of Binary Operator)

3. OVERLOADING BINARY OPERATOR USING A FRIEND FUNCTION

OBJECTS AND CLASSES 52


In this approach, the operator overloading function must be preceded by the friend keyword,
and declare the function in the class scope. Keeping in mind, the friend operator function takes
two parameters in a binary operator and varies one parameter in a unary operator. All the
working and implementation would same as the binary operator function except this function
will be implemented outside the class scope.

Example: Below is the C++ program to show binary operator overloading using a friend
function.

// C++ program to show binary operator overloading using a Friend Function

#include <iostream>

using namespace std;

class Distance {

public:

int feet, inch;

Distance()

this->feet = 0;

this->inch = 0;

Distance(int f, int i)

this->feet = f;

this->inch = i;

// Declaring friend function

// using friend keyword

OBJECTS AND CLASSES 53


friend Distance operator + (Distance&,

Distance&);

};

// Implementing friend function

// with two parameters

// Call by reference

Distance operator+(Distance& d1,

Distance& d2)

// Create an object to return

Distance d3;

d3.feet = d1.feet + d2.feet;

d3.inch = d1.inch + d2.inch;

// Return the resulting object

return d3;

// Driver Code

int main()

Distance d1(8, 9);

Distance d2(10, 2);

Distance d3;

// Use overloaded operator

d3 = d1 + d2;

OBJECTS AND CLASSES 54


cout << "\nTotal Feet & Inches: " <<

d3.feet << "'" << d3.inch;

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.

OBJECTS AND CLASSES 55


13. C++ BASICS

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:

1. IMPLICIT TYPE CONVERSION

Also known as ‘automatic 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 ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double

• 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:

// An example of implicit conversion

#include <iostream>

using namespace std;

int main()

int x = 10; // integer x

char y = 'a'; // character c

C++ BASICS 2
// y implicitly converted to int. ASCII

// value of 'a' is 97

x = x + y;

// x is implicitly converted to float

float z = x + 1.0;

cout << "x = " << x << endl

<< "y = " << y << endl

<< "z = " << z << endl;

return 0;

Output:

x = 107

y=a

z = 108

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.

In C++, it can be done by two ways:

• Converting by assignment: This is done by explicitly defining the required type in


front of the expression in parenthesis. This can be also considered as forceful
casting.

Syntax:

(type) expression

where type indicates the data type to which the final result is converted.

C++ BASICS 3
Example:

// C++ program to demonstrate

// explicit type casting

#include <iostream>

using namespace std;

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

cout << "Sum = " << sum;

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>

C++ BASICS 4
using namespace std;

int main()

float f = 3.5;

// using cast operator

int b = static_cast<int>(f);

cout << b;

OUTPUT:

ADVANTAGES OF TYPE CONVERSION

• This is done to take advantage of certain features of type hierarchies or type


representations.
• It helps to compute expressions containing variables of different data types.

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 5

You might also like