Summer Training Report: Bachelor of Technology

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

SUMMER TRAINING REPORT

Submitted in partial fulfilment of the requirements for the award of the degree
of

BACHELOR OF TECHNOLOGY

In

ELECTRONICS & COMMUNICATION ENGINEERING

By

ANANT BHARDWAJ
42311502816

DEPARTMENT OF ELECTRONICS & COMMUNICATION


ENGINEERING
BHARATI VIDYAPEETH’S COLLEGE OF ENGINEERING
(AFFILIATED TO GURU GOBIND SINGH INDRAPRASTHA
UNIVERSITY, DELHI)
NEW DELHI – 110063
AUG 2018
SUMMER TRAINING REPORT
Submitted in partial fulfilment of the requirements for the award of the degree
of

BACHELOR OF TECHNOLOGY

in

ELECTRONICS & COMMUNICATION ENGINEERING

by

ANANT BHARDWAJ
42311502816

Guided by
Mr.Ankur Kumar
(Coding Mentor, Coding Ninjas)

DEPARTMENT OF ELECTRONICS & COMMUNICATION


ENGINEERING
BHARATI VIDYAPEETH’S COLLEGE OF ENGINEERING
(AFFILIATED TO GURU GOBIND SINGH INDRAPRASTHA
UNIVERSITY, DELHI)
NEW DELHI – 110063
AUG 2018
SUMMER TRAINING REPORT

SUCCESSFULLY COMPLETED TRAINING OF

DURATION-8 WEEKS

AT:

CODING NINJAS

FROM:

11th JUNE 2018 TO 3rd AUGUST 2018

GUIDED BY:-

MR. ANKUR KUMAR

(Coding Mentor)
CANDIDATE’S DECLARATION

It is hereby certified that the work which is being presented in the B. Tech Major
Project Report entitled "JAVA WITH DATA STRUCTURES" in partial
fulfilment of the requirements for the award of the degree of Bachelor of
Technology and submitted in the Department of Electronics & Communication
Engineering of BHARATI VIDYAPEETH’S COLLEGE OF ENGINEERING,
New Delhi (Affiliated to Guru Gobind Singh Indraprastha University, Delhi) is an
authentic record of my own work carried out during a period from June 2018 to
August 2018 under the guidance of Mr.Ankur Kumar, Coding Mentor.
The matter presented in the B. Tech Major Project Report has not been submitted
by me for the award of any other degree of this or any other Institute.

ANANT BHARDWAJ
_________________________
ABSTRACT
The topic highlighted in report includes few algorithms & data structures
structure. It also consist of overview of few problems that were solved by
me during the duration of course and a game of tic tac toe was also
prepared.
The questions were solved and game was prepared using basic java
language & implementation of data structures wherever needed.

1 . JAVA
Java is a simple language that finds its application in wide range of
technologies which include anderoid, web development.
It is one of the basic language that is used for getting a good hold over data
structures.

2 . DATA STRUCTURES
A data structure is a particular way of organizing data in a computer so
that it can be used effectively. The idea is to reduce the space and time
complexities of different tasks.

3. TIC TAC TOE


A game of tic tac toe is being implemented by using few concepts of
data structures.
ACKNOWLEDGEMENT

I am grateful to the authorities of Coding Ninjas for providing me training in


“Java with Data Structures” for partial fulfillment of Bachelor of Technology
(Electronics and Communication Engineering) degree syllabus of Bharati
Vidyapeeth’s College of Engineering, New Delhi.

The information and data given in the report is authentic to the best of my
knowledge. This Training Report is not submitted to any other university for award
of any other Degree, Diploma or Fellowship.

My sincere thanks and gratitude to Mr. Ankur Kumar for his valuable support
and guidance throughout my training.

ANANT BHARDWAJ
TABLE OF CONTENTS

1. CANDIDATE’S DECLARATION
2. CERTIFICATE
3. ABSTRACT
4. ACKNOWLEDGEMENT
5. TABLE OF CONTENTS
6. JAVA
7. DATA STRUCTURES
8. TIC TAC TOE
JAVA
Introduction
Java is one of the most popular programming languages in use, particularly for
client-server web applications. Programs written in Java have a reputation for
being slower and requiring more memory than those written in C++. The syntax of
Java is largely influenced by C++. Unlike C++, which combines the syntax for
structured, generic, and object-oriented programming, Java was built almost
exclusively as an object-oriented language.

Where it all started?


