0% found this document useful (0 votes)
40 views91 pages

Bindiya

The document describes the development of a digital snake and ladder game using C programming. It discusses the objectives, hardware requirements, software requirements and provides an overview of the different sections in the project report including introduction, system analysis, design phase, language used, coding, output, and conclusion.

Uploaded by

Rajni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views91 pages

Bindiya

The document describes the development of a digital snake and ladder game using C programming. It discusses the objectives, hardware requirements, software requirements and provides an overview of the different sections in the project report including introduction, system analysis, design phase, language used, coding, output, and conclusion.

Uploaded by

Rajni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

PROJECT REPORT

ON
Snake And Ladder Game

Submitted in the partial fulfillment for the requirement

M.Sc 2nd Year (Comp. Science)


(2022-2024)

Submitted to: Submitted By:


Mrs. Sonia Mam Bindiya

Assistant Professor Roll No- 602240

GOVT. PG. COLLEGE FOR WOMEN,


ROHTAK

1
ACKNOWLEDGEMENT
I would like to express my sincere gratitude to all those who have contributed to the successful
completion of the Snake and Ladder Game project.

First and foremost, I extend my heartfelt thanks to Mrs. Sonia Mam, my project supervisor, for
providing valuable guidance, encouragement, and constructive feedback throughout the
development process. Your insights and expertise have been instrumental in shaping this project.

I am grateful to the faculty members of the Computer Science Department, Govt. PG. College for
Women, Rohtak their support and encouragement during this project endeavor.

I would also like to thank my classmates and friends for their assistance and collaboration during
the various stages of the project. Your contributions and insights have been invaluable.

Last but not the least, I extend my appreciation to my family for their unwavering support and
encouragement throughout my academic journey.

Thank you all for your contributions and support, which have enriched my learning experience and
contributed to the successful completion of this project.

Bindiya
Roll No - 602240

2
Final Project Submission Certificate
This is to certify that the project titled Snake and Ladder Game Project was carried out by Bindiya
under the supervision of Mrs. Sonia (Ass. Prof.) at Govt. P.G. College for Women, Rohtak. The
project work was completed and submitted in partial fulfillment of the requirements for Master’s
of Computer Science.
Date: 15/04/2024
Signature:
Bindiya
Signature:
Mrs. Sonia
Assistant Professor

3
Table of Contents
1 INTRODUCTION ..................................................................................................................................... 5
1.1 Objective ............................................................................................................ 6

1.2 Hardware Requirements .................................................................................... 7

1.3 Software Requirements...................................................................................... 8

2 SYSTEM ANALYSIS ............................................................................................................................... 9


3 DESIGN PHASE ..................................................................................................................................... 12
3.1 Types of System Design ....................................................................................... 13

3.2 E-R DIAGRAM .................................................................................................... 14

3.3 Data flow diagram................................................................................................. 15

3.4 Gantt Chart ............................................................................................................ 18

4 LANGUAGE USED ................................................................................................................................ 20


5 CODING .......................................................................................................................................... 67
6 OUTPUT .......................................................................................................................................... 73
7 CONCLUSION ........................................................................................................................................ 88
8 FUTURE PLANS .................................................................................................................................... 90
BIBLIOGRAPHY ....................................................................................................................................... 91

4
1 INTRODUCTION
This project report documents the development and implementation of a digital adaptation of the
classic "Snake and Ladder" board game using the C programming language. "Snake and Ladder"
is a popular game known for its simplicity and excitement, making it an ideal choice for this
software development endeavor.

The primary goal of this project is to create an interactive game experience that mirrors the
traditional board game's mechanics and rules. Through this project, we aimed to explore various
aspects of software development, including random number generation, game logic
implementation, and console-based user interaction.

Key components of the game include:

• Dice Rolling Simulation: The game incorporates a simulated dice roll using C's random
number generation capabilities (`rand()` function).
• Game Logic: The implementation covers the rules of movement based on dice outcomes,
as well as the integration of snake and ladder effects on player positions.
• User Interface: The game interface is text-based, presented within the console window,
utilizing formatted text and grid-based visualization to depict the game board and player
positions.

By undertaking this project, we sought to enhance our programming skills, particularly in


algorithm design and implementation. This report will provide insights into the software
development process, detailing the challenges faced, solutions devised, and lessons learned
throughout the project lifecycle.

The documentation aims to serve as a reference for those interested in game development using C
and to showcase the application of programming principles in creating engaging interactive
experiences. Through this project, we aim to contribute to the body of knowledge surrounding
software development and inspire further exploration into game programming and simulation
projects.

5
1.1 OBJECTIVE
The primary objective of this project is to design, develop, and implement a console-based "Snake
and Ladder" game using the C programming language. The specific goals include:

1. Software Development Proficiency: Gain practical experience in software development by


creating a game application from scratch using C.
2. Game Mechanics Implementation: Implement the core mechanics of the "Snake and
Ladder" game, including dice rolling, player movement, and interactions with game board
elements (snakes and ladders).
3. Algorithmic Problem Solving: Develop algorithms to simulate dice rolls, manage player
positions, and handle game logic efficiently within a console-based environment.
4. User Interface Design: Create a user-friendly console interface that displays the game
board and player positions clearly, allowing for an engaging gameplay experience.
5. Learning and Skill Development: Enhance programming skills, particularly in C
programming, by tackling challenges related to random number generation, conditional
statements, loops, and array manipulation.
6. Documentation and Presentation: Document the project's development process, challenges
faced, solutions implemented, and outcomes achieved in a comprehensive project report.

By achieving these objectives, this project aims to demonstrate competence in software


development practices, showcase the application of programming concepts in game development,
and provide insights into the complexities of implementing interactive systems within a console
environment. The project also seeks to contribute to personal skill enhancement and foster a deeper
understanding of algorithm design and implementation.

6
1.2 Hardware Requirements
• Central Processor
a. Main Memory of 1GB
b. One Hard disk of 120GB
c. Processor 386
• Moniter
a. Size:80*25- Character Display
b. .SVGA colored montier
• Keyboard

a. keyboard of 86 ,104 keys

• Printer

a.Type: Laser printer

b.Speed :20ppm

7
1.3 Software Requirements

TheOnTimeRTOS-32hosttoolsrununderthefollowingoperatingsystems:

• Windows XP/Vista/7/8/10(32-bitversions)
• Windows XP/Vista/7/8/10/11(64-bit version s,no support forcross
debugging over parallel ports)

The following software components are necessary for building and executing the system:

1. C Compiler:
A C compiler is required to compile the C source code into executable machine code.

• MinGW (Minimalist GNU for Windows) or TDM-GCC for Windows.

2. Text Editor or Integrated Development Environment (IDE):


A text editor or IDE is needed for writing and editing the C source code files.

• Visual Studio Code

3. Terminal or Command Prompt:


Windows users can use Command Prompt or PowerShell.
4. Operating System:
Windows
5. Standard C Libraries:
Standard C libraries (`stdio.h`, `stdlib.h`, `string.h`, etc.) are required for performing
input/output operations, memory allocation, string manipulation, and other essential
functionalities.

8
2 SYSTEM ANALYSIS
• The aim of the proposed system is to develop a system of improved facilities.
• The proposed system can overcome all the limitations of the existing system.
• The system provides proper security and reduces the manual work.
• Security of data.
• Ensure data accuracy’s
• Proper control of the higher officials.
• Minimize manual data entry.
• Minimum time needed for the various processing
• Greater efficiency.
• User friendliness and interactive.
• Better service.

System Analysis

System development is a systematic process comprising phases such as planning, analysis, design,
deployment, and maintenance. In this tutorial, our primary focus will be on system analysis.

System analysis involves studying a system or its components to identify objectives and improve
efficiency. It is a problem-solving technique aimed at ensuring that all system components function
effectively to achieve their intended purpose. Analysis defines the functionality and requirements
of the system, specifying what the system should do to meet user needs and organizational goals.
Through thorough analysis, potential issues and opportunities for improvement are identified,
laying the groundwork for the subsequent phases of system development.

What is a System?

A system is derived from the Greek word "Systema," signifying an organized relationship between
a set of components aimed at achieving a common cause or objective. It is defined as an orderly
grouping of interdependent components linked together according to a plan to achieve a specific
goal.

9
Constraints of a System

A system must adhere to three basic constraints:

• Structured Behavior: The system must possess a defined structure and behavior designed
to achieve predefined objectives.
• Interconnectivity: Interconnectivity and interdependence among system components are
essential for proper functioning.
• Alignment with Objectives: The objectives of the organization take precedence over the
objectives of its subsystems.

Examples of systems include traffic management systems, payroll systems, automatic library
systems, and human resources information systems.

