Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Pps Notes (4 Files Merged)

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

What is Computer?

A computer is an electronic device that accepts data, performs operations, displays results, and stores the
data or results as needed. It is a combination of hardware and software resources that integrate together
and provides various functionalities to the user. Hardware is the physical components of a computer like a
processor, memory devices, monitor, keyboard, etc., while software is a set of programs or instructions
that are required by the hardware resources to function properly.

Components of a Computer
There are basically three important components of a computer:
1. Input Unit
2. Central Processing Unit(CPU)
3. Output Unit

1. Input Unit:
The input unit consists of input devices that are attached to the computer. These devices take input and
convert it into binary language that the computer understands. Some of the common input devices are
keyboard, mouse, joystick, scanner etc.
 The Input Unit is formed by attaching one or more input devices to a computer.
 A user input data and instructions through input devices such as a keyboard, mouse, etc.
 The input unit is used to provide data to the processor for further processing.

2. Central Processing Unit:


Once the information is entered into the computer by the input device, the processor processes it. The
CPU is called the brain of the computer because it is the control centre of the computer. It first fetches
instructions from memory and then interprets them so as to know what is to be done. If required, data is
fetched from memory or input device. Thereafter CPU executes or performs the required computation,
and then either stores the output or displays it on the output device. The CPU has three main components,
which are responsible for different functions: Arithmetic Logic Unit (ALU), Control Unit (CU) and
Memory registers
A. Arithmetic and Logic Unit (ALU): The ALU, as its name suggests performs mathematical
calculations and takes logical decisions. Arithmetic calculations include addition, subtraction,
multiplication and division. Logical decisions involve the comparison of two data items to see which one
is larger or smaller or equal.
 Arithmetic Logical Unit is the main component of the CPU
 It is the fundamental building block of the CPU.
 Arithmetic and Logical Unit is a digital circuit that is used to perform arithmetic and logical
operations.

B. Control Unit: The Control unit coordinates and controls the data flow in and out of the CPU, and also
controls all the operations of ALU, memory registers and also input/output units. It is also responsible for
carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and
sends control signals to input/output devices until the required operation is done properly by ALU and
memory.
 The Control Unit is a component of the central processing unit of a computer that directs the
operation of the processor.
 It instructs the computer’s memory, arithmetic and logic unit, and input and output devices on
how to respond to the processor’s instructions.
 In order to execute the instructions, the components of a computer receive signals from the
control unit.
 It is also called the central nervous system or brain of the computer.

C. Memory Registers: A register is a temporary unit of memory in the CPU. These are used to store the
data, which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and
so on) and each register inside the CPU has a specific function, like storing data, storing an instruction,
storing address of a location in memory etc. The user registers can be used by an assembly language
programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the
ALU and contains one of the operands of an operation to be performed in the ALU.

Memory attached to the CPU is used for the storage of data and instructions, and is called internal
memory The internal memory is divided into many storage locations, each of which can store data or
instructions. Each memory location is of the same size and has an address. With the help of the address,
the computer can read any memory location easily without having to search the entire memory. When a
program is executed, its data is copied to the internal memory and stored in the memory till the end of the
execution. The internal memory is also called the Primary memory or Main memory. This memory is also
called RAM, i.e., Random Access Memory. The time of access of data is independent of its location in
memory, therefore, this memory is also called Random Access memory (RAM).
 Memory Unit is the primary storage of the computer.
 It stores both data and instructions.
 Data and instructions are stored permanently in this unit so that they are available whenever
required.

3. Output Unit :
The output unit consists of output devices that are attached to the computer. It converts the binary data
coming from the CPU to human understandable form. The common output devices are monitor, printer,
plotter, etc.
 The output unit displays or prints the processed data in a user-friendly format.
 The output unit is formed by attaching the output devices of a computer.
 The output unit accepts the information from the CPU and displays it in a user-readable form.
Characteristics of a Computer
1. Speed: Computers can perform millions of calculations per second. The computation speed is
extremely fast.
2. Accuracy: Because computers operate on pre-programmed software, there is no space for human error.
3. Diligence: They can perform complex and long calculations at the same time and with the same
accuracy.
4. Versatile: Computers are designed to be versatile. They can carry out multiple operations at the same
time.
5. Storage: Computers can store a large amount of data/ instructions in its memory, which can be
retrieved at any point of time.

Computer Memory
A memory is just like a human brain. It is used to store data and instructions. Computer memory is the
storage space in the computer, where data is to be processed and instructions required for processing are
stored. The memory is divided into large number of small parts called cells. Each location or cell has a
unique address, which varies from zero to memory size minus one. For example, if the computer has 64k
words, then this memory unit has 64 * 1024 = 65536 memory locations. The address of these locations
varies from 0 to 65535.
Memory is primarily of three types −

 Cache Memory
 Primary Memory/Main Memory
 Secondary Memory

Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up the CPU. It acts as a
buffer between the CPU and the main memory. It is used to hold those parts of data and program which
are most frequently used by the CPU. The parts of data and programs are transferred from the disk to
cache memory by the operating system, from where the CPU can access them.
Advantages
The advantages of cache memory are as follows −

 Cache memory is faster than main memory.


 It consumes less access time as compared to main memory.
 It stores the program that can be executed within a short period of time.
 It stores data for temporary use.
Disadvantages
The disadvantages of cache memory are as follows −

 Cache memory has limited capacity.


 It is very expensive.
Primary Memory (Main Memory)
Primary memory holds only those data and instructions on which the computer is currently working. It
has a limited capacity and data is lost when power is switched off. It is generally made up of
semiconductor device. These memories are not as fast as registers. The data and instruction required to be
processed resides in the main memory. It is divided into two subcategories RAM and ROM.
Characteristics of Main Memory
 These are semiconductor memories.
 It is known as the main memory.
 Usually volatile memory.
 Data is lost in case power is switched off.
 It is the working memory of the computer.
 Faster than secondary memories.
 A computer cannot run without the primary memory.

Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than the main
memory. These are used for storing data/information permanently. CPU directly does not access these
memories, instead they are accessed via input-output routines. The contents of secondary memories are
first transferred to the main memory, and then the CPU can access it. For example, disk, CD-ROM, DVD,
etc.
Characteristics of Secondary Memory
 These are magnetic and optical memories.
 It is known as the backup memory.
 It is a non-volatile memory.
 Data is permanently stored even if power is switched off.
 It is used for storage of data in a computer.
 Computer may run without the secondary memory.
 Slower than primary memories.

What is an Algorithm?
In computer programming terms, an algorithm is a set of well-defined instructions to solve a particular
problem. It takes a set of input(s) and produces the desired output. For example,

An algorithm to add two numbers:

1. Take two number inputs

2. Add numbers using the + operator

3. Display the result

Qualities of a Good Algorithm

 Input and output should be defined precisely.

 Each step in the algorithm should be clear and unambiguous.

 Algorithms should be most effective among many different ways to solve a problem.

 An algorithm shouldn't include computer code. Instead, the algorithm should be written in such a
way that it can be used in different programming languages.

Algorithm Examples

Algorithm 1: Add two numbers entered by the user

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 5: Display sum

Step 6: Stop
Algorithm 2: Find the largest number among three numbers

Step 1: Start

Step 2: Declare variables a,b and c.

Step 3: Read variables a,b and c.

Step 4: If a > b

If a > c

Display a is the largest number.

Else

Display c is the largest number.

Else

If b > c

Display b is the largest number.

Else

Display c is the greatest number.

Step 5: Stop

Flowchart In Programming

A flowchart is a diagrammatic representation of an algorithm. A flowchart can be helpful for both writing
programs and explaining the program to others.

Symbols Used In Flowchart

Symbol Purpose Description


Indicates the flow of logic
Flow line
by connecting symbols.

Represents the start and


Terminal(Stop/Start)
the end of a flowchart.

Used for input and output


Input/Output
operation.

Used for arithmetic


Processing operations and data-
manipulations.

Used for decision making


Decision between two or more
alternatives.

Used to join different


On-page Connector
flowline

Used to connect the


Off-page Connector flowchart portion on a
different page.
Represents a group of
Predefined
statements performing
Process/Function
one processing task.

Examples of flowcharts in programming

1. Add two numbers entered by the user.

Flowchart to add two numbers

2. Find the largest among three different numbers entered by the user.
Flowchart to find the largest among three numbers.

Types of Errors in C
There are five different types of errors in C.

1. Syntax Error
2. Run Time Error
3. Logical Error
4. Semantic Error
5. Linker Error

1. Syntax Error

Syntax errors occur when a programmer makes mistakes in typing the code's syntax correctly or
makes typos. In other words, syntax errors occur when a programmer does not follow the set of
rules defined for the syntax of C language.
Syntax errors are sometimes also called compilation errors because they are always detected by
the compiler. Generally, these errors can be easily identified and rectified by programmers.

The most commonly occurring syntax errors in C language are:

 Missing semi-colon (;)


 Missing parenthesis ({})
 Assigning value to a variable without declaring it

Let us take an example to understand syntax errors:

#include <stdio.h>

void main() {
var = 5; // we did not declare the data type of variable

printf("The variable is: %d", var);


}

Output:

error: 'var' undeclared (first use in this function)

If the user assigns any value to a variable without defining the data type of the variable, the
compiler throws a syntax error.

Let's see another example:

#include <stdio.h>

void main() {

for (int i = 0;) { // incorrect syntax of the for loop


printf("Scaler Academy");
}
}

Output:

error: expected expression before ')' token

A for loop needs 3 arguments to run. Since we entered only one argument, the compiler threw a
syntax error.

2. Runtime Error

Errors that occur during the execution (or running) of a program are called RunTime Errors.
These errors occur after the program has been compiled successfully. When a program is
running, and it is not able to perform any particular operation, it means that we have encountered
a run time error. For example, while a certain program is running, if it encounters the square root
of -1 in the code, the program will not be able to generate an output because calculating the
square root of -1 is not possible. Hence, the program will produce an error.

Runtime errors can be a little tricky to identify because the compiler can not detect these errors.
They can only be identified once the program is running. Some of the most common run time
errors are: number not divisible by zero, array index out of bounds, string index out of bounds,
etc.

Runtime errors can occur because of various reasons. Some of the reasons are:

1. Mistakes in the Code: Let us say during the execution of a while loop, the programmer forgets
to enter a break statement. This will lead the program to run infinite times, hence resulting in a
run time error.
2. Memory Leaks: If a programmer creates an array in the heap but forgets to delete the array's
data, the program might start leaking memory, resulting in a run time error.
3. Mathematically Incorrect Operations: Dividing a number by zero, or calculating the square root
of -1 will also result in a run time error.
4. Undefined Variables: If a programmer forgets to define a variable in the code, the program will
generate a run time error.

Example 1:

// A program that calculates the square root of integers


#include <stdio.h>
#include <math.h>

int main() {
for (int i = 4; i >= -2; i--) {
printf("%f", sqrt(i));
printf("\n");
}
return 0;
}

Output:

2.000000
1.732051
1.414214
1.000000
0.000000
-1.#IND00
-1.#IND00

**In some compilers, you may also see this output: **

2.000000
1.732051
1.414214
1.000000
0.000000
-nan
-nan

In the above example, we used a for loop to calculate the square root of six integers. But because
we also tried calculating the square root of two negative numbers, the program generated two
errors (the IND written above stands for "Indeterminate"). These errors are the run time errors. -
nan is similar to IND.

Example 2:

#include<stdio.h>

void main() {
int var = 2147483649;

printf("%d", var);
}

Output:

-2147483647

This is an integer overflow error. The maximum value an integer can hold in C is 2147483647.
Since in the above example, we assigned 2147483649 to the variable var, the variable overflows,
and we get -2147483647 as the output (because of the circular property).

3. Logical Error

Sometimes, we do not get the output we expected after the compilation and execution of a
program. Even though the code seems error free, the output generated is different from the
expected one. These types of errors are called Logical Errors. Logical errors are those errors in
which we think that our code is correct, the code compiles without any error and gives no error
while it is running, but the output we get is different from the output we expected.

In 1999, NASA lost a spacecraft due to a logical error. This happened because of some
miscalculations between the English and the American Units. The software was coded to work
for one system but was used with the other.

For Example:

#include <stdio.h>

void main() {
float a = 10;
float b = 5;

if (b = 0) { // we wrote = instead of ==
printf("Division by zero is not possible");
} else {
printf("The output is: %f", a/b);
}
}

Output:

The output is: inf

INF signifies a division by zero error. In the above example, at line 8, we wanted to check
whether the variable b was equal to zero. But instead of using the equal to comparison
operator (==), we use the assignment operator (=). Because of this, the if statement became false
and the value of b became 0. Finally, the else clause got executed.

4. Semantic Error

Errors that occur because the compiler is unable to understand the written code are called
Semantic Errors. A semantic error will be generated if the code makes no sense to the compiler,
even though it is syntactically correct. It is like using the wrong word in the wrong place in the
English language. For example, adding a string to an integer will generate a semantic error.