James Gosling,Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. Java was originally designed for interactive television, but it
was too advanced for the digital cable television industry at the time. The
language was initially called Oak after an oak tree that stood outside Gosling's
office. Later the project went by the name Greenand was finally renamed Java,
from Java coffee.

Features of Java
 Java is a platform independent language
Compiler present in editor Eclipse converts source code (.java file) to the byte
code(.class file). JVM executes the bytecode produced by compiler. This byte code
can run on any platform such as Windows, Linux, Mac OS etc. Which means a
program that is compiled on windows can run on Linux and vice-versa. Each
operating system has different JVM, however the output they produce after
execution of bytecode is same across all operating systems. That is why we call
java as platform independent language.
 Java is an Object Oriented language
Object oriented programming is a way of organizing programs as collection of
objects, each of which represents an instance of a class.

4 main concepts of Object Oriented programming are:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

 Simple
Java is considered as one of simple language because it does not have complex
features like Operator overloading, Multiple inheritance, pointers and Explicit
memory allocation.

 Robust Language
Robust means reliable. Java programming language is developed in a way that
puts a lot of emphasis on early checking for possible errors, that’s why java
compiler is able to detect errors that are not easy to detect in other programming
languages. The main features of java that makes it robust are garbage collection,
Exception Handling and memory allocation.

 Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several
security flaws like stack corruption or buffer overflow is impossible to exploit in
Java.

 Java is distributed
Using java programming language we can create distributed applications.
RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for
creating distributed applications in java. In simple words: The java programs can
be distributed on more than one systems that are connected to each other using
internet connection. Objects on one JVM (java virtual machine) can execute
procedures on a remote JVM.

 Multithreading
Java supports multithreading. Multithreading is a Java feature that allows
concurrent execution of two or more parts of a program for maximum utilisation
of CPU.

 Portable
Java code that is written on one machine can run on another machine. The
platform independent byte code can be carried to any platform for execution that
makes java code portable.

Parameters used commonly in java


program
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

o class keyword is used to declare a class in java.


o public keyword is an access modifier which represents visibility, it means it
is visible to all.
o static is a keyword, if we declare any method as static, it is known as static
method. The core advantage of static method is that there is no need to
create object to invoke the static method. The main method is executed by
the JVM, so it doesn't require to create object to invoke the main method. So
it saves memory.
o void is the return type of the method, it means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used print statement. We will learn about the
internal working of System.out.println statement later.

OOPs (Object-Oriented Programming


System)
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object
Any entity that has state and behavior is known as an object. For example a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address


and takes up some space in memory. Objects can communicate without knowing
the details of each other's data or code. The only necessary thing is the type of
message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.

Class
Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism
If one task is performed by different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve


polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For


example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.

Application
According to Sun, 3 billion devices run Java. There are many devices where Java
is currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
DATA STRUCTURES
Introduction
Data Structure can be defined as the group of data elements which provides an
efficient way of storing and organising data in the computer so that it can be
used efficiently. Some examples of Data Structures are arrays, Linked List,
Stack, Queue, etc. Data Structures are widely used in almost every aspect of
Computer Science i.e. Operating System, Compiler Design, Artifical
intelligence, Graphics and many more.

Data Structures are the main part of many computer science algorithms as they
enable the programmers to handle the data in an efficient way. It plays a vitle
role in enhancing the performance of a software or a program as the main
function of the software is to store and retrieve the user's data as fast as possible

Basic Terminology
Data structures are the building blocks of any program or the software.
Choosing the appropriate data structure for a program is the most difficult task
for a programmer. Following terminology is used as far as data structures are
concerned

Data: Data can be defined as an elementary value or the collection of values, for
example, student's name and its id are the data about the student.

Group Items: Data items which have subordinate data items are called Group
item, for example, name of a student can have first name and the last name.

Record: Record can be defined as the collection of various data items, for
example, if we talk about the student entity, then its name, address, course and
marks can be grouped together to form the record for the student.

File: A File is a collection of various records of one type of entity, for example,
if there are 60 employees in the class, then there will be 20 records in the related
file where each record contains the data about each employee.
Attribute and Entity: An entity represents the class of certain objects. it
contains various attributes. Each attribute represents the particular property of
that entity.

Field: Field is a single elementary unit of information representing the attribute


of an entity.

Need of Data Structures


As applications are getting complexed and amount of data is increasing day by
day, there may arrise the following problems:

Processor speed: To handle very large amout of data, high speed processing is
required, but as the data is growing day by day to the billions of files per entity,
processor may fail to deal with that much amount of data.