Properties of a System

A system exhibits the following properties:

• Organization: Organization refers to the structure and order of components arranged to


achieve predetermined objectives.
• Interaction: Components within the system operate with each other in a specified manner.
For instance, in an organization, the purchasing department interacts with the production
department, and payroll interacts with the personnel department.
• Interdependence: Components within a system depend on one another for proper
functioning. They are coordinated and linked according to a specified plan, with the output
of one subsystem serving as the input for another.
• Integration: Integration involves how system components are connected together. Despite
each part performing a unique function, they work together within the system.
• Central Objective: The system must have a central objective, whether real or stated. It's
essential for users to understand the main objective of a computer application early in the
analysis phase to ensure successful design and implementation.

Elements of system

INPUT → PROCESSER (CPU) → OUTPUT

10
System Elements:

• Input: The primary purpose of a system is to produce useful output for its users. Inputs are
the information that enters the system for processing.
• Output: The output is the result of processing the input, which is intended to be useful for
the system's users.
• Processor(s): The processor is the component responsible for transforming input into
output. It performs the actual operations or transformations required by the system.
Processors may fully or partially modify the input based on the output specifications. In
some cases, input may also be modified to facilitate processing.
• Control: The control element directs the system's operations. It serves as the decision-
making subsystem that governs the activities related to input, processing, and output. The
behavior of a computer system is controlled by the operating system and software. Output
specifications determine the input required to maintain system balance.
• Feedback: Feedback provides control in a dynamic system. Positive feedback is routine
and encourages system performance, while negative feedback is informational and
provides the controller with data for action.
• Environment: The environment represents the broader context within which an
organization operates. It encompasses external elements that impact the system. The
environment determines how the system must function and may impose constraints on its
performance. Examples include vendors, competitors, and other external factors that
influence the organization's operations.

11
3 DESIGN PHASE
In the system design process, the primary objective is to identify user requirements and develop a
system that fulfills these requirements. Essentially, the design phase focuses on determining "how"
the system will be developed. Design entails outlining the final system and the process by which
it will be constructed. It involves specifying the technical details that will be utilized in
implementing the proposed system.

The design phase represents the second significant step in the system development life cycle.
During this phase, the analyst undertakes the following activities:

• Scheduling Design Activities: Planning and organizing various design tasks and activities
to ensure a systematic approach to system development.
• Collaborating with Users: Working closely with users to ascertain different data inputs
required by the system and to gather insights into their requirements and preferences.
• Creating System Models: Developing models of the new system, often utilizing tools such
as data flow diagrams and entity-relationship diagrams to visually represent system
components and their interactions.
• Defining Data Requirements: Establishing the data needs of the system through the
creation of a data dictionary, which serves as a comprehensive repository of data elements
and their definitions.
• Writing Program Specifications: Detailing the specifications for programming tasks,
outlining the functionalities and features to be incorporated into the system.
• Identifying and Procuring Hardware and Software: Identifying necessary hardware and
software components required for the implementation of the system design, and making
arrangements for their acquisition.
During the design phase, meticulous attention is paid to ensuring that the proposed system
aligns with user expectations and organizational objectives. By systematically planning
and defining the technical aspects of the system, the design phase lays the groundwork for
successful implementation and development of the final system.

12
3.1 Types of System Design

• Logical Design
Logical design pertains to an abstract representation of the data flow, inputs, and outputs
of the system. It describes the inputs (sources), outputs (destinations), databases (data
stores), procedures (data flows) all in a format that meets the user requirements.While
preparing the logical design of a system, the system analyst specifies the user needs at level
of detail that virtually determines the information flow into and out of the system and the
required data sources. Data flow diagram, E-R diagram modeling are used.
• Physical Design
Physical design relates to the actual input and output processes of the system. It focuses on
how data is entered into a system, verified, processed, and displayed as output. It produces
the working system by defining the design specification that specifies exactly what the
candidate system does. It is concerned with user interface design, process design, and data
design.

It consists of the following steps −

o Specifying the input/output media, designing the database, and specifying backup
procedures.
o Planning system implementation.
o Devising a test and implementation plan, and specifying any new hardware and
software.
o Updating costs, benefits, conversion dates, and system constraints.
• Architectural Design
It is also known as high level design that focuses on the design of system architecture. It
describes the structure and behavior of the system. It defines the structure and relationship
between various modules of system development process.
• Detailed Design
It follows Architectural design and focuses on development of each module.

13
3.2 E-R DIAGRAM

An Entity Relationship (ER) Diagram is a type of flowchart that illustrates how “entities” such as
people, objects or concepts relate to each other within a system. ER Diagrams are most often used
to design or debug relational databases in the fields of software engineering, business information
systems, education and research.

History of ER models

Peter Chen (a.k.a. Peter Pin-Shan Chen), currently a faculty member at Carnegie-Mellon
University in Pittsburgh, is credited with developing ER modeling for database design in the
1970s. While serving as an assistant professor at MIT’s Sloan School of Management, he
published a seminal paper in 1976 titled “The Entity-Relationship Model: Toward a Unified View
of Data.”

Uses of entity relationship diagrams

• Database design: ER diagrams are used to model and design relational databases, in terms
of logic and business rules (in a logical data model) and in terms of the specific technology
to be implemented (in a physical data model.)
• Database troubleshooting: ER diagrams are used to analyze existing databases to find and
resolve problems in logic or deployment. Drawing the diagram should reveal where it’s
going wrong.
• Business information systems: The diagrams are used to design or analyze relational
databases used in business processes.
• Business process re-engineering (BPR): ER diagrams help in analyzing databases used in
business process re-engineering and in modeling a new database setup.
• Education: Databases are today’s method of storing relational information for educational
purposes and later retrieval, so ER Diagrams can be valuable in planning those data
structures.
• Research: Since so much research focuses on structured data, ER diagrams can play a key
role in setting up useful databases to analyze the data.

14
3.3 Data flow diagram
A data flow diagram (DFD) maps out the flow of information for any process or system. It uses
defined symbols like rectangles, circles and arrows, plus short text labels, to show data inputs,
outputs, storage points and the routes between each destination. Data flowcharts can range from
simple, even hand-drawn process overviews, to in-depth, multi-level DFDs that dig progressively
deeper into how the data is handled. They can be used to analyze an existing system or model a
new one. Like all the best diagrams and charts, a DFD can often visually “say” things that would
be hard to explain in words, and they work for both technical and nontechnical audiences, from
developer to CEO. That’s why DFDs remain so popular after all these years. While they work well
for data flow software and systems, they are less applicable nowadays to visualizing interactive,
real-time or database-oriented software or systems.

15
Symbols and Notations Used in DFDs

Three common systems of symbols are named after their creators:

• Yourdon and Coad


• Yourdon and DeMarco
• Gane and Sarson

One main difference in their symbols is that Yourdon-Coad and Yourdon-DeMarco use circles for
processes, while Gane and Sarson use rectangles with rounded corners, sometimes called lozenges.
There are other symbol variations in use as well, so the important thing to keep in mind is to be
clear and consistent in the shapes and notations you use to communicate and collaborate with
others.

Using any convention’s DFD rules or guidelines, the symbols depict the four components of data
flow diagrams.

External entity: an outside system that sends or receives data, communicating with the system
being diagrammed. They are the sources and destinations of information entering or leaving the
system. They might be an outside organization or person, a computer system or a business system.
They are also known as terminators, sources and sinks or actors. They are typically drawn on the
edges of the diagram.

Process: any process that changes the data, producing an output. It might perform computations,
or sort data based on logic, or direct the data flow based on business rules. A short label is used to
describe the process, such as “Submit payment.”

Data store: files or repositories that hold information for later use, such as a database table or a
membership form. Each data store receives a simple label, such as “Orders.”

Data flow: the route that data takes between the external entities, processes and data stores. It
portrays the interface between the other components and is shown with arrows, typically labeled
with a short data name, like “Billing details.”

16
Here is a comprehensive look at diagram symbols and notations and how they’re used.

A. Entitiy

B. Process

C. Data Store

D. Data Flow

Structure of Data flow Diagram

17
Types of DFD :

DFD is of two types:

• Logical DFD:
Logical data flow diagram mainly focuses on the system process. It illustrates how data
flows in the system. Logical DFD is used in various organizations for the smooth running
of system. Like in a Banking software system, it is used to describe how data is moved
from one entity to another.
• Physical DFD:
Physical data flow diagram shows how the data flow is actually implemented in the system.
Physical DFD is more specific and close to implementation.

DFD rules and tips:

• Each process should have at least one input and an output.


• Each data store should have at least one data flow in and one data flow out.
• Data stored in a system must go through a process.
• All processes in a DFD go to another process or a data store

