C, OOP's, Programing
C, OOP's, Programing
C, OOP's, Programing
co
1
1
www.gradeup.co
1 C PROGRAMMING
▪ In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
ffgff %d
char %c
float %f
double %lf
unsigned int %u
signed char %c
unsigned char %c
Here's a list of commonly used C data types and their format specifiers.
2
2
www.gradeup.co
3
3
www.gradeup.co
Example-
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
Output-
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
▪ The format specifier %d is used in scanf() statement. So that, the value entered is received
as an integer and %s for string.
▪ Ampersand is used before variable name “ch” in scanf() statement as &ch.
3. C – DATA TYPES
4
4
www.gradeup.co
void type
void type means no value. This is usually used to specify the type of functions which
returns nothing. We will get acquainted to this datatype as we start learning more
advanced topics in C language, like functions, pointers etc.
5
5
www.gradeup.co
4. C TOKENS
The smallest individual units are known as C tokens. C has six types of tokens: Keywords,
Identifiers, Constants, Operators, Delimiters / Separators and Special symbols.
4.1. Keywords: All keywords are basically the sequences of characters that have one or more
fixed meanings.
• Keywords are pre-defined words in a C compiler.
• Each keyword is meant to perform a specific function in a C program.
• Since keywords are referred names for compiler, they can’t be used as variable name.
• All C keywords must be written in lowercase letters.
continue for do if
4.2. Identifiers: A C identifier is a name used to identify a variable, function, or any other
user-defined item.
RULES FOR CONSTRUCTING IDENTIFIER NAME IN C:
• First character should be an alphabet or underscore.
• Succeeding characters might be digits or letter.
• Punctuation and special characters aren’t allowed except underscore.
• Identifiers should not be keywords.
4.3. Constants: Fixed values that do not change during the execution of a C program.
Example: 100 is integer constant, 'a' is character constant, etc.
4.4. Operators: Operator is a symbol that tells computer to perform certain mathematical or
logical manipulations.
Example: Arithmetic operators (+, -, *, /), Logical operators, Bitwise operators, etc.
4.5. Delimiters / Separators: These are used to separate constants, variables and
statements.
Example: comma, semicolon, apostrophes, double quotes, blank space etc.
4.6. Strings: String constants are specified in double quotes.
Example: "gateexam" is string constant
6
6
www.gradeup.co
5. TYPES OF OPERATORS
Figure 2
Operators Symbols
Arithmetic operators +, -, *, /, %, ++, --
Assignment operator =, +=, -=, *=, etc
Relational operators <, <=, >, >=, !=, ==
Logical operators &&, ||, !
Bitwise operators &, |, ~, ^, <<, >>
Special operators sizeof(), comma, →
Pointer operators * - Value at address (indirection), & - Address Operator
Table 2
5.1. Post Increment & Pre Increment
int i, x; int i, x;
i = 2; i = 2;
x = ++i; x = i++;
// now i = 3, x = 3 // now i = 3, x = 2
7
7
www.gradeup.co
Operator precedence relations are given below from highest to lowest order:
Table 2
8
8
www.gradeup.co
7. C VARIABLE
• C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
• The value of the C variable may get change in the program.
• C variable might be belonging to any of the data type like int, float, char etc.
7.1. DECLARING & INITIALIZING C VARIABLE:
• Variables should be declared in the C program before to use.
• Memory space is not allocated for a variable while declaration. It happens only on
variable definition.
• Variable initialization means assigning a value to the variable.
Type Syntax
data_type variable_name;
Variable declaration
Example: int x, y, z; char flat, ch;
9
9
www.gradeup.co
8. TYPE CONVERSIONS
8.1. Implicit Type Conversion: There are certain cases in which data will get automatically
converted from one type to another:
8.1.1. When data is being stored in a variable, if the data being stored does not match
the type of the variable.
8.1.2. The data being stored will be converted to match the type of the storage variable.
8.1.3. When an operation is being performed on data of two different types. The "smaller"
data type will be converted to match the "larger" type.
• The following example converts the value of x to a double precision value before
performing the division. Note that if the 3.0 were changed to a simple 3, then integer
division would be performed, losing any fractional values in the result.
• average = x / 3.0;
8.1.4. When data is passed to or returned from functions.
8.2. Explicit Type Conversion: Data may also be expressly converted, using the typecast
operator. The following example converts the value of x to a double precision value before
performing the division. ( y will then be implicitly promoted, following the guidelines listed
above. )
8.2.1. average = ( double ) x / y;
8.2.2. Note that x itself is unaffected by this conversion.
10
10
www.gradeup.co
} default case
Note: Here constant can be either character or Reason:
integer Missing break after each
9.3. The Conditional Operators (? : ): case, leads to execution of all the
The ? : operators are just like an if-else statement except
cases from that because
matching it is an operator
case.
we can use it within expressions. ? : are a ternary operators in that it takes three values.
They are the only ternary operator in C language.
Syntax→ Boolean Expression ? First Statement : Second Statement
flag = (x < 0) ? 0 : 1;
This conditional statement can be evaluated as following with equivalent if else statement.
if (x < 0) flag = 0;
else flag = 1;
Example- int a=100, b=200,c=300,x;
x = (a>b) ? ((a>c)? a : c) : ((b>c) ? b : c);
Soln- a>b → false therefore, x=c,
Hence x=300
11
11
www.gradeup.co
12
12
www.gradeup.co
(b) The do while loops runs atleast once in any condition(even if the loops control
condition is false)
13
13
www.gradeup.co
9.5.2. The continue Statement: The 'continue' statement is used to take the control
to the beginning of the loop, by passing the statement inside the loop, which have not
yet been executed.
****
14
14
www.gradeup.co
15
15
www.gradeup.co
1
16
www.gradeup.co
2 OOPs CONCEPTS
OOPs Concept
Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-
oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism
etc in programming. The main aim of OOP is to bind together the data and the functions that operate
on them so that no other part of the code can access this data except that function. The primary
purpose of object-oriented programming is to increase the flexibility and maintainability of programs.
1. WHAT IS AN OBJECT
2
17
www.gradeup.co
Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Examples of states and behaviors
Example 1:
Object: House
State: Address, Color, Area
Behavior: Open door, close door
2. CLASS
A class is a user defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
a. Modifiers: A class can be public or has default access (Refer this for details).
b. Class name: The name should begin with a initial letter (capitalized by convention).
c. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
d. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one interface.
e. Body: The class body surrounded by braces, { }.
3. METHOD
A method is a collection of statements that perform some specific task and return result to the
caller. A method can perform some specific task without returning anything. Methods allow us
to reuse the code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the code.
3.1. Method Declaration
In general, method declarations has six components:
a. Access Modifier: Defines access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 type of the access specifiers.
➢ public: accessible in all class in your application.
➢ protected: accessible within the package in which it is defined and in its
subclass(es)(including subclasses declared outside the package)
➢ private: accessible only within the class in which it is defined.
➢ default (declared/defined without using any modifier): accessible within same
class and package within which its class is defined.
3
18
www.gradeup.co
b. The return type: The data type of the value returned by the method or void if does
not return a value.
c. Method Name: the rules for field names apply to method names as well, but the
convention is a little different.
d. Parameter list: Comma separated list of the input parameters are defined, preceded
with their data type, within the enclosed parenthesis. If there are no parameters, you
must use empty parentheses ().
e. Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s).
f. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations.
methods in java
4. POLYMORPHISM
4
19
www.gradeup.co
5. INHERITANCE
The process by which one class acquires the properties and functionalities of another class is
called inheritance. Inheritance provides the idea of reusability of code and each sub class
defines only those features that are unique to it, rest of the features can be inherited from the
parent class.
Important terminology:
• Super Class: The class whose features are inherited is known as superclass(or a base class
or a parent class).
• Sub Class: The class that inherits the other class is known as subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, 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. By doing this, we are reusing the fields and
methods of the existing class.
Types of Inheritance:
5.1. Single Inheritance: refers to a child and parent class relationship where a class extends
the another class.
5.2. Multilevel inheritance: refers to a child and parent class relationship where a class
extends the child class. For example class A extends class B and class B extends class C.
5.3. Hierarchical inheritance: refers to a child and parent class relationship where more
than one classes extends the same class. For example, class B extends class A and class
C extends class A.
5.4. Multiple Inheritance: refers to the concept of one class extending more than one
classes, which means a child class has two parent classes.
6. ENCAPSULATION
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. Another way to think about encapsulation
is, it is a protective shield that prevents the data from being accessed by the code outside this
shield.
• Technically in encapsulation, the variables or data of a class is hidden from any other class
and can be accessed only through any member function of own class in which they are
declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
5
20
www.gradeup.co
• Encapsulation can be achieved by Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.
7. ABSTRACTION
Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is
viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the objects.
6
21
www.gradeup.co
Note 1: There can be some scenarios where it is difficult to implement all the methods
in the base class. In such scenarios one can define the base class as an abstract class
which signifies that this base class is a special kind of class which is not complete on its
own.
A class derived from the abstract base class must implement those methods that are not
implemented(means they are abstract) in the abstract class.
Note 2: Abstract class cannot be instantiated which means you cannot create the object
of abstract class. To use this class, you need to create another class that extends this
abstract class provides the implementation of abstract methods, then you can use the
object of that child class to call non-abstract parent class methods as well as implemented
methods(those that were abstract in parent but implemented in child class).
Note 3: If a child does not implement all the abstract methods of parent class(the
abstract class), then the child class must need to be declared abstract.
9. 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 will invoke a
function in the receiving object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function and the information to be sent.
Questions For Practice-
1. Which is known as a generic class?
a) Abstract class
b) Final class
c) Template class
d) Efficient Code
Answer: c
Explanation: Template classes are known to be generic classes because those can be used for
any data type value and the same class can be used for all the variables of different data types.
2. Which class can have member functions without their implementation?
a) Default class
b) String class
c) Template class
d) Abstract class
Answer: d
Explanation: Abstract classes can have member functions with no implementation, where the
inheriting subclasses must implement those functions.
7
22
www.gradeup.co
****
8
23
www.gradeup.co
9
24
www.gradeup.co
1
25
www.gradeup.co
3 FUNCTIONS
Functions
In c, we can divide a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times
to provide reusability and modularity to the C program. In other words, we can say that the collection
of functions creates a program.
Advantage of functions in C
There are the following advantages of C functions.
• By using functions, we can avoid rewriting same logic/code again and again in a program.
• We can call C functions any number of times in a program and from any place in a program.
• We can track a large C program easily when it is divided into multiple functions.
• Reusability is the main achievement of C functions.
• However, Function calling is always a overhead in a C program.
1. FUNCTION ASPECTS
2
26
www.gradeup.co
2. TYPES OF FUNCTIONS
3. RETURN VALUE
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
Example without return value:
void hello(){
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int,
long, char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
Example with return value:
int get(){
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want
to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return
type of the method.
float get(){
return 10.2;
}
Now, you need to call the function, to get the value of the function.
3
27
www.gradeup.co
A function may or may not accept any argument. It may or may not return any value. Based
on these facts, There are four different aspects of function calls.
a) function without arguments and without return value
b) function without arguments and with return value
c) function with arguments and without return value
d) function with arguments and with return value
4
28
www.gradeup.co
5
29
www.gradeup.co
6. POINTERS
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type i
nteger.
6.1. Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
int *a; //pointer to int
char *c; //pointer to char
6
30
www.gradeup.co
To access the value stored in the address we use the unary operator (*) that returns the
value of the variable located at the address specified by its operand.
Example-
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number the
refore
printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference
a
pointer therefore if we print *p, we will get
the value stored at the address contained by p.
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
6.1.1 Pointer to array
int arr[10];
int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integ
er array arr.
6.1.2 Pointer to a function
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a function
6.1.3 Pointer to structure
struct st {
int i;
float f;
}ref;
1. struct st *p = &ref;
2.
7
31
www.gradeup.co
8
32
www.gradeup.co
• decremented ( — )
• an integer may be added to a pointer ( + or += )
• an integer may be subtracted from a pointer ( – or -= )
Pointer arithmetic is meaningless unless performed on an array.
Note : Pointers contain addresses. Adding two addresses makes no sense, because there
is no idea what it would point to. Subtracting two addresses lets you compute the offset
between these two addresses.
Example 1- The output of following program is ________.
int main()
{
int a = 5;
int *ptr ;
ptr = &a;
*ptr = *ptr
* 3;
printf("%d",
a);
return 0;
}
Output: 15
Explanation:
ptr = &a; copies the address of a in ptr making *ptr = a and the statement *ptr = *ptr
* 3; can be written as a = a * 3; making a as 15.
Example 2- The output of following program is ________.
int main()
{
int x = 10;
int *y, **z;
y = &x;
z = &y;
printf("x = %d, y = %d, z = %d\n", x, *y, **z);
return 0;
}
Output: x=10 y=10 z=10
9
33
www.gradeup.co
Explanation:
*y is a pointer variable whereas **z is a pointer to a pointer variable. *y gives the value
at the address it holds and **z searches twice i.e., it first takes the value at the address
it holds and then gives the value at that address.
7. RECURSION IN C
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and such
function calls are called recursive calls. Recursion involves several numbers of recursive calls.
However, it is important to impose a termination condition of recursion. Recursion code is
shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
In the following example, recursion is used to calculate the factorial of a number.
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Output
// let n=5
factorial = 120
We can understand the above program of the recursive method call by the figure given below:
10
34
www.gradeup.co
11
35
www.gradeup.co
{
Void fun ( );
fun ( );
fun ( );
}
void fun ( );
{
static int i = 1;
auto int j = 5;
printf (“%d”, (i++));
printf (“%d”, (j++));
}
A. 1 5 2 6 3 7
B. 2 6 3 7 4 8
C. 1 5 2 5
D. 1 5 2 5 3 5
Answer-C
Solution :
(c)
An object whose storage class is auto, is reinitialized at every function call whereas an
object a whose storage class static persist its value between different function calles.
When the function fun ( ) is called for the first time, value of i and j are printed and
sequentially incremented. During the second function call, i return its incremented value
whereas j is reintialized, h ence i will print 2 and j will print 5 gain.
8. STORAGE CLASSES IN C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C
• Automatic
• External
• Static
• Register
12
36
www.gradeup.co
8.1. Automatic
• Automatic variables are allocated memory automatically at runtime.
• The visibility of the automatic variables is limited to the block in which they are defined.
• The scope of the automatic variables is limited to the block in which they are defined.
• The automatic variables are initialized to garbage by default.
• The memory assigned to automatic variables gets freed upon exiting from the block.
• The keyword used for defining automatic variables is auto.
• Every local variable is automatic in C by default.
Example 1
#include <stdio.h>
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}
Output:
11 20 20 20 11
13
37
www.gradeup.co
8.2. Static
• The variables defined as static specifier can hold their value between the multiple
function calls.
• Static local variables are visible only to the function or the block in which they are
defined.
• A same static variable can be declared many times but can be assigned at only one
time.
• Default initial value of the static integral variable is 0 otherwise null.
• The visibility of the static global variable is limited to the file in which it has declared.
• The keyword used to define static variable is static.
Example 1
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value b/w multiple function calls.
}
}
Output:
10 24
11 25
12 26
8.3. Register
• The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
• We cannot dereference the register variables, i.e., we can not use &operator for the
register variable.
14
38
www.gradeup.co
• The access time of the register variables is faster than the automatic variables.
• The initial default value of the register local variables is 0.
• The register keyword is used for the variable which should be stored in the CPU
register. However, it is compilers choice whether or not; the variables can be stored
in the register.
• We can store pointers into the register, i.e., a register can store the address of a
variable.
• Static variables can not be stored into the register since we can not use more than one
storage specifier for the same variable.
8.4. External
• The external storage class is used to tell the compiler that the variable defined as
extern is declared with an external linkage elsewhere in the program.
• The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
• The default initial value of external integral type is 0 otherwise null.
• We can only initialize the extern variable globally, i.e., we can not initialize the external
variable within any block or method.
• An external variable can be declared many times but can be initialized at only once.
• If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then
the compiler will show an error.
Example-1
#include <stdio.h>
int a = 20;
int main()
{
extern int a;
printf("%d",a);
}
Output
20
****
15
39
www.gradeup.co
16
40
www.gradeup.co
1
41
www.gradeup.co
4 ARRAYS
1. ARRAYS
• Array is a collection of similar elements having same data type, accessed using a common
name.
• An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the
first element of the array.
• Array elements occupy contiguous memory locations.
• If first element is “i” and last element is “j” then:
Number of elements before j = j - i
Number of elements including j = j – i + 1
1.1. Declaration of an Array:
type variable[num_elements];
Example: int A[100];
• It creates an array A with 100 integer elements.
• The size of an array A can’t be changed.
• We cannot declare an array without assigning size. If we declare an array without size,
it will throw compile time error.
• The number between the brackets must be a constant.
2. TYPES OF ARRAYS
2
42
www.gradeup.co
3. INITIALIZATION OF AN ARRAY
Note:
int a[10] : It will be read as an array of 10 elements with integer data type.
• Every array contains a base address which is the address of the first element of the array.
• An array variable is just a pointer to the first element in the array.
• You can access array elements using array notation or pointers.
• print a will print the base address of the array.
• a[0] is the same as *a
• a[1] is the same as *(a + 1)
• a[2] is the same as *(a + 2)
• a = a+0 = &a[0]
• a+1 = &a[1]
3
43
www.gradeup.co
• a+i = &a[i]
• &(*(a+i)) = &a[i] = a+i
• *(&a[i]) = *(a+i) = a[i]
• Address of an element i of array a = a + i * sizeof(element)
Let b be the 2- Dimensional Array b[i][j]
• *(*(b + i) + j) is equivalent to b[i][j], here first * is used to select the rows and the second
* selects the element.
• &b +1 means whole 2-D array is skipped.
• &b gives the base address of the array.
• *b + 1 skips one element.
• *(b + i) + j is equivalent to &b[i][j]
• *(b[i] + j) is equivalent to b[i][j]
• b[i] + j is equivalent to &b[i][j]
• (*(b+i))[j] is equivalent to b[i][j]
4
44
www.gradeup.co
5
45
www.gradeup.co
6. STRINGS
• Strings are defined as an array of characters. The difference between a character array and
a string is the string is terminated with a special character ‘\0’.
• A string is a sequence of characters terminated with a null character \0
• Declaring a string is as simple as declaring a 1- Dimensional array.
• Below is the basic syntax for declaring a string in C programming language.
char str_name[size];
String Declration
1. char str [] = {‘A’, ‘B’, ‘C’, ‘D’, ‘\0’};
2. char st [] = “ABCD”;
⇓
‘\0’ would automatically
Inserted at the end in this type of declaration
Example 5: The string "hello world" contains 12 characters including '\0'
• Before the string class, the abstract idea of a string was implemented with just an array of
characters. For example, here is a string:
char label[] = "Single";
The array in the memory will be as follows:
S i n g l e \0
where the beginning of the array is at some location in computer memory.
• A character array can have more characters than the abstract string held in it, as below:
char label [10] = "Single";
The array will look like:
S i n g l e \0
****
6
46
www.gradeup.co
7
47
www.gradeup.co
1
48
www.gradeup.co
5 STRUCTURES
Structures-
Structure is a user-defined datatype in C language which allows us to combine data of different types
together. Structure helps to construct a complex data type which is more meaningful. It is somewhat
similar to an Array, but an array holds data of similar type only. But structure on the other hand, can
store data of any type, which is practical more useful.
1. DEFINING A STRUCTURE
struct keyword is used to define a structure. struct defines a new data type which is a collection
of primary and derived datatypes.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's optional to
provide your structure a name, we suggest you to give it a name, then inside the curly braces,
we have to mention all the member variables, which are nothing but normal C language
variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this is
optional.
Note: The closing curly brace in the structure type declaration must be followed by a
semicolon(;).
Example of Structure
struct Student
{
char name[25];
int age;
2
49
www.gradeup.co
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4
data fields, namely name, age, branch and gender. These fields are called structure
elements or members.
Each member can have different datatype, like in this case, name is an array of char type
and age is of int type etc. Student is the name of the structure and is called as the structure
tag.
It is possible to declare variables of a structure, either along with structure definition or after
the structure is defined. Structure variable declaration is similar to the declaration of any
normal variable of any other datatype. Structure variables can be declared in following two
ways:
2.1. Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
2.2. Declaring Structure variables with structure definition
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much
recommended.
3
50
www.gradeup.co
Structure members can be accessed and assigned values in a number of ways. Structure
members have no meaning individually without the structure. In order to assign a value to any
structure member, the member name must be linked with the structure variable using a
dot . operator also called period or member access operator.
For example:
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10]; //F for female and M for male
char gender;
};
int main()
{
struct Student s1; /*s1 is a variable of Student type and age is a member of Student*/
s1.age = 18; /* using string function to add name */
strcpy(s1.name, "Camy"); /*displaying the stored values*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
4. STRUCTURE INITIALIZATION
Like a variable of any other datatype, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
4
51
www.gradeup.co
int age;
};
5. ARRAY OF STRUCTURE
We can also declare an array of structure variables. in which each element of the array will
represent a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of
type Employee.
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
};
5
52
www.gradeup.co
6. NESTED STRUCTURES
Nesting of structures, is also permitted in C language. Nested structures means, that one
structure has another structure as member variable.
Example:
struct Student
{
char[30] name;
int age;
/* here Address is a structure */
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};
We can pass a structure as a function argument just like we pass any other variable or an array
as a function argument.
Example:
#include<stdio.h>
struct Student
{
char name[10];
int roll;
};
void show(struct Student st);
6
53
www.gradeup.co
void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
void show(struct Student st)
{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}
In this tutorial, you'll learn to use pointers to access members of structs in C programming.
You will also learn to dynamically allocate memory of struct types.
C Pointers to struct
Here's how you can create pointers to structs
struct name {
member1;
member2;
---
---
};
int main()
{
struct name *ptr, Harry;
}
Here, ptr is a pointer to struct.
Example: Access members using Pointer
To access members of a structure using pointers, we use the -> operator.
#include <stdio.h>
struct person
{
7
54
www.gradeup.co
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
In this example,
the address of person1 is stored in the personPtr pointer using personPtr = &person1;.
Now, you can access the members of person1 using the personPtr pointer.
By the way,
• personPtr->age is equivalent to (*personPtr).age
• personPtr->weight is equivalent to (*personPtr).weight
8
55
www.gradeup.co
Self Referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’
is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing,
as by default it contains garbage value.
Types of Self Referential Structures
1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links
9.1. Self Referential Structure with Single Link: These structures can have only one self-
pointer as their member. The following example will show us how to connect the objects
of a self-referential structure with the single link and access the corresponding data
members. The connection formed is shown in the following figure.
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
9
56
www.gradeup.co
int main()
{
struct node ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
10
57
www.gradeup.co
10. APPLICATIONS
Self referential structures are very useful in creation of other complex data structures like:
• Linked Lists
• Stacks
• Queues
• Trees
• Graphs etc.
****
11
58
www.gradeup.co
12
59
www.gradeup.co
1
60
www.gradeup.co
6 LINKED LISTS
1. LINKED LIST
• Linked List is a very commonly used linear data structure which consists of group
of nodes in a sequence.
• Each node holds its own data and the address of the next node hence forming a chain
like structure.
• Linked Lists are used to create trees and graphs.
1.1. Representation of linked list:
A linked list is represented by a pointer to the first node of the linked list. The first node
is called the head. If the linked list is empty, then the value of the head is NULL.
Each node in a list consists of at least two parts:
1) data
2) Pointer (Or Reference) to the next node
1.2. Advantages of Linked Lists
• They are a dynamic in nature which allocates the memory when required.
• Insertion and deletion operations can be easily implemented.
• Stacks and queues can be easily executed.
• Linked List reduces the access time.
1.3. Disadvantages of Linked Lists
• Extra memory space for a pointer is required with each element of the list.
2
61
www.gradeup.co
3
62
www.gradeup.co
• In the above figure, the address of the first node is always store in a reference node
known as Head or Front. Reference part of the last node must be null.
Advantage
1) Insertions and Deletions can be done easily.
2) It does not need movement of elements for insertion and deletion.
3) Space is not wasted as we can get space according to our requirements.
5) It can be extended or reduced according to requirements as size is not fixed.
6) Elements may or may not be stored in consecutive memory available, even then we
can store the data in computer.
7) It is less expensive.
Disadvantage
1) It requires more space as pointers are also stored with the data.
2) Different amount of time is required to access each element.
3) If we have to go to a particular element then we have to go through all those
elements that come before that element.
4) We cannot traverse it from last & only from the beginning.
5) It is not easy to sort the elements stored in the linear linked list.
2.2. Doubly linked list
• Doubly linked list is a sequence of elements in which every node has link to its
previous node and next node.
• Traversing can be done in both directions and displays the contents in the whole list.
4
63
www.gradeup.co
5
64
www.gradeup.co
6
65
www.gradeup.co
3. CREATION OF A NODE
Creation of a Node:
Structure of a Node:
#include <stdio.h>
struct Node {
#include <stdlib.h>
int data;
struct node
struct Node* next;
{
};
int data;
p= malloc(sizeof(struct node)) : We are allocating the space required for a node by the malloc
function. Now, ‘p’ points to a node (or space allocated for the node).
scanf("%d",&p->data) : We are giving a value to the ‘data’ of ‘p’ after taking the input from
the user.
p->next=NULL : We have given the value to ‘data’ in the previous line and a value of the
pointer ‘next’ (NULL) in this line and thus making our node ‘p’ complete.
7
66
www.gradeup.co
};
Creation of a Node:
void create()
node *newnode;
newnode=(node*)malloc(sizeof(node));
scanf("%d",&newnode->info);
newnode->next=NULL;
if(rear==NULL)
front=rear=newnode;
else
rear->next=newnode;
rear=newnode;
rear->next=front;
8
67
www.gradeup.co
9
68
www.gradeup.co
Step 2 – Traverse to node just before the required position of new node
struct node *temp = head;
if(temp->next != NULL) {
temp = temp->next;
}
}
Step 3 - Change next pointers to include new node in between
newNode->next = temp->next;
temp->next = newNode;
ii. Deletion:
a. At Beginning:
Step 1 - The first node of the list is to be deleted, therefore, we just need to make the
head, point to the next of the head. This will be done by using the following statements.
ptr = head;
head = ptr->next;
Step 2 - Now, free the pointer ptr which was pointing to the head node of the list. This
will be done by using the following statement.
free(ptr)
b. At End-
Step 1 - If head → next = NULL , then the only node head of the list will be assigned to
null.
ptr = head
head = NULL
free(ptr)
Step 2 - The condition head → next = NULL would fail and therefore, so traverse the
node in order to reach the last node of the list.
For this purpose, declare a temporary pointer temp and assign it to head of the list and
also keep track of the second last node of the list. For this purpose, two pointers ptr and
ptr1 will be used where ptr will point to the last node and ptr1 will point to the second
last node of the list.
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
10
69
www.gradeup.co
Step 3 - Now, make the pointer ptr1 point to the NULL and the last node of the list that
is pointed by ptr will become free. It will be done by using the following statements.
ptr1->next = NULL;
free(ptr);
c. In the Middle:
Step 1 – If head is null.
if (head == NULL)
return NULL;
if (head->next == NULL)
{
delete head;
return NULL;
}
Step 2 – If had is not null then. Initialize slow and fast pointers to reach the middle of
linked list .
struct Node *slow_ptr = head;
struct Node *fast_ptr = head;
Step 3 - Find the middle and previous of middle.
struct Node *prev; // To store previous of slow_ptr
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
prev = slow_ptr;
slow_ptr = slow_ptr->next;
}
Step 4 - Delete the middle node
prev->next = slow_ptr->next;
delete slow_ptr;
return head;
}
4.2. Doubly Linked List
i. Insertion:
a. At end-
Step 1 - Create a HEAD pointer which points to the first node of the linked list.
Step 2 - Create a new node TEMP.
Temp ->Data = New_Value;
Temp->Prev = Null;
Temp->Next = Null;
11
70
www.gradeup.co
Step 3 –
if (HEAD ==NULL)
Then, move the address of the new node TEMP into HEAD
else,
Traverse pointer until reached the last node,
Assign HEAD to TEMP->prev and TEMP to Head->next.
b. At beginning-
Step 1 - Allocate the space for the new node in the memory. This will be done by using
the following statement.
ptr = (struct node *)malloc(sizeof(struct node));
Step 2 - Check whether the list is empty or not. The list is empty if the condition head
== NULL holds. In that case, the node will be inserted as the only node of the list and
therefore the prev and the next pointer of the node will point to NULL and the head
pointer will point to this node.
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
Step 3 - In the second scenario, the condition head == NULL become false and the
node will be inserted in beginning. The next pointer of the node will point to the existing
head pointer of the node. The prev pointer of the existing head will point to the new node
being inserted.
ptr->next = head;
head→prev=ptr;
c. In the middle-
Step 1 - Allocate the memory for the new node. Use the following statements for this.
ptr = (struct node *)malloc(sizeof(struct node));
Step 2 - Traverse the list by using the pointer temp to skip the required number of nodes
in order to reach the specified node.
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL) // the temp will be //null if the list doesn't last long //up to
mentioned location
{
return;
}
}
12
71
www.gradeup.co
Step 3 - The temp would point to the specified node at the end of the for loop. The new
node needs to be inserted after this node therefore we need to make a few pointer
adjustments here. Make the next pointer of ptr point to the next node of temp.
ptr → next = temp → next;
Step 4 - Make the prev of the new node ptr point to temp.
ptr → prev = temp;
Step 5 - Make the next pointer of temp point to the new node ptr.
temp → next = ptr;
Step 6 - Make the previous pointer of the next node of temp point to the new node.
temp → next → prev = ptr;
ii. Deletion:
a. At end-
Step 1 - Traverse to second last element
struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
Step 2 - Change its next pointer to null
temp->next = NULL;
b. At Beginning-
Step 1 - Copy the head pointer to pointer ptr and shift the head pointer to its next.
Ptr = head;
head = head → next;
Step 2 - Now make the prev of this new head node point to NULL. This will be done by
using the following statements.
head → prev = NULL
Step 3 - Now free the pointer ptr by using the free function.
free(ptr)
c. In the Middle-
Step 1 - Traverse to element before the element to be deleted
for(int i=2; i< position; i++) {
if(temp->next!=NULL) {
temp = temp->next;
}
}
Step 2 - Change next pointers to exclude the node from the chain
temp->next = temp->next->next;
13
72
www.gradeup.co
14
73
www.gradeup.co
Step 2 - In the first scenario, the condition head == NULL will be true. Since, the list in
which, we are inserting the node is a circular singly linked list, therefore the only node of
the list (which is just inserted into the list) will point to itself only. We also need to make
the head pointer point to this node. This will be done by using the following statements.
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
Step 3 - In the second scenario, the condition head == NULL will become false which
means that the list contains at least one node. In this case, traverse the list in order to
reach the last node of the list.
temp = head;
while(temp->next != head)
temp = temp->next;
Step 4 - At the end of the loop, the pointer temp would point to the last node of the list.
Since, the new node which is being inserted into the list will be the new last node of the
list. Therefore, the existing last node i.e. temp must point to the new node ptr.
temp -> next = ptr;
Step 5 - The new last node of the list i.e. ptr will point to the head node of the list.
ptr -> next = head;
c. In the Middle-
Step 1: Declaring head and tail pointer as null.
struct node *head = NULL;
struct node *tail = NULL;
int size = 0;
Step 2: Creating new node.
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
Step 3: Checks if the list is empty. If list is empty, both head and tail would point to
new node.
if(head == NULL){
head = newNode;
tail = newNode;
newNode->next = head;
}else {
tail->next = newNode;
tail = newNode;
tail->next = head;
}
15
74
www.gradeup.co
16
75
www.gradeup.co
Step 3 - If the list contains more than one node then, in that case, traverse the list by
using the pointer ptr to reach the last node of the list.
ptr = head;
while(ptr -> next != head)
ptr = ptr -> next;
Step 4 - At the end of the loop, the pointer ptr point to the last node of the list. Since,
the last node of the list points to the head node of the list. Therefore, this will be changed
as, the last node of the list will point to the next of the head node.
ptr->next = head->next;
Step 5 - Free the head pointer by using the free() method in C language.
free(head);
Step 6 - Make the node pointed by the next of the last node, the new head of the list.
head = ptr->next;
b. At End:
Step 1 - If the list is empty then the condition head == NULL will become true, in this
case, print underflow on the screen and make exit.
if(head == NULL)
{
printf("\nUNDERFLOW");
return;
}
Step 2 - If the list contains single node then, the condition head → next == head will
become true. In this case, delete the entire list and make the head pointer free.
if(head->next == head)
{
head = NULL;
free(head);
}
Step 3 - If the list contains more than one element, then in order to delete the last
element, we need to reach the last node. We also need to keep track of the second last
node of the list. For this purpose, the two pointers ptr and preptr are defined.
ptr = head;
while(ptr ->next != head)
{
preptr=ptr;
ptr = ptr->next;
}
17
76
www.gradeup.co
Step 4 - Make just one more pointer adjustment. Make the next pointer of preptr point
to the next of ptr (i.e. head) and then make pointer ptr free.
preptr->next = ptr -> next;
free(ptr);
c. In the Middle:
Step 1: Find length of list
int len = Length(*head);
int count = 1;
struct Node *previous = *head, *next = *head;
Step 2: Check if list doesn't have any node.
if (*head == NULL) {
printf("\nDelete Last List is empty\n");
return;
}
Step 3: Check whether given index is in list or not
if (index >= len || index < 0) {
printf("\nIndex is not Found\n");
return;
}
Step 4: Delete first node and traverse to the last node and delete the required node.
if (index == 0) {
DeleteFirst(head);
return;
}
while (len > 0) {
if (index == count) {
previous->next = next->next;
free(next);
return;
}
previous = previous->next;
next = previous->next;
len--;
count++;
}
return;
}
18
77
www.gradeup.co
5. TIME COMPLEXITY
Insertion Deletion
Example 1: Consider the below code, which deletes a node from the beginning of a
list:
Void deletefront()
{
If (head == Null)
return;
else
{
……………….
.………………
……………….
}
}
Which lines will correctly implement else part of above code?
(a) if (head → next == Null )
head = head → next;
(b) if ( head == tail )
head = tail = Null;
else
head = head → next;
(c) if ( head == tail == null)
Head = head → next;
(d) head = head -> next;
Example 2: What does the following function do for a given linked list :
void fun1(struct Node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
19
78
www.gradeup.co
Sol: fun1() prints the given Linked List in reverse manner. For Linked List 1->2->3->4->5,
fun1() prints 5->4->3->2->1.
Example 3: Consider the following function that takes reference to head of a Doubly Linked
List as parameter. Assume that a node of doubly linked list has previous pointer as prev and
next pointer as next.
void fun(struct node **head_ref)
{
struct node *temp = NULL;
struct node *current = *head_ref;
while (current != NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if(temp != NULL )
*head_ref = temp->prev;
}
Assume that reference of head of following doubly linked list is passed to above
function.
1 2 3 4 5 6.
What should be the modified linked list after the function call?
(a) 2 1 4 3 6 5
(b) 5 4 3 2 1 6.
(c) 6 5 4 3 2 1.
(d) 6 5 4 3 1 2
Sol. The given function reverses the given doubly linked list.
Hence, option C is correct.
Example 4 : The following C function takes a simply-linked list as input argument. It modifies
the list by moving the last element to the front of the list and returns the modified list. Some
part of the code is left blank. Choose the correct alternative to replace the blank line.
typedef struct node
{
int value;
struct node *next;
20
79
www.gradeup.co
}Node;
Node *move_to_front(Node *head)
{
Node *p, *q;
if ((head == NULL: || (head->next == NULL))
return head;
q = NULL; p = head;
while (p-> next !=NULL)
{
q = p;
p = p->next;
}
return head;
}
(a) q = NULL; p->next = head; head = p;
(b) q->next = NULL; head = p; p->next = head;
(c) head = p; p->next = q; q->next = NULL;
(d) q->next = NULL; p->next = head; head = p;
Sol: Option D is correct.
****
21
80
www.gradeup.co
22
81
www.gradeup.co
1
82
www.gradeup.co
7 STACKS
1. STACKS
• A stack is a last in first out (LIFO) abstract data type and data structure.
• There are basically three operations that can be performed on stacks. They are:
a) PUSH: Inserting an item into a stack
b) POP: Deleting an item from the stack.
c) PEEK: Displaying the contents of the stack.
2
83
www.gradeup.co
2. IMPLEMENTATION OF STACK
2.1. Array Implementation: Array implementation aims to create an array where the first
element inserted is placed at stack[0] and it will be deleted last. In array implementation
track of the element inserted at the top must be kept.
Implementing PUSH:
void push (int val,int n) //n is size of the stack
{
if (top == n )
printf("\n Overflow");
else
{
top = top +1;
stack[top] = val;
}
}
Implementing POP:
int pop ()
{
if(top == -1)
{
printf("Underflow");
return 0;
}
else
{
return stack[top - - ];
}
}
2.2. Linked List Implementation: It is also called as dynamic implementation as the stack
size can grow and shrink as the elements are added or removed respectively from the
stack.
• The PUSH operation on stack is same as insert a node in Single linked list.
• The POP operation is same as delete a node in Single linked List.
3
84
www.gradeup.co
Implementing PUSH:
void push ()
{
int val;
struct node *ptr =(struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed");
}
}
Implementing POP:
void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
4
85
www.gradeup.co
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
}
2.3. Queue Implementation: A stack can be implemented using two queues. Let stack to
be implemented be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Stack ‘s’ can be
implemented as:
Newly entered element is always at the front of ‘q1’, so that pop operation just dequeues
from ‘q1’. ‘q2’ is used to put every new element at front of ‘q1’.
a) push(s, x) operation’s step are described below:
• Enqueue x to q2
• One by one dequeue everything from q1 and enqueue to q2.
• Swap the names of q1 and q2
b) pop(s) operation’s function are described below:
• Dequeue an item from q1 and return it.
3. EXPRESSION NOTATION
a) Infix Expression: Here, the binary operator comes between the operands.
Eg: a+b
b) Postfix Expression: Here, the binary operator comes after both the operands. It is also
known as Polish Notation.
Eg: ab+
c) Prefix Expression: Here, the binary operator comes before both the operands. . It is also
known as Reverse Polish Notation.
Eg: +ab
5
86
www.gradeup.co
4. APPLICATIONS OF STACK
6
87
www.gradeup.co
7
88
www.gradeup.co
5 5
2 5, 2
3 5, 2, 3
4 5, 2, 3, 4
+ 4 3 7 5, 2
5, 2, 7
* 7 2 14 5
5, 14
8
89
www.gradeup.co
9
90
www.gradeup.co
/ -de )/
) -de )/)
c c-de )/)
* c-de )/)*
b bc-de )/)*
( *bc-de )/
+ /*bc-de )+
a a/*bc-de )+
( +a/*bc-de Empty
10
91
www.gradeup.co
Example 3: What is the result of the given postfix expression? abc*+ where a=1,
b=2, c=3.
a) 4
b) 5
c) 6
d) 7
Answer: D
The infix expression is a+b*c. Evaluating it, we get 1+2*3=7
Example 4: +9*26
a. 22
b. 23
c. 21
d. 20
Character Stack (Front to
Explanation
Scanned Back)
6 6 6 is an operand, push to Stack
Result: 21
11
92
www.gradeup.co
Pop C from stack [AK/L-] Pop two operands from stack, B and C. Perform BC/
/
and push BC/to stack
[AK/L-,
Push BC/ to stack
BC/]
[AK/L-,
A Push A to stack
BC/,A]
[AK/L-,
Pop A from stack
BC/]
Pop BC/ from Pop two operands from stack, A and BC. Perform ABC/-
- [AK/L-]
stack and push ABC/-to stack
Push ABC/- to [AK/L-,
stack ABC/-]
Pop ABC/- from
[AK/L-]
stack
Pop AK/L- from Pop two operands from stack, ABC/- and AK/L-.
* []
stack Perform ABC/-AK/L-* and push ABC/-AK/L-* to stack
Push ABC/-AK/L- [ABC/-
* to stack AK/L-*]
Postfix Expression: ABC/-AK/L-*
****
12
93
www.gradeup.co
13
94
www.gradeup.co
1
95
www.gradeup.co
8 QUEUES
1. QUEUES
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is
open at both its ends.
One end is always used to insert data (enqueue) and the other is used to remove data
(dequeue).
Queues follow the First In First Out (FIFO) i.e. the first element that is added to the queue
is the first one to be removed.
Elements are always added to the back and removed from the front.
2. TYPES OF QUEUE
A simple queue performs the operations simply. i.e., the insertion and deletions are
performed likewise. Insertion occurs at the rear (end) of the queue and deletions are
performed at the front (beginning) of the queue list.
All nodes are connected to each other in a sequential manner. The pointer of the first
node points to the value of the second and so on.
The first node has no pointer pointing towards it whereas the last node has no pointer
pointing out from it.
Adding an element will be performed after checking whether the queue is full or not. If
rear < n which indicates that the array is not full then store the element at arr[rear] and
increment rear by 1 but if rear == n then it is said to be an Overflow condition as the
array is full.
An element can only be deleted when there is at least an element to delete i.e. rear > 0.
Now, element at arr[front] can be deleted but all the remaining elements have to shifted
to the left by one position in order for the dequeue operation to delete the second element
from the left on another dequeue operation.
2
96
www.gradeup.co
2. 2. Circular Queue
Unlike the simple queues, in a circular queue each node is connected to the next node in
sequence but the last node’s pointer is also connected to the first node’s address. Hence,
the last node and the first node also gets connected making a circular link overall.
A circular queue overcomes the problem of un-utilized space in linear queues
implemented as arrays. We can make following assumptions for circular queue.
• If : (Rear+1) % n == Front, then queue is Full
• If Front = Rear, the queue will be empty.
• Each time a new element is inserted into the queue, the Rear is incremented by 1. Rear
= (Rear + 1) ) % n
• Each time, an element is deleted from the queue, the value of Front is incremented by
one. Front = (Front + 1) % n
2.3. Priority Queue
Priority queue makes data retrieval possible only through a pre-determined priority
number assigned to the data items.
While the deletion is performed in accordance to priority number (the data item with
highest priority is removed first), insertion is performed only in the order.
3
97
www.gradeup.co
The doubly ended queue or dequeue allows the insert and delete operations from both
ends (front and rear) of the queue.
Queues are an important concept of the data structures and understanding their types
is very necessary for working appropriately with them.
3. OPERATIONS ON QUEUE
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueuing
(or storing) data in the queue we take help of rear pointer.
3.1. Enqueue:
Add (store) an item to the queue.
If the queue is not full, this function adds an element to the back of the queue, else it
prints “OverFlow”.
Step 1: Check if the queue is full.
Step 2: If the queue is full, produce overflow error and exit.
Step 3: If the queue is not full, increment rear pointer to point the next empty space.
Step 4: Add data element to the queue location, where the rear is pointing.
Step 5: return success.
procedure enqueue(data)
Pseudo Code of Enqueue:
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Implementation of enqueue() in C program:
void enqueue(int queue[], int element, int& rear, int arraySize) {
if(rear == arraySize) // Queue is full
4
98
www.gradeup.co
printf(“OverFlow\n”);
else{
queue[rear] = element; // Add the element to the back
rear++; }
}
3.2. Dequeue:
Remove (access) an item from the queue. Accessing data from the queue is a process
of two tasks − access the data where front is pointing and remove the data after
access.
If the queue is not empty, this function removes the element from the front of the
queue, else it prints “UnderFlow”.
Step 1: Check if the queue is empty.
Step 2: If the queue is empty, produce underflow error and exit.
Step 3: If the queue is not empty, access the data where front is pointing.
Step 4: Increment front pointer to point to the next available data element.
Step 5: Return success.
1
Implementation of enqueue() in C program:
void dequeue(int queue[], int& front, int rear) {
if(front == rear) // Queue is empty
printf(“UnderFlow\n”);
else {
queue[front] = 0; // Delete the front element
front++;
}
}
5
99
www.gradeup.co
Time Complexities:
• queue insertion i.e. Enqueue takes O(1).
• queue deletion i.e. Dequeue takes O(1).
• Access time is O(n).
4. APPLICATIONS OF QUEUE
One area where this comes into play is breadth first search. Let’s say you have a tree of
nodes:
The root node (1), would have a data property of 1, with a children array of nodes 8, 5,
and 2. The node with the data property of 8 would have children array of nodes 6, 4, and
3, and so on.
6
100
www.gradeup.co
7
101
www.gradeup.co
6. APPLICATIONS OF QUEUE
8
102
www.gradeup.co
9
103
www.gradeup.co
1
104
www.gradeup.co
9 TREES
1. TREES
• A tree is a non-linear data structure designated at a special node called the root and
elements are arranged in levels without containing cycles.
• All the elements are arranged in layers.
• A unique path traverses from root to any node of tree.
• Every child has only one parent, but the parent can have many children.
• If a tree has N vertices(nodes) than the number of edges is always one less than the number
of nodes(vertices) i.e N-1. If it has more than N-1 edges it is called a graph not a tree.
2
105
www.gradeup.co
2. TYPES OF TREES
• Time Complexities:
Insertion: O(n) {Every Case}
Deletion: O(n) {Every Case}
2n
Number of different Binary Tree possible with ‘n’ labelled nodes = Cn
n!
n+1
2𝑛𝐶𝑛
Number of different Binary Tree possible with ‘n’ unlabelled nodes =
𝑛+1
3
106
www.gradeup.co
4
107
www.gradeup.co
• In a complete binary tree, every internal node has exactly two children and all leaf
nodes are at same level.
• For example, at Level 2, there must be 22 = 4 nodes and at Level 3 there must be 23 =
8 nodes.
c. Skewed Binary Tree
• If a tree which is dominated by left child node or right child node, is said to be
a Skewed Binary Tree.
• In a skewed binary tree, all nodes except one have only one child node. The remaining
node has no child.
• In a left skewed tree, most of the nodes have the left child without corresponding right
child.
• In a right skewed tree, most of the nodes have the right child without corresponding
left child.
d. Strict Binary Tree:
• If every non-leaf node in a binary tree has nonempty left and right subtrees, the tree is
called a strict binary tree.
• A strict binary tree with n leaves always contains 2n -1 nodes.
• If every non-leaf node in a binary tree has nonempty left and right subtrees,
the tree is termed a strict binary tree. Or, to put it another way, all of the nodes in
a strict binary tree are of degree zero or two, never degree one.
5
108
www.gradeup.co
6
109
www.gradeup.co
3. TREE TRAVERSAL
Pre-order : A B D F E C G I H J
In-order : F D B E A G I C H J
Post-order : F D E B I G J H C A
Pre-order, In-order and post-order uniquely identify the tree.
7
110
www.gradeup.co
8
111
www.gradeup.co
9
112
www.gradeup.co
In the following image, the node 50 is to be deleted which is the root node of the tree.
The in-order traversal of the tree given below.
6, 25, 30, 50, 52, 60, 70, 75.
replace 50 with its in-order successor 52. Now, 50 will be moved to the leaf of the tree,
which will simply be deleted.
NOTE:
Example 3: Which of the following list of nodes corresponds to post order traversal of
the binary tree shown below?
(A) A B C D E F G H I J
(B) J I H G F E D C B A
(C) D H E B I F J G C A
(D) D E H F I G J B C A
Sol: The correct option is C as in post oredr traversal we follow left child, right child, root.
Hence DHEBIFJGCA.
9. A binary search tree is generated by inserting in order the following integers :
55, 15, 65, 5, 25, 59, 90, 2, 7, 35, 60, 23
The number of nodes in the left subtree and right sub tree of the root respectively are
(A) 8, 3
(B) 7, 4
(C) 3, 8
(D) 4, 7
10
113
www.gradeup.co
Here 55 is the root node so, all the elements smaller than 55 will go on the left of all the
elements greater than 55 will go on the RHS.
Hence, option B is correct
Example 4 : How many distinct binary search trees can be constructed out of 4
distinct keys?
a. 14
b. 24
c. 35
d. 5
Solution-
Number of distinct binary search trees possible with 4 distinct keys
= 2n
Cn / n+1
= 2×4
C4 / 4+1
= C4 / 5
8
= 14
Thus, Option (A) is correct.
Example 5: Consider we want to draw all the binary trees possible with 3
unlabelled nodes.
Sol: Number of binary trees possible with 3 unlabelled nodes
= 2x3
C3 / (3 + 1)
= 6C3 / 4
=5
11
114
www.gradeup.co
5. HEAPS
• Heap is a special case of balanced binary tree data structure where the root-node key is
compared with its children and arranged accordingly.
• Heaps also has an additional property that all leaves should be at h or h-1 levels, where h
is the height of the tree.
Min-Heap − Where the value of the root node is less than or equal to either of its children.
The same property must be true for all subtrees.
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
The same property must be true for all subtrees.
10 14 19 26 31 42 27 10 26 14
12
115
www.gradeup.co
One important property of heap is that, if an element is not satisfying the heap property
then all the elements from that element to root will also have the same problem.
In below example, element 1 is not satisfying the heap property and its parent 31 is also
having the issue. Similarly, if we heapify an element then all the elements from that
element to root will also satisfy the heap property automatically.
In the above heap, the element 1 is not satisfying the heap property so, heapifying this
element.
To heapify 1, find maximum of its children and swap with that.
Continue this process until the element satisfies the heap properties. Now, swap 1 with
8.
13
116
www.gradeup.co
In-order to heapify this element (19), compare it with its parent and adjust them.
Swapping 19 and 14 gives :
14
117
www.gradeup.co
15
118
www.gradeup.co
6. AVL TREE
• The above tree is AVL tree because the difference between heights of left and right subtrees
for every node is less than or equal to 1.
• The above tree is not AVL because the difference between heights of left and right subtrees
for 9 and 19 is greater than 1.
• It checks the height of the left and right subtree and assures that the difference is not more
than 1. The difference is called balance factor.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
• The minimum number of nodes with height h is:
N(h) = minimum number of nodes with height h-1 + minimum number of nodes with height h-2 + 1
16
119
www.gradeup.co
i. Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree of the right
subtree, then we perform a single left rotation −
Here, node A has become unbalanced as a node is inserted in the right subtree of A's
right subtree. Hence, left rotation is performed by making A the left-subtree of B.
ii. Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of the left
subtree. The tree then needs a right rotation.
Here, the unbalanced node becomes the right child of its left child by performing a right
rotation.
iii. Left-Right Rotation
A left-right rotation is a combination of left rotation followed by right rotation.
17
120
www.gradeup.co
State Action
A node has been inserted into the right subtree of the left subtree. This makes C an
unbalanced node. These scenarios cause AVL tree to perform left-right rotation.
first perform the left rotation on the left subtree of C. This makes A, the left subtree
of B.
Node C is still unbalanced, however now, it is because of the left-subtree of the left-
subtree.
Now right-rotate the tree, making B the new root node of this subtree. C now
becomes the right subtree of its own left subtree.
18
121
www.gradeup.co
4. Right-Left Rotation
The second type of double rotation is Right-Left Rotation. It is a combination of right
rotation followed by left rotation.
State Action
A node has been inserted into the left subtree of the right subtree. This makes A,
an unbalanced node with balance factor 2.
First, perform the right rotation along C node, making C the right subtree of its
own left subtree B. Now, B becomes the right subtree of A.
Node A is still unbalanced because of the right subtree of its right subtree and
requires a left rotation.
19
122
www.gradeup.co
b. Deletion:
Delete(T,k) means delete a node with the key k from the AVL tree T.
I) Find the node x where k is stored
II) Delete the contents of node x
There are three possible cases:
1) If x has no children (i.e., is a leaf), delete x.
2) If x has one child, let x' be the child of x.
20
123
www.gradeup.co
Sol: In this case, the node B has balance factor 0, therefore the tree will be rotated by
using R0 rotation as shown in the following image. The node B(10) becomes the root,
while the node A is moved to its right. The right child of node B will now become the left
child of node A.
21
124
www.gradeup.co
7. B- TREE
• B Tree is a specialized m-way tree that can be widely used for disk access.
• A B-Tree of order m can have at most m-1 keys and m children.
• One of the main reason of using B tree is its capability to store large number of keys in a
single node and large key values by keeping the height of the tree relatively small.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
8. B+ TREE
• B+ Tree is an extension of B Tree which allows efficient insertion, deletion and search
operations.
• In B Tree, Keys and records both can be stored in the internal as well as leaf nodes. Whereas,
in B+ tree, records (data) can only be stored on the leaf nodes while internal nodes can only
store the key values.
• The leaf nodes of a B+ tree are linked together in the form of a singly linked lists to make
the search queries more efficient.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
Example 9: Construct minimal AVL trees of height 0, 1, 2, 3, and 4. What is the number of
nodes in a minimal AVL tree of height 5?
Sol. Let n(h) be the number of nodes in a minimal AVL tree with height h.
N(0) = 1
22
125
www.gradeup.co
N(1) = 2
N(h) = 1 + N (h – 1) + N(h – 2)
23
126
www.gradeup.co
24
127
www.gradeup.co
1
128
www.gradeup.co
9 TREES
1. TREES
• A tree is a non-linear data structure designated at a special node called the root and
elements are arranged in levels without containing cycles.
• All the elements are arranged in layers.
• A unique path traverses from root to any node of tree.
• Every child has only one parent, but the parent can have many children.
• If a tree has N vertices(nodes) than the number of edges is always one less than the number
of nodes(vertices) i.e N-1. If it has more than N-1 edges it is called a graph not a tree.
2
129
www.gradeup.co
2. TYPES OF TREES
• Time Complexities:
Insertion: O(n) {Every Case}
Deletion: O(n) {Every Case}
2n
Number of different Binary Tree possible with ‘n’ labelled nodes = Cn
n!
n+1
2𝑛𝐶𝑛
Number of different Binary Tree possible with ‘n’ unlabelled nodes =
𝑛+1
3
130
www.gradeup.co
4
131
www.gradeup.co
• In a complete binary tree, every internal node has exactly two children and all leaf
nodes are at same level.
• For example, at Level 2, there must be 22 = 4 nodes and at Level 3 there must be 23 =
8 nodes.
c. Skewed Binary Tree
• If a tree which is dominated by left child node or right child node, is said to be
a Skewed Binary Tree.
• In a skewed binary tree, all nodes except one have only one child node. The remaining
node has no child.
• In a left skewed tree, most of the nodes have the left child without corresponding right
child.
• In a right skewed tree, most of the nodes have the right child without corresponding
left child.
d. Strict Binary Tree:
• If every non-leaf node in a binary tree has nonempty left and right subtrees, the tree is
called a strict binary tree.
• A strict binary tree with n leaves always contains 2n -1 nodes.
• If every non-leaf node in a binary tree has nonempty left and right subtrees,
the tree is termed a strict binary tree. Or, to put it another way, all of the nodes in
a strict binary tree are of degree zero or two, never degree one.
5
132
www.gradeup.co
6
133
www.gradeup.co
3. TREE TRAVERSAL
Pre-order : A B D F E C G I H J
In-order : F D B E A G I C H J
Post-order : F D E B I G J H C A
Pre-order, In-order and post-order uniquely identify the tree.
7
134
www.gradeup.co
8
135
www.gradeup.co
9
136
www.gradeup.co
In the following image, the node 50 is to be deleted which is the root node of the tree.
The in-order traversal of the tree given below.
6, 25, 30, 50, 52, 60, 70, 75.
replace 50 with its in-order successor 52. Now, 50 will be moved to the leaf of the tree,
which will simply be deleted.
NOTE:
Example 3: Which of the following list of nodes corresponds to post order traversal of
the binary tree shown below?
(A) A B C D E F G H I J
(B) J I H G F E D C B A
(C) D H E B I F J G C A
(D) D E H F I G J B C A
Sol: The correct option is C as in post oredr traversal we follow left child, right child, root.
Hence DHEBIFJGCA.
9. A binary search tree is generated by inserting in order the following integers :
55, 15, 65, 5, 25, 59, 90, 2, 7, 35, 60, 23
The number of nodes in the left subtree and right sub tree of the root respectively are
(A) 8, 3
(B) 7, 4
(C) 3, 8
(D) 4, 7
10
137
www.gradeup.co
Here 55 is the root node so, all the elements smaller than 55 will go on the left of all the
elements greater than 55 will go on the RHS.
Hence, option B is correct
Example 4 : How many distinct binary search trees can be constructed out of 4
distinct keys?
a. 14
b. 24
c. 35
d. 5
Solution-
Number of distinct binary search trees possible with 4 distinct keys
= 2n
Cn / n+1
= 2×4
C4 / 4+1
= C4 / 5
8
= 14
Thus, Option (A) is correct.
Example 5: Consider we want to draw all the binary trees possible with 3
unlabelled nodes.
Sol: Number of binary trees possible with 3 unlabelled nodes
= 2x3
C3 / (3 + 1)
= 6C3 / 4
=5
11
138
www.gradeup.co
5. HEAPS
• Heap is a special case of balanced binary tree data structure where the root-node key is
compared with its children and arranged accordingly.
• Heaps also has an additional property that all leaves should be at h or h-1 levels, where h
is the height of the tree.
Min-Heap − Where the value of the root node is less than or equal to either of its children.
The same property must be true for all subtrees.
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
The same property must be true for all subtrees.
10 14 19 26 31 42 27 10 26 14
12
139
www.gradeup.co
One important property of heap is that, if an element is not satisfying the heap property
then all the elements from that element to root will also have the same problem.
In below example, element 1 is not satisfying the heap property and its parent 31 is also
having the issue. Similarly, if we heapify an element then all the elements from that
element to root will also satisfy the heap property automatically.
In the above heap, the element 1 is not satisfying the heap property so, heapifying this
element.
To heapify 1, find maximum of its children and swap with that.
Continue this process until the element satisfies the heap properties. Now, swap 1 with
8.
13
140
www.gradeup.co
In-order to heapify this element (19), compare it with its parent and adjust them.
Swapping 19 and 14 gives :
14
141
www.gradeup.co
15
142
www.gradeup.co
6. AVL TREE
• The above tree is AVL tree because the difference between heights of left and right subtrees
for every node is less than or equal to 1.
• The above tree is not AVL because the difference between heights of left and right subtrees
for 9 and 19 is greater than 1.
• It checks the height of the left and right subtree and assures that the difference is not more
than 1. The difference is called balance factor.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
• The minimum number of nodes with height h is:
N(h) = minimum number of nodes with height h-1 + minimum number of nodes with height h-2 + 1
16
143
www.gradeup.co
i. Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree of the right
subtree, then we perform a single left rotation −
Here, node A has become unbalanced as a node is inserted in the right subtree of A's
right subtree. Hence, left rotation is performed by making A the left-subtree of B.
ii. Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of the left
subtree. The tree then needs a right rotation.
Here, the unbalanced node becomes the right child of its left child by performing a right
rotation.
iii. Left-Right Rotation
A left-right rotation is a combination of left rotation followed by right rotation.
17
144
www.gradeup.co
State Action
A node has been inserted into the right subtree of the left subtree. This makes C an
unbalanced node. These scenarios cause AVL tree to perform left-right rotation.
first perform the left rotation on the left subtree of C. This makes A, the left subtree
of B.
Node C is still unbalanced, however now, it is because of the left-subtree of the left-
subtree.
Now right-rotate the tree, making B the new root node of this subtree. C now
becomes the right subtree of its own left subtree.
18
145
www.gradeup.co
4. Right-Left Rotation
The second type of double rotation is Right-Left Rotation. It is a combination of right
rotation followed by left rotation.
State Action
A node has been inserted into the left subtree of the right subtree. This makes A,
an unbalanced node with balance factor 2.
First, perform the right rotation along C node, making C the right subtree of its
own left subtree B. Now, B becomes the right subtree of A.
Node A is still unbalanced because of the right subtree of its right subtree and
requires a left rotation.
19
146
www.gradeup.co
b. Deletion:
Delete(T,k) means delete a node with the key k from the AVL tree T.
I) Find the node x where k is stored
II) Delete the contents of node x
There are three possible cases:
1) If x has no children (i.e., is a leaf), delete x.
2) If x has one child, let x' be the child of x.
20
147
www.gradeup.co
Sol: In this case, the node B has balance factor 0, therefore the tree will be rotated by
using R0 rotation as shown in the following image. The node B(10) becomes the root,
while the node A is moved to its right. The right child of node B will now become the left
child of node A.
21
148
www.gradeup.co
7. B- TREE
• B Tree is a specialized m-way tree that can be widely used for disk access.
• A B-Tree of order m can have at most m-1 keys and m children.
• One of the main reason of using B tree is its capability to store large number of keys in a
single node and large key values by keeping the height of the tree relatively small.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
8. B+ TREE
• B+ Tree is an extension of B Tree which allows efficient insertion, deletion and search
operations.
• In B Tree, Keys and records both can be stored in the internal as well as leaf nodes. Whereas,
in B+ tree, records (data) can only be stored on the leaf nodes while internal nodes can only
store the key values.
• The leaf nodes of a B+ tree are linked together in the form of a singly linked lists to make
the search queries more efficient.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
Example 9: Construct minimal AVL trees of height 0, 1, 2, 3, and 4. What is the number of
nodes in a minimal AVL tree of height 5?
Sol. Let n(h) be the number of nodes in a minimal AVL tree with height h.
N(0) = 1
22
149
www.gradeup.co
N(1) = 2
N(h) = 1 + N (h – 1) + N(h – 2)
23
150
www.gradeup.co
24
151
www.gradeup.co
1
152
www.gradeup.co
1. JAVA
2
153
www.gradeup.co
Therefore here is a simple task of printing “Hello World” in Java. During this process, major
components and their syntaxes are explained clearly.
3. Comments in Java: In a program, comments take part in making the program become more
human-readable by placing the detail of code involved and proper use of comments makes
maintenance easier and finding bugs easily. Comments are ignored by the compiler while
compiling the code.
4. Data Types in Java: Each variable in Java has an associated data type. Each data type
requires different amounts of memory and has some specific operations which can be
performed over it.
5. Variables in Java: A variable is the name given to a memory location. It is the basic unit of
storage in a program.
6. Keywords in Java: Keywords or Reserved words are the words in a language that are used
for some internal process or represent some predefined actions. These words are therefore
not allowed to use as variable names or objects. Doing this will result in a compile-time
error.
7. Operators in Java: Operators are the foundation of any programming language. Thus the
functionality of Java programming language is incomplete without the use of operators. 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.
8. Decision Making (Control Statements) in Java: Decision Making in programming is similar to
decision making in real life. In programming also we face some situations where we want a
certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the
program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.
9. Loops in Java: Looping in programming languages is a feature which facilitates the execution
of a set of instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition checking time.
1.1. How JVM Works – JVM Architecture?
JVM (Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the
one that calls the main method present in a java code. JVM is a part of JRE (Java Runtime
Environment).
JVM (Java Virtual Machine) Architecture
1. Java Virtual Machine
2. Internal Architecture of JVM
3
154
www.gradeup.co
4
155
www.gradeup.co
• Encapsulation. This is the practice of keeping fields within a class private, then
providing access to them via public methods. It’s a protective barrier that keeps the data
and code safe within the class itself. This way, we can re-use objects like code
components or variables without allowing open access to the data system-wide.
• Inheritance. This is a special feature of Object Oriented Programming in Java. It lets
programmers create new classes that share some of the attributes of existing classes.
This lets us build on previous work without reinventing the wheel.
• Polymorphism. This Java OOP concept lets programmers use the same word to mean
different things in different contexts. One form of polymorphism in Java is method
overloading. That’s when different meanings are implied by the code itself. The other
form is method overriding. That’s when the different meanings are implied by the
values of the supplied variables. See more on this below.
1.3. What is String in java
Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create a string
object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool, that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant
pool".
Why Java uses the concept of String literal?
5
156
www.gradeup.co
To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer
to the object in a heap (non-pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output-
java
strings
example
1.4. Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In this page, we will learn about Java exceptions, its type and the difference between
checked and unchecked exceptions.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
6
157
www.gradeup.co
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is
why we use exception handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed.
That is why we use exception handling in Java.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
7
158
www.gradeup.co
Additionally, it can access all the members of outer class including private data members
and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
1.6. Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in
a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
8
159
www.gradeup.co
• Each process has an address in memory. In other words, each process allocates a
separate memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
1.6. What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path
of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
Java Multithreading
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.
2. (DOT) .NET
The .Net framework is a software development platform developed by Microsoft. The framework
was meant to create applications, which would run on the Windows Platform. The first version
of the .Net framework was released in the year 2002.
9
160
www.gradeup.co
The version was called .Net framework 1.0. The .Net framework has come a long way since
then, and the current version is 4.7.1.
The .Net framework can be used to create both - Form-based and Web-
based applications. Web services can also be developed using the .Net framework.
The framework also supports various programming languages such as Visual Basic and C#. So
developers can choose and select the language to develop the required application. In this
chapter, you will learn some basics of the .Net framework.
• Net Framework Architecture
The basic architecture of the .Net framework is as shown below.
10
161
www.gradeup.co
o The database connection is no longer required. If the application has finished all
operations on a database, then the database connection may no longer be required.
• Working with Various programming languages –
As noted in an earlier section, a developer can develop an application in a variety of .Net
programming languages.
1. Language - The first level is the programming language itself, the most common ones
are VB.Net and C#.
2. Compiler – There is a compiler which will be separate for each programming language.
So underlying the VB.Net language, there will be a separate VB.Net compiler. Similarly,
for C#, you will have another compiler.
3. Common Language Interpreter – This is the final layer in .Net which would be used to
run a .net program developed in any programming language. So the subsequent compiler
will send the program to the CLI layer to run the .Net application.
11
162
www.gradeup.co
• WinForms – This is used for developing Forms-based applications, which would run on
an end user machine. Notepad is an example of a client-based application.
• ASP.Net – This is used for developing web-based applications, which are made to run
on any browser such as Internet Explorer, Chrome or Firefox.
o The Web application would be processed on a server, which would have Internet
Information Services Installed.
o Internet Information Services or IIS is a Microsoft component which is used to execute
an Asp.Net application.
o The result of the execution is then sent to the client machines, and the output is shown
in the browser.
• ADO.Net – This technology is used to develop applications to interact with Databases
such as Oracle or Microsoft SQL Server.
Microsoft always ensures that .Net frameworks are in compliance with all the supported
Windows operating systems.
.Net Framework Design Principle
The following design principles of the .Net framework is what makes it very relevant to
create .Net based applications.
1. Interoperability - The .Net framework provides a lot of backward support. Suppose if
you had an application built on an older version of the .Net framework, say 2.0. And if
you tried to run the same application on a machine which had the higher version of the
.Net framework, say 3.5. The application would still work. This is because with every
release, Microsoft ensures that older framework versions gel well with the latest version.
2. Portability- Applications built on the .Net framework can be made to work on any
Windows platform. And now in recent times, Microsoft is also envisioning to make
Microsoft products work on other platforms, such as iOS and Linux.
3. Security - The .NET Framework has a good security mechanism. The inbuilt security
mechanism helps in both validation and verification of applications. Every application can
explicitly define their security mechanism. Each security mechanism is used to grant the
user access to the code or to the running program.
4. Memory management - The Common Language runtime does all the work or memory
management. The .Net framework has all the capability to see those resources, which
are not used by a running program. It would then release those resources accordingly.
This is done via a program called the "Garbage Collector" which runs as part of the .Net
framework.
The garbage collector runs at regular intervals and keeps on checking which system
resources are not utilized, and frees them accordingly.
12
163
www.gradeup.co
5. Simplified deployment - The .Net framework also have tools, which can be used to
package applications built on the .Net framework. These packages can then be distributed
to client machines. The packages would then automatically install the application.
Summary
• .Net is a programming language developed by Microsoft. It was designed to build
applications which could run on the Windows platform.
• The .Net programming language can be used to develop Forms based applications, Web
based applications, and Web services.
• Developers can choose from a variety of programming languages available on the .Net
platform. The most common ones are VB.Net and C#.
3. PHP
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers
to create dynamic content that interacts with databases. PHP is basically used for developing
web based software applications.
What is PHP?
• PHP know as Hypertext Preprocessor is a recursive acronym.
• PHP is a server side scripting which is embedded with HTML.
• PHP used to manage CMS, dynamic content, databases, ecommerce sites, and application
tool.
• PHP is free to use and download. it is a open source scripting language.
• PHP support most of all databases like as MySQL, PostgreSQL, Sybase, Oracle, MicrosoftSQL.
• POP3, IMAP, LDAP and a large number of major protocols support PHP
Where I can use PHP – PHP Common Use:
• PHP performs dynamic content management function by generate dynamic page content
• Collect data from databases and user input by PHP
• Databases Creation, modification and deletion can be perform by PHP.
• File on server can be open read, write and close by PHP.
• Cookies can be send or receive by PHP.
• Data encryption can be by PHP.
• Users can decline to access webpages and web site by PHP.
• Data can send through E-mail by PHP.
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
3.1. Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
13
164
www.gradeup.co
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in
PHP function "echo" to output the text "Hello World!" on a web page:
Example-
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements end with a semicolon (;).
3.2. PHP Case Sensitivity
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
Example-
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
3.3. PHP Variables
Variables are "containers" for storing information.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
14
165
www.gradeup.co
Example-
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello
world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a
variable. It is created the moment you first assign a value to it.
3.4. PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:
• local
• global
• static
3.5. PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print.
echo and print are more or less the same. They are both used to output data to the
screen.
The differences are small: echo has no return value while print has a return value of 1 so
it can be used in expressions. echo can take multiple parameters (although such usage
is rare) while print can take one argument. echo is marginally faster than print.
15
166
www.gradeup.co
4. PYTHON
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
16
167
www.gradeup.co
• system scripting.
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-orientated way or a functional way.
Good to know
• The most recent major version of Python is Python 3, which we shall be using in this
tutorial. However, Python 2, although not being updated with anything other than security
updates, is still quite popular.
• In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse
which are particularly useful when managing larger collections of Python files.
Python Syntax compared to other programming languages
• Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.
4.1. Execute Python Syntax
As we learned in the previous page, Python syntax can be executed by writing directly
in the Command Line:
>>> print("Hello, World!")
Hello, World!
Or by creating a python file on the server, using the .py file extension, and running it in
the Command Line:
17
168
www.gradeup.co
18
169
www.gradeup.co
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Assign Value to Multiple Variables
• Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
4.4. Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
19
170
www.gradeup.co
5. GOLANG
20
171
www.gradeup.co
4. Interface type
Here, we will discuss Basic Data Types in the Go language. The Basic Data Types are
further categorized into three subcategories which are:
1. Numbers
2. Booleans
3. Strings
Numbers: In Go language, numbers are divided into three sub-categories that are:
• Integers: In Go language, both signed and unsigned integers are available in four
different sizes as shown in the below table. The signed int is represented by int and the
unsigned integer is represented by uint.
DATA TYPE DESCRIPTION
int8 8-bit signed integer
int16 16-bit sinned integer
int32 32-bit signed integer
int64 64-bit signed integer
uint8 8-bit unsigned integer
uint16 16-bit unsigned integer
uint32 32-bit unsigned integer
uint64 64-bit unsigned integer
int Both in and uint contain same size, either 32 or 64 bit.
uint Both in and uint contain same size, either 32 or 64 bit.
rune It is a synonym of int32 and also represent Unicode code points.
byte It is a synonym of int8.
uintptr It is an unsigned integer type. Its width is not defined, but its can hold
all the bits of a pointer value.
• Complex Numbers: The complex numbers are divided into two parts are shown in
the below table. float32 and float64 are also part of these complex numbers. The in-
built function creates a complex number from its imaginary and real part and in-built
imaginary and real function extract those parts.
21
172
www.gradeup.co
5.3. Variables
A Variable is a placeholder of the information which can be changed at runtime. And
variables allow to Retrieve and Manipulate the stored information.
Rules for Naming Variables:
• Variable names must begin with a letter or an underscore(_). And the names may
contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
• Gradeup, garte, _goprep23 // valid variable
• 123Gradeup, 23grade // invalid variable
• A variable name should not start with a digit.
• The name of the variable is case sensitive.
gradeup and Gradeup are two different variables
• Keywords is not allowed to use as a variable name.
• There is no limit on the length of the name of the variable, but it is advisable to use
an optimum length of 4 – 15 letters only.
There are two ways to declare a variable in Golang as follows:
1. Using var Keyword: In Go language, variables are created using var keyword of a
particular type, connected with name and provide its initial value.
Syntax:
var variable_name type = expression
2. Using short variable declaration: The local variables which are declared and
initialize in the functions are declared by using short variable declaration.
Syntax:
variable_name:= expression
****
22
173
www.gradeup.co
23
174