Data Search: Consider an inventory size of 106 items in a store, If our


application needs to search for a particular item, it needs to traverse 106 items
every time, results in slowing down the search process.

Multiple requests: If thousands of users are searching the data simultaneously


on a web server, then there are the chances that a very large server can be failed
during that process in order to solve the above problems, data structures are
used. Data is organized to form a data structure in such a way that all items are
not required to be searched and required data can be searched instantly.

Advantages of Data Structures


Efficiency: Efficiency of a program depends upon the choice of data structures.
For example: suppose, we have some data and we need to perform the search for
a particular record. In that case, if we organize our data in an array, we will have
to search sequentially element by element. hence, using array may not be very
efficient here. There are better data structures which can make the search easy.

Reusability: Data structures are reusable, i.e. once we have implemented a


particular data structure, we can use it at any other place. Implementation of data
structures can be compiled into libraries which can be used by different clients.
Abstraction: Data structure is specified by the ADT which provides a level of
abstraction. The client program uses the data structure through interface only,
without getting into the implementation details.

Data Structure Classification

Linear Data Structures: A data structure is called linear if all of its elements
are arranged in the linear order. In linear data structures, the elements are stored
in non-hierarchical way where each element has the successors and predecessors
except the first and last element.

Types of Linear Data Structures are given below:


Arrays: An array is a collection of similar type of data items and each data item
is called an element of the array. The data type of the element may be any valid
data type like char, int, float or double.

The elements of array share the same variable name but each one carries a
different index number known as subscript. The array can be one dimensional,
two dimensional or multidimensional.

The individual elements of the array age are:

age[0], age[1], age[2], age[3],??? age[98], age[99].

Linked List: Linked list is a linear data structure which is used to maintain a list
in the memory. It can be seen as the collection of nodes stored at non-contiguous
memory locations. Each node of the list contains a pointer to its adjacent node.

Stack: Stack is a linear list in which insertion and deletions are allowed only at
one end, called top.

A stack is an abstract data type (ADT), can be implemented in most of the


programming languages. It is named as stack because it behaves like a real-
world stack, for example: - piles of plates or deck of cards etc.

Queue: Queue is a linear list in which elements can be inserted only at one end
called rear and deleted only at the other end called front.

It is an abstract data structure, similar to stack. Queue is opened at both end


therefore it follows First-In-First-Out (FIFO) methodology for storing the data
items.

Non Linear Data Structures: This data structure does not form a sequence i.e.
each item or element is connected with two or more other items in a non-linear
arrangement. The data elements are not arranged in sequential structure.

Types of Non Linear Data Structures are given below:

Trees: Trees are multilevel data structures with a hierarchical relationship


among its elements known as nodes. The bottommost nodes in the herierchy are
called leaf node while the topmost node is called root node. Each node contains
pointers to point adjacent nodes.

Tree data structure is based on the parent-child relationship among the nodes.
Each node in the tree can have more than one children except the leaf nodes
whereas each node can have atmost one parent except the root node. Trees can
be classfied into many categories which will be discussed later in this tutorial.

Graphs: Graphs can be defined as the pictorial representation of the set of


elements (represented by vertices) connected by the links known as edges. A
graph is different from tree in the sense that a graph can have cycle while the
tree can not have the one.

Operations on data structure


1) Traversing: Every data structure contains the set of data elements.
Traversing the data structure means visiting each element of the data structure in
order to perform some specific operation like searching or sorting.

Example: If we need to calculate the average of the marks obtained by a student


in 6 different subject, we need to traverse the complete array of marks and
calculate the total sum, then we will devide that sum by the number of subjects
i.e. 6, in order to find the average.

2) Insertion: Insertion can be defined as the process of adding the elements to


the data structure at any location.

If the size of data structure is n then we can only insert n-1 data elements into it.

3) Deletion:The process of removing an element from the data structure is


called Deletion. We can delete an element from the data structure at any random
location.

If we try to delete an element from an empty data structure


then underflow occurs.

4) Searching: The process of finding the location of an element within the data
structure is called Searching. There are two algorithms to perform searching,
Linear Search and Binary Search. We will discuss each one of them later in this
tutorial.

5) Sorting: The process of arranging the data structure in a specific order is


known as Sorting. There are many algorithms that can be used to perform
sorting, for example, insertion sort, selection sort, bubble sort, etc.

6) Merging: When two lists List A and List B of size M and N respectively, of
similar type of elements, clubbed or joined to produce the third list, List C of
size (M+N), then this process is called merging