3.4 Gantt Chart

A Gantt chart is a project management tool that allows project managers to create a project
schedule by mapping project tasks over a visual timeline which shows the order in which they’ll
be completed, when they’re due, their duration and other details about them such as their
percentage of completion. Every Gantt chart has two main parts, a grid or task list on the left side
and a project timeline on the right.

The Gantt chart was created by Henry Gantt in the early 20th century to improve project planning,
scheduling and tracking by illustrating completed work compared to planned work. Today, project
managers and team members use Gantt charts to plan projects, create a project schedule, allocate
resources and track progress with just one project management tool.

Benefits of a Gantt Chart

18
The chart identifies tasks that may be executed in parallel and those that can't be started or finished
until others are complete. It can help detect potential bottlenecks and identify tasks that may have
been excluded from the project timeline.

The chart depicts things like task slack time or additional time for completion of a task that
shouldn't delay the project; noncritical activities that may be delayed; and critical activities that
must be executed on time.

Gantt charts can be used in managing projects of all sizes and types. These may include building
infrastructures like dams, bridges, and highways. They may also include software development
and other technologies. Project management tools, such as Microsoft Visio, Project, SharePoint,
and Excel, or specialized software, such as Gantto or Matchware, can help in designing Gantt
charts.

Example of a Gantt Chart

Company A is taking on a project to install new software on the servers of a large investment bank.
Company A decides to create a Gantt chart to help manage the project and its different components.

The project's tasks that require completion include conducting research, selecting a software
product, testing the software, and installing it. These tasks appear as vertical lines on the Gantt
chart. A milestone of the project is selecting the software.

The project's duration is 40 days as agreed upon between Company A and the investment bank.
Each task takes 10 days to complete, and each task is dependent on the previous task. A critical
activity is testing the software in the development and test environments.

The task start and end dates, duration, and milestones appear as horizontal bars on the Gantt chart.
The percentage of work completed for each task also is displayed on the horizontal bars.

Gantt Charts Used for:

Gantt charts help visualize various tasks and projects that occur simultaneously within an
organization, and how far along they have progressed. They are used by management to plan and
schedule such projects so that resources can be allocated in an optimal way and that projects that
are prioritized can finish before less important ones begin.

19
4 LANGUAGE USED
The Snake and Ladder game project is implemented primarily using the C programming language.
C is chosen for its simplicity, efficiency, and suitability for system-level programming tasks,
making it ideal for developing low-level software applications like inventory management
systems.

In addition to C, the project may involve using standard libraries such as `stdio.h` and `stdlib.h`
for input/output operations and memory management. These libraries provide essential
functionalities for reading user input, displaying output, and managing dynamic memory allocation
within the C environment.

The Stationery Stock Management System is designed to be a console-based application, focusing


on command-line interactions for simplicity and portability across different platforms. This
approach allows the project to focus on core programming concepts and logic without the
complexity of graphical user interfaces (GUIs).

Overall, the choice of C as the primary programming language ensures a solid foundation in
software development principles and systems programming techniques, emphasizing efficient
resource utilization and direct control over hardware resources, which are crucial for developing
robust and reliable inventory management software.

C language Introduction

C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at
Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to
write the UNIX operating system.
The main features of the C language include:

• General Purpose and Portable

• Low-level Memory Access

• Fast Speed

• Clean Syntax

20
These features make the C language suitable for system programming like an operating system or
compiler development.

Many later languages have borrowed syntax/features directly or indirectly from the C language.
Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on the C
language. C++ is nearly a superset of C language (Only a few programs may compile in C, but not
in C++).

So, if a person learns C programming first, it will help him to learn any modern programming
language as well. As learning C help to understand a lot of the underlying architecture of the
operating system. Like pointers, working with memory locations, etc.

Structure of C program:

#include<stdio.h>