Semantic errors are different from syntax errors, as syntax errors signify that the structure of a
program is incorrect without considering its meaning. On the other hand, semantic errors signify
the incorrect implementation of a program by considering the meaning of the program.

The most commonly occurring semantic errors are: use of un-initialized variables, type
compatibility, and array index out of bounds.

Example 1:

#include <stdio.h>

void main() {
int a, b, c;

a * b = c;
// This will generate a semantic error
}

Output:

error: lvalue required as left operand of assignment

When we have an expression on the left-hand side of an assignment operator (=), the program
generates a semantic error. Even though the code is syntactically correct, the compiler does not
understand the code.

Example 2:

#include <stdio.h>
void main() {
int arr[5] = {5, 10, 15, 20, 25};

int arraySize = sizeof(arr)/sizeof(arr[0]);

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


{
printf("%d \n", arr[i]);
}
}

Output:

5
10
15
20
25
32764

In the above example, we printed six elements while the array arr only had five. Because we
tried to access the sixth element of the array, we got a semantic error and hence, the program
generated a garbage value.

5. Linker Error

Linker is a program that takes the object files generated by the compiler and combines them into
a single executable file. Linker errors are the errors encountered when the executable file of the
code can not be generated even though the code gets compiled successfully. This error is
generated when a different object file is unable to link with the main object file. We can run into
a linked error if we have imported an incorrect header file in the code, we have a wrong function
declaration, etc.

For Example:

#include <stdio.h>

void Main() {
int var = 10;
printf("%d", var);
}

Output:

undefined reference to `main'

In the above code, as we wrote Main() instead of main(), the program generated a linker error.
This happens because every file in the C language must have a main() function. As in the above
program, we did not have a main() function, the program was unable to run the code, and we got
an error. This is one of the most common type of linker error.
Both compilers and interpreters are the language processors used to convert software codes written in
high-level language into machine language codes. Compilers and interpreters are types of system
software. They are required because a computer cannot process a code written in high-level
programming language like C, C++, Java, etc. Therefore, we convert a HLL code into machine code for
execution.

What is a Compiler?
A compiler is a translator that produces an output of low-level language (like an
assembly or machine language) by taking an input of high-level language. It is basically
a computer program used to transform codes written in a programming language into
machine code (human-readable code to a binary 0 and 1 bits language for a computer
processor to understand). The computer then processes the machine code for
performing the corresponding tasks.

 Compilers check all types of errors, limits, and ranges. Thus, it’s more intelligent.
 The run time of its program is longer, and it occupies more memory.

What Is an Interpreter?
It is a program that functions for the translation of a programming language into a
comprehensible one. It is a computer program used for converting high-level program
statements into machine codes. It includes pre-compiled code, source code, and
scripts.

 An interpreter translates only one statement at a time of the program.


 They create an exe of the programming language before the program runs.

Difference Between Compiler and Interpreter


Parameter Compiler Interpreter

Steps of  Creation of the program.  Creation of the program.


Programming  The Compiler analyses all the  It doesn’t require the linking of files or
language statements and generation of machine code.
throws an error when it finds  It executes the source statements line
something incorrect. by line during the execution.
 If there’s zero error, the
compiler converts the source
code to machine one.
 It links various code files into a
runnable program (exe).
 It runs the program.

Advantage The code execution time is They are fairly easy to use and execute, even
comparatively less because the for a beginner.
program code already gets translated
into machine code.

Disadvantage One can’t change a program without Only computers with the corresponding
getting back to the source code. Interpreter can run the interpreted programs.

Machine Code It stores the machine language on the It doesn’t save the machine language at all.
disk in the form of machine code.

Running Time The compiled codes run comparatively The interpreted codes run comparatively slower.
faster.

Model It works on the basis of the language- It works on the basis of the Interpretation
translation linking-loading model. method.

Generation of It generates an output program in the It doesn’t generate an output program. Meaning,
Program exe format. A user can run it it evaluates the source program every time
independently from the originally during individual execution.
intended program.

Execution One can separate the program Execution of the program is one of the steps of
execution from the compilation. Thus, the Interpretation process. So, you can perform
you can perform it only after it line by line.
completing the compilation of the
entire output.

Memory Target programs execute Interpreter originally exists in the memory at the
Requirement independently. They don’t require the time of interpretation.
Compiler in the memory.

Best Fitted For You cannot port the Compiler because They work the best in web environments- where
it stays bound to the specific target the load time is very crucial. Compiling takes a
machine. The compilation model is relatively long time, even with small codes that
very common in programming may not run multiple times due to the exhaustive
languages like C and C++. analysis. Interpretations are better in such
cases.

Optimization of A compiler is capable of seeing the An interpreter sees a code line by line. The
Code entire code upfront. Thus, it makes the optimization is, thus, not very robust when
codes run faster by performing plenty compared to Compilers.
of optimizations.

Dynamic Compilers are very difficult to The Interpreted language supports Dynamic
Typing implement because they can’t predict Typing.
anything that happens during the turn
time.

Use It works best for the Production It works the best for the programming and
Environment. development environment.

Execution of A Compiler displays every error and An Interpreter reads every statement, then
Error warning while compiling. So, you can’t displays the errors, if any. A user must resolve
run this program unless you fix the these errors in order to interpret the next line.
errors.

Input A Compiler takes a program as a An Interpreter takes single lines of a code.


whole.

Output The Compilers generate intermediate The Interpreters never generate any
machine codes. intermediate machine codes.

Errors This translator displays all the errors It displays the errors of every single line one by
after compiling- together at the same one.
time.

Programming Java, Scala, C#, C, C++ use Perl, Ruby, PHP use Interpreters.
Languages Compilers.

Operating System Definition and Function


In the Computer System (comprises of Hardware and software), Hardware can only
understand machine code (in the form of 0 and 1) which doesn't make any sense to a
naive user.

We need a system which can act as an intermediary and manage all the processes and
resources present in the system.

An Operating System can be defined as an interface between user and hardware. It


is responsible for the execution of all the processes, Resource
Allocation, CPU management, File Management and many other tasks.

The purpose of an operating system is to provide an environment in which a user can


execute programs in convenient and efficient manner.

Structure of a Computer System


A Computer System consists of:

o Users (people who are using the computer)


o Application Programs (Compilers, Databases, Games, Video player, Browsers, etc.)
o System Programs (Shells, Editors, Compilers, etc.)
o Operating System ( A special program which acts as an interface between user and
hardware )
o Hardware ( CPU, Disks, Memory, etc)
What does an Operating system do?
1. Process Management
2. Process Synchronization
3. Memory Management
4. CPU Scheduling
5. File Management
6. Security

What is an Operating System?


An operating system (OS) manages all other applications and programs in a computer,
and it is loaded into the computer by a boot program. It enables applications to interact
with a computer’s hardware. Through a designated application programme interface,
the application programmes request services from the operating system (API). The
kernel is the software that contains the operating system’s core components. To run
other programmes, every computer has to have at least one operating system installed.
Operating System

Windows, Linux, and Android are examples of operating systems that enable the user to
use programs like MS Office, Notepad, and games on the computer or mobile phone. It
is necessary to have at least one operating system installed in the computer to run
basic programs like browsers.

The core functions of an operating system include:

 Managing hardware resources: An operating system manages resources such as


CPU, memory, and disk space, and assigns these resources to running applications.
 Running applications: An operating system provides an environment in which
applications can run and interact with the user.
 Providing a user interface: An operating system provides a graphical user interface
(GUI) that allows users to interact with the computer.
 Examples of popular operating systems include:
 Windows: Microsoft Windows is the most popular desktop operating system, used by
over 1 billion users worldwide. It has a wide range of features and applications,
including the Office suite, gaming, and productivity tools.
 macOS: macOS is the desktop operating system used by Apple Mac computers. It is
known for its clean, user-friendly interface, and is popular among creative
professionals.
 Linux: Linux is an open-source operating system that is available for free and can be
customized to meet specific needs. It is used by developers and businesses, as well
as individuals who prefer an open-source, customizable operating system.

Functions of Operating System


 Processor Management: An operating system manages the processor’s work by
allocating various jobs to it and ensuring that each process receives enough time
from the processor to function properly.
 Memory Management: An operating system manages the allocation and
deallocation of the memory to various processes and ensures that the other process
does not consume the memory allocated to one process.
 Device Management: There are various input and output devices. An OS controls
the working of these input-output devices. It receives the requests from these
devices, performs a specific task, and communicates back to the requesting
process.
 File Management: An operating system keeps track of information regarding the
creation, deletion, transfer, copy, and storage of files in an organized way. It also
maintains the integrity of the data stored in these files, including the file directory
structure, by protecting against unauthorized access.
 Security: The operating system provides various techniques which assure the
integrity and confidentiality of user data. Following security measures are used to
protect user data:
 Protection against unauthorized access through login.
 Protection against intrusion by keeping Firefall active.
 Protecting the system memory against malicious access.
 Displaying messages related to system vulnerabilities.
 Error Detection: From time to time, the operating system checks the system for any
external threat or malicious software activity. It also checks the hardware for any
type of damage. This process displays several alerts to the user so that the
appropriate action can be taken against any damage caused to the system.
 Job Scheduling: In a multitasking OS where multiple programs run simultaneously,
the operating system determines which applications should run in which order and
how time should be allocated to each application.
Features of Operating Systems
Here is a list of some important features of operating systems:

1. Provides a platform for running applications


2. Handles memory management and CPU scheduling
3. Provides file system abstraction
4. Provides networking support
5. Provides security features
6. Provides user interface
7. Provides utilities and system services
8. Supports application development
Components of Operating System
Now to perform the functions mentioned above, the operating system has two
components:

 Shell
 Kernel
Executable Code

Executable Code is the end translated machine understandable code of a program.All .exe
files and .o files are executable codes.Each programming language generates an executable
code but in different ways.A normal C,C++ program when compiled is first translated into
Assembly Language and then to Machine Language and that Machine Language code is
stored in an .exe file which is abbreviated as executable code .To understand well,use Dev-
CPP compiler which creates an exe file for every program compiled or executed.

What is Object Code


The computer does not understand the source program or the source code. Therefore,
the compiler converts the source program into an object program. It contains the instructions for
the machine to perform. These instructions are in the form of binary digits. The machine
understands this object code. Therefore, the computer can execute this code. Generally, the
object code is specific to the system architecture.

Furthermore, if the programmer does any modifications to the source code, it is necessary to
compile the program to make those changes appear in the object code.
What is Executable Code
Executable code is a file or a program that indicates tasks according to encoded instructions. The
CPU can directly execute an executable file to defined tasks. In other words, it is machine code
instructions for a physical CPU. As a CPU can directly execute an object code, we can also
consider the object code as an executable code. Furthermore, it is sometimes possible to
consider a bytecode or scripting language instructions as an executable code.
Difference Between Object Code and Executable Code
Definition
Object code is a sequence of statements in binary that is generated after compiling the source
program. In contrast, an executable code is a file or a program that indicates tasks according to
encoded instructions which are directly executed by the CPU.

The C Language is developed by Dennis Ritchie for creating system applications that
directly interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why
it is known as mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

1) C as a mother language
C language is considered as the mother language of all the modern programming
languages because most of the compilers, JVMs, Kernels, etc. are written in C
language, and most of the programming languages follow C syntax, for example, C++,
Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc. that are
being used in many languages like C++, Java, C#, etc.
2) C as a system programming language
A system programming language is used to create system software. C language is a
system programming language because it can be used to do low-level programming
(for example driver and kernel). It is generally used to create hardware devices, OS,
drivers, kernels, etc. For example, Linux kernel is written in C.

It can't be used for internet programming like Java, .Net, PHP, etc.

3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be declared


before being used.

4) C as a structured programming language


A structured programming language is a subset of the procedural language. Structure
means to break a program into parts or blocks so that it may be easy to understand.

In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.

5) C as a mid-level programming language


C is considered as a middle-level language because it supports the feature of both
low-level and high-level languages. C language program is converted into assembly
code, it supports pointer arithmetic (low-level), but it is machine independent (a feature
of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is machine
dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine independent. It is


easy to understand.

C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change
the C program code.

File: main.c

1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories


of AT&T (American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system. It inherits


many features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard


B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Features of C Language

C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with
some machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system
applications such as kernel, driver, etc. It also supports the features of a high-level
language. That is why it is known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the program
into parts using functions. So, it is easy to understand and modify. Functions also
provide code reusability.

5) Rich Library
C provides a lot of inbuilt functions that make the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.

10) Extensible
C language is extensible because it can easily adopt new features.

Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily
identified.

Let's see the syntax to declare a variable:

1. type variable_list;

The example of declaring the variable is given below:

1. int a;
2. float b;
3. char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

1. int a=10,b=20;//declaring 2 variable of integer type


2. float f=20.8;
3. char c='A';

Rules for defining variables


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

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

1. int 2;
2. int a b;
3. int long;

Types of Variables in C
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable
A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

1. void function1(){
2. int x=10;//local variable
3. }

You must have to initialize the local variable before it is used.

Global Variable
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

1. int value=20;//global variable


2. void function1(){
3. int x=10;//local variable
4. }
Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }

If you call this function many times, the local variable will print the same value for
each function call, e.g, 11,11,11 and so on. But the static variable will print the
incremented value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default.
We can explicitly declare an automatic variable using auto keyword.

1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }

External Variable
We can share a variable in multiple C source files by using an external variable. To
declare an external variable, you need to use extern keyword.

myfile.h

1. extern int x=10;//external variable (also global)


program1.c

1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports
both signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit
operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535


long int 4 byte -2,147,483,648 to 2,147,4

signed long int 4 byte -2,147,483,648 to 2,147,4

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Int:
Integers are entire numbers without any fractional or decimal parts, and the int data
type is used to represent them.

It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.

An int takes up 4 bytes of memory on most devices, allowing it to store values between
around -2 billion and +2 billion.

Char:
Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols,
or commas. There are 256 characters that can be represented by a single char, which
takes up one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in
single quotes.

Float:
To represent integers, use the floating data type. Floating numbers can be used to
represent fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not
be very precise. It can store values with an accuracy of about 6 decimal places and a
range of about 3.4 x 1038 in 4 bytes of memory.

Double:
Use two data types to represent two floating integers. When additional precision is
needed, such as in scientific calculations or financial applications, it provides greater
accuracy compared to float.

Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.

1. int age = 25;


2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the person's age,
a char variable for the student's grade, a float variable for the temperature reading,
and two variables for the number pi.

Derived Data Type


Beyond the fundamental data types, C also supports derived data
types, including arrays, pointers, structures, and unions. These data types give
programmers the ability to handle heterogeneous data, directly modify memory, and
build complicated data structures.

Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the
same type. It provides a mechanism for joining multiple targets of the same data under
the same name.

The index is used to access the elements of the array, with a 0 index for the first entry.
The size of the array is fixed at declaration time and cannot be changed during program
execution. The array components are placed in adjacent memory regions.
Here is an example of declaring and utilizing an array:

1. #include <stdio.h>
2.
3. int main() {
4. int numbers[5]; // Declares an integer array with a size of 5 elements
5.
6. // Assign values to the array elements
7. numbers[0] = 10;
8. numbers[1] = 20;
9. numbers[2] = 30;
10. numbers[3] = 40;
11. numbers[4] = 50;
12.
13. // Display the values stored in the array
14. printf("Values in the array: ");
15. for (int i = 0; i < 5; i++) {
16. printf("%d ", numbers[i]);
17. }
18. printf("\n");
19.
20. return 0;
21. }

Output:

Values in the array: 10 20 30 40 50

Pointer:
A pointer is a derived data type that keeps track of another data type's memory
address. When a pointer is declared, the data type it refers to is stated first, and then
the variable name is preceded by an asterisk (*).

You can have incorrect access and change the value of variable using pointers by
specifying the memory address of the variable. Pointers are commonly used
in tasks such as function pointers, data structures, and dynamic memory allocation.
Here is an example of declaring and employing a pointer:

1. #include <stdio.h>
2.
3. int main() {
4. int num = 42; // An integer variable
5. int *ptr; // Declares a pointer to an integer
6.
7. ptr = # // Assigns the address of 'num' to the pointer
8.
9. // Accessing the value of 'num' using the pointer
10. printf("Value of num: %d\n", *ptr);
11.
12. return 0;
13. }

Output:

Value of num: 42

Structure:
A structure is a derived data type that enables the creation of composite data types by
allowing the grouping of many data types under a single name. It gives you the ability
to create your own unique data structures by fusing together variables of various sorts.

1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
3. A structure's members can be accessed by using the dot (.) operator.

A declaration and use of a structure is demonstrated here:

1. #include <stdio.h>
2. #include <string.h>
3. // Define a structure representing a person
4. struct Person {
5. char name[50];
6. int age;
7. float height;
8. };
9.
10. int main() {
11. // Declare a variable of type struct Person
12. struct Person person1;
13.
14. // Assign values to the structure members
15. strcpy(person1.name, "John Doe");
16. person1.age = 30;
17. person1.height = 1.8;
18.
19. // Accessing the structure members
20. printf("Name: %s\n", person1.name);
21. printf("Age: %d\n", person1.age);
22. printf("Height: %.2f\n", person1.height);
23.
24. return 0;
25. }

Output:

Name: John Doe


Age: 30
Height: 1.80

Union:
A derived data type called a union enables you to store various data types in the same
memory address. In contrast to structures, where each member has a separate memory
space, members of a union all share a single memory space. A value can only be held by
one member of a union at any given moment. When you need to represent many data
types interchangeably, unions come in handy. Like structures, you can access the
members of a union by using the dot (.) operator.

Here is an example of a union being declared and used:


1. #include <stdio.h>
2. // Define a union representing a numeric value
3. union NumericValue {
4. int intValue;
5. float floatValue;
6. char stringValue[20];
7. };
8. int main() {
9. // Declare a variable of type union NumericValue
10. union NumericValue value;
11. // Assign a value to the union
12. value.intValue = 42;
13. // Accessing the union members
14. printf("Integer Value: %d\n", value.intValue);
15. // Assigning a different value to the union
16. value.floatValue = 3.14;
17. // Accessing the union members
18. printf("Float Value: %.2f\n", value.floatValue);
19.
20. return 0;
21. }

Output:

Integer Value: 42
Float Value: 3.14

Enumeration Data Type


A set of named constants or enumerators that represent a collection of connected
values can be defined in C using the enumeration data type (enum).
Enumerations give you the means to give names that make sense to a group of integral
values, which makes your code easier to read and maintain.

Here is an example of how to define and use an enumeration in C:

1. #include <stdio.h>
2.
3. // Define an enumeration for days of the week
4. enum DaysOfWeek {
5. Monday,
6. Tuesday,
7. Wednesday,
8. Thursday,
9. Friday,
10. Saturday,
11. Sunday
12. };
13.
14. int main() {
15. // Declare a variable of type enum DaysOfWeek
16. enum DaysOfWeek today;
17.
18. // Assign a value from the enumeration
19. today = Wednesday;
20.
21. // Accessing the enumeration value
22. printf("Today is %d\n", today);
23.
24. return 0;
25. }

Output:

Today is 2

Void Data Type


The void data type in the C language is used to denote the lack of a particular
type. Function return types, function parameters, and pointers are three situations
where it is frequently utilized.
Function Return Type:
A void return type function does not produce a value. A void function executes a task
or action and ends rather than returning a value.

Example:

1. void printHello() { printf("Hello, world!\n"); }

Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.

Example:

1. void processInput(void) { /* Function logic */ }

Pointers:
Any address can be stored in a pointer of type void*, making it a universal pointer. It
offers a method for working with pointers to ambiguous or atypical types.

Example:

1. void* dataPtr;

The void data type is helpful for defining functions that don't accept any arguments
when working with generic pointers or when you wish to signal that a function doesn't
return a value. It is significant to note that while void* can be used to build generic
pointers, void itself cannot be declared as a variable type.

Here is a sample of code that shows how to utilize void in various situations:

1. #include <stdio.h>
2. // Function with void return type
3. void printHello() {
4. printf("Hello, world!\n");
5. }
6. // Function with void parameter
7. void processInput(void) {
8. printf("Processing input...\n");
9. }
10.
11. int main() {
12. // Calling a void function
13. printHello();
14.
15. // Calling a function with void parameter
16. processInput();
17.
18. // Using a void pointer
19. int number = 10;
20. void* dataPtr = &number;
21. printf("Value of number: %d\n", *(int*)dataPtr);
22.
23. return 0;
24. }

Output:

Hello, world!
Processing input...
Value of number: 10

Conclusion:
As a result, data types are essential in the C programming language because they
define the kinds of information that variables can hold. They provide the data's size and
format, enabling the compiler to allot memory and carry out the necessary actions. Data
types supported by C include void, enumeration, derived, and basic types. In addition
to floating-point types like float and double, basic data types in C also include integer-
based kinds like int, char, and short. These forms can be signed or unsigned, and they
fluctuate in size and range. To create dependable and efficient code, it is crucial to
comprehend the memory size and scope of these types.

A few examples of derived data types are unions, pointers, structures, and arrays.
Multiple elements of the same kind can be stored together in contiguous memory due
to arrays. Pointers keep track of memory addresses, allowing for fast data structure
operations and dynamic memory allocation. While unions allow numerous variables to
share the same memory space, structures group relevant variables together.

Code becomes more legible and maintainable when named constants are defined using
enumeration data types. Enumerations give named constants integer values to enable
the meaningful representation of related data. The void data type indicates the lack of a
particular type. It is used as a return type for both functions and function
parameters that don't take any arguments and don't return a value. The void*
pointer also functions as a general pointer that can store addresses of various types.

C programming requires a solid understanding of data types. Programmers can ensure


adequate memory allocation, avoid data overflow or truncation, and enhance the
readability and maintainability of their code by selecting the right data type. C
programmers may create effective, dependable, and well-structured code that satisfies
the requirements of their applications by having a firm understanding of data types.

Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name,
etc. There are only 32 reserved words (keywords) in the C language.

A list of 32 keywords in the c language is given below:

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

C Identifiers
C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such as
uppercase, lowercase letters, underscore, digits, but the starting letter should be either
an alphabet or an underscore. If the identifier is not used in the external linkage, then it
is called as an internal identifier. If the identifier is used in the external linkage, then it is
called as an external identifier.
We can say that an identifier is a collection of alphanumeric characters that begins
either with an alphabetical character or an underscore, which are used to represent
various programming elements such as variables, functions, arrays, structures, unions,
labels, etc. There are 52 alphabetical characters (uppercase and lowercase), underscore
character, and ten numerical digits (0-9) that represent the identifiers. There is a total of
63 alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers


o The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers

1. total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

1. 2sum (starts with a numerical digit)


2. int (reserved word)
3. char (reserved word)
4. m+n (special character, i.e., '+')

Types of identifiers
o Internal identifier
o External identifier

Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal
identifier. The internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier.
The external identifiers can be function names, global variables.

Differences between Keyword and Identifier

Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It must be written in a lowercase letter. It can be written in both lowercase and

Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c com

It is a combination of alphabetical characters. It is a combination of alphanumeric cha

It does not contain the underscore character. It can contain the underscore character

Let's understand through an example.

1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }

Output
Value of a is : 10
Value of A is :20

The above output shows that the values of both the variables, 'a' and 'A' are different.
Therefore, we conclude that the identifiers are case sensitive.

C Operators
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C


language.

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator

Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right
or right to left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated
before + (additive operator).

The precedence and associativity of C operators is given below:


Category Operator

Postfix () [] -> . ++ - -

Unary + - ! ~ ++ - - (type)* & sizeof

Multiplicative */%

Additive +-

Shift << >>

Relational < <= > >=

Equality == !=

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

Conditional ?:

Assignment = += -= *= /= %=>>= <<= &= ^= |=

Comma ,
C Programming Operators
An operator is a symbol that operates on a value or a variable. For
example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.

C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

Example 1: Arithmetic Operators


// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}
Run Code

Output

a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1

The operators + , - and * computes addition, subtraction, and multiplication


respectively as you might have expected.
In normal calculation, 9/4 = 2.25 . However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also
an integer. The compiler neglects the term after the decimal point and shows
answer 2 instead of 2.25 .

The modulo operator % computes the remainder. When a=9 is divided by b=4 ,

the remainder is 1 . The % operator can only be used with integers.


Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number


a/b = 2.5

a/d = 2.5

c/b = 2.5

// Both operands are integers

c/d = 2

C Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to change
the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the
value by 1. These two operators are unary operators, meaning they only
operate on a single operand.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

return 0;
}
Run Code

Output

++a = 11
--b = 99
++c = 11.500000
--d = 99.500000

Here, the operators ++ and -- are used as prefixes. These two operators can
also be used as postfixes like a++ and a-- . Visit this page to learn more about
how increment and decrement operators work when used as postfix.

C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b
Operator Example Same as

%= a %= b a = a%b

Example 3: Assignment Operators


// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);

return 0;
}
Run Code

Output

c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C Relational Operators

A relational operator checks the relationship between two operands. If the


relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.


Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

return 0;
}
Run Code

Output

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1

C Logical Operators

An expression containing logical operator returns either 0 or 1 depending


upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming.
Operator Meaning Example

&& Logical AND. True only if all operands If c = 5 and d = 2 then, expression ((c==5) &&
Operator Meaning Example

are true (d>5)) equals to 0.

Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c==5) ||
||
operand is true (d>5)) equals to 1.

Logical NOT. True only if the operand is


! If c = 5 then, expression !(c==5) equals to 0.
0

Example 5: Logical Operators


// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", result);

return 0;
}
Run Code

Output

(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

Explanation of logical operator program


 (a == b) && (c > 5) evaluates to 1 because both operands (a ==

b) and (c > b) is 1 (true).


 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c

< b) are 0 (false).


 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence,
!(a != b) is 1 (true).
 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is
0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes processing
faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.


Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;
The sizeof operator

The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));

return 0;
}
Run Code

Output

Size of int = 4 bytes


Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

Bitwise Operators in C
Programming
In the arithmetic-logic unit (which is within the CPU), mathematical operations
like: addition, subtraction, multiplication and division are done in bit-level. To
perform bit-level operations in C programming, bitwise operators are used.
Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise complement

Shift left

>> Shift right

Bitwise AND Operator &


The output of bitwise AND is 1 if the corresponding bits of two operands is 1.
If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
In C Programming, the bitwise AND operator is denoted by & .
Let us suppose the bitwise AND operation of two integers 12 and 25.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Example 1: Bitwise AND


#include <stdio.h>

int main() {

int a = 12, b = 25;


printf("Output = %d", a & b)
;

return 0;
}
Run Code

Output

Output = 8

Bitwise OR Operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands
is 1. In C Programming, bitwise OR operator is denoted by | .

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)
Example 2: Bitwise OR
#include <stdio.h>

int main() {

int a = 12, b = 25;


printf("Output = %d", a | b);

return 0;
}
Run Code

Output

Output = 29

Bitwise XOR (exclusive OR) Operator ^


The result of bitwise XOR operator is 1 if the corresponding bits of two
operands are opposite. It is denoted by ^ .

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
________
00010101 = 21 (In decimal)

Example 3: Bitwise XOR


#include <stdio.h>

int main() {
int a = 12, b = 25;
printf("Output = %d", a ^ b);

return 0;
}
Run Code

Output

Output = 21

Bitwise Complement Operator ~


Bitwise complement operator is a unary operator (works on only one
operand). It changes 1 to 0 and 0 to 1. It is denoted by ~ .

35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Twist in Bitwise Complement Operator in C Programming

The bitwise complement of 35 ( ~35 ) is -36 instead of 220, but why?


For any integer n , bitwise complement of n will be -(n + 1) . To understand
this, you should have the knowledge of 2's complement.
2's Complement

Two's complement is an operation on binary numbers. The 2's complement of


a number is equal to the complement of that number plus 1. For example:
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)

Note: Overflow is ignored while computing 2's complement.

The bitwise complement of 35 is 220 (in decimal). The 2's complement


of 220 is -36. Hence, the output is -36 instead of 220.
Bitwise Complement of Any Number N is -(N+1). Here's how:

bitwise complement of N = ~N (represented in 2's complement form)


2'complement of ~N= -(~(~N)+1) = -(N+1)

Example 4: Bitwise complement


#include <stdio.h>

int main() {

printf("Output = %d\n", ~35);


printf("Output = %d\n", ~-12);

return 0;
}
Run Code

Output

Output = -36
Output = 11
Shift Operators in C programming
There are two shift operators in C programming:

 Right shift operator

 Left shift operator.

Right Shift Operator

Right shift operator shifts all bits towards right by certain number of specified
bits. It is denoted by >> .

212 = 11010100 (In binary)


212 >> 2 = 00110101 (In binary) [Right shift by two bits]
212 >> 7 = 00000001 (In binary)
212 >> 8 = 00000000
212 >> 0 = 11010100 (No Shift)

Left Shift Operator

Left shift operator shifts all bits towards left by a certain number of specified
bits. The bit positions that have been vacated by the left shift operator are
filled with 0. The symbol of the left shift operator is << .

212 = 11010100 (In binary)


212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)
Example #5: Shift Operators
#include <stdio.h>

int main() {

int num=212, i;

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


printf("Right shift by %d: %d\n", i, num >> i);

}
printf("\n");

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


printf("Left shift by %d: %d\n", i, num << i);

return 0;
}
Run Code

Right Shift by 0: 212


Right Shift by 1: 106
Right Shift by 2: 53

Left Shift by 0: 212


Left Shift by 1: 424
Left Shift by 2: 848

What Are Control Statements in C?


In simple words, Control statements in C help the computer execute a certain logical
statement and decide whether to enable the control of the flow through a certain set of
statements or not. Also, it is used to direct the execution of statements under certain
conditions.

Types of Control Statements in C

The primary types of control statements in C are:

 Decision-making control statements


1. Simple if statement
2. If-else statements
3. Nested if-else statements
4. else-if ladder

 Conditional statements

 Goto statements in C

 Loop control statements in C


1. While Loop
2. Do-while Loop
3. For Loop

Decision-Making Control Statements Are:

 Simple if statement

 If-else statements

 Nested if-else statements

 else-if ladder

Now, you will go through them in detail.

 Simple if Statement

Simple if statements are carried out to perform some operation when the condition is
only true. If the condition of the if statement is true then the statements under the if
block is executed else the control is transferred to the statements outside the if block.
Syntax of the if statement is as given below:

Flow Chart:

Example:
Output:

If-else Statement

In some situations, you may have to execute statements based on true or false under
certain conditions, therefore; you use if-else statements. If the condition is true, then if
block will be executed otherwise the else block is executed.

Syntax of the if-else statement is as given below:


Flow Chart:

Example:
Output:

 Nested if-else Statements

The nested if-else statements consist of another if or else. Therefore; if the condition of
“if” is true (i.e., an outer if) then outer if’s if block is executed which contains another if
(that is inner if) and if the condition of if block is true, statements under if block will be
executed else the statements of inner if’s “else” block will be executed.

If the outer “if” condition is not true then the outer if’s “else” block is executed which
consists of another if. The outer else’s inner if the condition is true then the statement
under outer else’s inner if is executed else the outer else’s else block is executed.
Syntax of the nested if-else statement is as given below:

Flow Chart:
Example:
Output:

 Else-if Ladder Statements


The else-if ladder statements contain multiple else-if, when either of the condition is true
the statements under that particular “if” will be executed otherwise the statements under
the else block will be executed.

Suppose the “if” condition is true, statements under “if” will be executed else the other
“if” condition is tested, and if that condition is true statements under that particular “if”
will be executed. This process will repeat as long as the else-if’s are present in the
program.

Syntax of the else-if ladder statement is as given below:

Flow Chart:
Example:
Output:

So far, you have looked at the decision-making control statements in C. Now, go ahead
and take the next step and learn conditional statements in C.

Conditional Control Statements in C


As per the value of the switch expression, the switch statement will allow multi-way
branching.

Depending on the expression, the control is transferred to that particular case label and
executed the statements under it. If none of the cases are matched with the switch
expression, then the default statement is executed.

The syntax of the switch statement is as given below:

Flow Chart:
Example:
Output:

After the conditional statement, you have the goto statement in C.

Goto Statements in C

The goto statements are used to transfer the flow of control in a program, goto
statement is also known as a jump control statement because it is used to jump to the
specified part of the program. The label in goto statement is a name used to direct the
branch to a specified point in the program.

Syntax of the goto statement is as given below:


After goto statements in C, you are now heading towards the loop control statements in
C.

Loop Control Statements in C

 While Loop

A while loop is also known as an entry loop because in a while loop the condition is
tested first then the statements underbody of the while loop will be executed.

If the while loop condition is false for the first time itself then the statements under the
while loop will not be executed even once.

The syntax of the while loop is as given below:

Flow Chart:
Example:
Output:

do-while Loop

The do-while is also known as an exit loop because in the do-while loop, the statements
will be executed first and then the condition is checked.

If the condition of the while loop is true then the body of the loop will be executed again
and again until the condition is false. Once the condition is false, the control will transfer
outside the do-while loop and execute statements followed soon after the do-while loop.

The syntax of the do-while loop is as given below:

Flow Chart:
Example:
Output:

For Loop

The for loop is also known as a pre-test loop. From the following syntax, expression1 is
an initialization, expression2 is the conditional expression and expression3 is an
updation. The variables can be initialized in for the statement itself.

The syntax of the do-while loop is as given below:


In the for loop, expression1 is used to initialize the variable, expression2 is evaluated
and if the condition is true, then the body of for loop will be executed and then the
statements under expression3 will be executed. This process is repeated as long as the
for loop condition is true, once the condition is false control will return to the statements
following the for loop and execute those statements.

Flow Chart:
Example:

Output:
C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable. Here, We can define various statements in the multiple cases for the
different values of a single variable.

The syntax of switch statement in c language is given below:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Rules for switch statement in C language


1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break
statement found in the case, all the cases will be executed present after the matched
case. It is known as fall through the state of C switch statement.

Let's try to understand it by the examples. We are assuming that there are following
variables.

1. int x,y,z;
2. char a,b;
3. float f;

Valid Switch Invalid Switch Valid Case

switch(x) switch(f) case 3;

switch(x>y) switch(x+2.5) case 'a';

switch(a+b-2) case 1+2;

switch(func(x,y)) case 'x'>'y';

Flowchart of switch statement in C


Functioning of switch case statement
First, the integer expression specified in the switch statement is evaluated. This value is
then matched one by one with the constant values given in the different cases. If a
match is found, then all the statements specified in that case are executed along with
the all the cases present after that case including the default statement. No two cases
can have similar values. If the matched case contains a break statement, then all the
cases present after that will be skipped, and the control comes out of the switch.
Otherwise, all the cases following the matched case will be executed.
Let's see a simple example of c language switch statement.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

Switch case example 2


1. #include <stdio.h>
2. int main()
3. {
4. int x = 10, y = 5;
5. switch(x>y && x+y>0)
6. {
7. case 1:
8. printf("hi");
9. break;
10. case 0:
11. printf("bye");
12. break;
13. default:
14. printf(" Hello bye ");
15. }
16.
17. }

Output

hi

C Switch statement is fall-through

In C language, the switch statement is fall through; it means if you don't use a break
statement in the switch case, all the cases after the matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given
below.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }

Output

enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

C break statement
The break is a keyword in C which is used to bring the program control out of the loop.
The break statement is used inside loops or switch statement. The break statement
breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first
and then proceeds to outer loops. The break statement in C can be used in the
following two scenarios:

1. With switch case


2. With loop

Syntax:
1. //loop or switch case
2. break;
Flowchart of break in c

Example
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. int i;
6. for(i = 0; i<10; i++)
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }

Output

0 1 2 3 4 5 came outside of loop i = 5


Example of C break statement with switch case
Click here to see the example of C break with the switch statement.

C break statement with the nested loop


In such case, it breaks only the inner loop, but not outer loop.

1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on the console, 2 3 is not printed because there is a break
statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the
break statement is used to break the inner loop only.

break statement with while loop


Consider the following example to use break statement inside while loop.
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(1)
6. {
7. printf("%d ",i);
8. i++;
9. if(i == 10)
10. break;
11. }
12. printf("came out of while loop");
13. }

Output

0 1 2 3 4 5 6 7 8 9 came out of while loop

break statement with do-while loop


Consider the following example to use the break statement with a do-while loop.

1. #include<stdio.h>
2. void main ()
3. {
4. int n=2,i,choice;
5. do
6. {
7. i=1;
8. while(i<=10)
9. {
10. printf("%d X %d = %d\n",n,i,n*i);
11. i++;
12. }
13. printf("do you want to continue with the table of %d , enter any non-
zero value to continue.",n+1);
14. scanf("%d",&choice);
15. if(choice == 0)
16. {
17. break;
18. }
19. n++;
20. }while(1);
21. }

Output

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to
continue.1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to
continue.0

C continue statement
The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues with
the next iteration. It is mainly used for a condition so that we can skip some code for a particular
condition.

Syntax:
1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped

Continue statement example 1

1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(i!=10)
6. {
7. printf("%d", i);
8. continue;
9. i++;
10. }
11. }

Output

infinite loop

Continue statement example 2

1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }

Output
1
2
3
4
6
7
8
9
10

As you can see, 5 is not printed on the console because loop is continued at i==5.

C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be
used to repeat some part of the code for a particular condition. It can also be used to
break the multiple loops which can't be done by using a single break statement.
However, using goto is avoided these days since it makes the program less readable and
complecated.

Syntax:

1. label:
2. //some part of the code;
3. goto label;

goto example
Let's see a simple example to use goto statement in C language.

1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }

Output:

Enter the number whose table you want to print?10


10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

When should we use goto?


The only condition in which using goto is preferable is when we need to break the
multiple loops using a single statement at the same time. Consider the following
example.

1. #include <stdio.h>
2. int main()
3. {
4. int i, j, k;
5. for(i=0;i<10;i++)
6. {
7. for(j=0;j<5;j++)
8. {
9. for(k=0;k<3;k++)
10. {
11. printf("%d %d %d\n",i,j,k);
12. if(j == 3)
13. {
14. goto out;
15. }
16. }
17. }
18. }
19. out:
20. printf("came out of the loop");
21. }
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop

Unit – III

Arrays

C Array
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc. It also has the capability to store the
collection of derived data types, such as pointers, structure, etc. The array is the simplest data
structure where each data element can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the marks
in the different subject. Instead of that, we can define an array which can store the marks in each
subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.

Properties of Array
The array contains the following properties.

Backward Skip 10sPlay VideoForward Skip 10s

o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element
is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of C Array
We can declare an array in the c language in the following way.

1. data_type array_name[array_size];

Now, let us see the example to declare the array.

1. int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.

1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }

Output

80
60
70
85
75

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.

1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.

1. int marks[]={20,30,40,50,60};

Let's see the C program to declare and initialize the array in C.

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }

Output

20
30
40
50
60

C Array Example: Sorting an array


In the following program, we are using bubble sort method to sort the array in ascending order.

1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }

Program to print the largest and second largest element of the array.

1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays
are created to implement a relational database lookalike data structure. It provides ease of
holding the bulk of data at once which can be passed to any number of functions wherever
required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];

Consider the following example.

1. int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.

Backward Skip 10sPlay VideoForward Skip 10s

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously. However, this will not work with 2D arrays. We will have to
define at least the second dimension of the array. The two-dimensional array can be declared
and defined in the following way.

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

Two-dimensional array example in C


1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

C 2D array example: Storing elements in a matrix and printing it.


1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }

Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78

What is Character Array in C?


 A Character array is a derived data type in C that is used to store a collection of characters or
strings.
 A char data type takes 1 byte of memory, so a character array has the memory of the number of
elements in the array. (1* number_of_elements_in_array).
 Each character in a character array has an index that shows the position of the character in the
string.
 The first character will be indexed 0 and the successive characters are indexed 1,2,3 etc...
 The null character \0 is used to find the end of characters in the array and is always stored in the
index after the last character or in the last index.

Consider a string "character", it is indexed as the following image in a character array.

Syntax
There are many syntaxes for creating a character array in c. The most basic syntax is,
char name[size];

 The name depicts the name of the character array and size is the length of the character array.
 The size can be greater than the length of the string but can not be lesser. If it is lesser then the
full string can't be stored and if it is greater the remaining spaces are just left unused.

Example
Before seeing the example, let us understand the method of dynamic memory allocation which is used to
create the dynamic array.

 Dynamic memory allocation is an efficient way to allocate memory for a variable in c.


 The memory is allocated in the runtime after getting the number of characters from the user.
 It uses pointers, which are structures that point to an address where the real value of the
variable is stored.
 The malloc() function is used for dynamic memory allocation. Its syntax is,

dataType *ptr = (dataType*) malloc(size);

 The malloc function returns a void pointer which is cast (converted) to the required data type.
 The sizeof() function gives the size of data types and has the syntax,

sizeof(datatype)

 The malloc method is present in the header stdlib.h.

Now, let us see the example of how we can create a dynamic single-dimension character array by getting
input from the user.

#include<stdio.h>
#include<stdlib.h>

int main()
{
int n, i;
char *arr;

printf("Enter number of characters to store: ");


scanf("%d", &n); //getting size

arr = (char*)malloc(n*sizeof(char));
printf("Enter the string: ");
for(i=0; i < n; i++)
{
scanf(" %c",arr+i);
}
printf("\nThe string entered is: \n\n");

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


{
printf("%c ", arr[i]);
}
printf("\The elements at index 2: %c ",arr[2]);
return 0;
}

Output:

Enter the number of characters to store: 9


Enter the string: character
The string entered is:

c h a r a c t e r
The elements at index 2: a

C Programming Strings
In C programming, a string is a sequence of characters terminated with a null character \0 . For
example:

char c[] = "c string";

When the compiler encounters a sequence of characters enclosed in the double quotation marks, it
appends a null character \0 at the end by default.

Memory Diagram

How to declare a string?


Here's how you can declare strings:

char s[5];

String Declaration in C

Here, we have declared a string of 5 characters.


How to initialize strings?
You can initialize strings in a number of ways.

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};

String Initialization in C

Let's take another example:

char c[5] = "abcde";

Here, we are trying to assign 6 characters (the last character is '\0' ) to a char array having 5
characters. This is bad and you should never do this.

Assigning Values to Strings


Arrays and strings are second-class citizens in C; they do not support the assignment operator once
it is declared. For example,

char c[100];
c = "C programming"; // Error! array type is not assignable.

Note: Use the strcpy() function to copy the string instead.

Read String from the user


You can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it encounters whitespace (space,
newline, tab, etc.).

Example 1: scanf() to read a string

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output

Enter name: Dennis Ritchie


Your name is Dennis.

Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in
the name string. It's because there was a space after Dennis .

Also notice that we have used the code name instead of &name with scanf() .

scanf("%s", name);

This is because name is a char array, and we know that array names decay to pointers in C.
Thus, the name in scanf() already points to the address of the first element in the string, which is why
we don't need to use & .

How to read a line of text?

You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

Example 2: fgets() and puts()

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}

Output

Enter name: Tom Hanks


Name: Tom Hanks

Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string

The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the
size of the name string.
To print the string, we have used puts(name); .

Note: The gets() function can also be to take input from the user. However, it is removed from the C
standard.

It's because gets() allows you to input any length of characters. Hence, there might be a buffer
overflow.

Passing Strings to Functions


Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to a
function.

Example 3: Passing string to a Function

#include <stdio.h>
void displayString(char str[]);

int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}

Strings and Pointers


Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to
manipulate elements of the string. We recommended you to check C Arrays and Pointers before you
check this example.

Example 4: Strings and Pointers

#include <stdio.h>

int main(void) {
char name[] = "Harry Potter";

printf("%c", *name); // Output: H


printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o

char *namePtr;

namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}
Commonly Used String Functions

 strlen() - calculates the length of a string


 strcpy() - copies a string to another
 strcmp() - compares two strings
 strcat() - concatenates two strings

String Manipulations In C Programming Using


Library Functions
You need to often manipulate strings according to the need of a problem. Most, if not all, of the time
string manipulation can be done manually but, this makes programming complex and large.
To solve this, C supports a large number of string handling functions in the standard
library "string.h" .

Few commonly used string handling functions are discussed below:

Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase

Strings handling functions are defined under "string.h" header file.

#include <string.h>

Note: You have to include the code below to run string handling functions.
gets() and puts()

Functions gets() and puts() are two string functions to take string input from the user and display it
respectively as mentioned in the previous chapter.
#include<stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

Note: Though, gets() and puts() function handle strings, both these functions are defined
in "stdio.h" header file.

Calculate Length of String without Using strlen() Function


#include <stdio.h>
int main() {
char s[] = "Programming is fun";
int i;

for (i = 0; s[i] != '\0'; ++i);

printf("Length of the string: %d", i);


return 0;
}

Output

Length of the string: 18

Here, using a for loop, we have iterated over characters of the string from i = 0 to
until '\0' (null character) is encountered. In each iteration, the value of i is increased
by 1.
When the loop ends, the length of the string will be stored in the i variable.

Note: Here, the array s[] has 19 elements. The last element s[18] is the null
character '\0'. But our loop does not count this character as it terminates upon
encountering it.
Concatenate Two Strings Without Using strcat()
#include <stdio.h>
int main() {
char s1[100] = "programming ", s2[] = "is awesome";
int length, j;

// store length of s1 in the length variable


length = 0;
while (s1[length] != '\0') {
++length;
}

// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length) {
s1[length] = s2[j];
}

// terminating the s1 string


s1[length] = '\0';

printf("After concatenation: ");


puts(s1);

return 0;
}

Output

After concatenation: programming is awesome

Here, two strings s1 and s2 and concatenated and the result is stored in s1.
It's important to note that the length of s1 should be sufficient to hold the string after
concatenation. If not, you may get unexpected output.

Unit – IV

Linear Search in C
Linear search in C is a searching method/algorithm. In the linear search algorithm, we traverse through the data structure from any
one point and traverse until the data item is found in the data structure.
These data structures could be array, string, Linked-List, Stack, Queue, or any other data structure.

Linear Search Example:


Find the number 34 in the given data structure Array.

Array:

24 56 -1 90 4 12 34 89 37

0 1 2 3 4 5 6 7 8
Solution:

Index Number Working

0 24 24 != 34 * We will continue our search

1 56 56 != 34 *We will continue our search

2 -1 -1 != 34 => We will continue our search

3 90 90 != 34 => We will continue our search

4 4 4 != 34 => We will continue our search

5 12 12 != 34 => We will continue our search

6 34 34 == 34 => As a result, we have ended our search

7 89

8 37
Because 6 is the index of our element (34), our answer is 6 for 0-based indexing arrays and 7 for 1-based indexing arrays. This is how
linear search works in an array.

Problem Description
Write a C Program which finds the position of an element in an array using Linear Search Algorithm. We have
to take an array and a value to be searched in the array as input from the user, and then find the position of that
element in array by using linear search algorithm.

Problem Solution
1. We will create an array of numbers by taking input from user. We will also read the element to be searched
by the user.
2. In order to look for that element in the array, we’ll go sequentially in increasing index values. If we
encounter the element requested by the user we will return the position of that element in array, but if it is not
there we will return -1 which indicates the absence of element which was searched.

Linear Search Algorithm:


Input: An array A[1..n] of n elements and an element x to be found and output its position.
Output:
J if x = A[j], 1 ≤ j ≤ n, and 0 otherwise.
J := 1
while J<n && A[J] ≠ x
j := j+1
end while
if A[J] = x then return J Else return 0
There are several ways to implement Linear Search in C language. Let’s take a detailed look at all the
approaches to implement Linear Search algorithm.

Program/Source Code
Here is source code of the C Program to find the position of an element requested by the user using Linear
Search Algorithm. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on
Windows 10. The program output is also shown below.

1. /*
2. * C program to input N numbers and store them in an array.
3. * Do a linear search for a given key and report success or failure.
4. */
5.
6. #include <stdio.h>
7.
8. void main()
9. { int num;
10.
11. int i, keynum, found = 0;
12.
13. printf("Enter the number of elements ");
14. scanf("%d", &num);
15. int array[num];
16. printf("Enter the elements one by one \n");
17. for (i = 0; i < num; i++)
18. {
19. scanf("%d", &array[i]);
20. }
21.
22. printf("Enter the element to be searched ");
23. scanf("%d", &keynum);
24.
25. /* Linear search begins */
26. for (i = 0; i < num ; i++)
27. {
28. if (keynum == array[i] )
29. {
30. found = 1;
31. break;
32. }
33. }
34. if (found == 1)
35. printf("Element is present in the array at position
%d",i+1);
36. else
37. printf("Element is not present in the array\n");
38. }

Program Explanation
1. In Linear search, we search an element or value in a given array by traversing the array from the starting, till
the desired element or value is found.
2. The array is searched sequentially and the position is returned if the key element to be searched is available
in the array, otherwise -1 is returned.
3. Here in this C Program we have not made any function specifically for linear search, rather we can look for
presence of element in an array in the main function itself.
4. We traverse the array from the 0th index in increasing order of index, if we find the element we break the
loop there itself and print the position of the element in the array, but if the element requested is not there in
array, we simply print that “Element is not present in the array”.
5. If we’d have created a separate function for linear search and the element could not be found in the array, we
would have returned -1 in that case denoting absence of the element.
Time Complexity:
Average & Worst Case: O(n)
As the name suggests it is a linear search and we used a loop to iterate over the array from start to end, hence
we can affirm that it is of O(n) complexity.
Best Case: O(1)
The best-case complexity will be found if you find the element at the first index from the start *(according to
the approach we used). It can be denoted as O(1)
Space Complexity: O(n + k)
space complexity of the linear search algorithm is O(n + k), where n = size of the array and k = auxiliary
variables.

Binary Search
Binary Search is a searching algorithm for finding an element's position in a sorted array.

In this approach, the element is always searched in the middle of a portion of an array.

Binary search can be implemented only on a sorted list of items. If the elements are not sorted
already, we need to sort them first.

Binary Search Working


Binary Search Algorithm can be implemented in two ways which are discussed below.

1. Iterative Method

2. Recursive Method

The recursive method follows the divide and conquer approach.


The general steps for both methods are discussed below.
1. The array in which searching is to be performed

is: Initial array


Let x = 4 be the element to be searched.
2. Set two pointers low and high at the lowest and the highest positions

respectively. Setting pointers

3. Find the middle element mid of the array ie. arr[(low + high)/2] =

6. Mid element
4. If x == mid, then return mid.Else, compare the element to be searched with m.

5. If x > mid , compare x with the middle element of the elements on the right side of mid . This is
done by setting low to low = mid + 1 .

6. Else, compare x with the middle element of the elements on the left side of mid . This is done

by setting high to high = mid - 1 .

Finding mid element


7. Repeat steps 3 to 6 until low meets high. Mid element

8. x = 4 is found. Found

Binary Search Algorithm


Iteration Method

do until the pointers low and high meet each other.

mid = (low + high)/2

if (x == arr[mid])

return mid

else if (x > arr[mid]) // x is on the right side

low = mid + 1

else // x is on the left side

high = mid - 1

Recursive Method

binarySearch(arr, x, low, high)

if low > high

return False
else

mid = (low + high) / 2

if x == arr[mid]

return mid

else if x > arr[mid] // x is on the right side

return binarySearch(arr, x, mid + 1, high)

else // x is on the left side

return binarySearch(arr, x, low, mid - 1)

This C program implements Binary search with window.


Here is the source code of the C program Implement a binary search algorithm such that search starts from the
pth element and searches subsequently with a jump of 2^i i.e. p+1,p+2,p+4,p+8,…and continues until the
correct window for the key is obtained. Now binary search is implemented in this window.. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.

1. /*
2. * C program to implement Binary search with window
3. */
4. #include <stdio.h>
5. #include <conio.h>
6.
7. /* Function for Binary search */
8. void binary_search(int array[], int first, int last, int n)
9. {
10. int i ,middle;
11. middle = (first + last) / 2;
12.
13. while (first <= last) {
14. if (array[middle] < n)
15. first = middle + 1;
16. else if (array[middle] == n) {
17. printf("%d found at location %d.\n", n, middle+1);
18. break;
19. }
20. else
21. last = middle - 1;
22.
23. middle = (first + last) / 2;
24. }
25. if ( first > last )
26. printf("Not found! %d is not present in the list.\n", n);
27. }
28. /* End of binary_search() */
29.
30. /* Function to search for the window */
31. search(int arr[], int size, int data)
32. {
33. int p = (size - 1) / 2, low, high, a1 = 0, a2 = 1, i = 1;
34. low = p + a1;
35. high = p + a2;
36. while(i)
37. {
38. if(data >= arr[low] && data <= arr[high])
39. {
40. binary_search(arr, low, high, data);
41. break;
42. }
43. else if(data < arr[low])
44. {
45. binary_search(arr, 0, low, data);
46. break;
47. }
48. else
49. {
50. a2 = a2 * 2;
51. low = high;
52. high = p + a2;
53. }
54. }
55. }
56. /* End of search() */
57.
58. /* The main() begins */
59. int main()
60.
61. {
62. int a[200], i, j, n, size;
63. printf("Enter the size of the list:");
64. scanf("%d", &size);
65. printf("Enter %d Integers in ascending order\n", size);
66. for (i = 0; i < size; i++)
67. scanf("%d", &a[i]);
68. printf("Enter value to find\n");
69. scanf("%d", &n);
70. search(a, size, n );
71. return 0;
72. }

Enter the size of the list:10


Enter 10 Integers in ascending order
1 2 3 4 5 6 7 8 9 10
Enter value to find
7
7 found at location 7.

Bubble sort program in C


Bubble sort is a simple and intuitive sorting algorithm. It repeatedly swaps adjacent elements if
they are in the wrong order until the array is sorted. In this algorithm, the largest element
"bubbles up" to the end of the array in each iteration. Bubble sort is inefficient for large data
sets, but it is useful for educational purposes and small data sets. In this article, we will
implement the bubble sort algorithm in C programming language.
The first step is to define the bubble sort function. This function takes an integer array and the
size of the array as its parameters. The function returns nothing as it modifies the original array.
Here is the function definition:

1. void bubble_sort(int arr[], int n) {


2. int i, j;
3. for (i = 0; i < n - 1; i++) {
4. for (j = 0; j < n - i - 1; j++) {
5. if (arr[j] > arr[j + 1]) {
6. int temp = arr[j];
7. arr[j] = arr[j + 1];
8. arr[j + 1] = temp;
9. }
10. }
11. }
12. }

The function has two loops. The outer loop runs from the first element to the second-last
element of the array. The inner loop runs from the first element to the second-last element of
the unsorted part of the array. The condition of the inner loop is n - i - 1 because the last i
elements of the array are already sorted.

In each iteration of the inner loop, we compare adjacent elements. If the left element is greater
than the right element, we swap them. After the inner loop completes, the largest element is
guaranteed to be at the end of the unsorted part of the array.

Now, we can write the main function to test our bubble sort implementation. Here is the main
function along with the previous part:

C Program:

Program/Source Code
Here is the source code of the C program to sort integers using Bubble Sort technique. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.

1. /*
2. * C Program to sort an array using Bubble Sort technique
3. */
4.
5. #include <stdio.h>
6. void bubblesort(int arr[], int size)
7. {
8. int i, j;
9. for (i = 0; i < size; i++)
10. {
11. for (j = 0; j < size - i; j++)
12. {
13. if (arr[j] > arr[j+1])
14. swap(&arr[j], &arr[j+1]);
15.
16. }
17. }
18. }
19. void swap(int *a, int *b)
20. {
21. int temp;
22. temp = *a;
23. *a = *b;
24. *b = temp;
25. }
26. int main()
27. {
28. int array[100], i, size;
29. printf("How many numbers you want to sort: ");
30. scanf("%d", &size);
31. printf("\nEnter %d numbers : ", size);
32. for (i = 0; i < size; i++)
33. scanf("%d", &array[i]);
34. bubblesort(array, size);
35. printf("\nSorted array is ");
36.
37. for (i = 0; i < size; i++)
38. printf(" %d ", array[i]);
39. return 0;
40. }
Time Complexity: O(n2)
In the worst case, it should have to swap the n elements if the array is reverse sorted. The size of the list is n.
Space Complexity: O(1)
There is no need to use an extra space that depends on the size of the array. Hence the space completixty of
bubble sort program is constant.

Characteristics:
o Bubble sort is a simple sorting algorithm.
o It works by repeatedly swapping adjacent elements if they are in the wrong order.
o The algorithm sorts the array in ascending or descending order.
2
o It has a time complexity of O(n ) in the worst case, where n is the size of the array.

Usage:
o Bubble sort is useful for educational purposes and small data sets.
o It is not suitable for large data sets because of its time complexity.

Advantages:
o Bubble sort is easy to understand and implement.
o It requires minimal additional memory space to perform the sorting.

Disadvantages:
o It is not efficient for large data sets because of its time complexity.
o It has poor performance compared to other sorting algorithms, such as quicksort and mergesort.

Conclusion:
Bubble sort is a simple and intuitive sorting algorithm that is useful for educational purposes and small data sets.
However, its time complexity makes it inefficient for large data sets. Therefore, it is not commonly used in real-world
applications. Other sorting algorithms, such as quicksort and mergesort, are more efficient for large data sets.

Selection Sort Algorithm


In this article, we will discuss the Selection sort Algorithm. The working procedure of selection
sort is also simple. This article will be very helpful and interesting to students as they might face
selection sort as a question in their examinations. So, it is important to discuss the topic.

In selection sort, the smallest value among the unsorted elements of the array is selected in
every pass and inserted to its appropriate position into the array. It is also the simplest
algorithm. It is an in-place comparison sorting algorithm. In this algorithm, the array is divided
into two parts, first is sorted part, and another one is the unsorted part. Initially, the sorted part
of the array is empty, and unsorted part is the given array. Sorted part is placed at the left, while
the unsorted part is placed at the right.

In selection sort, the first smallest element is selected from the unsorted array and placed at the
first position. After that second smallest element is selected and placed in the second position.
The process continues until the array is entirely sorted.

The average and worst-case complexity of selection sort is O(n2), where n is the number of
items. Due to this, it is not suitable for large data sets.

PauseNext

Unmute

Current Time 0:32

Duration 18:10
Loaded: 8.81%

Fullscreen

Selection sort is generally used when -

o A small array is to be sorted


o Swapping cost doesn't matter
o It is compulsory to check all elements

Now, let's see the algorithm of selection sort.

Algorithm
1. SELECTION SORT(arr, n)
2.
3. Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
4. Step 2: CALL SMALLEST(arr, i, n, pos)
5. Step 3: SWAP arr[i] with arr[pos]
6. [END OF LOOP]
7. Step 4: EXIT
8.
9. SMALLEST (arr, i, n, pos)
10. Step 1: [INITIALIZE] SET SMALL = arr[i]
11. Step 2: [INITIALIZE] SET pos = i
12. Step 3: Repeat for j = i+1 to n
13. if (SMALL > arr[j])
14. SET SMALL = arr[j]
15. SET pos = j
16. [END OF if]
17. [END OF LOOP]
18. Step 4: RETURN pos

Working of Selection sort Algorithm


Now, let's see the working of the Selection sort Algorithm.
To understand the working of the Selection sort algorithm, let's take an unsorted array. It will be
easier to understand the Selection sort via an example.

Let the elements of array are -

Now, for the first position in the sorted array, the entire array is to be scanned sequentially.

At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is
the smallest value.

So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.

For the second position, where 29 is stored presently, we again sequentially scan the rest of the
items of unsorted array. After scanning, we find that 12 is the second lowest element in the array
that should be appeared at second position.

Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the
sorted array. So, after two iterations, the two smallest values are placed at the beginning in a
sorted way.

The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.
Now, the array is completely sorted.

Selection sort complexity


Now, let's see the time complexity of selection sort in best case, average case, and in worst case.
We will also see the space complexity of the selection sort.

1. Time Complexity
Case Time Complexity

Best Case O(n2)

Average Case O(n2)

Worst Case O(n2)

o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is
already sorted. The best-case time complexity of selection sort is O(n2).
o Average Case Complexity - It occurs when the array elements are in jumbled order that
is not properly ascending and not properly descending. The average case time
complexity of selection sort is O(n2).
o Worst Case Complexity - It occurs when the array elements are required to be sorted in
reverse order. That means suppose you have to sort the array elements in ascending
order, but its elements are in descending order. The worst-case time complexity of
selection sort is O(n2).

2. Space Complexity
Space Complexity O(1)

Stable YES

o The space complexity of selection sort is O(1). It is because, in selection sort, an extra
variable is required for swapping.

Implementation of selection sort


Now, let's see the programs of selection sort in different programming languages.

Program: Write a program to implement selection sort in C language.

Here is source code of the C program to implement selection sort method using functions. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.

1. /*
2. * C program for SELECTION sort which uses following functions
3. * a) To find maximum of elements
4. * b) To swap two elements
5. */
6. #include <stdio.h>
7.
8. int findmax(int b[10], int k);
9. void exchang(int b[10], int k);
10. void main()
11. {
12. int array[10];
13. int i, j, n, temp;
14.
15. printf("Enter the value of n \n");
16. scanf("%d", &n);
17. printf("Enter the elements one by one \n");
18. for (i = 0; i < n; i++)
19. {
20. scanf("%d", &array[i]);
21. }
22. printf("Input array elements \n");
23. for (i = 0; i < n ; i++)
24. {
25. printf("%d\n", array[i]);
26. }
27. /* Selection sorting begins */
28. exchang(array, n);
29. printf("Sorted array is...\n");
30. for (i = 0; i < n; i++)
31. {
32. printf("%d\n", array[i]);
33. }
34. }
35. /* function to find the maximum value */
36. int findmax(int b[10], int k)
37. {
38. int max = 0, j;
39. for (j = 1; j <= k; j++)
40. {
41. if (b[j] > b[max])
42. {
43. max = j;
44. }
45. }
46. return(max);
47. }
48. void exchang(int b[10], int k)
49. {
50. int temp, big, j;
51. for (j = k - 1; j >= 1; j--)
52. {
53. big = findmax(b, j);
54. temp = b[big];
55. b[big] = b[j];
56. b[j] = temp;
57. }
58. return;
59. }

Insertion Sort Algorithm


Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each
iteration.
Insertion sort works similarly as we sort cards in our hand in a card game.

We assume that the first card is already sorted then, we select an unsorted card. If the unsorted card
is greater than the card in hand, it is placed on the right otherwise, to the left. In the same way, other
unsorted cards are taken and put in their right place.

A similar approach is used by insertion sort.


Working of Insertion Sort
Suppose we need to sort the following array.

Initial array

1. The first element in the array is assumed to be sorted. Take the second element and store it
separately in key .

Compare key with the first element. If the first element is greater than key , then key is placed in front

of the first element.


2. If the first element is greater than key, then key is placed in front of the first element.
3. Now, the first two elements are sorted.

Take the third element and compare it with the elements on the left of it. Placed it just behind the
element smaller than it. If there is no element smaller than it, then place it at the beginning of the

array. Place 1 at the beginning


4. Similarly, place every unsorted element at its correct

position. Place 4 behind


1 Place 3 behind 1 and the array is
sorted

Insertion Sort Algorithm

insertionSort(array)
mark first element as sorted
for each unsorted element X
'extract' the element X
for j <- lastSortedIndex down to 0
if current element j > X
move sorted element to the right by 1
break loop and insert X here
end insertionSort

Insertion Sort in C
// Insertion sort in C
#include <stdio.h>

// Function to print an array


void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}

void insertionSort(int array[], int size) {


for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;

// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}

// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
}

Insertion Sort Complexity


Time Complexity

Best O(n)

Worst O(n2)

Average O(n2)
Space Complexity O(1)

Stability Yes

C Program to find the roots of quadratic equation


Quadratic equations are the polynomial equation with degree 2. It is represented as ax2 + bx +c
= 0, where a, b and c are the coefficient variable of the equation. The universal rule of quadratic
equation defines that the value of 'a' cannot be zero, and the value of x is used to find the roots
of the quadratic equation (a, b). A quadratic equation's roots are defined in three ways: real and
distinct, real and equal, and real and imaginary.

Nature of the roots


The nature of the roots depends on the Discriminant (D) where D is.

1. If D > 0, the roots are real and distinct (unequal)


2. If D = 0, the roots are real and equal.
3. If D < 0, the roots are real and imaginary.

Steps to find the square roots of the quadratic equation


1. Initialize all the variables used in the quadratic equation.
2. Take inputs of all coefficient variables x, y and z from the user.
3. And then, find the discriminant of the quadratic equation using the formula:
Discriminant = (y * y) - (4 * x *z).
4. Calculate the roots based on the nature of the discriminant of the quadratic equation.
5. If discriminant > 0, then
Root1 = (-y + sqrt(det)) / (2 * x)
Root2 = (-y + sqrt(det)) / (2 * x)
Print the roots are real and distinct.
6. Else if (discriminant = 0) then,
Root1 = Root2 = -y / (2 * x).
Print both roots are real and equal.
7. Else (discriminant < 0), the roots are distinct complex where,
Real part of the root is: Root1 = Root2 = -y / (2 * x) or real = -y / (2 * x).
Imaginary part of the root is: sqrt( -discriminant) / (2 * x).
Print both roots are imaginary, where first root is (r + i) img and second root is (r -
i) img.
8. Exit or terminate the program.

Pseudo Code of the Quadratic Equation


1. Start
2. Input the coefficient variable, x, y and z.
3. D <- sqrt (y * y - 4 * x * z).
4. R1 <- (-y + D) / ( 2 * x).
5. R2 <- (-y - D) / (2 * x).
6. Print the roots R1 and R2.
7. Stop

Let's implements the above steps in a C program to find the roots of the quadratic equation.

1. /* C Program to Find the Roots of the Quadratic Equation */


2. #include<stdio.h>
3. #include<math.h> // it is used for math calculation
4. #include<conio.h>
5. void main()
6. {
7. float x, y, z, det, root1, root2, real, img;
8. printf("\n Enter the value of coefficient x, y and z: \n ");
9. scanf("%f %f %f", &x, &y, &z);
10. // define the quadratic formula of the nature of the root
11. det = y * y - 4 * x * z;
12. // defines the conditions for real and different roots of the quadratic equation
13. if (det > 0)
14. {
15. root1 = (-y + sqrt(det)) / (2 * x);
16. root2 = (-y + sqrt(det)) / (2 * x);
17. printf("\n Value of root1 = %.2f and value of root2 = %.2f", root1, root2);
18. }
19. // elseif condition defines both roots ( real and equal root) are equal in the quadratic e
quation
20. else if (det == 0)
21. {
22. root1 = root2 = -y / (2 * x); // both roots are equal;
23. printf("\n Value of root1 = %.2f and Value of root2 = %.2f", root1, root2);
24. }
25. // if det < 0, means both roots are real and imaginary in the quadratic equation.
26. else {
27. real = -y / (2 * x);
28. img = sqrt(-det) / (2 * x);
29. printf("\n value of root1 = %.2f + %.2fi and value of root2 = %.2f -
%.2fi ", real, img, real, img);
30. }
31. getch();
32. }

Output:
Unit – 5

C Functions
In c, we can divide a large program into the basic building blocks known as function. The function contains the set of
programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity
to the C program. In other words, we can say that the collection of functions creates a program. The function is also
known as procedureor subroutinein other programming languages.

Advantage of functions in C
There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Function Aspects
There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the compiler about the
function name, function parameters, and return type.

o Function call Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is declared in the
function declaration.

o Function definition It contains the actual statements which are to be executed. It is the most important
aspect to which the control comes when the function is called. Here, we must notice that only one value can
be returned from the function.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)


3 Function definition return_type function_name (argument list) {function body;}

The syntax of creating function in c language is given below:

1. return_type function_name(data_type parameter...){


2. //code to be executed
3. }

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(),
puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so that he/she can use it
many times. It reduces the complexity of a big program and optimizes the code.

Return Value
A C function may or may not return a value from the function. If you don't have to return any value from the function,
use void for the return type.

Let's see a simple example of C function that doesn't return any value from the function.

Example without return value:

1. void hello(){
2. printf("hello c");
3. }

If you want to return any value from the function, you need to use any data type such as int, long, char, etc. The return
type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

1. int get(){
2. return 10;
3. }

In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-point
value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.

1. float get(){
2. return 10.2;
3. }

Now, you need to call the function, to get the value of the function.

Different aspects of function calling


A function may or may not accept any argument. It may or may not return any value. Based on these facts, There are
four different aspects of function calls.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value

Example 1

1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("Javatpoint");
11. }

Output

Hello Javatpoint

Example 2

1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value

Example 1

1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the area of the square

1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }

Output

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000

Example for Function with argument and without return value

Example 1

1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers.

1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000
Example for Function with argument and with return value

Example 1

1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }

Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place called the library. Such
functions are used to perform some specific operations. For example, printf is a library function used to print on the
console. The library functions are created by the designers of compilers. All C standard library functions are defined
inside the different header files saved with the extension .h. We need to include these header files in our program to
make use of the library functions defined in such header files. For example, To use the library functions such as
printf/scanf we need to include stdio.h in our program which is a header file that contains all the library functions
regarding standard input/output.

The list of mostly used header files is given in the following table.

SN Header Description
file

1 stdio.h This is a standard input/output header file. It contains all the library functions regarding standard
input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(), puts(),etc.

4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header file.

10 setjmp.h This file contains all the jump functions.

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.
Let's understand call by value and call by reference in c language one by one.

Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:

1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }

Output

Before function call x=100


Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables

1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the valu
e of a and b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual par
ameters do not change by changing the formal parameters in call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters,
a = 20, b = 10
18. }

Output

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C
o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored
at the address of the actual parameters, and the modified value gets stored at the same
address.

Consider the following example for the call by reference.

1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }

Output

Before function call x=100


Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Call by reference Example: Swapping the values of the two variables

1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the valu
e of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual p
arameters do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal paramete
rs, a = 20, b = 10
18. }

Output

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c


No. Call by value Call by reference

1 A copy of the value is passed into the function An address of value is passed into the function

2 Changes made inside the function is limited to the Changes made inside the function validate out
function only. The values of the actual parameters do the function also. The values of the actual para
not change by changing the formal parameters. do change by changing the formal parameters.

3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location memory location

Passing Array to Function in C


In C, there are various general problems which requires passing more than one variable of the
same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters
from the main function. Here, instead of declaring 10 different numbers and then passing into
the function, we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of values.

As we know that the array_name contains the address of the first element. Here, we must notice
that we need to pass only the name of the array in the function which is intended to accept an
array. The array defined as the formal parameter will automatically refer to the array specified by
the array name defined as an actual parameter.

Consider the following syntax to pass an array to the function.

1. functionname(arrayname);//passing array

Methods to declare a function that receives an array as an argument


There are 3 ways to declare the function which is intended to receive an array as an argument.

PlayNext

Unmute

Current Time 0:04

/
Duration 18:10

Loaded: 3.67%

Fullscreen

First way:

1. return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.

Second way:

1. return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].

Third way:

1. return_type function(type *arrayname)

You can also use the concept of a pointer. In pointer chapter, we will learn about it.

ADVERTISING

C language passing an array to function example


1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d \n",min);
19. return 0;
20. }

Output

minimum number is 3

C function to sort the array


1. #include<stdio.h>
2. void Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. Bubble_Sort(arr);
7. }
8. void Bubble_Sort(int a[]) //array a[] points to arr.
9. {
10. int i, j,temp;
11. for(i = 0; i<10; i++)
12. {
13. for(j = i+1; j<10; j++)
14. {
15. if(a[j] < a[i])
16. {
17. temp = a[i];
18. a[i] = a[j];
19. a[j] = temp;
20. }
21. }
22. }
23. printf("Printing Sorted Element List ...\n");
24. for(i = 0; i<10; i++)
25. {
26. printf("%d\n",a[i]);
27. }
28. }

Output

Printing Sorted Element List ...


7
9
10
12
23
23
34
44
78
101

Returning array from the function


As we know that, a function can not return more than one value. However, if we try to write the
return statement as return a, b, c; to return three values (a,b,c), the function will return the last
mentioned value which is c in our case. In some problems, we may need to return multiple
values from a function. In such cases, an array is returned from the function.

Returning an array is similar to passing the array into the function. The name of the array is
returned from the function. To make a function returning an array, the following syntax is used.

1. int * Function_name() {
2. //some statements;
3. return array_type;
4. }

To store the array returned from the function, we can define a pointer which points to that array.
We can traverse the array by increasing that pointer since pointer initially points to the base
address of the array. Consider the following example that contains a function returning the
sorted array.

1. #include<stdio.h>
2. int* Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. int *p = Bubble_Sort(arr), i;
7. printf("printing sorted elements ...\n");
8. for(i=0;i<10;i++)
9. {
10. printf("%d\n",*(p+i));
11. }
12. }
13. int* Bubble_Sort(int a[]) //array a[] points to arr.
14. {
15. int i, j,temp;
16. for(i = 0; i<10; i++)
17. {
18. for(j = i+1; j<10; j++)
19. {
20. if(a[j] < a[i])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. return a;
29. }

Output

Printing Sorted Element List ...


7
9
10
12
23
23
34
44
78
101
Unit – 6

Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller
problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls.
Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition of
recursion. Recursion code is shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of
similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any problem that
can be solved recursively, can also be solved iteratively. However, some problems are best suited to be solved by the
recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

PlayNext
Unmute

Current Time 0:02

Duration 18:10
Loaded: 3.30%
Â
Fullscreen

1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }

Output

Enter the number whose factorial you want to calculate?5


factorial = 120

Fibonacci Series in C
Fibonacci Series in C: In case of fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1,
2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series are 0 and 1.

There are two ways to write the fibonacci series program:

o Fibonacci Series without recursion


o Fibonacci Series using recursion

Fibonacci Series in C without recursion

Let's see the fibonacci series program in c without recursion.

1. #include<stdio.h>
2. int main()
3. {
4. int n1=0,n2=1,n3,i,number;
5. printf("Enter the number of elements:");
6. scanf("%d",&number);
7. printf("\n%d %d",n1,n2);//printing 0 and 1
8. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
9. {
10. n3=n1+n2;
11. printf(" %d",n3);
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }

Output:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Fibonacci Series using recursion in C

Let's see the fibonacci series program in c using recursion.

1. #include<stdio.h>
2. void printFibonacci(int n){
3. static int n1=0,n2=1,n3;
4. if(n>0){
5. n3 = n1 + n2;
6. n1 = n2;
7. n2 = n3;
8. printf("%d ",n3);
9. printFibonacci(n-1);
10. }
11. }
12. int main(){
13. int n;
14. printf("Enter the number of elements: ");
15. scanf("%d",&n);
16. printf("Fibonacci Series: ");
17. printf("%d %d ",0,1);
18. printFibonacci(n-2);//n-2 because 2 numbers are already printed
19. return 0;
20. }

Output:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Quick Sort in C
Quick sort is a commonly used sorting algorithm that is often preferred over other sorting algorithms due to its
efficiency and effectiveness. It proceeds by splitting an array into two parts, one with elements smaller than a selected
pivot element and the other with elements bigger than the pivot. The algorithm then applies this procedure
recursively to each partition until the complete array is sorted.
Quick sort can be used in any scenario where sorting is required, such as in database applications, scientific
computing, and web applications. It is frequently utilized when a large dataset must be rapidly and effectively sorted.
Some specific use cases where quick sort is commonly used include:

o Sorting arrays in programming languages such as C, Java, and Python.


o Sorting database records in database management systems.
o Sorting large datasets in scientific computing, such as in numerical simulations and data analysis.
o Sorting search results in web applications and e-commerce platforms.

Overall, quick sort is a versatile and widely used algorithm that can be applied in a variety of domains where sorting is
required. Its low average-case time complexity and simplicity of execution make it an appealing choice for efficiently
sorting large datasets.

Here is a C code of quick sort:

C Programming Language:
1. #include <stdio.h>
2.
3. // Function to swap two elements
4. void swap(int* a, int* b) {
5. int t = *a;
6. *a = *b;
7. *b = t;
8. }
9. int partition(int arr[], int low, int high) {
10. int pivot = arr[high];
11. int i = (low - 1);
12.
13. for (int j = low; j <= high - 1; j++) {
14. if (arr[j] < pivot) {
15. i++;
16. swap(&arr[i], &arr[j]);
17. }
18. }
19. swap(&arr[i + 1], &arr[high]);
20. return (i + 1);
21. }
22. void quickSort(int arr[], int low, int high) {
23. if (low < high) {
24. int pi = partition(arr, low, high);
25. quickSort(arr, low, pi - 1);
26. quickSort(arr, pi + 1, high);
27. }
28. }
29.
30. // Function to print the array
31. void printArray(int arr[], int size) {
32. int i;
33. for (i = 0; i < size; i++)
34. printf("%d ", arr[i]);
35. printf("\n");
36. }
37.
38. int main() {
39. int arr[] = { 12, 17, 6, 25, 1, 5 };
40. int n = sizeof(arr) / sizeof(arr[0]);
41. quickSort(arr, 0, n - 1);
42. printf("Sorted array: \n");
43. printArray(arr, n);
44. return 0;
45. }

Output

Sorted array:
1 5 6 12 17 25
o The quick_sort function takes an array arr, and the indices of the first and last elements of the subarray to be
sorted, low and high. If low is less than high, the function selects a pivot element using the partition function,
and recursively applies the quick_sort function to the two subarrays to the left and right of the pivot.
o The partition function takes the same arguments as quick_sort, and returns the index of the pivot element
after partitioning the subarray. It begins by selecting the pivot as the last element of the subarray, and
initializes an index i to the left of the subarray. It then iterates through the subarray, swapping any element
less than the pivot with the element at arr[i] and incrementing i. The centre is then switched for the element
at arr[i+1] before returning i+1.
o The swap method changes the values of two pointers to integers.
o To use this implementation of quick sort, you can simply call quick_sort(arr, 0, n-1), where arr is the array to
be sorted and n is its length.
o Take note that the pivot in this implementation is the final member of the subarray. This is a simple and
commonly used method, but it can lead to poor performance in certain cases, such as when the array is
already sorted or nearly sorted. In these situations, efficiency can be enhanced by utilising more
sophisticated pivot selection techniques. Additionally, this implementation uses recursion, which can be a
source of performance overhead in certain cases. Iterative implementations of quick sort are also possible.

Characteristics:
o Quick sort divides an array into two sections according to a pivot element, usually the last element in the
array.
o All elements smaller than the pivot are put in one partition, and all elements larger than the pivot are placed
in the other, dividing the array into two partitions.
o The algorithm repeats this procedure for each division until the array as a whole is sorted.
o If the data is already ordered or the pivot element is not carefully chosen, quick sort has a worst-case time
complexity of O(n2).

Advantages:
o Quick sort has a fast average-case time complexity of O(nlogn), making it efficient for large datasets.
o It is a simple and easy-to-implement algorithm that can be implemented in a few lines of code.
o Quick sort can be easily parallelized, making it suitable for use on multicore and distributed systems.
o It is an in-place sorting algorithm, which means that it does not require additional memory to store
temporary variables or data structures.

Disadvantages:
o Quick sort has a worst-case time complexity of O(n^2) if the pivot element is chosen poorly or the data is
already sorted.
o It is not a stable sorting algorithm, which means that it does not guarantee the relative order of equal
elements in the sorted array.
o Quick sort is not suitable for sorting large datasets that do not fit in memory, as it requires multiple passes
over the data.

Conclusion:
Quick sort is a popular and efficient sorting algorithm that works by splitting an array into two parts and applying the
procedure to each partition recursively until the complete array is sorted. It has an average and best case time
2
complexity of O(nlogn) and a worst-case time complexity of O(n ). Quick sort is frequently favoured over other sorting
algorithms due to its simplicity, performance, and ease of implementation, despite its worst-case time complexity.

3 way merge sort in c


This article discusses 3 ways to merge sort in c. In merge sort, the array is recursively split into
two parts, sorted, and finally merged.

The merge sort variant is treated as a 3-way merge sort that splits the array into three parts
instead of splitting it into two parts. Merge sort recursively splits an array into half-sized
subarrays. Similarly, a three-way merge sort decomposes an array into subarrays of one-third
the size.

In merge sort, the array is recursively split into two parts, sorted, and finally merged. A variant of
merge sort is called 3-way merge sort, where instead of splitting the array into two parts, he
splits it into three parts.

Examples of the merge sort: The example of merge sort is given below -

PlayNext
Unmute
Current Time 0:00

Duration 18:10
Loaded: 2.94%
Â
Fullscreen

1. Input: 4, 8, -4, -9, 10, 55, 46, 70, -56, 78, 90, 67, 85, 20, 29
2. Output: -56 -9 -4 4 8 10 20 29 46 55 67 70 78 85 90
3. Input: 98, -67
4. Output: -67 98

The time complexity of a three-way merge sort is nlog3n.

Example 1: Here, we give an example of 3 way to merge sort in c. The example is given below -

1. #include <bits/stdc++.h>
2. usingnamespacestd;
3. voidmerge1(intgArr1[], intlow1, intmid1,intmid2, inthigh1, intdestArr1[])
4. {
5. inti = low1, a = mid1, b = mid2, c = low1;
6. while((i < mid1) && (a < mid2) && (b < high1))
7. {
8. if(gArr1[i] < gArr1[j])
9. {
10. if(gArr1[i] < gArr1[b])
11. {
12. destArr1[c++] = gArr1[i++];
13. }
14. else {
15. destArr1[c++] = gArr1[b++];
16. }
17. }
18. else{
19. if(gArr1[j] < gArr1[b]){
20. destArr1[c++] = gArr1[a++];
21. }
22. else{
23. destArr1[c++] = gArr1[b++];
24. }
25. }
26. }
27. while((i < mid1) && (a < mid2)){
28. if(gArr1[i] < gArr1[a]){
29. destArr1[c++] = gArr1[i++];
30. }
31. else{
32.
33. destArr1[c++] = gArr1[a++];
34. }
35. }
36. while((a < mid2) && (b < high1)){
37. if(gArr1[a] < gArr1[b]){
38. destArr1[c++] = gArr1[a++];
39. }
40. else{
41. destArr1[c++] = gArr1[b++];
42. }
43. }
44. while((i < mid1) && (b < high1))
45. {
46. if(gArr1[i] < gArr1[b])
47. {
48. destArr1[c++] = gArr1[i++];
49. }
50. else{
51. destArr1[c++] = gArr1[b++];
52. }
53. }
54. while(i < mid1)
55. destArr1[c++] = gArr1[i++];
56. while(a < mid2)
57. destArr1[c++] = gArr1[b++];
58. while(b < high)
59. destArr1[c++] = gArr1[b++];
60. }
61. voidmergeSort3WayRec(intgArr1[], intlow1, inthigh1, intdestArr1[])
62. {
63. if(high1 - low1 < 2)
64. return;
65. intmid1 = low1 + ((high1 - low1) / 3);
66. intmid2 = low1 + 2 * ((high1 - low1) / 3) + 1;
67. mergeSort3WayRec(destArr1, low1, mid1, gArr1);
68. mergeSort3WayRec(destArr1, mid1, mid2, gArr1);
69. mergeSort3WayRec(destArr1, mid2, high1, gArr1);
70. merge(destArr1, low1, mid1, mid2, high1, gArr1);
71. }
72. voidmergeSort3Way(intgArr1[], intn1){
73. if(n1 == 0)
74. return;
75. intfArr1[n];
76. for(inti = 0; i < n1; i++)
77. fArr1[i] = gArr1[i];
78. mergeSort3WayRec(fArray1, 0, n, gArray1);
79. for(inti = 0; i < n1; i++)
80. gArr1[i] = fArr1[i];
81. }
82. int main(){
83. intdata1[] = {4, 8, -4, -9, 10, 55, 46, 70, -56, 78, 90, 67, 85, 20, 29};
84. mergeSort3Way(data1,10);
85. cout<< "The result after the three way of merge sort is: ";
86. for(inti = 0; i < 10; i++)
87. {
88. cout<< data1[i] << " ";
89. }
90. return0;
91. }

Result: Now we compile the above program, and after successful compilation, we run it. Then
the result is given below -
The result after the three way of merge sort is: -56 -9 -4 4 8 10 20 29 46 55
67 70 78 85 90

How does the above code work?


Here we first replica the contents of the statistics array into every other array called fArr. Then
type the array by locating the midpoint that divides the array into three elements and calls the
type characteristic on every array. The basic case of recursion is when an array has size 1 and is
returned from a function. Then the array merging starts, and finally, the sorted array is in fArr
and copied to gArr.

The time complexity of the merge sort:


Three-way merge sort equation is: T(n) = 2T(n/2) + O(n)

Similarly, for a three-way merge sort, we have: T( n) = 3T(n/3) + O(n)

Solving with the master method, its complexity is O(n log 3n).

Time complexity appears less than a two-way merge sort, but the more comparisons in the
merge function, the more time it might take in practice.

So, in this article, we briefly discuss 3 ways to merge sort in c. The merge sort variant is treated
as a 3-way merge sort that splits the array into three parts instead of splitting it into two parts.
We also give an example that is related to this topic.

Write a C Program to implement Ackermann function using


recursion
By Tunde A | 25.03.2017

2 Comments

C Program to implement Ackermann function

Write a C Program to implement Ackermann function using recursion. Here’s simple Program to implement
Ackermann’s function using recursion in C Programming Language.

Recursion : :
 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.
 The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function, otherwise it will
go into an infinite loop.
 Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.

Ackermann Function

The Ackermann function is the simplest example of a well-defined total function which is computable but not
primitive recursive, providing a counterexample to the belief in the early 1900’s that every computable function
was also primitive recursive . It grows faster than an exponential function, or even a multiple exponential
function.

Below is the source code for C Program to implement Ackermann function using recursion which is
successfully compiled and run on Windows System to produce desired output as shown below :

SOURCE CODE : :

/* C Program to implement Ackermann function using recursion */

#include<stdio.h>

int A(int m, int n);

main()

{
int m,n;

printf("Enter two numbers :: \n");

scanf("%d%d",&m,&n);

printf("\nOUTPUT :: %d\n",A(m,n));

int A(int m, int n)

if(m==0)

return n+1;

else if(n==0)

return A(m-1,1);

else

return A(m-1,A(m,n-1));

OUTPUT : :

************* OUTPUT **************

************* FIRST RUN ***********


Enter two numbers ::

OUTPUT :: 2

************* SECOND RUN ***********

Enter two numbers ::

OUTPUT :: 6
ARAVALI COLLEGE OF ENGINEERING & MANAGEMENT
1st Sessional October -2023
st
B.Tech (CSE) 1 Semester
Subject Name: PPS Subject Code: ESC-103
Time: 2hrs M.Marks:50
General instruction:
1: Part- A is compulsory. 2: Attempt any 4 questions from Part- B.
………………………………………………………………………………………………………………………………………
Part- A
Q1 Answer the Following Questions (1*10)
a) Algorithm
b) Flowchart
c) Compiler
d) Interpreter
e) Computer
f) Operating System
g) Variable
h) Data type
i) Expression
j) Decision making statement

Part- B
Q2 What are various data types in C? Explain each with an example. (10)

Q3 a) Write the structure of C Program. (5)


b) What are the components of Computer System? Explain with diagram. (5)

Q4 What are various operators available in C? Explain each with an example. (10)

Q5 Write a program to print the grades of student. (10)

Q6 Explain each statement with an example:


a) If-else (5)
b) Switch (5)
PPS Practical File Questions
1. C Program to calculate a simple interest

2. C program to convert Total days to year, month and days

3. C Program to check whether number is EVEN or ODD

4. C Program to find largest number among three numbers

5. C program to calculate Gross Salary of an employee

6. C program to convert temperature from Fahrenheit to Celsius and vice versa

7. C Program to check the occurence of digit in a given number

8. C Program to find out the sum of first n numbers

9. C Program to generate a table of a given input number

10. C program to check whether number is Prime or Not

11. C Program to check whether character is vowel or not

12. C Program for Fibonacci numbers

13. C Program to find the roots of a quadratic equation

14. C Program to Print value in Decimal, Octal, Hexadecimal using printf

15. C program to convert feet to inches

16. C program to print ASCII value of entered character

17. C Program to pass array elements to a function

18. C Program to display student details using structure members

19. C Program to check whether number is palindrome or not

20. C Program to reverse a number entered by user

21. C Program to find Prime numbers between two Limits(Range)

22. C Program to display Armstrong numbers between Limits (Range)

23. C Program to find out the sum of first n numbers

24. C Program to Count length of string using library function

25. C Program to compare two strings

26. C Program to reverse any string

27. C Program to find frequency of characters


28. C program to find maximum and minimum element in array

29. C program to search an element in the array

30. C program to add two matrices

31. C program to multiply two matrices

32. C program to find sum of upper triangular matrix

33. C Program to Print Numbers in Pyramid

34. C Program to implement Bubble Sort using Array

35. C Program to sort the numbers using selection sort

36. C Program to Perform Merge Sort using Recursion

37. C Program Swap Numbers Using Call by Reference

38. C Program to write to file using fprintf() function

39. C Program to copy data from One file to Another file

40. C Program to read text file using File Handling

41. C program to merge two files using file handling

You might also like