Algorithm
An algorithm is a procedure having well defined steps for solving a particular
problem. Algorithm is finite set of logic or instructions, written in order for
accomplish the certain predefined task. It is not the complete program or code, it is
just a solution (logic) of a problem, which can be represented either as an informal
description using a Flowchart or Pseudo code.

The major categories of algorithms are given below:

o Sort: Algorithm developed for sorting the items in certain order.


o Search: Algorithm developed for searching the items inside a data structure.
o Delete: Algorithm developed for deleting the existing element from the data
structure.
o Insert: Algorithm developed for inserting an item inside a data structure.
o Update: Algorithm developed for updating the existing element inside a
data structure.

Characteristics of an Algorithm
An algorithm must follow the mentioned below characteristics:

o Input: An algorithm must have 0 or well defined inputs.


o Output: An algorithm must have 1 or well defined outputs, and should
match with the desired output.
o Feasibility: An algorithm must be terminated after the finite number of
steps.
o Independent: An algorithm must have step-by-step directions which is
independent of any programming code.
o Unambiguous: An algorithm must be unambiguous and clear. Each of their
steps and input/outputs must be clear and lead to only one meaning.

Different data structures are discussed below:-

Array
Definition
o Arrays are defined as the collection of similar type of data items stored at
contiguous memory locations.
o Arrays are the derived data type in C programming language which can store
the primitive type of data such as int, char, double, float, etc.
o Array is the simplest data structure where each data element can be
randomly accessed by using its index number.
o For example, if we want to store the marks of a student in 6 subjects, then
we don't need to define different variable for the marks in different subject.
instead of that, we can define an array which can store the marks in each
subject at a the contiguous memory locations.

Properties of the Array


1. Each element is of same data type and carries a same size i.e. int = 4 bytes.
2. Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
3. Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size
of data element.
Need of using Array
In computer programming, the most of the cases requires to store the large number
of data of similar type. To store such amount of data, we need to define a large
number of variables. It would be very difficult to remember names of all the
variables while writing the programs. Instead of naming all the variables with a
different name, it is better to define an array and store all the elements into it.

Following example illustrates, how array can be useful in writing code for a
particular problem.

In the following example, we have marks of a student in six different subjects. The
problem intends to calculate the average of all the marks of the student.

In order to illustrate the importance of array, we have created two programs, one is
without using array and other involves the use of array to store marks.

Advantages of Array
o Array provides the single name for the group of variables of the same type
therefore, it is easy to remember the name of all the elements of an array.
o Traversing an array is a very simple process, we just need to increment the
base address of the array in order to visit each element one by one.
o Any element in the array can be directly accessed by using the index.

Memory Allocation of the array


All the data elements of an array are stored at contiguous locations in the main
memory. The name of the array represents the base address or the address of first
element in the main memory. Each element of the array is represented by a proper
indexing.

The indexing of the array can be defined in three ways.

1. 0 (zero - based indexing) : The first element of the array will be arr[0].
2. 1 (one - based indexing) : The first element of the array will be arr[1].
3. n (n - based indexing) : The first element of the array can reside at any
random index number.
In the following image, here is shown the memory allocation of an array arr of size
5. The array follows 0-based indexing approach. The base address of the array is
100th byte. This will be the address of arr[0]. Here, the size of int is 4 bytes
therefore each element will take 4 bytes in the memory.

Linked List
o Linked List can be defined as collection of objects called nodes that are
randomly stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the
pointer which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.

Uses of Linked List


o The list is not required to be contiguously present in the memory. The node
can reside any where in the memory and linked together to make a list. This
achieves optimized utilization of space.
o list size is limited to the memory size and doesn't need to be declared in
advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?


Till now, array data structure was used to organize the group of elements that are
to be stored individually in the memory. However, Array has several advantages
and disadvantages which must be known in order to decide the data structure
which will be used throughout the program.
Array contains following limitations:

1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible
to expand the size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory.
Inserting any element in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array.
Using linked list is useful because,

1. It allocates the memory dynamically. All the nodes of linked list are non-
contiguously stored in the memory and linked together with the help of
pointers.
2. Sizing is no longer a problem since we do not need to define its size at the
time of declaration. List grows as per the program's demand and limited to
the available memory space.

Singly linked list or One way chain


Singly linked list can be defined as the collection of ordered set of elements. The
number of elements may vary according to need of the program. A node in the
singly linked list consist of two parts: data part and link part. Data part of the node
stores actual information that is to be represented by the node while the link part of
the node stores the address of its immediate successor.