int main(){

printf(“hello world”);

return 0;

Components of a C Program:

1. Header Files Inclusion – Line 1 [#include <stdio.h>]


The first and foremost component is the inclusion of the Header files in a C program. A
header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. All lines that start with # are processed
by a preprocessor which is a program invoked by the compiler. In the above example, the
preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called
header files in C.
Some of the C Header files:

stddef.h – Defines several useful types and macros.

stdint.h – Defines exact width integer types.

21
stdio.h – Defines core input and output functions

stdlib.h – Defines numeric conversion functions, pseudo-random number generator, and


memory allocation

string.h – Defines string handling functions

math.h – Defines common mathematical functions.

2. Main Method Declaration – Line 2 [int main()]


The next part of a C program is to declare the main() function. It is the entry point of a C
program and the execution typically begins with the first line of the main(). The empty
brackets indicate that the main doesn’t take any parameter (See this for more details). The
int that was written before the main indicates the return type of main(). The value returned
by the main indicates the status of program termination. See this post for more details on
the return type.
3. Body of Main Method – Line 3 to Line 6 [enclosed in {}]

The body of a function in the C program refers to statements that are a part of that function.
It can be anything like manipulations, searching, sorting, printing, etc. A pair of curly
brackets define the body of a function. All functions must start and end with curly brackets.

4. Statement – Line 4 [printf(“Hello World”);]

Statements are the instructions given to the compiler. In C, a statement is always terminated
by a semicolon (;). In this particular case, we use printf() function to instruct the compiler
to display “Hello World” text on the screen.

5. Return Statement – Line 5 [return 0;]

The last part of any C function is the return statement. The return statement refers to the
return values from a function. This return statement and return value depend upon the
return type of the function. The return statement in our program returns the value from
main(). The returned value may be used by an operating system to know the termination
status of your program. The value 0 typically means successful termination.

Application of C

22
• Operating systems: C is widely used for developing operating systems such as
Unix, Linux, and Windows.

• Embedded systems: C is a popular language for developing embedded systems such


as microcontrollers, microprocessors, and other electronic devices.

• System software: C is used for developing system software such as device drivers,
compilers, and assemblers.

• Networking: C is widely used for developing networking applications such as web


servers, network protocols, and network drivers.

• Database systems: C is used for developing database systems such as Oracle,


MySQL, and PostgreSQL.

• Gaming: C is often used for developing computer games due to its ability to handle
low-level hardware interactions. Artificial Intelligence: C is used for developing
artificial intelligence and machine learning applications such as neural networks
and deep learning algorithms.

• Scientific applications: C is used for developing scientific applications such as


simulation software and numerical analysis tools.

• Financial applications: C is used for developing financial applications such as stock


market analysis and trading systems.

Features of C Programming Language

The main features of C language include low-level access to memory, a simple set of keywords,
and a clean style, these features make C language suitable for system programming like an
operating system or compiler development.

Here are some of the most important features of the C language:

• Procedural Language

• Fast and Efficient

• Modularity

• Statically Type

23
• General-Purpose Language

• Rich set of built-in Operators

• Libraries with Rich Functions

• Middle-Level Language

• Portability

• Easy to Extend

C Comments

The comments in C are human-readable explanations or notes in the source code of a C program.
A comment makes the program easier to read and understand. These are the statements that are
not executed by the compiler or an interpreter.

It is considered to be a good practice to document our code using comments.

A person reading a large code will be bemused if comments are not provided about details of the
program.

• C Comments are a way to make a code more readable by providing more


descriptions.

• C Comments can include a description of an algorithm to make code


understandable.

• C Comments can be used to prevent the execution of some parts of the code.

Types of comments in C

In C there are two types of comments in C language:

• Single-line comment

• Multi-line comment

1. Single-line Comment in C

A single-line comment in C starts with ( // ) double forward slash. It extends till the end of the line
and we don’t need to specify its end.

24
2. Multi-line Comment in C

The Multi-line comment in C starts with a forward slash and asterisk ( /* ) and ends with an asterisk
and forward slash ( */ ). Any text between /* and */ is treated as a comment and is ignored by the
compiler.

It can apply comments to multiple lines in the program.

Tokens in C

A token in C can be defined as the smallest individual element of the C programming language
that is meaningful to the compiler. It is the basic component of a C program.

Types of Tokens in C:

The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:

• Keywords

• Identifiers

• Constants

• Strings

• Special Symbols

• Operators

Keywords:

Keywords are predefined or reserved words that have special meanings to the compiler. These are
part of the syntax and cannot be used as identifiers in the program. A list of keywords in C or
reserved words in the C programming language are mentioned below:

Auto, break, case, char etc.

C Variables

A variable in C language is the name associated with some memory location to store data of
different types. There are many types of variables in C depending on the scope, storage class,

25
lifetime, type of data they store, etc. A variable is the basic building block of a C program that can
be used in expressions as a substitute in place of the value it stores.

C Variable Syntax

The syntax to declare a variable in C specifies the name and the type of the variable.

data_type variable_name = value; // defining single variable

Here,

data_type: Type of data that a variable can store.

variable_name: Name of the variable given by the user.

value: value assigned to the variable by the user.

Example:

int var; // integer variable

char a; // character variable

float fff; // float variables

Constants in C

The constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program. The type of constant can be an integer constant, a floating pointer
constant, a string constant, or a character constant. In C language, the const keyword is used to
define the constants.

In this article, we will discuss about the constants in C programming, ways to define constants in
C, types of constants in C, their properties and the difference between literals and constants.

Types of Constants in C

The type of the constant is the same as the data type of the variables. Following is the list of the
types of constants

• Integer Constant

26
• Character Constant

• Floating Point Constant

• Double Precision Floating Point Constant

• Array Constant

• Structure Constant

Data Types in C

Each variable in C has an associated data type. It specifies the type of data that the variable can
store like integer, character, floating, double, etc. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. The data type is a
collection of data with values having fixed values, meaning as well as its characteristics.

The data types in C can be classified as follows:

Types:

• Primitive Data Types:Primitive data types are the most basic data types that are
used for representing simple values such as integers, float, characters, etc.

• User Defined Data Types: The user-defined data types are defined by the user
himself.

• Derived Types: The data types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types.

Literals in C

In C, Literals are the constant values that are assigned to the variables. Literals represent fixed
values that cannot be modified. Literals contain memory but they do not have references as
variables. Generally, both terms, constants, and literals are used interchangeably.

For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a constant
integer literal.

Types of C Literals

There are 4 types of literal in C:

27
• Integer Literal

• Float Literal

• Character Literal

• String Literal

bool in C

The bool in C is a fundamental data type in most that can hold one of two values: true or false. It
is used to represent logical values and is commonly used in programming to control the flow of
execution in decision-making statements such as if-else statements, while loops, and for loops. In
this article, we will explore how to use the bool data type in C.

Boolean in C

In C, the bool data type is not a built-in data type. However, the C99 standard for C language
supports bool variables. Boolean can store values as true-false, 0-1, or can be yes-no. It can be
implemented in C using different methods as mentioned below:

Using header file “stdbool.h”

Using Enumeration type

Using define to declare boolean values

Character Arithmetic

Character arithmetic is used to implement arithmetic operations like addition, subtraction,


multiplication, and division on characters in C language.

In character arithmetic character converts into an integer value to perform the task. For this ASCII
value is used.

It is used to perform actions on the strings.

Example 1

// C program to demonstrate character arithmetic.

#include <stdio.h>

28
int main()

char ch1 = 125, ch2 = 10;

ch1 = ch1 + ch2;

printf("%d\n", ch1);

printf("%c\n", ch1 - ch2 - 4);

return 0;

Basic Input and Output in C

C language has standard libraries that allow input and output in a program. The stdio.h or standard
input output library in C that has methods for input and output.

a.) scanf()

The scanf() method, in C, reads the value from the console as per the type specified and store it in
the given address.

Syntax:

scanf("%X", &variableOfXType);

where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of
variableOfXType, stored at this address in the memory.

b.) printf()

The printf() method, in C, prints the value passed as the parameter to it, on the console screen.

Syntax:

printf("%X", variableOfXType);

29
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and variableOfXType is the variable to be printed.

Formatted and Unformatted Input/Output functions in C with Examples

This article focuses on discussing the following topics in detail-

• Formatted I/O Functions.

• Unformatted I/O Functions.

• Formatted I/O Functions vs Unformatted I/O Functions.

Formatted I/O Functions: Formatted I/O functions are used to take various inputs from the user
and display multiple outputs to the user. These types of I/O functions can help to display the output
to the user in different formats using the format specifiers. These I/O supports all data types like
int, float, char, and many more.

Unformatted Input/Output functions: Unformatted I/O functions are used only for character
data type or character array/string and cannot be used for any other datatype. These functions are
used to read single input from the user at the console and it allows to display the value at the
console.

Operators in C

In C language, operators are symbols that represent operations to be performed on one or more
operands. They are the basic components of the C programming. In this article, we will learn about
all the built-in operators in C with examples.

C Operator:

An operator in C can be defined as the symbol that helps us to perform some specific mathematical,
relational, bitwise, conditional, or logical computations on values and variables. The values and
variables used with operators are called operands. So we can say that the operators are the symbols
that perform operations on operands.

Types of Operators in C

30
C language provides a wide range of operators that can be classified into 6 types based on their
functionality:

• Arithmetic Operators

• Relational Operators

• Logical Operators

• Bitwise Operators

• Assignment Operators

• Other Operators

Unary operators in C

Unary operators are the operators that perform operations on a single operand to produce a new
value.

Types of unary operators

• Unary minus ( – )

• Increment ( ++ )

• Decrement ( — )

• NOT ( ! )

• Addressof operator ( & )

• sizeof()

Bitwise Operators in C

In C, the following 6 operators are bitwise operators (also known as bit operators as they work at
the bit-level). They are used to perform bitwise operations in C.

• The & (bitwise AND) in C takes two numbers as operands and does AND on every
bit of two numbers. The result of AND is 1 only if both bits are 1.

• The | (bitwise OR) in C takes two numbers as operands and does OR on every bit
of two numbers. The result of OR is 1 if any of the two bits is 1.

31
• The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every
bit of two numbers. The result of XOR is 1 if the two bits are different.

• The << (left shift) in C takes two numbers, the left shifts the bits of the first operand,
and the second operand decides the number of places to shift.

• The >> (right shift) in C takes two numbers, right shifts the bits of the first operand,
and the second operand decides the number of places to shift.

• The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

C Logical Operators

Logical operators in C are used to combine multiple conditions/constraints. Logical Operators


returns either 0 or 1, it depends on whether the expression result is true or false. In C programming
for decision-making, we use logical operators.

We have 3 logical operators in the C language:

• Logical AND ( && )

• Logical OR ( || )

• Logical NOT ( ! )

Assignment operators

Assignment operators are used for assigning value to a variable. The left side operand of the
assignment operator is a variable and right side operand of the assignment operator is a value. The
value on the right side must be of the same data-type of the variable on the left side otherwise the
compiler will raise an error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the
right to the variable on the left. Example:

a = 10;

b = 20;

ch = 'y';

32
2. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left. Example:

(a += b) can be written as (a = a + b)

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value
on the right from the current value of the variable on left and then assigns the result to the variable
on the left. Example:

(a -= b) can be written as (a = a - b)

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left. Example:

(a *= b) can be written as (a = a * b)

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by the value on the right and then assigns the result to the variable on
the left. Example:

(a /= b) can be written as (a = a / b)

If initially value stored in a is 6. Then (a /= 2) = 3.

Increment and Decrement Operators in C

The increment ( ++ ) and decrement ( — ) operators in C are unary operators for incrementing and
decrementing the numeric values by 1 respectively. The incrementation and decrementation are
one of the most frequently used operations in programming for looping, array traversal, pointer
arithmetic, and many more.

• Increment Operator in C

33
The increment operator ( ++ ) is used to increment the value of a variable in an expression
by 1. It can be used on variables of the numeric type such as integer, float, character,
pointers, etc.

Syntax of Increment Operator

Increment Operator can be used in two ways which are as follows:

// AS PREFIX

++m

// AS POSTFIX

m++

where m is variable.

How to use the increment operator?

Both pre-increment and post-increment increase the value of the variable but there is a little
difference in how they work.

1. Pre-Increment

In pre-increment, the increment operator is used as the prefix. Also known as prefix increment, the
value is incremented first according to the precedence and then the less priority operations are
done.

Example

result = ++var1;

The above expression can be expanded as

var = var + 1;

result = var;

2. Post-Increment

34
In post-increment, the increment operator is used as the suffix of the operand. The increment
operation is performed after all the other operations are done. It is also known as postfix increment.

Example

result = var1++;

The above expression is equivalent

result = var;

var = var + 1;

Conditional or Ternary Operator (?:) in C

Last Updated : 03 Apr, 2023

The conditional operator in C is kind of similar to the if-else statement as it follows the same
algorithm as of if-else statement but the conditional operator takes less space and helps to write
the if-else statements in the shortest way possible. It is also known as the ternary operator in C as
it operates on three operands.

Syntax of Conditional/Ternary Operator in C

The conditional operator can be in the form

variable = Expression1 ? Expression2 : Expression3;

Or the syntax can also be in this form

variable = (condition) ? Expression2 : Expression3;

sizeof operator in C

Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to
compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually
denoted by size_t. sizeof can be applied to any data type, including primitive types such as integer
and floating-point types, pointer types, or compound datatypes such as Structure, union, etc.

Syntax:

sizeof(Expression);
35
where ‘Expression‘ can be a data type or a variable of any type.

Return: It returns the size size of the given expression.

Time Complexity: O(1)

Auxiliary Space: O(1)

Usage of sizeof() operator

sizeof() operator is used in different ways according to the operand type.

Decision Making in C (if , if..else, Nested if, if-else-if )

The conditional statements (also known as decision control structures) such as if, if else, switch,
etc. are used for decision-making purposes in C programs.

They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These decision-
making statements in programming languages decide the direction of the flow of program
execution.

Need of Conditional Statements

There come situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next. Similar situations arise in programming also where
we need to make some decisions and based on these decisions we will execute the next block of
code. For example, in C if x occurs then execute y else execute z. There can also be multiple
conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r.
This condition of C else-if is one of the many ways of importing multiple conditions.

Types of Conditional Statements in C

• if Statement

• if-else Statement

• Nested if Statement

• if-else-if Ladder

36
• switch Statement

• Conditional Operator

• Jump Statements:

• break

• continue

• goto

• return

1. if in C

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

Syntax of if Statement

if(condition)

// Statements to execute if

// condition is true

2. if-else in C

The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won’t. But what if we want to do something else when the condition is
false? Here comes the C else statement. We can use the else statement with the if statement to
execute a block of code when the condition is false. The if-else statement consists of two blocks,
one for false expression and one for true expression.

Syntax of if else in C

if (condition)

37
{

// Executes this block if

// condition is true

else

// Executes this block if

// condition is false

3. Nested if-else in C

A nested if in C is an if statement that is the target of another if statement. Nested if statements


mean an if statement inside another if statement. Yes, C allow us to nested if statements within if
statements, i.e, we can place an if statement inside another if statement.

Syntax of Nested if-else

if (condition1)

// Executes when condition1 is true

if (condition2)

// Executes when condition2 is true

else

38
// Executes when condition2 is false

4. if-else-if Ladder in C

The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed. if-else-if
ladder is similar to the switch statement.

Syntax of if-else-if Ladder

if (condition)

statement;

else if (condition)

statement;

..

else

statement;

5. switch Statement in C

The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement. The switch
block consists of cases to be executed based on the value of the switch variable.

Syntax of switch

switch (expression) {

case value1:

39
statements;

case value2:

statements;

....

....

....

default:

statements;

6. Jump Statements in C

These statements are used in C for the unconditional flow of control throughout the functions in a
program. They support four types of jump statements:

A) break

This loop control statement is used to terminate the loop. As soon as the break statement is
encountered from within a loop, the loop iterations stop there, and control returns from the loop
immediately to the first statement after the loop.

Syntax of break

break;

Basically, break statements are used in situations when we are not sure about the actual number of
iterations for the loop or we want to terminate the loop based on some condition.

B) continue

This loop control statement is just like the break statement. The continue statement is opposite to
that of the break statement, instead of terminating the loop, it forces to execute the next iteration
of the loop.

40
As the name suggests the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and the next iteration of the loop will begin.

C) goto