One way chain or singly linked list can be traversed only in one direction. In other
words, we can say that each node contains only next pointer, therefore we can not
traverse the list in the reverse direction.

Consider an example where the marks obtained by the student in three subjects are
stored in a linked list as shown in the figure.
In the above figure, the arrow represents the links. The data part of every node
contains the marks obtained by the student in the different subject. The last node in
the list is identified by the null pointer which is present in the address part of the
last node. We can have as many elements we require, in the data part of the list.

Doubly linked list


Doubly linked list is a complex type of linked list in which a node contains a
pointer to the previous as well as the next node in the sequence. Therefore, in a
doubly linked list, a node consists of three parts: node data, pointer to the next
node in sequence (next pointer) , pointer to the previous node (previous pointer). A
sample node in a doubly linked list is shown in the figure.

A doubly linked list containing three nodes having numbers from 1 to 3 in their
data part, is shown in the following image.
Circular Singly Linked List
In a circular Singly linked list, the last node of the list contains a pointer to the first
node of the list. We can have circular singly linked list as well as circular doubly
linked list.We traverse a circular singly linked list until we reach the same node
where we started. The circular singly liked list has no beginning and no ending.
There is no null value present in the next part of any of the nodes.

The following image shows a circular singly linked list.

Stack
1. Stack is an ordered list in which, insertion and deletion can be performed
only at one end that is called top.
2. Stack is a recursive data structure having pointer to its top element.
3. Stacks are sometimes called as Last-In-First-Out (LIFO) lists i.e. the element
which is inserted first in the stack, will be deleted last from the stack.

Applications of Stack
1. Recursion
2. Expression evaluations and conversions
3. Parsing
4. Browsers
5. Editors
6. Tree Traversals

Operations on Stack
There are various operations which can be performed on stack.

1. Push : Adding an element onto the stack


2. Pop : Removing an element from the stack

3.Peek : Look all the elements of stack without removing them.

Queue
1.A queue can be defined as an ordered list which enables insert operations to
be performed at one end called REAR and delete operations to be performed at
another end called FRONT.

2. Queue is referred to be as First In First Out list.


3. For example, people waiting in line for a rail ticket form a queue.

Applications of Queue
Due to the fact that queue performs actions on first in first out basis which is
quite fair for the ordering of actions. There are various applications of queues
discussed as below.

1. Queues are widely used as waiting lists for a single shared resource like
printer, disk, CPU.
2. Queues are used in asynchronous transfer of data (where data is not being
transferred at the same rate between two processes) for eg. pipes, file IO,
sockets.
3. Queues are used as buffers in most of the applications like MP3 media
player, CD player, etc.
4. Queue are used to maintain the play list in media players in order to add
and remove the songs from the play-list.
5. Queues are used in operating systems for handling interrupts.
Tree
o A Tree is a recursive data structure containing the set of one or more data
nodes where one node is designated as the root of the tree while the
remaining nodes are called as the children of the root.
o The nodes other than the root node are partitioned into the non empty sets
where each one of them is to be called sub-tree.Nodes of a tree either
maintain a parent-child relationship between them or they are sister nodes.
o In a general tree, A node can have any number of children nodes but it can
have only a single parent.
o The following image shows a tree, where the node A is the root node of the
tree while the other nodes can be seen as the children of A.
Basic terminology
o Root Node :- The root node is the topmost node in the tree hierarchy. In
other words, the root node is the one which doesn't have any parent.
o Sub Tree :- If the root node is not null, the tree T1, T2 and T3 is called sub-
trees of the root node.
o Leaf Node :- The node of tree, which doesn't have any child node, is called
leaf node. Leaf node is the bottom most node of the tree. There can be any
number of leaf nodes present in a general tree. Leaf nodes can also be called
external nodes.
o Path :- The sequence of consecutive edges is called path. In the tree shown
in the above image, path to the node E is A→ B → E.
o Ancestor node :- An ancestor of a node is any predecessor node on a path
from root to that node. The root node doesn't have any ancestors. In the tree
shown in the above image, the node F have the ancestors, B and A.
o Degree :- Degree of a node is equal to number of children, a node have. In
the tree shown in the above image, the degree of node B is 2. Degree of a
leaf node is always 0 while in a complete binary tree, degree of each node is
equal to 2.
o Level Number :- Each node of the tree is assigned a level number in such a
way that each node is present at one level higher than its parent. Root node
of the tree is always present at level 0.