The goto statement in C also referred to as the unconditional jump statement can be used to jump
from one point to another within a function.

Syntax of goto

Syntax1 | Syntax2

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

goto label; | label:

. | .

label: | goto label;

D) return

The return in C returns the flow of the execution to the function from where it is called. This
statement does not mandatorily need any conditional statements. As soon as the statement is
executed, the flow of the program stops immediately and returns the control from where it was
called. The return statement may or may not return anything for a void function, but for a non-void
function, a return value must be returned.

C Functions

A function in C is a set of statements that when called perform some specific task. It is the basic
building block of a C program that provides modularity and code reusability. The programming
statements of a function are enclosed within { } braces, having certain meanings and performing
certain operations. They are also called subroutines or procedures in other languages.

Syntax of Functions in C

41
The syntax of function can be divided into 3 aspects:

• Function Declaration

• Function Definition

• Function Calls

• Function Declarations

In a function declaration, we must provide the function name, its return type, and the number and
type of its parameters. A function declaration tells the compiler that there is a function with the
given name defined somewhere else in the program.

Syntax

return_type name_of_the_function (parameter_1, parameter_2);

The parameter name is not mandatory while declaring functions. We can also declare the function
without using the name of the data variables.

Example

int sum(int a, int b);

int sum(int , int);

Function Declaration

Function Declaration

Note: A function in C must always be declared globally before calling it.

Function Definition

The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function).

A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly. The below
example serves as both a function definition and a declaration.

return_type function_name (para1_type para1_name, para2_type para2_name)

42
{

// body of the function

Function Defination in C

Function Definition in C

Function Call

A function call is a statement that instructs the compiler to execute the function. We use the
function name and parameters in the function call.

In the below example, the first sum function is called and 10,30 are passed to the sum function.
After the function call sum of a and b is returned and control is also returned back to the main
function of the program.

Note: Function call is neccessary to bring the program control to the function definition. If not
called, the function statements will not be executed.

Conditions of Return Types and Arguments

In C programming language, functions can be called either with or without arguments and might
return values. They may or might not return values to the calling functions.

• Function with no arguments and no return value

• Function with no arguments and with return value

• Function with argument and with no return value

• Function with arguments and with return value

To know more about function Arguments and Return values refer to the article – Function
Arguments & Return Values in C.

Working of the C function can be broken into the following steps as mentioned below:

• Declaring a function: Declaring a function is a step where we declare a function.


Here we define the return types and parameters of the function.

43
• Defining a function:

• Calling the function: Calling the function is a step where we call the function by
passing the arguments in the function.

• Executing the function: Executing the function is a step where we can run all the
statements inside the function to get the final result.

• Returning a value: Returning a value is the step where the calculated value after the
execution of the function is returned. Exiting the function is the final step where all
the allocated memory to the variables, functions, etc is destroyed before giving full
control to the main function.

Types of Functions

There are two types of functions in C:

• Library Functions

• User Defined Functions

1. Library Function

A library function is also referred to as a “built-in function”. A compiler package already exists
that contains these functions, each of which has a specific meaning and is included in the package.
Built-in functions have the advantage of being directly usable without being defined, whereas user-
defined functions must be declared and defined before being used.

For Example:

pow(), sqrt(), strcmp(), strcpy() etc.

Advantages of C library functions

• C Library functions are easy to use and optimized for better performance.

• C library functions save a lot of time i.e, function development time.

• C library functions are convenient as they always work.

2. User Defined Function

44
Functions that the programmer creates are known as User-Defined functions or “tailor-made
functions”. User-defined functions can be improved and modified according to the need of the
programmer. Whenever we write a function that is case-specific and is not defined in any header
file, we need to declare and define our own functions according to the syntax.

Advantages of User-Defined Functions

• Changeable functions can be modified as per need.

• The Code of these functions is reusable in other programs.

• These functions are easy to understand, debug and maintain.

We can pass arguments to the C function in two ways:

• Pass by Value

• Pass by Reference

1. Pass by Value

Parameter passing in this method copies values from actual parameters into formal function
parameters. As a result, any changes made inside the functions do not reflect in the caller’s
parameters.

2. Pass by Reference

The caller’s actual parameters and the function’s actual parameters refer to the same locations, so
any changes made inside the function are reflected in the caller’s actual parameters.

Advantages of Functions in C

Functions in C is a highly useful feature of C with many advantages as mentioned below:

• The function can reduce the repetition of the same statements in the program.

• The function makes code readable by providing modularity to our program.

• There is no fixed number of calling functions it can be called as many times as you
want.

• The function reduces the size of the program.

45
• Once the function is declared you can just use it without thinking about the internal
working of the function.

Disadvantages of Functions in C

The following are the major disadvantages of functions in C:

• Cannot return multiple values.

• Memory and time overhead due to stack frame allocation and transfer of program
control.

Conclusion
the following points about the function as mentioned below:
• The function is the block of code that can be reused as many times as we want
inside a program.

• To use a function we need to call a function.

• Function declaration includes function_name, return type, and parameters.

• Function definition includes the body of the function.

• The function is of two types user-defined function and library function.

• In function, we can according to two types call by value and call by reference
according to the values passed.

User-Defined Function in C

A user-defined function is a type of function in C language that is defined by the user himself to
perform some specific task. It provides code reusability and modularity to our program. User-
defined functions are different from built-in functions as their working is specified by the user and
no header file is required for their usage.

In this article, we will learn about user-defined function, function prototype, function definition,
function call, and different ways in which we can pass parameters to a function.

How to use User-Defined Functions in C?

46
To use a user-defined function, we first have to understand the different parts of its syntax. The
user-defined function in C can be divided into three parts:

• Function Prototype

• Function Definition

• Function Call

1) C Function Prototype