TIC TAC TOE GAME


Summary of the game
The tic tac toe game is commonly known as zero katta game.the game is simple
and implements on the concepts of basic java and use of swings.
In the game if no one wins then the message to be appeared on the screen as
“draw” and if either X wins or 0 wins then message appers to be “X all the way” or
“0’s rule”.

Code of the game:-


package projectreport;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TTT extends JFrame implements ActionListener {
private JButton[][] board;
private boolean crossTurn;
private final static int BOARD_SIZE = 3;
private final static int CROSS_WINS = 1;
private final static int ZERO_WINS = 2;
private final static int INCOMPLETE = 3;
private final static int DRAW = 4;
public static void main(String[] args) {
new TTT();
}

TTT() {
super("Tic Tac Toe");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 640);
setResizable(false);
GridLayout grid = new GridLayout(BOARD_SIZE, BOARD_SIZE);
setLayout(grid);
board = new JButton[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = new JButton();
board[i][j].setFont(new Font("Times New Roman", 1, 225));
add(board[i][j]);
}
}
startGame();
}

private void startGame() {


for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j].addActionListener(this);
}
}
crossTurn = true;
}
public void actionPerformed(ActionEvent e) {
JButton clickedButton = (JButton) e.getSource();
if (clickedButton.getText().equals("")) {
makeMove(clickedButton);
// check if the game is finished
int gameStatus = getGameStatus();
if (gameStatus == INCOMPLETE) {
// flip next Turn
crossTurn = !crossTurn;
this.setTitle(crossTurn? "X's turn": "0's turn");
} else {
declareWinner(gameStatus);
dispose();
}
} else {
JOptionPane.showMessageDialog(null, "Invalid move.");
}}
private void makeMove(JButton source) {
if (crossTurn) {
source.setText("X");
} else {
source.setText("0");
}}
private int getGameStatus() {
int i = 0, j = 0;
String text1 = "", text2 = "";
// rows
for (i = 0; i < BOARD_SIZE; i++) {
j = 0;
while (j < BOARD_SIZE - 1) {
text1 = this.board[i][j].getText();
text2 = this.board[i][j + 1].getText();
if (text1.equals("") || !text1.equals(text2)) {
break;
}
j++;
}if (j == BOARD_SIZE - 1) {
return text1.equals("X")? CROSS_WINS : ZERO_WINS;
}}
// columns
for (i = 0; i < BOARD_SIZE; i++) {
j = 0;
while (j < BOARD_SIZE - 1) {
text1 = this.board[j][i].getText();
text2 = this.board[j + 1][i].getText();
if (text1.equals("") || !text1.equals(text2)) {
break;
}
j++;
}
if (j == BOARD_SIZE - 1) {
return text1.equals("X")? CROSS_WINS : ZERO_WINS;}}
// diagonal 1i = 0;
while (i < BOARD_SIZE - 1) {
text1 = this.board[i][i].getText();
text2 = this.board[i + 1][i + 1].getText();
if (text1.equals("") || !text1.equals(text2)) {
break;
}
i++;
}
if (i == BOARD_SIZE - 1) {
return text1.equals("X")? CROSS_WINS : ZERO_WINS;
} // diagonal 2
i = 0;
while (i < BOARD_SIZE - 1) {
text1 = this.board[i][BOARD_SIZE - 1 - i].getText();
text2 = this.board[i + 1][BOARD_SIZE - 1 - i - 1].getText();
if (text1.equals("") || !text1.equals(text2)) {
break;}
i++;
}
if (i == BOARD_SIZE - 1) {
return text1.equals("X")? CROSS_WINS : ZERO_WINS;}
// Incomplete
for (i = 0; i < BOARD_SIZE; i++) {
for (j = 0; j < BOARD_SIZE; j++) {
if (this.board[i][j].getText().equals("")) {
return INCOMPLETE;}}}
// if nothing else, then its a draw
return DRAW;
}private void declareWinner(int gameStatus) {
if(gameStatus == DRAW){
JOptionPane.showMessageDialog(null, "Draw.");}
else if(gameStatus == CROSS_WINS){
JOptionPane.showMessageDialog(null, "X all the way."); }
else {
JOptionPane.showMessageDialog(null, "0's rule."); }}}

Output of the game is:-


If it’s a draw
If x wins

If 0 wins
REFERENCES

1.Data Structures and Algorithms made easy by Narasimha


Karumanchi

2.Let us Java by Yashwant Kanetkar

3.Internet

You might also like