A function prototype is also known as a function declaration which specifies the function’s name,
function parameters, and return type. The function prototype does not contain the body of the
function. It is basically used to inform the compiler about the existence of the user-defined
function which can be used in the later part of the program.

2) C Function Definition

Once the function has been called, the function definition contains the actual statements that will
be executed. All the statements of the function definition are enclosed within { } braces.

Syntax

return_type function_name (type1 arg1, type2 arg2 .... typeN argN) {

// actual statements to be executed

// return value if any

3) C Function Call

In order to transfer control to a user-defined function, we need to call it. Functions are called using
their names followed by round brackets. Their arguments are passed inside the brackets.

Syntax

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

47
Components of Function Definition

There are three components of the function definition:

• Function Parameters

• Function Body

• Return Value

1. Function Parameters

Function parameters (also known as arguments) are the values that are passed to the called function
by the caller. We can pass none or any number of function parameters to the function.

We have to define the function name and its type in the function definition and we can only pass
the same number and type of parameters in the function call.

Example

int foo (int a, int b);

Here, a and b are function parameters.

Note: C language provides a method using which we can pass variable number of arguments to
the function. Such functions are called variadic function.

2. Function Body

The function body is the set of statements that are enclosed within { } braces. They are the
statements that are executed when the function is called.

Example

int foo (int a, int b) {

int sum = a + b;

return sum;

Here, the statements between { and } is function body.

48
3. Return Value

The return value is the value returned by the function to its caller. A function can only return a
single value and it is optional. If no value is to be returned, the return type is defined as void.

The return keyword is used to return the value from a function.

Syntax

return (expression);

Recursion in C

A recursive function in C is a function that calls itself. Recursion is the process of repeating items
in a self-similar way. In programming languages, if a program allows you to call a function inside
the same function, then it is called a "recursive call of the function".

A recursive function is used when a certain problem is defined in terms of itself. Although it
involves iteration, using iterative approach to solve such problems can be tedious. Recursive
approach provides a very concise solution to seemingly complex problems.

Syntax of a Recursive Function

This is how a general recursive function looks like −

void recursive_function(){

recursion(); // function calls itself

int main(){

recursive_function();

While using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.

Factorial Using Recursion

49
Recursive functions are very useful to solve many mathematical problems such as calculating the
factorial of a number, generating Fibonacci series, etc.

The most popular example of recursion is calculation of factorial. Mathematically, a factorial is


defined as −

n! = n X (n-1)!

It can be seen that we use factorial itself to define factorial. Hence this is a fit case to write a
recursive function. Let us expand the above definition for calculating the factorial value of 5.

Arrays:

Arrays in C are a kind of data structure that can store a fixed-size sequential collection of elements
of the same type. Arrays are used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.

An array in C is a collection of data items of similar data type. One or more values same data type,
which may be primary data types (int, float, char), or user-defined types such as struct or pointers
can be stored in an array. In C, the type of elements in the array should match with the data type
of the array itself.

The size of the array, also called the length of the array, must be specified in the declaration itself.
Once declared, the size of a C array cannot be changed. When an array is declared, the compiler
allocates a continuous block of memory required to store the declared number of elements.

Declaring an Array in C

To declare an array in C, you need to specify the type of the elements and the number of elements
to be stored in it.

type arrayName[size];

The "size" must be an integer constant greater than zero and its "type" can be any valid C data
type. There are different ways in which an array is declared in C.

Declaring an Uninitialized Array

50
In such type of declaration, the uninitialized elements in the array may show certain random
garbage values.

Example:

int a[5];

Initializing an Array in C

If a set of comma-separated sequence values put inside curly brackets is assigned in the declaration,
the array is created with each element initialized with their corresponding value.

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

Properties of Array

Arrays are a very important data structure in C. Use of array in C program makes it easier to handle
large amount of data. Arrays have a number of advantages over singular variables as a result of
their number of properties. Most of the important properties of array are a result of its composition
− that an array is a collection of values of same data type, and in a continuous block of memory.

The array in C is characterized by the following properties −

• Array is a collection of values of same data type


• All elements of an array must be of the same data type. This ensures consistent access and
operations on the data.

Multi−dimensional array

The array is declared with one value of size in square brackets , it is called one dimensional array.
In a one dimensional array, each element is identified by its index or subscript. In C, you can
declare with more indices to simulate a two, three or multidimensional array.

For example, following is the example of a two−dimensional array −

int a[3][3] = { {1, 2, 3}, {11, 22, 33}, {111, 222, 333}};

51
You can think of a one dimensional array as a list, and a two dimensional array as a table or a
matrix. Theoretically, there is no limit to the number of dimensions of an array, but in practice,
two−dimensional arrays are used in design of spreadsheets, databases etc.

Return array from function in C

Functions in C help the programmers to adapt modular program design. A function can be defined
to accept one or more than one arguments, it is able to return a single value to the calling
environment. However, the function can be defined to return an array of values. In C, a function
can be made to return an array by one of following methods −

• Passing the array as argument and returning the pointer


• Declaring a static array in a function and returning its pointer
• Using malloc() function

Embedding the array inside a struct variable and passing it to a function

We implement these methods to calculate the square, the cube and the square root of a given
number.

Pass array by reference

In the following example, we declare an uninitialized array in main() and pass it to a function,
along with an integer. Inside the function, the array is filled with the square, cube and square root.
The function returns the pointer of this array, using which the values are access and printed in
main() function.

Return static array

Instead of passing an empty array from main(), we can declare an array inside the called function
itself, fill it with the required values, and return its pointer. However, returning a pointer of a local
variable is not acceptable, as it points to a variable that no longer exists. Note that a local variable
ceases to exist as soon as the scope of the function is over. Hence, we need to use a static array
inside the called function (arrfunction) and return its pointer back to main().

Using malloc() function

52
The malloc() function is available as a library function in stdlib.h header file. It dynamically
allocates a block of memory during the runtime of a program. Normal declaration of variables
causes the memory to be allocated at the compile time.

void *malloc(size_t size);

The malloc() function returns a generic void pointer. To assign values of a certain data type in the
allocated memory, it must be typecast to the required type. For example, to store an int data, it
must be typecast to int * as follows −

int *x = (int *)malloc(sizeof(int);

Let us allocate a block of memory sufficient to store three float values corresponding to square,
cube and square root of a number, and return the float pointer to main(), inside which the computed
values are displayed.

Using array element in struct

In this method, we will declare a struct, inside which there is an float array as its element. The
called function (myfunction) declares a struct variable, populates the array element with square,
cube and the square root of the argument received by it, and returns it to the main() function.

Return string from function

Using the same approaches, you can pass and return a string to a function. A string in C is an array
of char type. In the following example, we pass the string with a pointer, manipulate it inside the
function, and return it back to main().

Inside the called function, there is a local string. The string passed is concatenated with the local
string before returning.

Variable Length Arrays in C

A Variable length array in C are also called variable sized or runtime−sized arrays. It is an array
whose length is determined at the run−time rather than at the time of compiling the program. Is
size depends on a value generated during the run−time of a program, usually received as the input
from the user.

53
Usually, the array size is declared beforehand in the program as follows −

int arr[10];

The size of an array once declared is fixed during the execution of the program and cannot be
changed during its run−time. However, support to VLA (Variable Length Array) was added in the
C99 standard. In case of a VLA, the compiler allocates the memory with automatic storage
duration on the stack.

Pointers in C

Pointers in C are easy and fun to learn. Some complex C programming tasks can be performed
more easily with pointers, while some other tasks such as dynamic memory allocation cannot be
performed without using pointers. So it becomes necessary to learn pointers to become a perfect
C programmer.

With pointers, you can access and modify the data located in the memory, pass the data efficiently
between the functions, and create dynamic data structures like linked lists, trees, and graphs.

Example: Address of the Variables

As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using the ampersand (&) operator, which denotes an address in
memory.

A pointer is a variable whose value is the address of another variable, i.e., the direct address of a
memory location. Like any variable or constant, you must declare a pointer before using it to store
any variable address. The general form of a pointer variable declaration is −

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Take a look at some of the valid pointer declarations −

int *ip; /* pointer to an integer */


54
double *dp; /* pointer to a double */

float *fp; /* pointer to a float */

char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the pointer
points .

Referencing and Dereferencing in C

A pointer references a location in memory. Obtaining the value stored at that location is known as
dereferencing the pointer.

In C, it is important to understand the purpose of the following two operators in the context of
pointer mechanism −

The & Operator − It is also known as the "Address-of operator". It is used for Referencing which
means taking the address of an existing variable (using &) to set a pointer variable.

The * Operator − It is also known as the "dereference operator". Dereferencing a pointer is carried
out using the * operator to get the value from the memory address that is pointed by the pointer.

Pointers are used to pass parameters by reference. This is useful if a programmer wants a function's
modifications to a parameter to be visible to the function's caller. This is also useful for returning
multiple values from a function.

How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very frequently.
(a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally
access the value at the address available in the pointer variable. This is done by using unary
operator * that returns the value of the variable located at the address specified by its operand.

55
Nested Structures

In the programming context, the term “nesting” refers to enclosing a particular programming
element inside the similar element. For example, nested loops and nested conditional statements,
etc. In this chapter, we shall learn about nested structures. When one of the elements in the
definition of a struct type is of another struct type, the we call it as nested structure in C.

A general syntax of nested structure is as follows −

struct struct1{

type var1;

type var2;

struct struct2 strvar;

We can think of nested structures in the following situation.

If we want to define a struct type representing a student with name and age as its elements, and
other element is the course that is characterized by the course ID, the title, and the credit points.
Here, the student structure has an inner course structure.

struct student{

char *name;

int age;

struct course c1;

};

The nesting of structures can be performed by two methods −

• Defining inline structure


• Including the element of a structure already defined

56
Unions

The union keyword in C lets you define a derived data type, very mush similar to the struct
keyword. A union data type in C also that allows to store different data types in the consecutive
memory location. However, unlike a struct variable, a variable of union type, only one of its
members can contain a value at any given time, whereas a struct variable stores values of all the
elements.

Defining a Union

To define a union, you must use the union keyword in the same way as you did while defining a
structure. The union keyword defines a new data type with more than one member for your
program. The format of the union statement is as follows −

union [union tag] {

member definition;

member definition;

...

member definition;

} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i;
or float f; or any other valid variable definition. At the end of the union's definition, before the
final semicolon, you can specify one or more union variables.

Here is a definition of union type called myunion −

union myunion{

int a;

double b;

char c;

};

57
It may be noted that the definition of union is similar to the definition of struct. A definition od
struct type mystruct with the same elements looks like this −

struct mystruct{

int a;

double b;

char c;

};

The main difference between struct and union is the size of the variables. The compiler allocates
the memory to a struct variable, to be able to store values for all the elements. In mystruct, there
are three elements one each int, double and char, requiring 13 bytes (4+8+1). Hence,

sizeof(struc mystruct)

returns 13.

On the other hand, for a union type variable, the compiler allocates a chunk of memory of the size
enough to accommodate the element of largest byte size. The myunion type has an int, double and
a char element. Out of which the size of double is the largest − 8. Hence,

sizeof(union myunion)

returns 8.

Another point to take into consideration, is that a union variable can hold value of only one its
elements. When you assign value to one element, the other elements are undefined. If you try to
use, it will result in some garbage.

Bit Fields

Previous

Next

58
Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure
called status, as follows −

struct {

unsigned int widthValidated;

unsigned int heightValidated;

} status;

This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1
in each of the variables. The C programming language offers a better way to utilize the memory
space in such situations.

If you are using such variables inside a structure then you can define the width of a variable which
tells the C compiler that you are going to use only those number of bytes. For example, the above
structure can be re-written as follows −

struct {

unsigned int widthValidated : 1;

unsigned int heightValidated : 1;

} status;

The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be
used to store the values.

If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will
use 4 bytes. However as soon as you have 33 variables, it will allocate the next slot of the memory
and it will start using 8 bytes. Let us check the following example to understand the concept −

#include <stdio.h>

59
#include <string.h>

/* define simple structure */

struct {

unsigned int widthValidated;

unsigned int heightValidated;

} status1;

/* define a structure with bit fields */

struct {

unsigned int widthValidated : 1;

unsigned int heightValidated : 1;

} status2;

int main( ) {

printf( "Memory size occupied by status1 : %d\n", sizeof(status1));

printf( "Memory size occupied by status2 : %d\n", sizeof(status2));

return 0;

When the above code is compiled and executed, it produces the following result −

Memory size occupied by status1 : 8

Memory size occupied by status2 : 4

60
Bit Field Declaration

The declaration of a bit-field has the following form inside a structure −

struct {

type [member_name] : width ;

};

The following table describes the variable elements of a bit field −

• Type-An integer type that determines how a bit-field's value is interpreted. The type may
be int, signed int, or unsigned int.
• member_name - The name of the bit-field.
• Width- The number of bits in the bit-field. The width must be less than or equal to the bit
width of the specified type.

The variables defined with a predefined width are called bit fields. A bit field can hold more than
a single bit; for example, if you need a variable to store a value from 0 to 7, then you can define a
bit field with a width of 3 bits as follows −

struct {

unsigned int age : 3;

} Age;

Typedef

The C programming language provides a keyword called typedef, which you can use to give a type
a new name. Following is an example to define a term BYTE for one-byte numbers −

typedef unsigned char BYTE;

After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned
char, for example..

BYTE b1, b2;

61
By convention, uppercase letters are used for these definitions to remind the user that the type
name is really a symbolic abbreviation, but you can use lowercase, as follows −

typedef unsigned char byte;

typedef vs #define

#define is a C-directive which is also used to define the aliases for various data types similar to
typedef but with the following differences −

typedef is limited to giving symbolic names to types only where as #define can be used to define
alias for values as well, q., you can define 1 as ONE etc.

typedef interpretation is performed by the compiler whereas #define statements are processed by
the pre-processor.

Header Files

A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the files
that the programmer writes and the files that comes with your compiler.

You request to use a header file in your program by including it with the C preprocessing directive
#include, like you have seen inclusion of stdio.h header file, which comes along with your
compiler.

Including a header file is equal to copying the content of the header file but we do not do it because
it will be error-prone and it is not a good idea to copy the content of a header file in the source
files, especially if we have multiple source files in a program

A simple practice in C or C++ programs is that we keep all the constants, macros, system wide
global variables, and function prototypes in the header files and include that header file wherever
it is required.

Include Syntax

Both the user and the system header files are included using the preprocessing directive #include.
It has the following two forms −

62
#include <file>

This form is used for system header files. It searches for a file named 'file' in a standard list of
system directories. You can prepend directories to this list with the -I option while compiling your
source code.

#include "file"

This form is used for header files of your own program. It searches for a file named 'file' in the
directory containing the current file. You can prepend directories to this list with the -I option
while compiling your source code.

Include Operation

The #include directive works by directing the C preprocessor to scan the specified file as input
before continuing with the rest of the current source file. The output from the preprocessor contains
the output already generated, followed by the output resulting from the included file, followed by
the output that comes from the text after the #include directive. For example, if you have a header
file header.h as follows −

char *test (void);

and a main program called program.c that uses the header file, like this −

int x;

#include "header.h"

int main (void) {

puts (test ());

the compiler will see the same token stream as it would if program.c read.

int x;

char *test (void);

int main (void) {

63
puts (test ());

Once-Only Headers

If a header file happens to be included twice, the compiler will process its contents twice and it
will result in an error. The standard way to prevent this is to enclose the entire real contents of the
file in a conditional, like this −

#ifndef HEADER_FILE

#define HEADER_FILE

the entire header file file

#endif

This construct is commonly known as a wrapper #ifndef. When the header is included again, the
conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over the
entire contents of the file, and the compiler will not see it twice.

Computed Includes

Sometimes it is necessary to select one of the several different header files to be included into your
program. For instance, they might specify configuration parameters to be used on different sorts
of operating systems. You could do this with a series of conditionals as follows −

#if SYSTEM_1

# include "system_1.h"

#elif SYSTEM_2

# include "system_2.h"

#elif SYSTEM_3

...

#endif

64
But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for
the header name. This is called a computed include. Instead of writing a header name as the direct
argument of #include, you simply put a macro name there −

#define SYSTEM_H "system_1.h"

...

#include SYSTEM_H

SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include
had been written that way originally. SYSTEM_H could be defined by your Makefile with a -D
option.

Type Casting

Converting one datatype into another is known as type casting or, type-conversion. For example,
if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You
can convert the values from one type to another explicitly using the cast operator as follows −

(type_name) expression

Consider the following example where the cast operator causes the division of one integer variable
by another to be performed as a floating-point operation −

#include <stdio.h>

main() {

int sum = 17, count = 5;

double mean;

mean = (double) sum / count;

printf("Value of mean : %f\n", mean );

When the above code is compiled and executed, it produces the following result −

Value of mean : 3.400000


65
It should be noted here that the cast operator has precedence over division, so the value of sum is
first converted to type double and finally it gets divided by count yielding a double value.

Type conversions can be implicit which is performed by the compiler automatically, or it can be
specified explicitly through the use of the cast operator. It is considered good programming
practice to use the cast operator whenever type conversions are necessary.

Integer Promotion

Integer promotion is the process by which values of integer type "smaller" than int or unsigned int
are converted either to int or unsigned int. Consider an example of adding a character with an
integer −

#include <stdio.h>

main() {

int i = 17;

char c = 'c'; /* ascii value is 99 */

int sum;

sum = i + c;

printf("Value of sum : %d\n", sum );

When the above code is compiled and executed, it produces the following result −

Value of sum : 116

Here, the value of sum is 116 because the compiler is doing integer promotion and converting the
value of 'c' to ASCII before performing the actual addition operation.

66
5 CODING

//C program for creating & simulating a Snake & Ladder Game
// Coded by: Bindiya . /\('-')/\
//Constraints and Rules
/*
1.The game will begin with any dice value.
2.If a 6(six) is appeared then a chance is awarded to that player.
3.Only the location of current player is shown on the board,
the location of other player is mentioned below the board.
4.Snakes:- 99 to 1, 65 to 40, 25 to 9.
5.Ladder:- 70 to 93, 60 to 83, 13 to 42.

*/
#include<stdio.h>
#include<stdlib.h>
int rd()
{
int rem;
A:rem=rand()%7;
if(rem==0)
goto A;
else
return rem;
}
void displaychart(int curp,char player[4])
{ int i,j,t,c,sft=0,diceres,pos1,pos2;

67
if(curp==100)
{
printf("*****Congratulations*****\n\n\nPlayer %s wins\n",player);
scanf("%*s");
exit(0);
}

for(i=10;i>0;i--)
{
t=i-1;
if((sft%2)==0)
{
c=0;
for(j=10;j>=1;j--)
{
diceres=(i*j)+(t*c++);

if(curp==diceres)
printf("%s\t",player);
else
printf("%d\t",diceres);
}
sft++;
}
else
{
c=9;
for(j=1;j<=10;j++)

68
{
diceres=(i*j)+(t*c--);

if(curp==diceres)
printf("%s\t",player);
else
printf("%d\t",diceres);
}
sft++;
}
printf("\n\n");
}
printf("--------------------------------------------------------------------------\n");
}
void main()
{
int i,dice,cur_pos1=0,cur_pos2=0;
char ch;
while(1)
{
printf(" ** SNAKE AND LADDER GAME** \n Coded By Akash Mahesh
Ganjal\n");
printf("Snakes:- 25 to 9,\t 65 to 40,\t 99 to 1.\nLadder:- 13 to 42,\t 60 to 83,\t 70 to 93.\n");
printf("Choose your option\n");
printf("1. Player 1 plays\n");
printf("2. Player 2 plays\n");
printf("3. Exit\n");
scanf("%s",&ch);

69
switch(ch)
{

case '1':dice=rd();
system("cls");
printf("\t\t\t\tDice = %d\n\n",dice);
if(dice==6)
printf("Dice=6: You have earned a chance to play one more time.\n");
cur_pos1=dice+cur_pos1;
if(cur_pos1<101){
if(cur_pos1==99)
{
displaychart(1,"$P1$");//snake
}
if(cur_pos1==65)
{
displaychart(40,"$P1$");//snake
}
if(cur_pos1==25)
{
displaychart(9,"$P1$");//snake
}
if(cur_pos1==70)
{
displaychart(93,"$P1$");//ladder
}
if(cur_pos1==60)
{

70
displaychart(83,"$P1$");//ladder
}
if(cur_pos1==13)
{
displaychart(42,"$P1$");//ladder
}
else{
displaychart(cur_pos1,"$P1$");
}
}
else{
cur_pos1=cur_pos1-dice;
printf("Range exceeded of Player 1.\n");
displaychart(cur_pos1,"$P1$");
}
printf("Player 2 position is %d\n",cur_pos2);
break;
case '2':dice=rd();
system("cls");
printf("\t\t\t\tDice = %d\n\n",dice);
cur_pos2=dice+cur_pos2;
if(cur_pos2<101){
if(cur_pos2==99) //snake
{
displaychart(1,"$P2$");
}
if(cur_pos2==65) //snake
{

71
displaychart(40,"$P2$");
}
if(cur_pos2==25) //snake
{
displaychart(9,"$P2$");
}
if(cur_pos2==70) //ladder
{
displaychart(93,"$P2$");
}
if(cur_pos2==60) //ladder
{
displaychart(83,"$P2$");
}
if(cur_pos2==13) //ladder
{
displaychart(42,"$P2$");
}
else{
displaychart(cur_pos2,"$P2$");
}
}
else{
cur_pos2=cur_pos2-dice;
printf("Range exceeded of Player 2.\n");
displaychart(cur_pos2,"$P2$");
}
printf("Player 1 position is %d\n",cur_pos1);

72
break;
case '3':exit(0);
break;
default:printf("Incorrect choice.Try Again\n");
}
}
}

6 OUTPUT

73
74
75
1

76
77
78
79
80
81
82
83
84
85
86
87
7 CONCLUSION

88
In conclusion, the development and implementation of the console-based "Snake and Ladder"
game using C have been successfully executed, achieving the intended objectives of the project.
The following key conclusions can be drawn from this endeavor:

• Software Development Proficiency: Through this project, we have enhanced our


proficiency in software development, particularly in the domain of game
programming. Implementing the game required a solid understanding of C
programming concepts, including data structures, control flow, and algorithm
design.

• Game Mechanics Implementation: The core mechanics of the "Snake and Ladder"
game, such as dice rolling, player movement, and interaction with game board
elements, have been effectively implemented. The game functions as intended,
providing an engaging and enjoyable gameplay experience.

• Algorithmic Problem Solving: We successfully addressed algorithmic challenges


related to simulating dice rolls, managing player positions, and incorporating game
rules (snakes and ladders) into the gameplay. This project allowed us to apply
problem-solving skills to real-world programming scenarios.

• User Interface Design: The console-based user interface designed for the game
effectively displays the game board and player positions. The use of formatted text
and grid visualization contributes to a clear and intuitive user experience.

• Learning Outcomes and Skill Development: This project served as a valuable


learning experience, enabling us to deepen our knowledge of C programming and
gain practical insights into game development techniques. We have expanded our
skill set in areas such as random number generation, array manipulation, and error
handling.

In summary, the completion of this project underscores the importance of hands-on experience in
software development and highlights the application of programming skills in creating
interactive applications.

89
8 FUTURE PLANS
Looking forward, there are several exciting avenues for expanding and improving our "Snake and
Ladder" game project:

• Graphical User Interface (GUI) Development: Transitioning the game from a text-based
console interface to a graphical user interface (GUI) using modern graphics libraries. This
upgrade will enhance the visual presentation and user experience.
• Multiplayer Functionality: Implementing multiplayer capabilities to allow multiple players
to compete against each other in real-time, either locally or over the internet. This addition
will add a social and competitive dimension to the game.
• Customization Features: Introducing options for players to customize game settings such
as board size, difficulty levels, and the number of snakes and ladders. This customization
will enhance replayability and player engagement.
• Artificial Intelligence (AI) Opponents: Developing AI-controlled opponents with varying
difficulty levels to provide challenging gameplay for solo players. This will add depth and
versatility to the gaming experience.
• Game Statistics and Achievements: Implementing a system to track player statistics, such
as win-loss ratios and highest scores, and integrating achievements or badges to reward
player progress and accomplishments.
• Cross-Platform Adaptation: Adapting the game for mobile devices or web browsers to
reach a wider audience and enable gameplay on different platforms.
• Localization and Globalization: Localizing the game by translating it into multiple
languages and incorporating cultural elements to make it more accessible and appealing to
players from diverse backgrounds.

By pursuing these future plans, we aim to evolve our "Snake and Ladder" game into a polished
and engaging experience that caters to a broad audience of players. This iterative development
approach reflects our commitment to continuous enhancement and innovation in game design and
software development.

90
BIBLIOGRAPHY

Websites
I. https://www.investopedia.com/terms/g/gantt-chart.asp
II. https://www.geeksforgeeks.org/what-is-dfddata-flow-diagram/
III. https://www.tutorialspoint.com/system_analysis_and_design/system_design.htm
IV. https://www.lucidchart.com/pages/er-diagrams#:~:text=Make%20an%20ERD-
,What%20is%20an%20ER%20diagram%3F,each%20other%20within%20a%20system.
V. https://www.javatpoint.com/
VI. www.ineuron.ai
VII. https://www.w3schools.com/c/c_intro.php

Books:

I. Web Design with HTML, CSS, JavaScript and Jquery Set- Jon Duckeet

91

You might also like