SlideShare a Scribd company logo
1 of 93
Download to read offline
0
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 1/105
THE
C
PROGRAMMING FOR
PROBLEM-SOLVING
Compiled by
Er. SAROJ KUMAR
SIT Sitamarhi Desire
Sitamarhi institute of Technology
The More You Practice, The Better You Get.
Follow me
Disclaimer: While compiled by the book have made every effort to avoid any mistakes or omissions
and have used their skill, expertise, and knowledge to the best of my capacity to provide accurate and
updated information. Any mistake, or error noted may be brought to the notice of the book provider
which shall be taken care of in the next edition.
The compiled book expressly disclaims all and any liability/ responsibility to any person whether a
purchaser or reader of this book or not. In respect of anything and everything forming part of the
content of this book. It is notified that neither that book provider nor the Compiled by book will be
responsible for any damage or loss to anyone of any kind in any manner therefrom.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 2/105
Further, the appearance of the personal name location place, and incidence, if any; in the illustrations
used herein is purely coincidental and a work of imagination. Thus the same should in no manner be
termed as defamatory to any individual.
Ownership of Content: In this pdf, I’m taking references from different platforms if you want more
information about any topic then you can take this reference we describe the website Name and link
hereJatatpoint
Tutorialspoint
Geeksforgeeks
Efacility
Programiz
Scaler
W3schools
Study tonight
Guru99
This pdf is only design for B.Tech, BCA, MCA and polytechnic student of all Engineering Collage.
This pdf provides help in the exam time for a quick revision in sorting the time.
Unit Syllabus
unit-1
Introduction to Components of a Computer System: Memory, Processor, I/O
Devices, Storage, Operating System, Concept of Assembler, Compiler, Interpreter,
Loader, and Linker.
The idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo Code with
Examples, From Algorithms to Programs,
Source Code. Programming Basics: Structure of C Program,
Writing and Executing the First C Program, Syntax and Logical Errors inCompilation,
Object and Executable Code. Components of C Language. Standard I/O in C,
Fundamental Data types,
Variables and Memory Locations, Storage Classes.
Unit-2
Arithmetic Expressions and Precedence: Operators and
Expression Using Numeric and Relational Operators, Mixed Operands, Type
Conversion, Logical Operators, Bit Operations, Assignment Operator, Operator
precedence, and Associatively.
Conditional Branching: Applying if and Switch Statements,
Nesting if and Else and Switch.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 3/105
Unit-3
Iteration and Loops: Use of While, do While, and for Loops,
Multiple Loop Variables, Use of Break, Goto and Continue
Statements.
Arrays: Array Notation and Representation, Manipulating Array Elements, using
Multi-Dimensional Arrays. Character Arrays and Strings, Structure, union,
Enumerated Data types, Array of
Structures, Passing Arrays to Functions.
Unit-4
Functions: Introduction, Types of Functions, Functions with Array, Passing
Parameters to Functions, Call by Value, Call by Reference, Recursive Functions.
Basic of searching and Sorting Algorithms: Searching &
Sorting Algorithms ( Linear Search, Binary search, Bubble Sort, Insertion, and
Selection Sort)
Unit-5
Pointers: Introduction, Declaration, Applications, Introduction to Dynamic
Memory Allocation (Malloc, Calloc, Realloc, Free),
String and String functions, Use of Pointers in Self-Referential Structures, Notion of
Linked List (No Implementation)
File Handling: File I/O Functions, Standard C Preprocessors, De ning and Calling
Macros and Command-Line Arguments.
Table of Content
Content Page no
Introduction 02
Syllabus 03
Table of Content 04-06
Unit-1 (Component of a Computer System and Basic Programming)
07-25
Introduction to Component of a Computer System 07-13
Memory and its Type, Memory unit 07-08
Central Processing Unit(CPU) 08-09
I/O Device 09-10
Operating System, Assembler, compiler, Linker and Loader 10-13
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 4/105
The idea of The Algorithm 13-15
Introduction to Algorithms 13-14
Flowchart, Pseudo-code 14-15
Programming Basic 15-25
C Programming introduction 15-16
Structure of the c Program 16-17
Programming Error in C 17-18
Component of C program 18-19
Variable and its Type 19-20
Data Type in C 21-22
Storage Class and it’s Type 22-25
Unit-2 (Arithmetic Expression, Conditional
Branching)
Precedence, and 26-43
Arithmetic Expessions and Precedence 26-33
Operator in C and its Type 26-30
Precedence of Operators in C 30-31
Type conversion 31-33
Conditional Branching 33-43
Conditions statement 33
If statement 33-35
If else Statement 35-37
If else if ladder Statement 37-39
Nested if else statement 39-41
Switch case Statement 41-43
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 5/105
Unit-3 (Loops And Arrays) 44-58
Iteration And Loops 44-53
Loop and its Type 44-51
Break Statement 51-52
Continue Statement 52
Goto Statement 53
Arrays 54
Array Introduction 54
One-Dimensional Array 54-55
Two-Dimensional Array 55-57
Multi-Dimensional Array 57
Passing array to function 57-58
Unit-4(Functions,
Algorithms)
Basic Searching and Sorting 59-80
Functions 59-69
Function Introduction 59-60
Type of Function 60-62
C Library function 62
Call by Value 63-64
Call by reference 64-66
Recursion Functions 66-68
Basic Searching And Sorting Algorithms 69-80
Searching Algorithm 69
Linear Search 69-70
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 6/105
Binary Search 70-71
Sorting Algorithms 72
Bubble Sort 72-75
Insertion Sort 75-77
Selection Sort 78-80
Unit-5 (Pointers and File Handling) 81-105
Pointers 81-96
Introduction of Pointer 81-82
Type of Pointer 83
Dynamic Memory allocation in C 84-98
Traversing Strings 89-91
String Function 91-95
Self Referential structure 95-96
Notation of Linked-list 96
File Handling 96-105
Introduction 96
File I/O Functions 97-99
C Preprocessor 99-100
C Macros 100-101
Preprocessor Operator 102-103
Command-Line Arguments 103-104
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 7/105
Introduction to Components of a Computer System
Memory:
● A memory is 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 the
education required for processing is stored.
● Memory is divided into a large number of small parts called cells. Each location or cell has a unique
address, which varies from zero to memory size minus one.
Memory is primarily of three types −
● Cache Memory
● Primary Memory/Main Memory
● Secondary Memory
Cache Memory: Cache memory is high-speed memory, which is small in size but faster than the mainmemory
(RAM). The CPU can access it more quickly than the primary memory. So, it is used to synchronize with high-
speed CPU and to improve its performance.
Primary 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 devices. These memories are not as fast as registers.
● It is divided into two subcategories RAM and ROM.
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.
● The contents of secondary memories are rst transferred to the main memory, and then the CPU can
access it. For example disk, CD-ROM, DVD, etc.
Memory Unit: Memory units are used to measure and represent data. Some of the commonly used memory
units are-
● Bit: The computer memory units start from bit. A bit is the smallest memory unit to measure data
stored in main memory and storage devices. A bit can have only one binary value out of 0 and 1.
● Nibble: A group of 4 bits is called a nibble.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 8/105
● Byte: It is the fundamental unit to measure data. It contains 8 bits or is equal to 8 bits. Thus a byte
can represent 2*8 or 256 values.
● Kilobyte: A kilobyte contains 1024 bytes.
● Megabyte: A megabyte contains 1024 kilobytes.
● Gigabyte: A gigabyte contains 1024 megabytes.
● Terabyte: A terabyte contains 1024 gigabytes.
● PetaByte (PB): 1 PB = 1024 TB
Central Processing Unit(CPU): A Central Processing Unit is also called a
processor, central processor, or microprocessor. Central Processing Unit (CPU) consists of the following features
−
● CPU is considered the brain of the computer.
● CPU performs all types of data processing operations.
● It stores data, intermediate results, and instructions (program).
● It controls the operation of all parts of the computer. Generally, a CPU has three components:
● ALU (Arithmetic Logic Unit)
● Control Unit
● Memory or Storage Unit
Memory Unit:
● It stores all the data and the instructions required for processing.
● It stores intermediate results of processing.
● It stores the nal results of processing before these results are released to an output device.
● All inputs and outputs are transmitted through the main memory.
Control Unit:
● It is responsible for controlling the transfer of data and instructions among other units of a computer.
● It manages and coordinates all the units of the computer.
● It obtains the instructions from the memory, interprets them, and directs the operation of the
computer.
● It communicates with Input/Output devices for the transfer of data or results from storage.
● It does not process or store data.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 9/105
Arithmetic Logic Unit(ALU): This unit consists of two subsections namely,
● Arithmetic Section
● Logic Section
Arithmetic Section: It is to perform arithmetic operations like addition, subtraction, multiplication, and division.
All complex operations are done by making repetitive use of the above operations.
Logic Section: It is to perform logic operations such as comparing, selecting, matching, and merging data.
I/O devices:
Input Device: The input device enables the user to send data, information, or control signals to a computer.
The Central Processing Unit (CPU) of a computer receives the input and processes it to produce the output.
● Keyboard
● Mouse
● Joy Stick
● Light pen
● Track Ball
● Scanner
● Graphic Tablet
● Microphone
● Magnetic Ink Card Reader(MICR)
● Optical Character Reader(OCR)
● Bar Code Reader
● Optical Mark Reader(OMR)
Output Device: The output device displays the result of the processing of raw data that is entered into the
computer through an input device. There are a number of output devices that display output in different ways
such as text, images, hard copies, and audio or video.
Some of the popular output devices are
1. Monitor
a. CRT Monitor
b. LCD Monitor
c. LED Monitor
d. Plasma Monitor
2. Printer
a. Impact Printers
i. Character Printers
1. Dot Matrix printers
b. Non-impact printers
i. Laser printers
ii. Inkjet printers 3. Projector
4.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 10/105
Operating System:
● An Operating System can be de ned as an interface between the user and hardware.
● An operating system is a program that acts as an interface between the software and the computer
hardware.
Characteristics of Operating System:
1. Process Management
2. Memory Management
3. Device Management
4. File Management
5. Security
Assembler: An assembler translates assembly language programs into machine code. The output of an
assembler is called an object le, which contains a combination of machine instructions as well as the data
required to place these instructions in memory.
Compiler: A compiler is a special program that translates a programming language's source code into machine
code or another programming language. The source code is typically written in a high-level, human-readable
language such as Java or C++.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 11/105
Linker: Linker is a computer program that links and merges various object les together in order to make an
executable le. All these les might have been compiled by separate assemblers.
Loader: The loader is a part of the operating system and is responsible for loading executable les into memory
and executing them. It calculates the size of a program (instructions and data) and creates memory space for it.
It initializes various registers to initiate execution.
Difference between a linker and a loader −
Linker Loader
The linker generates executable les of a source
program.
The loader is to load the executable module to the
main memory.
An assembler generates the object code, which is
taken as input by the linker.
The linker creates the executable module, which is
taken by the loader.
To generate an executable code, the linker combines
all the object modules and source code.
In the main memory, it loads executable codes for
further execution.
Linkage Editors and Dynamic linkers are the two
types of linkers.
Absolute loading, Dynamic Run-time loading, and
Relocatable loading are three kinds of the loader.
Combining all object modules is another use of a
linker.
The loader allocates the address to executable les.
Difference between the Compiler and the Interpreter.−
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 12/105
Compiler Interpreter
A compiler translates the entire source code in a
single run.
An interpreter translates the entire source code line
by line.
It consumes less time i.e., it is faster than an
interpreter. It consumes much more time than the compiler i.e.,
it is slower than the compiler.
It is more efficient. It is less efficient.
CPU utilization is more. CPU utilization is less compared to the
compiler.
The compiler is larger.
Interpreters are often smaller than
compilers.
It is not exible. It is exible.
The compiler is used in languages such as C, and
C++.
An interpreter is used in languages such as Java.
Both syntactic and semantic errors can be checked
simultaneously.
Only syntactic errors are checked.
The idea of the Algorithm
Algorithm: An Algorithm is a speci cation of steps that are required to solve a particular problem.
Characteristics of an Algorithm:
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 13/105
● Unambiguous − The algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
● Input − An algorithm should have 0 or more well-de ned inputs.
● Output − An algorithm should have 1 or more well-de ned outputs and should match the
desired output.
● Finiteness − Algorithms must terminate after a nite number of steps.
● Feasibility − This should be feasible with the available resources.
● Independent − An algorithm should have step-by-step directions, which should be
independent of any programming code.
Example:
Step 1 − Start
Step 2 − declare three integers x, y & z
Step 3 − de ne values of x & y
Step 4 − multiply values of x & y
Step 5 − store the result of step 4 to z
Step 6 − print z Step 7 −
Stop
The algorithm can be represented using a owchart or a pseudo-code.
Flowchart: A owchart is a graphical representation of an algorithm.
Example of owcharts:
1. Add two numbers entered by the user.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 14/105
2. Find the largest among three different numbers entered by the user.
Pseudo-Code: A pseudo-code is an intermediate between human language and a programming language.
Examples:
If the student's grade is greater than or equal to 60 Print
"passed" or else
Print "failed"
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 15/105
Programming Basics
C programming:
● C language combines the power of a low-level language and a high-level language.
● C is a general-purpose programming language created by Dennis Ritchie at the
Bell Laboratories in 1972.
● low-level languages are used for system programming, while
high-level languages are used for application programming.
● It is because such languages are exible and easy to use.
● The features of C programming make it possible to use the language for system programming,
development of interpreters, compilers, operating systems,
graphics, general utilities, etc.
● C is also used to write other applications, such as databases, compilers, word processors, and
spreadsheets.
First C Program:
1. #include <stdio.h>
2. int main(){
3. printf("Hello Edu Desire");
4. return 0;
5. }
#include <stdio.h> includes the standard input-output library functions. The printf() function is de ned in stdio.h.
int main() The main() function is the entrypoint of every program in the c language. printf() The printf() function
is used to print data on the console. return 0 The return 0 statement, returns the execution status to the OS.
The 0 value is used for successful execution and 1 for unsuccessful execution.
Basic Structure of the C program: A C program is divided into six sections:
Documentation, Link, De nition, Global Declaration, Main() Function, and
Subprograms.
Section Description
Documentation
The description of the program, programmer's name, and creation
date. These are generally written in the form of comments.
Link
The preprocessor section contains all the header les used in a program. It informs
the system to link the header les to the system libraries.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 16/105
De nition
The de ne section comprises different constants declared using the de ne
keyword.
Global Declaration
Includes declaration of global variables, function declarations, static global
variables, and functions.
Main Function
For every C program, the execution starts from the main() function. It is
mandatory to include a main() function in every C program.
Subprograms
Include all user-de ned functions (functions the user provides). They can contain
inbuilt functions.
Example 1: To nd the sum of two numbers given by the user
1. /* Sum of two numbers */
2. #include<stdio.h>
3. int main()
4. {
5. int a, b, sum;
6. printf("Enter two numbers to be added ");
7. scanf("%d %d", &a, &b);
8. // calculating sum
9. sum = a + b;
10. printf("%d + %d = %d", a, b, sum);
11. return 0; // return the integer value in the sum
12. }
Output:
Enter two numbers to be added 3 5 3+5=8
Programming Error in C: These errors are detected either during the time of compilation or execution. Thus,
the errors must be removed from the program for the successful execution of the program.
There are mainly ve types of errors that exist in C programming:
● Syntax error
● Run-time error
● Linker error
● Logical error
● Semantic error
Syntax Error: Syntax errors are also known as compilation errors as they occurred at the compilation time.
These errors mainly occurred due to mistakes while typing when the programmer does not follow the grammar
rule of the programming language.
These errors can be easily corrected.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 17/105
For example:
1. If we want to declare the variable of type integer,
2. int a; // this is the correct form
3. Int a; // this is an incorrect form.
Commonly occurred syntax errors are:
● If we miss the parenthesis (}) while writing the code.
● Displaying the value of a variable without its declaration.
● If we miss the semicolon (;) at the end of the statement.
Logical Error: The logical error is an error that leads to an undesired output. These errors produce incorrect
output, but they are error-free, known as logical errors. The occurrence of these errors mainly depends upon
the logical thinking of the developer.
Source Code: Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension.
Object Code: Object code is the output of a compiler after it processes the source code. The object code is
usually a machine code, also called machine language, which can be understood directly by a speci c type of
CPU.
Executable Code: Executable (also called the Binary) is the output of a linker after it processes the object
code. A machine code le can be immediately executable, or it might require linking with other object code les
(e.g. libraries) to produce a complete executable program.
Component of C Program: You have seen the basic structure of a C program, so it will be easy to understand
other basic building blocks of the C programming language.
Token: A C program consists of various tokens and a token is either a keyword, an identi er, a constant, a
string literal, or a symbol.
Semicolons: In a C program, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements −
printf("Hello, World! n"); return 0;
Comments: Comments are like helping text in your C program and they are ignored by the compiler. They start
with /* and terminate with the characters */ as shown below −
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 18/105
/* my rst program in C */
Identi ers:
● A C identi er is a name used to identify a variable, function, or any other user-de ned item.
● An identi er starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters,
underscores, and digits (0 to 9).
● C does not allow punctuation characters such as @, $, and % within identi ers.
● C is a case-sensitive programming language. Thus, X and x are two different identi ers in C.
Keywords: The followinglist shows the reservedwords in C. These reserved words may not beused as constants
or variables or any other identi er names.
auto else long switch
break enum register typedef
case extern return union
char oat short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
Whitespace in C: A line containing only whitespace, possibly with a comment, is known as a blank line, and a
C compiler totally ignores it.
Variable in C:
● A variable is the name of the memory location.
● It is used to store data.
● Its value can be changed, and it can be reused many times.
Rules for de ning variables:
● A variable can have alphabets, digits, and underscore.
● A variable name can start with the alphabet, and underscore only. It can't start with a digit.
● No whitespace is allowed within the variable name.
● A variable name must not be any reserved word or keyword, e.g. int, oat, etc.
Types of Variables in C: There are many types of variables in c
1. local variable
2. global variable
3. static variable
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 19/105
4. automatic variable
5. external variable
Local Variable: A variable that is declared inside the function or block is called a local variable.
1. void function1(){
2. int x=10;//local variable
3. }
Global Variable: A variable that is declared outside the function or block is called a global variable.
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 a 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. }
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 les by using an external variable. To declare
an external variable, you need to use the extern keyword.
1. extern int x=10;//external variable (also global)
Data Type In C: A data type speci es the type of data that a variable can store such as integer, oating,
character, etc.
There are the following data types in the C language.
Type Data Type
Basic Data Type
They are arithmetic types and are further classi ed into (a) integer types and
(b) oating-point types. ● int, char, oat, double
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 20/105
Derived Data Type
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types, and (e) Function types.
Enumeration Data Type
They are again arithmetic types and they are used to de ne variables that can
only assign certain discrete integer values throughout the program.
● enum
Void Data Type The type speci er void indicates that no value is available.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Integer Types: The following table provides the details of standard integer types with their storage sizes and
value ranges −
Data Type Memory Size Range
char 1 byte −128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
int 2 byte −32,768 to 32,767
signed int 2 byte -32768 to 32767
unsigned int 2 byte 0 to 65,535
signed short int 2 byte −32,768 to 32,767
unsigned short int 2 byte 0 to 65,535
signed Long int 4 byte -2,147,483,648 to 2,147,483,647
unsigned Long int 4 byte 0 to 4,294,967,295
Floating-Point Types: The following table provide the details of standard
oating-point types with storage sizes and value ranges and their precision −
Data Type Memory Size Range
oat 4 byte 1.2E-38 to 3.4E+38
double 8 bytes 2.3E-308 to 1.7E+308
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 21/105
long double 10 bytes 3.4E-4932 to 1.1E+4932
The void Type: The void type speci es that no value is available. It is used in three kinds of situations −
● Function returns as void
● Function arguments as void
● Pointers to void
Storage Classes: Storage classes in C are used to determine thelifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C
● Automatic
● External
● Static
● Register
Storage
Classes
Storage
Place
Value Scope Lifetime
auto RAM
Garbage Value
Local Within the function
extern RAM Zero Global
Till the end of the main program Maybe
declared anywhere in the program
static RAM Zero Local
Till the end of the main program, Retains
value between multiple
functions call
register Register
Garbage Value
Local Within the Function
The Automatic Storage Class:
● Automatic variables are allocated memory automatically at runtime.
● The visibility of the automatic variables is limited to the block in which they are de ned.
● The keyword used for de ning automatic variables is auto.
● Every local variable is automatic in C by default.
Example
#include <stdio.h>
int main()
{
int a; //auto
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 22/105
char b; oat c;
printf("%d %c %f", a,b,c); // printing initial default value of automatic variables a, b, and c.
return 0;
}
Output: garbage garbage
garbage
Static Storage Class:
● The variables de ned as static speci er can hold their value between the multiple function calls.
● Static local variables are visible(scope) only to the function or the block in which they are de ned.
● A same static variable can be declared many times but can be assigned at only one time.
● The keyword used to de ne static variable is static.
Example
#include<stdio.h>
void sum()
{
static int a = 10; static int b
= 24; printf("%d %d
n",a,b); a++; b++;
}
void main()
{ int i;
for(i = 0; i< 3; i++)
{ sum(); // The static variables hold their value between multiple function calls.
}
}
Output:
10 24
11 25
12 26
Register Storage Class:
● The variables de ned as the register is allocated the memory into the CPU registers depending upon
the size of the memory remaining in the CPU.
● The access time of the register variables is faster than the automatic variables.
● The initial default value of the register local variables is 0.
● We can store pointers in the register, i.e., a register can store the address of a variable.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 23/105
Example 1
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0. printf("%d",
a);
}
Output: 0
External Storage Class:
● The external storage class is used to tell the compiler that the variable de ned as extern is declared
with an external linkage elsewhere in the program.
● The variables declared as extern are not allocated any memory.
● The default initial value of the external integral type is 0 otherwise null.
● We can only initialize the extern variable globally, i.e., we can not initialize the external variable
within any block or method.
● An external variable can be declared many times but can be initialized only once.
Example
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is de ned globally, the memory will not be allocated to a
6. printf("%d", a);
7. }
Output: 0
SIT Sitmarhi Desire
The More You Practice, The Better You Get.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 24/105
Arithmetic Expressions and Precedence
Operators in C: An operator is a symbol that tells the compiler to perform speci c mathematical or logical
functions.
There are the following types of operators to perform different types of operations in C language.
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators
● Misc Operators
Arithmetic Operators: Arithmetic Operators are the operators which are used to perform mathematical
calculations. Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example
+ Adds two operands. A + B = 30
- Subtracts the second operand from the rst. A - B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B / A = 2
%
Modulus Operator and the remainder after an integer division.
B % A = 0
++ Increment operator increases the integer value by one. A++ = 11
- - Decrement operator decreases the integer value by one. A- - = 9
Relational Operator: Relational operators are speci cally used to compare two quantities or values in a
program. It checks the relationship between two operands. If the given relation is true, it will return 1 and if the
relation is false, then it will return 0. Assume variable A holds 10 and variable B holds 20 then −
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 25/105
Operator Description Example
==
Checks if the values of two operands are equal or not.
If yes, then the condition becomes true.
(A == B) is not true.
!=
Checks if the values of two operands are equal or not.
If the values are not equal, then the condition
becomes true.
(A != B) is true.
>
Checks if the value of the left operand is greater than
the value of the right operand.
(A > B) is not true.
<
Checks if the value of the left operand is less than the
value of the right operand.
(A > B) is true.
>=
Checks if the value of the left operand is greater than
or equal to the value of the right operand.
(A >= B) is not true.
<=
Checks if the value of the left operand is less than or
equal to the value of the right operand.
(A <= B) is true.
Logical Operator: In the C programming language, we have three logical operators when we need to test
more than one condition to make decisions. Assume variable A holds 1 and variable B holds 0, then −
Operator Description Example
&& Called Logical AND operator. If both operands are non-zero, then the
condition becomes true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two operands is non-zero,
then the condition becomes true.
(A || B) is true.
! Called Logical NOT Operator. It is used to reverse the logical state of its
operand. If a condition is true, then the Logical NOT operator will make
it false.
!(A && B) is true.
Bitwise Operator:
● Bitwise operators are the operators which work on bits and perform the bit-by-bit operation.
● Bitwise operators are especially used in C programming for performing bit-level operations.
● C programming language supports a special operator for bit operation between two variables.
The truth tables for &, |, and ^ are as follows −
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 26/105
p q p & q P | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Here, we will assume that A = 50 and B = 25 in binary format as follows.
A = 00110010
B = 00011001
-----------------
A&B = 00010000
A|B = 00111011
A^B = 00101011
~A = 11001101
The table provided below demonstrates the bitwise operators supported by C. Assume variable 'A' holds 50 and
variable 'B' holds 25.
Operator Description Example
&
Binary AND Operator.
It copies a bit to the result if it exists in both operands.
(A & B) = 16,
i.e. 00010000
|
Binary OR Operator.
It copies a bit if and only if it exists in either operand
(A | B) = 59, i.e.
00111011
^
Binary XOR Operator.
It copies the bit only if it is set in one operand but not both.
(A ^ B) = 43,
i.e. 00101011
~
Binary One's Complement Operator.
It is unary and has the effect of ' ipping' bits.
(~A ) = ~(50),
i.e,. -0111101
<<
Binary Left Shift Operator.
The value of the left operands is moved left by the number of bits speci
ed by the right operand.
A << 2 = 200
i.e. 11001000
>>
Binary Right Shift Operator.
The value of the left operands is moved right by the number of bits speci
ed by the right operand.
A >> 2 = 12 i.e.,
00001100
Assignment Operator: An assignment operator is mainly responsible for assigning a value to a variable in
a program.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 27/105
Operator Description Example
=
Simple assignment operator. Assigns values from right side
operands to left side operand
C = A + B will assign the
value of A + B to C
+=
Add AND assignment operator. It adds the right operand to
the left operand and assigns the result to the left operand.
C += A is equivalent to C =
C + A
-=
Subtract AND assignment operator. It subtracts the right
operand from the left operand and assigns the result to the
left operand.
C -= A is equivalent to C = C
- A
*=
Multiply AND assignment operator. It multiplies the right
operand with the left operand and assigns the result to the
left operand.
C *= A is equivalent to C = C
* A
/=
Divide AND assignment operator. It divides the left operand
with the right operand and assigns the result to the left
operand.
C /= A is equivalent to C = C
/ A
%=
Modulus AND assignment operator. It takes modulus using
two operands and assigns the result to the left operand.
C %= A is equivalent to C =
C % A
<<= Left shift AND assignment operator.
C <<= 2 is the same as C = C
<< 2
>>= Right shift AND assignment operator.
C >>= 2 is the same as C = C
>> 2
&= Bitwise AND assignment operator.
C &= 2 is the same as C = C
& 2
^=
Bitwise exclusive OR and assignment
operator.
C ^= 2 is the same as C = C
^ 2
|= Bitwise inclusive OR and assignment operator.
C |= 2 is the same as C = C
| 2
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 28/105
Misc Operator: Besides all the other operators discussed above, the C programming language also offers a
few other important operators including sizeof, comma, pointer(*), and conditional operator (?:).
Operator Description Example
sizeof() Returns the size of a variable.
sizeof(a), where a is an integer, will return 4.
&
Returns the address of a
variable.
&a; returns the actual address of the variable.
* Pointer to a variable. *a;
?: Conditional Expression.
If Condition is true? then value X:
Otherwise, value Y
Precedence of Operators in C: The precedence of operator species that which operator will be evaluated
rst and next. The associativity speci es the operator directly to be evaluated; it may be left to right or right to
left.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it
rst gets multiplied with 3*2 and then adds into 7.
Category Operator Associativity
Post x () [] ->. ++ - - Left to Right
Unary + - ! ~ ++ - - (type)* & sizeof Right to Left
Multiplication * / % Left to Right
Additive + - Left to Right
Category Operator Associativity
Shift << >> Left to Right
Relational < <= > >= Left to Right
Equality == != Left to Right
Bitwise AND & Left to Right
Bitwise OR | Left to Right
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 29/105
Bitwise XOR ^ Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Right to Left
Assignment = += -= *= /= %=>>= <<= &=
^= |=
Right to Left
Comma , Left to Right
Type Conversion:
Type conversion is the method to convert one data type into another data type. When we write a C program,
we declare some variables and constants, if we perform some operation or write some expression, the result of
that expression may be of some other type. So we need to do typecasting or type conversion in C programming.
Example:
#include <stdio.h> int
main() {
oat a = 12.3;
int b = (int) a + 3; //typecasting oat to int
printf("The value of b is: %d", b); return 0;
}
Output:
The value of b is: 15
‘C’ programming provides two types of type conversion operations:
Implicit type Conversion:
● The implicit type conversion takes place when more than one data type is present in an expression.
● It is done by the compiler itself it is also called automatic type conversion.
● Here the automatic type conversion takes place in order to prevent data loss, as the datatypes are
upgraded to the variable with the datatype having the largest value.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 30/105
Example 1 int a =
20;
double b = 20.5; a +
b;
Here, the rst operand is int type and the other is of type double. So, as per rule 2, the variable a will be converted
to double. Therefore, the nal answer is double a + b =
40.500000.
Example 2
char ch='a';
int a =13; a +
c;
Here, the rst operand is char type and the other is of type int. So, as per rule 1, the char variable will be converted
to int type during the operation and the nal answer will be of type int. We know the ASCII value for ch is 97.
Therefore, the nal answer is a
+ c = 97 + 13 = 110.
Explicit Type Conversion:
● It refers to the type conversion performed by a programmer by modifying the data type of an
expression using typecasting.
● It is also Called casting in another language. It is done by a programmer.
Let's start with an example. If we perform an arithmetic operation on two same types of datatype variables so
the output will be in the same data type. But there are some operations like the division that can give us output
in oat or double. a = 3; (int) b = 20; (int) c = b/a = 6
Here the expected output was 6.66 but a and b were integers so the output come as 6 integers. But if we need
6.66 as output we need explicit type conversion.
Example:
#include<stdio.h>
Int main()
{ int a = 3;
int b = 20;
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 31/105
oat X = b/a; // without explicit type conversion printf(“without
explicit type conversionL:%fn”, x);
x = b/( oat)a; //with explicit type conversion printf(“with explicit
type conversionL:%fn”, x);
return 0;
}
Output:
without explicit type conversion: 6.000000 without explicit
type conversion: 6.666667
Conditional Branching
Conditions statement: The if-else statement in C is used to perform the operations based on some speci c
condition. The operations speci ed in the if block is executed if and only if the given condition is true.
There are the following variants of if statement in C language.
● If statement
● If-else statement
● If else-if ladder Statement
● Nested if
● Switch statement If Statement:
● It is one of the powerful conditional statements.
● The if statement is used to check some given condition and perform some operations depending upon
the correctness of that condition.
● The condition evaluates to either true or false. True is always a non-zero value, and false is a value
that contains zero.
The syntax of the if statement is given below.
if(expression){
//code to be executed
}
Flowchart of if statement in C
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 32/105
Let's see a simple example of C language if statement.
#include<stdio.h> int main(){ int
number=0; printf("Enter a
number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number", number);
}
return 0;
}
Output
Enter a number: 4
4 is even number
Program to nd the largest number of the three.
#include <stdio.h>
int main()
{ int a, b, c;
printf("Enter three numbers?");
scanf("%d %d %d",&a,&b,&c); if(a>b &&
a>c)
{ printf("%d is largest",a);
}
if(b>a && b > c)
{ printf("%d is largest",b);
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 33/105
}
if(c>a && c>b)
{ printf("%d is largest",c);
}
if(a == b && a == c)
{ printf("All are equal");
}
}
Output
Enter three numbers?
12 23 34
34 is the largest
If-else Statement:
● The if-else statement is used to perform two operations for a single condition.
● If the given condition is true, then program control goes inside the if block and executes the Statement.
● The condition is false, then program control goes inside the else block and executes the corresponding
Statement. Syntax of if-else Statement if(expression){
//code to be executed if a condition is true
}
else{
//code to be executed if a condition is false
}
Flowchart of the if-else statement in C
Let's see the simple example to check whether a number is even or odd using if-else
statement in C language.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 34/105
#include<stdio.h> int main(){
int number=0; printf("enter a
number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number", number);
}
else{
printf("%d is odd number", number);
}
return 0;
}
Output:
Enter a number: 4
4 is even number
Enter a number: 5
5 is odd number
Program to check whether a person is eligible to vote or not.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age?"); scanf("%d",&age);
if(age>=18)
{ printf("You are eligible to vote...");
}
else
{ printf("Sorry ... you can't vote");
}
}
Output:
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote
If else-if ladder Statement:
● The if-else-if conditional Statement in c is used to execute one code from multiple conditions.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 35/105
● In the if-else-if ladder statement, if a condition is true then the statements de ned in the if block will
be executed, otherwise if some other condition is true then the statements de ned in the else-if block
will be executed, at the last if none of the condition is true then the statements de ned in the else
block will be executed.
● There are multiple else-if blocks possible. ● It is similar to the switch case statement. Syntax of If-
else-if Ladder Statement
if(condition1){
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
Flowchart of else-if ladder statement in C
Program to calculate the grade of the student according to the speci ed marks.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 36/105
#include <stdio.h> int
main()
{
int marks; printf("Enter your
marks?"); scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{ printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{ printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{ printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{ printf("You scored grade C ...");
}
else
{ printf("Sorry you are fail ...");
}
}
Output:
Enter your marks?10 Sorry you
are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats! you scored grade A ...
Nested If-else Statements
● A nested if-else statement is used to check more than one condition.
● Nested if-else is also known as a multi-way selection statement.
● if the result of the given condition is True, then the Statement inside the if block is executed.
● If the given condition is false, then it will check the rst else if part, and if the condition of is true then
the statements related to else if are Executed otherwise the pointer goes to the next else if, and this
process is contained And if the result of the all the else if a condition is false then the pointer is
automatically going to else part and the Statement of the else automatically executed. Syntax ofNested
if-else Statement
if(expression)
{
Statement
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 37/105
} else if
{
// Statement
} else if
{
//Statement
}
else
{
// Statement
}
Following the program to nd the greatest number among the three numbers.
#include<stdio.h>
#include<conio.h> void
main( )
{ int a,b,c;
clrscr();
printf(“Please Enter three number”);
scanf(“%d%d%d”,&a,&b,&c); if(a>b) { if(a>c) {
printf(“a is greatest number”);
}
else
{
printf(“c is greatest number”);
}
}
else
{ if(b>c)
{ printf(“b is greatest number”);
}
else
{
printf(“c is greatest”);
}
}
getch();
}
Output:
Please Enter three number
10
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 38/105
18 5 b is
greatest
Switch Case Statement:
● A switch case statement in C Programming tests the value of a choice variable and compares it with
multiple cases.
● When the case match is found, a block of statements associated with that speci c case is executed.
● If a case match is not found, then the default statement is executed, and the control goes out of the
switch block.
The syntax of switch statement
switch(expression){ case value1:
//code to be executed; break;
//optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Rules for switch statement:
● Case labels must have constants or constant expressions.
● Case label must be of integral Type (Integer, Character).
● Case label should not be ‘ oat type. ‘
● Switch case should have at most one default label ● The default label is Optional
● The default can be placed anywhere in the switch
● Break Statement takes control out of the switch
● Two or more cases may share one break statement.
Flowchart of a switch statement in C
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 39/105
Let's see a simple example of c language switch statement.
#include<stdio.h> int main(){
int number=0; printf("enter a
number:");
scanf("%d",&number);
switch(number){ case 10:
printf("number equals to 10"); break;
case 50:
printf("number is equal to 50"); break;
case 100:
printf("number is equal to 100"); break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output:
enter a number: 4 number is not equal to
10, 50 or 100 enter a number: 50 number is
equal to 50
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 40/105
SIT Sitamarhi Desire
The More You Practice, The Better You Get.
Iteration and Loops
Loops: A loop statement allows us to execute a statement or group of statements multiple times.
● It provides code reusability.
● Using loops, we do not need to write the same code again and again.
● Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops: There are three types of loops.
● While loop
● Do while loop
● For loop
while loop:
● While loop is also known as a pre-tested loop.
● While loop allows a part of the code to be executed multiple times depending upon a given boolean
condition.
● The while loop is mostly used in cases where the number of iterations is not known in advance.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 41/105
The syntax of a while loop in c language is given below:
while(condition){
//code to be executed
}
Flowchart of while loop in C
Let's see the simple program of while loop that prints table of 1.
#include<stdio.h> int
main(){ int i=1;
while(i<=10){
printf("%d n",i); i++;
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Example:
#include<stdio.h>
void main ()
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 42/105
{ int j = 1;
while(j+=2,j<=10)
{ printf("%d ",j);
}
printf("%d",j);
}
Output:
3 5 7 9 11
Example:
#include<stdio.h>
void main ()
{ int x = 10, y = 2;
while(x+y-1)
{ printf("%d %d",x--,y--);
}
}
Output:
In nite loop
do while loop:
● The do-while loop is a post-tested loop.
● Using the do-while loop, we can repeat the execution of several parts of the statements.
● The do-while loop is mainly used in the case where we need to execute the loop at least once.
● A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one
time.
The syntax of the C language do-while loop is given below:
do{
//code to be executed
}
while(condition);
Flowchart of do while loop
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 43/105
Program to print table for the given number using do while loop
#include<stdio.h> int main(){ int
i=1,number=0; printf("Enter a
number: ");
scanf("%d",&number); do{
printf("%d n",(number*i));
i++;
}
while(i<=10);
return 0;
}
Output:
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
for loop:
● The for loop in C language is used to iterate the statements or a part of the program several times.
● It is frequently used to traverse the data structures like the array and linked list.
● A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a speci c number of times.
The syntax of for loop in c language is given below:
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 44/105
for(Expression 1; Expression 2; Expression 3)
{
//code to be executed
}
Or
for ( init; condition; increment )
{
statement(s);
}
Flowchart of for loop in C
Example:
#include <stdio.h> int
main () { int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %dn", a);
}
return 0;
}
Output:
value of a: 10 value of
a: 11 value of a: 12
value of a: 13 value of
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 45/105
a: 14 value of a: 15
value of a: 16 value of
a: 17 value of a: 18
value of a: 19
Nested Loops:
● C programming allows to use one loop inside another loop.
● Any number of loops can be de ned inside another loop, i.e., there is no restriction for de ning any
number of loops.
● The nesting level can be de ned at n times. You can de ne any type of loop inside another loop; for
example, you can de ne a 'while' loop inside a 'for' loop.
Syntax of Nested loop
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
The syntax for a nested for loop statement for ( init;
condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 46/105
Example: Uses a nested loop to nd the prime numbers from 2 to 20 −
Live Demo
#include <stdio.h> int
main () {
/* local variable de nition */
int i, j;
for(i = 2; i<20; i++) { for(j = 2;
j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is primen", i);
}
return 0;
}
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
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 statements.
● The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner
loop rst and then proceeds to the outer loops. The break statement in C can be used in the following
two scenarios:
1. With switch
case
2. With loop
Syntax:
//loop or switch case break;
Flowchart of a break in c
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 47/105
Consider the following example to use break statement inside while loop.
#include<stdio.h>
void main ()
{ int i = 0;
while(1)
{ printf("%d ",i); i++;
if(i == 10) break;
}
printf("came out of while loop");
}
Output:
0 1 2 3 4 5 6 7 8 9 come out of while loop
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:
//loop statements continue;
//some lines of the code which is to be skipped
Continue statement example
#include<stdio.h> int
main(){
int i=1; //initializing a local variable
//starting a loop from 1 to 10 for(i=1;i<=10;i++){
if(i==5){//if the value of i is equal to 5, it will continue the loop continue;
}
printf("%d n",i); }//end of
for loop
return 0;
}
Output:
1
2
3
4
6
7
8
9
10
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 48/105
As you can see, 5 is not printed on the console because the loop is continued at i==5.
Goto statement:
● The goto statement is known as a jump statement in C.
● The goto statement can be used to repeat some part of the code for a particular condition.
● It can also be used to break 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 complicated.
Syntax: label:
//some part of the code; goto label;
Example:
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num); table: printf("%d x %d = %dn", num,i,num*i); i++;
if(i<=10)
goto table;
}
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
Arrays
● Arrays a kind of data structure that can store a xed-size sequential collection of elements of the same
type.
● An array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
The array contains the following properties.
● Each element of an array is of the same data type and carries the same size, i.e., int = 4 bytes.
● Elements of the array are stored at contiguous memory locations where the rst element is stored at
the smallest memory location.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 49/105
● 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:
● Code Optimization: Less code to access the data.
● Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
● Ease of sorting: To sort the elements of the array, we need a few lines of code only.
● Random Access: We can access any element randomly using the array.
Type of Array:
● 1D Array
● 2D Array
● Multi-Dimensional Array
One-Dimensional Arrays:
● A one-dimensional array in C is a list.
● Each element of the list contains only one value, whether that value be an int, char, or oat.
● To declare an array, three values are typically needed: the data type, the name of the array, and the
number of elements to be contained in the array.
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Example to declare the array 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.
marks[0]=80;//initialization of array
marks[1]=60; marks[2]=70;
marks[3]=85; marks[4]=75;
Array Example:
#include<stdio.h> int
main(){ int i=0;
int marks[5];//declaration of array marks[0]=80;//initialization of array
marks[1]=60; marks[2]=70;
marks[3]=85; marks[4]=75;
//traversal of an array
for(i=0;i<5;i++){ printf("%d n",
marks[i]); }//end of for loop
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 50/105
return 0;
}
Output:
80
60
70
85
75
Two-dimensional Arrays:
● The simplest form of multidimensional array is the two-dimensional array.
● The two-dimensional array can be de ned as an array of arrays.
● The 2D array is organized as matrices which can be represented as a collection of rows and columns.
● To declare a two-dimensional integer array of size [x][y], you would write something as follows − type
arrayName [ x ][ y ].
Declaration of two dimensional Array:
data_type array_name[rows][columns];
Consider the following example.
Column-0 Column-1 Column-2 Column-3
Row-0 A[0] [0] A[0] [1] A[0] [2] A[0] [3]
Row-1 A[1] [0] A[1] [1] A[1] [2] A[1] [3]
Row-2 A[2] [0] A[2] [1] A[2] [2] A[2] [3]
int twodimen[3][4];
Here, 3 is the number of rows, and 4 is the number of columns.
Initializing Two-Dimensional Arrays:
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array
with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Two-dimensional array example
#include<stdio.h> int
main(){ int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d n", i,j , arr[i][j]);
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 51/105
}//end of j }//end of
i
return 0;
}
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
Multi dimensional Arrays:
C programming language allows multidimensional arrays. Here is the general form of a multidimensional array
declaration − type name[size1][size2]...[sizeN];
For example, the following declaration creates a three-dimensional integer array − int threedim[5][10][4];
Passing Array to Function: If you want to pass a single-dimension array as an argument in a function, you
would have to declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be received.
Consider the following syntax to pass an array to the function. functionname(arrayname);//passing array
There are 3 ways to declare the function which is intended to receive an array as an argument.
Way-1: Formal parameters as a pointer −
void myFunction(int *arrayname) {
.
}
Way-2: Formal parameters as a sized array −
void myFunction(int arrayname[Size]) {
.
}
Way-3: Formal parameters as an unsized array −
void myFunction(int arrayname[]) {
.
}
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 52/105
Passing an array to function example
#include<stdio.h> int minarray(int
arr[], int size){ int min=arr[0]; int i=0;
for(i=1;i<size;i++){ if(min>arr[i]){
min=arr[i];
}
}//end of for return
min;
}//end of function
int main(){ int
i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array
min=minarray(numbers,6);//passing array with size
printf("minimum number is %d n", min); return 0;
}
Output:
Minimum number is 3
SIT Sitamarhi Desire
The More You Practice, The Better You Get.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 53/105
Functions
C Functions:
● In c, we can divide a large program into the basic building blocks known as functions.
● 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.
● A function is a group of statements that together perform a task.
● Every C program has at least one function, which is main(), and all the most trivial programs can de ne
additional functions.
Advantages of functions in C: There are the following advantages of C functions.
● By using functions, we can avoid rewriting the same logic/code again and again in a program.
● We can call C functions any number of times in a program and from any place in a program.
● We can track a large C program easily when it is divided into multiple functions.
● Reusability is the main achievement of C functions.
Here are all the parts of a function −
● Return Type: A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
● Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
● Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as an actual parameter or argument. The parameter list refers to
the type, order, and a number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
● Function Body: The function body contains a collection of statements that de ne what the function
does.
Function Aspects: There are three aspects of a C function.
● 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.
Syntax: return_type function_name (argument_list);
● Function call: The function can be called from anywhere in the program. We must pass the same
number of functions as it is declared in the function declaration.
Syntax: function_name (argument_list);
● Function de nition: It contains the actual statements which are to be executed. Syntax: return_type
function_name (argument_list){function_body};
Types of Functions: There are two types of functions in C programming:
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 54/105
● Library Functions: are the functions which are declared in the C header les such as scanf(), printf(),
gets(), puts(), ceil(), oor(), etc.
● User-de ned 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.
Example for Function without argument and return value
Example 1
#include<stdio.h> void
printName();
void main ()
{ printf("Hello ");
printName();
}
void printName()
{ printf("Edu Desire");
}
Output:
Hello Edu Desire
Example 2
#include<stdio.h> void
sum();
void main()
{
printf("nGoing to calculate the sum of two numbers:"); sum();
}
void sum()
{ int a,b;
printf("nEnter two numbers"); scanf("%d
%d",&a,&b);
printf("The sum is %d",a+b);
}
Output:
Going to calculate the sum of two numbers:
Enter two numbers
20
24
The sum is 44
Example for Function with argument and without return value
Example 1: a program to calculate the average of ve numbers.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 55/105
#include<stdio.h> void average(int, int,
int, int, int);
void main()
{ int a,b,c,d,e;
printf("nGoing to calculate the average of ve numbers:"); printf("nEnter
ve numbers:"); scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
oat avg;
avg = (a+b+c+d+e)/5;
printf("The average of given ve numbers: %f",avg);
}
Output:
Going to calculate the average of ve numbers:
Enter ve numbers:
10
20
30
40
50
The average of given ve numbers: 30.000000
C 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 speci c operations. For example, printf is a library function used
to print on the console.
The list of the most used header les is given in the following table.
Header File Description
stdio.h
This is a standard input/output header le. It contains all the library functions regarding
standard input/output.
conio.h This is a console input/output header le.
string.h It contains all string related library functions like gets(), puts(),etc.
math.h
This header le contains all the math operations related functions like sqrt(), pow(), etc.
time.h This header le contains all the time-related functions.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 56/105
ctype.h This header le contains all character handling functions.
locale.h This le contains locale functions.
stdlib.h
This header le contains all the general library functions like malloc(), calloc(), exit(), etc.
There are two methods to pass the data into the function in C language, i.e.,
● call by value
● call by reference
Call by value:
● The call by value method of passing arguments to a function copies the actual value of an argument
into the formal parameter of the function.
● In other words, we can say that the value of the variable is used in the function call in the call by value
method.
● In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
● 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.
Example:
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d n", num); num=num+100;
printf("After adding value inside function num=%d n", num);
}
int main() {
int x=100;
printf("Before function call x=%d n", x); change(x);//passing
value in function printf("After function call x=%d n", x);
return 0;
}
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
Now, let us call the function swap() by passing actual values as in the following example −
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 57/105
#include <stdio.h>
/* function declaration */ void
swap(int x, int y);
int main () {
/* local variable de nition */
int a = 100; int b
= 200;
printf("Before swap, value of a : %dn", a ); printf("Before swap,
value of b : %dn", b );
/* calling a function to swap the values */ swap(a, b);
printf("After swap, value of a : %dn", a ); printf("After swap,
value of b : %dn", b );
return 0;
}
void swap(int x, int y) { int temp;
temp = x; /* save the value of x */ x = y;
/* put y into x */ y = temp; /* put
temp into y */
return;
}
Output:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100 After swap,
value of b : 200
Call by reference:
● In call by reference, the address of the variable is passed into the function call as the actual
parameter.
● The value of the actual parameters can be modi ed by changing the formal parameters since the
address of the actual parameters is passed.
● The memoryallocation 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 modi ed value gets stored at the same address.
Example:
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 58/105
#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d n",*num);
(*num) += 100;
printf("After adding value inside function num=%d n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d n", x); change(&x);//passing
reference in function printf("After function call x=%d n", x);
return 0;
}
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
Let us now call the function swap() by passing values by reference as in the following example − Live Demo
#include <stdio.h> int main () {
/* local variable de nition */
int a = 100; int b
= 200;
printf("Before swap, value of a : %dn", a ); printf("Before swap,
value of b : %dn", b );
/* calling a function to swap the values */ swap(&a, &b);
printf("After swap, value of a : %dn", a ); printf("After swap,
value of b : %dn", b );
return 0;
}
void swap(int *x, int *y) { int
temp;
temp = *x; /* save the value of x */ *x =
*y; /* put y into x */ *y = temp; /* put
temp into y */
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 59/105
return;
}
Output:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
Difference between call by value and call by reference in c
Call by value Call by reference
A copy of the value is passed into the function An address of value is passed into the function
Actual and formal arguments are created at the
different memory location
Actual and formal arguments are created at the same
memory location
Original value not modi ed. The original value is modi ed.
Values of variables are passed using a
straightforward method.
Pointer variables are required to store the address of
variables.
Does not allow you to make any changes in the
actual variables.
Allows you to make changes in the values of variables
by using function calls.
Default in many programming languages like
C++.PHP. Visual Basic NET, and C#.
It is supported by most programming languages like
JAVA, but not as default.
Recursion Functions:
● 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.
● while using recursion, programmers need to be careful to de ne an exit condition from the function,
otherwise, it will go into an in nite loop.
● Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating the Fibonacci series, etc.
Syntax:
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
Example: Recursion is used to calculate the factorial of a number.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 60/105
#include <stdio.h>
int fact (int); int
main()
{ int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n); f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Output:
Enter the number whose factorial you want to calculate?5 factorial = 120
Example: To nd the nth term of the Fibonacci series.
Concept: b(5)
/ 
b(4) b(3)
/  / 
b(3) b(2) b(2) b(1)
/  /  / 
b(2) b(1) b(1) b(0) b(1) b(0)
/ 
b(1) b(0)
#include<stdio.h> int
bonacci(int); void main ()
{ int n,f;
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 61/105
printf("Enter the value of n?");
scanf("%d",&n); f = bonacci(n);
printf("%d",f);
}
int bonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return bonacci(n-1)+ bonacci(n-2);
}
}
Output:
Enter the value of n? 9
4
Basic Searching and Sorting Algorithms
Searching Algorithm:
● The searching algorithms are used to search or nd one or more than one element from a dataset.
● These types of algorithms are used to nd elements
from speci c data structures.
● Searching may be sequential or not.
● If the data in the dataset are random, then we need to use sequential searching. Otherwise, we can use
other different techniques to reduce the complexity.
In this Section, We are going to cover
● Linear Search
● Binary Search
Linear Search Algorithm:
● It is the simplest searching algorithm.
● Linear search is a sequential searching algorithm where we start from one end and check every element
of the list until the desired element is found. It is the simplest search algorithm.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 62/105
Working of Linear Search:
● Search for an element k = 1 in the given list.
8 5 1 14 10 24
● Start from the rst element, compare k with each element x. k != 8 k != 5 k = 1
● If x == k, return the index.
● Else, return not found.
Algorithm:
LinearSearch(array, key) for each
item in the array
if item == value
returns its index
Example:
// Linear Search in C #include <stdio.h> int
search(int array[], int n, int x) {
// Going through array sequentially
for (int i = 0; i < n; i++)
if (array[i] == x)
return I;
return -1;
}
int main() { int array[] = {8, 5, 1, 14,
10, 24}; int x = 1;
int n = sizeof(array) / sizeof(array[0]); int result =
search(array, n, x);
(result == -1)? printf("Element not found"): printf("Element found at index: %d", result);
}
Binary Search Algorithm:
● Binary Search is a search algorithm for nding the position of an element in a sorted 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 rst.
● In this approach, the element is always searched in the middle of a portion of an array.
The Binary Search Algorithm can be implemented in two ways:
● The recursive method follows the divide and conquers approach.
● Iterative Method
●
Example: Let x = 4 be the element to be searched in the given Array.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 63/105
5 8 7 4 3 6
Step 1: First we need to sort this array
3 4 5 6 7 8
Step 2: Set two pointers low and high at the lowest and the highest positions respectively.
● Low = 3
● Hingh = 8
Step 3: Find the middle element mid of the array ie. arr[(low + high)/2] = 5 or 6, let mid = 6 Step 4:
● If x == mid, then return mid.
● If x > mid, then set the value of low = mid + 1.
● If x < mid, then set the value of high = mid - 1.
Now
Low = 3
High = 5
Mid = 4
Repeat Step 2 to Step 4 Mid
= 4 x = 4 is found
Algorithm:
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 right side return
binarySearch(arr, x, low, mid - 1)
Sorting Algorithm: Sorting is the process of arranging the elements of an array so that they can be placed
either in ascending or descending order. Consider an array;
int A[10] = { 5, 4, 10, 2, 30, 45, 34, 14, 18, 9 )
The Array sorted in ascending order will be given as;
A[] = { 2, 4, 5, 9, 10, 14, 18, 30, 34, 45 }
In this Section, We are going to cover
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 64/105
● Bubble Sort
● Insertion Sort
● Selection Sort
Bubble Sort:
● It is inspired by observing the behavior of air bubbles over foam.
● Bubble sort is the easiest sorting algorithm to implement. ● It is an in-place sorting algorithm.
Step-by-Step Process:
● Select the rst element of the list (i.e., the Element at the rst position in the list).
● Compare the selected element with all the other elements in the list.
● In every comparision, if any element is found smaller than the selected element (for Ascending order),
then both are swapped.
● Repeat the same procedure with the element in the next position in the list till the entire list is sorted.
Bubble Sort Algorithm:
begin BubbleSort(arr)
for all array elements if
arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if end
for return arr
end BubbleSort
Example: Consider the following unsorted list of element..?
13 32 26 35 10
First Pass:
Sorting will start from the initial two elements. Let's compare them to check which is greater.
13 32 26 35 10
Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.
13 32 26 35 10
Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like this.
13 26 32 35 10
Now, compare 32 and 35.
13 26 32 35 10
Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
Now, the comparison will be between 35 and 10.
13 26 32 35 10
Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach
the end of the array. After the rst pass, the array will be -
13 26 32 10 35
Now, move to the second iteration.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 65/105
Second Pass
The same process will be followed for the second iteration.
13 26 32 10 35
13 26 32 10 35
Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -
13 26 10 32 35
Now, move to the third iteration.
Third Pass
The same process will be followed for the third iteration.
13 26 10 32 35
13 26 10 32 35
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -
13 10 26 32 35
13 10 26 32 35
13 10 26 32 35
Now, move to the fourth iteration.
The fourth pass
Similarly, after the fourth iteration, the array will be -
13 10 26 32 35
Here, 10 is smaller than 13. So, swapping is required. After swapping, the array will be -
10 13 26 32 35
Hence, there is no swapping required, so the array is completely sorted.
Program: Write a program to implement bubble sort in C language.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 66/105
#include<stdio.h> void print(int a[], int n) //function to print array
elements
{ int
i;
for(i = 0; i < n; i++)
{ printf("%d ",a[i]);
}
}
void bubble(int a[], int n) // function to implement bubble sort
{ int i, j, temp; for(i = 0;
i < n; i++)
{ for(j = i+1; j < n; j++)
{ if(a[j] < a[i])
{ temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void main ()
{ int i, j, temp; int
a[5] = { 10, 35,
32, 13, 26}; int
n =
sizeof(a)/sizeof(
a[0]);
printf("Before
sorting array
elements are -
n"); print(a, n);
bubble(a, n);
printf("nAfter sorting array elements are - n"); print(a, n);
}
Output:
Before sorting array element are -
10 35 32 13 26
After sorting array element is 10 13 26
32 35
Insertion Sort:
● Insertion sort is an in-place sorting algorithm.
● It is inspired by the way in which we sort playing cards.
● In the insertion sort algorithm, every iteration moves an element from the unsorted portion to the
sorted portion until all the elements are sorted in the list.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 67/105
Step-by-Step Process:
● Assume that the rst element in the list is in the sorted portion and all the remaining elements are in
the unsorted portion.
● Take the rst element from the unsorted portion and insert that element into the sorted portion in the
order speci ed.
● Repeat the above process until all the elements from the unsorted portion are moved into the sorted
portion.
Working of Insertion sort Algorithm:
Now, let's see the working of the insertion sort Algorithm.
Let the elements of the array be -
12 31 25 8 32 17
Initially, the rst two elements are compared in insertion sort.
12 31 25 8 32 17
Here, 31 is greater than 12. That means both elements are already in ascending order. So, for now, 12 is stored
in a sorted sub-array.
12 31 25 8 32 17
Now, move to the next two elements and compare them.
12 31 25 8 32 17
Here, 25 is smaller than 31. So, 31 is not in the correct position. Now, swap 31 with 25.
Along with swapping,
For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence, the sorted array
remains sorted after swapping.
12 25 31 8 32 17
Now, two elements in the sorted array are 12 and 25. Move forward to the next elements which are 31 and 8.
12 25 31 8 32 17
Both 31 and 8 are not sorted. So, swap them.
12 25 8 31 32 17
Now, elements 12 & 25, and 8 are unsorted. So, swap them.
8 12 25 31 32 17
Now, the sorted array has three items that are 8, 12, and 25. Move to the next items that are 31 and 32.
8 12 25 31 32 17
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 68/105
Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31. Move to the next elements
which are 32 and 17.
8 12 25 31 32 17
17 is smaller than 32, 31 & 25. So, swap them.
8 12 17 25 32 32
Now, the array is completely sorted.
Program: Write a program to implement insertion sort in C language.
#include <stdio.h>
void insert(int a[], int n) /* function to sort an aay with insertion sort */
{ int i, j, temp; for (i = 1; i <
n; i++) {
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position
ahead from their current position*/
{ a[j+1] = a[j]; j =
j-1;
}
a[j+1] = temp;
}
}
void printArr(int a[], int n) /* function to print the array */
{ int i;
for (i = 0; i < n; i++) printf("%d ",
a[i]);
}
int main()
{ int a[] = { 12, 31, 25, 8, 32, 17 }; int n =
sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - n"); printArr(a,
n); insert(a, n);
printf("nAfter sorting array elements are - n"); printArr(a, n);
return 0;
}
Output:
Before sorting array element are -
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 69/105
12 31 25 8 32 17
After sorting array element are 8 12 17
25 31 32
Selection Sort:
● It is also the simplest algorithm.
● It is an in-place comparison sorting algorithm.
● In this algorithm, the array is divided into two parts, the rst is the sorted part, and another one is the
unsorted part.
● Initially, the sorted part of the array is empty, and the unsorted part is the given array.
● Sorted part is placed at the left, while the unsorted part is placed at the right.
Step-by-step Process:
● It nd the rst smallest element.
● It swaps it with the rst element of the unordered list.
● It nd the second smallest element.
● It swaps it with the second element of the unordered list.
● Similarly, it continues to sort the given elements.
Working of Selection sort Algorithm:
Let the elements of the array be -
12 29 25 8 32 17 40
At present, 12 is stored at the rst position, after searching the entire array, it is found
So, swap 12 with 8. After the rst iteration, 8 will appear at the rst position in the sorted array.
8 29 25 12 32 17 40
At present, 29 is stored at the second position, after searching the entire array, it is found that 12 is the second
smallest value.
8 29 25 12 32 17 40
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the sorted array.
8 12 25 29 32 17 40
The same process is applied to the rest of the array elements. Now, we are showing a pictorial representation
of the entire sorting process.
8 12 25 29 32 17 40
8 12 17 29 32 25 40
8 12 17 29 32 25 40
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 70/105
8 12 17 25 32 29 40
8 12 17 25 32 29 40
8 12 17 25 29 32 40
8 12 17 25 29 32 40
8 12 17 25 29 32 40
8 12 17 25 29 32 40
Now, the array is completely sorted.
Program: Write a program to implement selection sort in C language.
#include <stdio.h>
void selection(int arr[], int n)
{ int i, j, small;
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array
for (j = i+1; j < n; j++) if
(arr[j] < arr[small])
small = j;
// Swap the minimum element with the rst element int temp =
arr[small]; arr[small] = arr[i]; arr[i] = temp;
}
}
void printArr(int a[], int n) /* function to print the array */
{ int i; for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{ int a[] = { 12, 29, 25, 8, 32, 17, 40 }; int n = sizeof(a) /
sizeof(a[0]); printf("Before sorting array elements are -
n"); printArr(a, n); selection(a, n);
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 71/105
printf("nAfter sorting array elements are - n"); printArr(a, n);
return 0;
}
Output:
Before sorting array elements are -
12 29 25 8 32 17 40
After sorting array elements are -
8 12 17 25 29 32 40
SIT Sitamarhi Desire
The More You Practice, The Better You Get.
Pointers
Pointers:
● The pointer in C language is a variable which stores the address of another variable.
● This variable can be of type int, char, array, function, or any other pointer.
● The size of the pointer depends on the architecture. However, in 32-bit architecture, the size of a
pointer is 2 byte.
● The asterisk * used to declare a pointer is the same
asterisk used for multiplication.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 72/105
Example: To de ne a pointer that stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Declaring a pointer: The pointer in c language can be declared using * (asterisk symbol). It is also known as
an indirection pointer used to dereference a pointer.
int *a;//pointer to int char
*c;//pointer to char
Advantage of Pointer:
● Pointers in C Programming are helpful to access a memory location ● Pointers are an effective way to
access the array structure elements ● Pointers are used for the allocation of dynamic memory.
● Pointers are used to build complicated data structures like a linked list, graph, trees, etc
Application of Pointer:
● To pass arguments by reference.
● For accessing array elements.
● To return multiple values.
● Dynamic memory allocation.
● To implement data structures.
● To do system-level programming where memory addresses are useful.
Example
An example of using pointers to print the address and value is given below.
As you can see in the above gure, the pointer variable stores the address of the number variable, i.e., fff4. The
value of the number variable is 50. But the address of pointer variable p is aaa3.
With the help of * (indirection operator), we can print the value of the pointer variable p.
Let's see the example as explained in the above gure.
#include<stdio.h> int
main(){
int number=50; int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x n",p); // p contains the address of the number, therefore, printing p gives
the address of number.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 73/105
printf("Value of p variable is %d n",*p); // As we know that * is used to dereference a pointer therefore if we
print *p, we will get the value stored at the address contained by p.
return 0;
}
Output:
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Type of Pointer:
There are majorly four types of pointers, they are:
● Null Pointer: If you assign a NULL value to a pointer during its declaration, it is called Null Pointer.
● Void Pointer: When a pointer is declared with a void keyword, then it is called a void pointer. To print
the value of this pointer, you need to typecast it.
● Wild Pointer: A wild pointer is only declared but not assigned an address of any variable. They are
very tricky, and they may cause segmentation errors.
● Dangling Pointer: Suppose there is a pointer p pointing at a variable at memory 1004. If you
deallocate this memory, then this p is called a dangling pointer. You can deallocate memory using a
free() function.
There are two types of memory in our machine● Static
Memory
● Dynamic Memory
Both memories are managed by our Operating System. Our operating system helps us in the allocation and
deallocation of memory blocks either during compile-time or during the run-time of our program.
Static Memory Allocation: When the memory is allocated during compile-time it is stored in the Static
Memory and it is known as Static Memory Allocation,
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 74/105
Dynamic Memory Allocation: when the memory is allocated during run-time it is stored in the Dynamic
Memory and it is known as Dynamic Memory Allocation.
Differences between Static Memory Allocation and Dynamic Memory Allocation.
Static Memory Allocation Dynamic Memory Allocation
Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while
executing a program
Memory can be increased while
executing the program
Used in the array. Used in link-list.
Stack space is used in Static Memory
Allocation.
Heap space is used in Dynamic Memory
Allocation.
We can't allocate or deallocate a memory block
during run-time.
We can allocate and deallocate a memory block
during run-time.
It doesn't provide reusability of memory while the
program is running. So, it is less efficient.
It provides reusability of memory while the program
is running. So, it is more efficient.
Dynamic memory allocation in C: The concept of dynamic memory allocation in c language enables the
C programmer to allocate memory at runtime.
Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header le.
● malloc() ● calloc()
● realloc()
● free()
malloc() function:
● The malloc() function allocates single block of requested memory.
● It doesn't initialize memory at execution time, so it has a garbage value initially.
● It returns NULL if memory is not sufficient.
Syntax:
ptr=(cast-data-type*)malloc(byte-size) Or
int *ptr = (int *)malloc(sizeof(int));
Example:
#include<stdio.h>
#include<stdlib.h> int
main(){
int n,i,*ptr,sum=0; printf("Enter a number of
elements: "); scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc if(ptr==NULL)
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 75/105
{ printf("Sorry! unable to allocate memory"); exit(0);
}
printf("Enter elements of an array: "); for(i=0;i<n;++i)
{ scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d", sum);
free(ptr);
return 0;
}
Output:
Enter the a number of elements: 3
Enter elements of an array: 10
10
10 Sum =
30
calloc() function:
● The calloc() function allocates multiple blocks of requested memory.
● It initially initialize all bytes to zero.
● It returns NULL if memory is not sufficient.
Syntax:
ptr=(cast-data-type*)calloc(number, byte-size)
Example:
#include<stdio.h> #include<stdlib.h>
int main(){
int n, i,*ptr,sum=0; printf("Enter a number of elements: "); scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc if(ptr==NULL)
{ printf("Sorry! unable to allocate memory"); exit(0);
}
printf("Enter elements of an array: ");
for(i=0; i<n;++i)
{ scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d", sum);
free(ptr);
return 0;
}
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 76/105
Output:
Enter elements of an array: 3
Enter elements of an array: 10
10
10 Sum =
30
realloc() function:
● If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function.
● “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory.
● If the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory.
Syntax:
ptr=realloc(ptr, new-size)
Example:
#include <stdio.h> #include
<stdlib.h>
int main() {
int *ptr, i , n1, n2; printf("Enter size: ");
scanf("%d", &n1); ptr = (int*) malloc(n1 *
sizeof(int));
printf("Addresses of previously allocated memory:n"); for(i = 0; i < n1;
++i)
printf("%pcn", ptr + i);
printf("nEnter the new size: "); scanf("%d", &n2);
// rellocating the memory ptr =
realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory:n");
for(i = 0; i < n2; ++i)
printf("%pcn", ptr + i); free(ptr);
return 0;
}
Output:
Enter size: 2
Addresses of previously allocated memory:
26855472
26855476
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 77/105
Enter the new size: 4
Addresses of newly allocated memory:
26855472
26855476
26855480
26855484
free() function:
● The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until the program exit.
Syntax: free(ptr)
String:
● The string can be de ned as the one-dimensional array of characters terminated by a null ('0').
● The character array or the string is used to manipulate text such as words or sentences.
● Each character in the array occupies one byte of memory, and the last character must always be 0.
● The termination character ('0') is important in a string since it is the only way to identify where the
string ends.
There are two ways to declare a string in c language.
1. By char array
2. By string literal
Example of declaring string by char array in C language.
While declaring a string, size is not mandatory. So we can write the code. char ch[10]={'e', 'd', 'u',
'd', 'e', 's', 'i', 'r', 'e', '0'};
As we know, array index starts from 0, so it will be represented as in the gure given below.
Index-> 0 1 2 3 4 5 6 7 8 9
String-> e d u d e s i r e 0
We can also de ne the string by the string literal in C language. For example:
char ch[]="edudesire";
In such case, '0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
Char array String literal
We need to add the null character '0' at the end of
the array.
In such a case, '0' will be appended at the end of the
string by the compiler.
we can reassign the characters of the array.
We cannot be reassigned to another set of
characters
Simple example where a string is declared and being printed. The '%s' is used as a format speci er for the
string in the c language.
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 78/105
#include<stdio.h> #include
<string.h>
int main(){
char ch[10]={'e', 'd', 'u', 'd', 'e', 's', 'i', 'r', 'e', '0'};
char ch2[10]="edudesire";
printf("Char Array Value is: %sn", ch); printf("String Literal
Value is: %sn", ch2);
return 0;
}
Output:
Char Array Value is: edudesire String Literal
Value is: edudesire
Traversing String:
● Traversing the string is one of the most important aspects in any of the programming languages.
● We may need to manipulate a very large text which can be done by traversing the text.
There are two ways to traverse a string. 1. By using
the length of string
2. By using the null character.
Using the length of the string:
Example of counting the number of vowels in a string.
#include<stdio.h>
void main ()
{
char s[10] = "edudesire";
int i = 0; int
count = 0;
while(i<10)
{ if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d", count);
}
Output
The number of vowels 5
Using the null character:
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 79/105
Example of counting the number of vowels by using the null character.
#include<stdio.h> void main
()
{
char s[10] = "edudesire";
int i = 0; int count = 0;
while(s[i] != NULL)
{ if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d", count);
}
Output
The number of vowels 4
Pointers with strings:
We have used pointers with the array, functions, and primitive data types so far.
However, pointers can be used to point to the strings.
The following example is to access the string via the pointer.
#include<stdio.h> void main
()
{
char s[10] = "edudesire"; char *p = s; // pointer p is pointing to string s.
printf("%s",p); // the string edudesire is printed if we print p.
}
Follow me Sit Desire )
YouTube Facebook Instagram Telegram Page 80/105
Output: edudesire
Index-> 0 1 2 3 4 5 6 7 8 9
Value-> e d u d e s i r e 0
Address-> 50 51 52 53 54 55 56 57 58 59
String Functions:
There are many important string functions de ned in "string.h" library.
String Length: strlen()
The stredudesirelen() function returns the length of the given string. It doesn't count the null
character '0'.
#include<stdio.h> #include
<string.h>
int main(){
char ch[20]={'e', 'd', 'u', 'd', 'e', 's', 'i', 'r', 'e', '0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:
Length of string is: 9
Copy String: strcpy()
The strcpy(destination, source) function copies the source string in the destination.
#include<stdio.h> #include
<string.h> int main(){
char ch1[20]={'e', 'd', 'u', 'd', 'e', 's', 'i', 'r', 'e', '0'}; char
ch2[20]; strcpy(ch2,ch1);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: edudesire
String Concatenation: strcat()
Variable-> ptr
Value-> 50
Address-> 101
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving
Programming for Problem Solving

More Related Content

Similar to Programming for Problem Solving

Computer Hardware and Software Elements
Computer Hardware and Software ElementsComputer Hardware and Software Elements
Computer Hardware and Software ElementsAdetula Bunmi
 
Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...
Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...
Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...SaffaIbrahim1
 
computer Systems & Memory .pptx
 computer Systems & Memory .pptx computer Systems & Memory .pptx
computer Systems & Memory .pptxafnanalkafre
 
The functionality of a pc
The functionality of a pcThe functionality of a pc
The functionality of a pcWaleed Alharbi
 
digital computers.ppt
digital computers.pptdigital computers.ppt
digital computers.pptnwelay6
 
Basics Of Computers | The Computer System
Basics Of Computers | The Computer SystemBasics Of Computers | The Computer System
Basics Of Computers | The Computer SystemNehaRohtagi1
 
Computer Organization and Architecture.pptx
Computer Organization and Architecture.pptxComputer Organization and Architecture.pptx
Computer Organization and Architecture.pptxAshokRachapalli1
 
Introduction to Computer UNIT 1 notes.pdf
Introduction to Computer UNIT 1 notes.pdfIntroduction to Computer UNIT 1 notes.pdf
Introduction to Computer UNIT 1 notes.pdfshubhangisonawane6
 
Computer Organisation unit 1 basics of computer Organisation
Computer Organisation unit 1 basics of computer OrganisationComputer Organisation unit 1 basics of computer Organisation
Computer Organisation unit 1 basics of computer Organisationluckyanirudhsai
 
Computer Archeticture
Computer ArchetictureComputer Archeticture
Computer Archeticturemahmoud
 
Cpu introduction to computer
Cpu introduction to computerCpu introduction to computer
Cpu introduction to computerBRS ENGINEERING
 
Unit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptx
Unit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptxUnit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptx
Unit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptxknowledge2intelligen
 

Similar to Programming for Problem Solving (20)

Computer Hardware and Software Elements
Computer Hardware and Software ElementsComputer Hardware and Software Elements
Computer Hardware and Software Elements
 
Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...
Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...
Computer Architecture in Organisation - COMP 3114 - LECTURE NOTES - 2023-2024...
 
computer Systems & Memory .pptx
 computer Systems & Memory .pptx computer Systems & Memory .pptx
computer Systems & Memory .pptx
 
Computer.pptx
Computer.pptxComputer.pptx
Computer.pptx
 
The functionality of a pc
The functionality of a pcThe functionality of a pc
The functionality of a pc
 
digital computers.ppt
digital computers.pptdigital computers.ppt
digital computers.ppt
 
Basics Of Computers | The Computer System
Basics Of Computers | The Computer SystemBasics Of Computers | The Computer System
Basics Of Computers | The Computer System
 
Computer Organization and Architecture.pptx
Computer Organization and Architecture.pptxComputer Organization and Architecture.pptx
Computer Organization and Architecture.pptx
 
Co notes3 sem
Co notes3 semCo notes3 sem
Co notes3 sem
 
1 introduction-to-computer
1 introduction-to-computer1 introduction-to-computer
1 introduction-to-computer
 
Ntroduction to computer architecture and organization
Ntroduction to computer architecture and organizationNtroduction to computer architecture and organization
Ntroduction to computer architecture and organization
 
Introduction to Computer UNIT 1 notes.pdf
Introduction to Computer UNIT 1 notes.pdfIntroduction to Computer UNIT 1 notes.pdf
Introduction to Computer UNIT 1 notes.pdf
 
Computer Organisation unit 1 basics of computer Organisation
Computer Organisation unit 1 basics of computer OrganisationComputer Organisation unit 1 basics of computer Organisation
Computer Organisation unit 1 basics of computer Organisation
 
Computer Archeticture
Computer ArchetictureComputer Archeticture
Computer Archeticture
 
Cpu introduction to computer
Cpu introduction to computerCpu introduction to computer
Cpu introduction to computer
 
Lecture 2 - Introductory Concepts
Lecture 2 - Introductory ConceptsLecture 2 - Introductory Concepts
Lecture 2 - Introductory Concepts
 
computer Unit 1
computer Unit 1computer Unit 1
computer Unit 1
 
Unit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptx
Unit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptxUnit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptx
Unit 1-PROBLEM SOLVING AND PYTHON PROGRAMMING R2021.pptx
 
CP Handout#1
CP Handout#1CP Handout#1
CP Handout#1
 
Computer lessons 2
Computer lessons 2Computer lessons 2
Computer lessons 2
 

More from Sitamarhi Institute of Technology (20)

Project Front_Page.pdf
Project Front_Page.pdfProject Front_Page.pdf
Project Front_Page.pdf
 
Module 1.pdf
Module 1.pdfModule 1.pdf
Module 1.pdf
 
Module 5.pdf
Module 5.pdfModule 5.pdf
Module 5.pdf
 
Module 6.pdf
Module 6.pdfModule 6.pdf
Module 6.pdf
 
Module 7.pdf
Module 7.pdfModule 7.pdf
Module 7.pdf
 
Module 2.pdf
Module 2.pdfModule 2.pdf
Module 2.pdf
 
Module 3.pdf
Module 3.pdfModule 3.pdf
Module 3.pdf
 
Module 4.pdf
Module 4.pdfModule 4.pdf
Module 4.pdf
 
short notes bio
short notes bioshort notes bio
short notes bio
 
Photosynthesis.pptx
Photosynthesis.pptxPhotosynthesis.pptx
Photosynthesis.pptx
 
Concept of Allele.pptx
Concept of Allele.pptxConcept of Allele.pptx
Concept of Allele.pptx
 
Genetics.pptx
Genetics.pptxGenetics.pptx
Genetics.pptx
 
8m Biology.pdf
8m Biology.pdf8m Biology.pdf
8m Biology.pdf
 
Module 5.pptx
Module 5.pptxModule 5.pptx
Module 5.pptx
 
Mendel’s experiment.pptx
Mendel’s experiment.pptxMendel’s experiment.pptx
Mendel’s experiment.pptx
 
microbiology.pptx
microbiology.pptxmicrobiology.pptx
microbiology.pptx
 
BIOLOGY 7sem.pdf
BIOLOGY 7sem.pdfBIOLOGY 7sem.pdf
BIOLOGY 7sem.pdf
 
Heirarchy of life forms and classification.pptx
Heirarchy of life forms and classification.pptxHeirarchy of life forms and classification.pptx
Heirarchy of life forms and classification.pptx
 
Amino acids and proteins.pptx
Amino acids and proteins.pptxAmino acids and proteins.pptx
Amino acids and proteins.pptx
 
BIO.docx
BIO.docxBIO.docx
BIO.docx
 

Recently uploaded

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 

Recently uploaded (20)

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 

Programming for Problem Solving

  • 1. 0
  • 2. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 1/105 THE C PROGRAMMING FOR PROBLEM-SOLVING Compiled by Er. SAROJ KUMAR SIT Sitamarhi Desire Sitamarhi institute of Technology The More You Practice, The Better You Get. Follow me Disclaimer: While compiled by the book have made every effort to avoid any mistakes or omissions and have used their skill, expertise, and knowledge to the best of my capacity to provide accurate and updated information. Any mistake, or error noted may be brought to the notice of the book provider which shall be taken care of in the next edition. The compiled book expressly disclaims all and any liability/ responsibility to any person whether a purchaser or reader of this book or not. In respect of anything and everything forming part of the content of this book. It is notified that neither that book provider nor the Compiled by book will be responsible for any damage or loss to anyone of any kind in any manner therefrom.
  • 3. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 2/105 Further, the appearance of the personal name location place, and incidence, if any; in the illustrations used herein is purely coincidental and a work of imagination. Thus the same should in no manner be termed as defamatory to any individual. Ownership of Content: In this pdf, I’m taking references from different platforms if you want more information about any topic then you can take this reference we describe the website Name and link hereJatatpoint Tutorialspoint Geeksforgeeks Efacility Programiz Scaler W3schools Study tonight Guru99 This pdf is only design for B.Tech, BCA, MCA and polytechnic student of all Engineering Collage. This pdf provides help in the exam time for a quick revision in sorting the time. Unit Syllabus unit-1 Introduction to Components of a Computer System: Memory, Processor, I/O Devices, Storage, Operating System, Concept of Assembler, Compiler, Interpreter, Loader, and Linker. The idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo Code with Examples, From Algorithms to Programs, Source Code. Programming Basics: Structure of C Program, Writing and Executing the First C Program, Syntax and Logical Errors inCompilation, Object and Executable Code. Components of C Language. Standard I/O in C, Fundamental Data types, Variables and Memory Locations, Storage Classes. Unit-2 Arithmetic Expressions and Precedence: Operators and Expression Using Numeric and Relational Operators, Mixed Operands, Type Conversion, Logical Operators, Bit Operations, Assignment Operator, Operator precedence, and Associatively. Conditional Branching: Applying if and Switch Statements, Nesting if and Else and Switch.
  • 4. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 3/105 Unit-3 Iteration and Loops: Use of While, do While, and for Loops, Multiple Loop Variables, Use of Break, Goto and Continue Statements. Arrays: Array Notation and Representation, Manipulating Array Elements, using Multi-Dimensional Arrays. Character Arrays and Strings, Structure, union, Enumerated Data types, Array of Structures, Passing Arrays to Functions. Unit-4 Functions: Introduction, Types of Functions, Functions with Array, Passing Parameters to Functions, Call by Value, Call by Reference, Recursive Functions. Basic of searching and Sorting Algorithms: Searching & Sorting Algorithms ( Linear Search, Binary search, Bubble Sort, Insertion, and Selection Sort) Unit-5 Pointers: Introduction, Declaration, Applications, Introduction to Dynamic Memory Allocation (Malloc, Calloc, Realloc, Free), String and String functions, Use of Pointers in Self-Referential Structures, Notion of Linked List (No Implementation) File Handling: File I/O Functions, Standard C Preprocessors, De ning and Calling Macros and Command-Line Arguments. Table of Content Content Page no Introduction 02 Syllabus 03 Table of Content 04-06 Unit-1 (Component of a Computer System and Basic Programming) 07-25 Introduction to Component of a Computer System 07-13 Memory and its Type, Memory unit 07-08 Central Processing Unit(CPU) 08-09 I/O Device 09-10 Operating System, Assembler, compiler, Linker and Loader 10-13
  • 5. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 4/105 The idea of The Algorithm 13-15 Introduction to Algorithms 13-14 Flowchart, Pseudo-code 14-15 Programming Basic 15-25 C Programming introduction 15-16 Structure of the c Program 16-17 Programming Error in C 17-18 Component of C program 18-19 Variable and its Type 19-20 Data Type in C 21-22 Storage Class and it’s Type 22-25 Unit-2 (Arithmetic Expression, Conditional Branching) Precedence, and 26-43 Arithmetic Expessions and Precedence 26-33 Operator in C and its Type 26-30 Precedence of Operators in C 30-31 Type conversion 31-33 Conditional Branching 33-43 Conditions statement 33 If statement 33-35 If else Statement 35-37 If else if ladder Statement 37-39 Nested if else statement 39-41 Switch case Statement 41-43
  • 6. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 5/105 Unit-3 (Loops And Arrays) 44-58 Iteration And Loops 44-53 Loop and its Type 44-51 Break Statement 51-52 Continue Statement 52 Goto Statement 53 Arrays 54 Array Introduction 54 One-Dimensional Array 54-55 Two-Dimensional Array 55-57 Multi-Dimensional Array 57 Passing array to function 57-58 Unit-4(Functions, Algorithms) Basic Searching and Sorting 59-80 Functions 59-69 Function Introduction 59-60 Type of Function 60-62 C Library function 62 Call by Value 63-64 Call by reference 64-66 Recursion Functions 66-68 Basic Searching And Sorting Algorithms 69-80 Searching Algorithm 69 Linear Search 69-70
  • 7. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 6/105 Binary Search 70-71 Sorting Algorithms 72 Bubble Sort 72-75 Insertion Sort 75-77 Selection Sort 78-80 Unit-5 (Pointers and File Handling) 81-105 Pointers 81-96 Introduction of Pointer 81-82 Type of Pointer 83 Dynamic Memory allocation in C 84-98 Traversing Strings 89-91 String Function 91-95 Self Referential structure 95-96 Notation of Linked-list 96 File Handling 96-105 Introduction 96 File I/O Functions 97-99 C Preprocessor 99-100 C Macros 100-101 Preprocessor Operator 102-103 Command-Line Arguments 103-104
  • 8. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 7/105 Introduction to Components of a Computer System Memory: ● A memory is 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 the education required for processing is stored. ● Memory is divided into a large number of small parts called cells. Each location or cell has a unique address, which varies from zero to memory size minus one. Memory is primarily of three types − ● Cache Memory ● Primary Memory/Main Memory ● Secondary Memory Cache Memory: Cache memory is high-speed memory, which is small in size but faster than the mainmemory (RAM). The CPU can access it more quickly than the primary memory. So, it is used to synchronize with high- speed CPU and to improve its performance. Primary 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 devices. These memories are not as fast as registers. ● It is divided into two subcategories RAM and ROM. 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. ● The contents of secondary memories are rst transferred to the main memory, and then the CPU can access it. For example disk, CD-ROM, DVD, etc. Memory Unit: Memory units are used to measure and represent data. Some of the commonly used memory units are- ● Bit: The computer memory units start from bit. A bit is the smallest memory unit to measure data stored in main memory and storage devices. A bit can have only one binary value out of 0 and 1. ● Nibble: A group of 4 bits is called a nibble.
  • 9. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 8/105 ● Byte: It is the fundamental unit to measure data. It contains 8 bits or is equal to 8 bits. Thus a byte can represent 2*8 or 256 values. ● Kilobyte: A kilobyte contains 1024 bytes. ● Megabyte: A megabyte contains 1024 kilobytes. ● Gigabyte: A gigabyte contains 1024 megabytes. ● Terabyte: A terabyte contains 1024 gigabytes. ● PetaByte (PB): 1 PB = 1024 TB Central Processing Unit(CPU): A Central Processing Unit is also called a processor, central processor, or microprocessor. Central Processing Unit (CPU) consists of the following features − ● CPU is considered the brain of the computer. ● CPU performs all types of data processing operations. ● It stores data, intermediate results, and instructions (program). ● It controls the operation of all parts of the computer. Generally, a CPU has three components: ● ALU (Arithmetic Logic Unit) ● Control Unit ● Memory or Storage Unit Memory Unit: ● It stores all the data and the instructions required for processing. ● It stores intermediate results of processing. ● It stores the nal results of processing before these results are released to an output device. ● All inputs and outputs are transmitted through the main memory. Control Unit: ● It is responsible for controlling the transfer of data and instructions among other units of a computer. ● It manages and coordinates all the units of the computer. ● It obtains the instructions from the memory, interprets them, and directs the operation of the computer. ● It communicates with Input/Output devices for the transfer of data or results from storage. ● It does not process or store data.
  • 10. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 9/105 Arithmetic Logic Unit(ALU): This unit consists of two subsections namely, ● Arithmetic Section ● Logic Section Arithmetic Section: It is to perform arithmetic operations like addition, subtraction, multiplication, and division. All complex operations are done by making repetitive use of the above operations. Logic Section: It is to perform logic operations such as comparing, selecting, matching, and merging data. I/O devices: Input Device: The input device enables the user to send data, information, or control signals to a computer. The Central Processing Unit (CPU) of a computer receives the input and processes it to produce the output. ● Keyboard ● Mouse ● Joy Stick ● Light pen ● Track Ball ● Scanner ● Graphic Tablet ● Microphone ● Magnetic Ink Card Reader(MICR) ● Optical Character Reader(OCR) ● Bar Code Reader ● Optical Mark Reader(OMR) Output Device: The output device displays the result of the processing of raw data that is entered into the computer through an input device. There are a number of output devices that display output in different ways such as text, images, hard copies, and audio or video. Some of the popular output devices are 1. Monitor a. CRT Monitor b. LCD Monitor c. LED Monitor d. Plasma Monitor 2. Printer a. Impact Printers i. Character Printers 1. Dot Matrix printers b. Non-impact printers i. Laser printers ii. Inkjet printers 3. Projector 4.
  • 11. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 10/105 Operating System: ● An Operating System can be de ned as an interface between the user and hardware. ● An operating system is a program that acts as an interface between the software and the computer hardware. Characteristics of Operating System: 1. Process Management 2. Memory Management 3. Device Management 4. File Management 5. Security Assembler: An assembler translates assembly language programs into machine code. The output of an assembler is called an object le, which contains a combination of machine instructions as well as the data required to place these instructions in memory. Compiler: A compiler is a special program that translates a programming language's source code into machine code or another programming language. The source code is typically written in a high-level, human-readable language such as Java or C++.
  • 12. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 11/105 Linker: Linker is a computer program that links and merges various object les together in order to make an executable le. All these les might have been compiled by separate assemblers. Loader: The loader is a part of the operating system and is responsible for loading executable les into memory and executing them. It calculates the size of a program (instructions and data) and creates memory space for it. It initializes various registers to initiate execution. Difference between a linker and a loader − Linker Loader The linker generates executable les of a source program. The loader is to load the executable module to the main memory. An assembler generates the object code, which is taken as input by the linker. The linker creates the executable module, which is taken by the loader. To generate an executable code, the linker combines all the object modules and source code. In the main memory, it loads executable codes for further execution. Linkage Editors and Dynamic linkers are the two types of linkers. Absolute loading, Dynamic Run-time loading, and Relocatable loading are three kinds of the loader. Combining all object modules is another use of a linker. The loader allocates the address to executable les. Difference between the Compiler and the Interpreter.−
  • 13. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 12/105 Compiler Interpreter A compiler translates the entire source code in a single run. An interpreter translates the entire source code line by line. It consumes less time i.e., it is faster than an interpreter. It consumes much more time than the compiler i.e., it is slower than the compiler. It is more efficient. It is less efficient. CPU utilization is more. CPU utilization is less compared to the compiler. The compiler is larger. Interpreters are often smaller than compilers. It is not exible. It is exible. The compiler is used in languages such as C, and C++. An interpreter is used in languages such as Java. Both syntactic and semantic errors can be checked simultaneously. Only syntactic errors are checked. The idea of the Algorithm Algorithm: An Algorithm is a speci cation of steps that are required to solve a particular problem. Characteristics of an Algorithm:
  • 14. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 13/105 ● Unambiguous − The algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning. ● Input − An algorithm should have 0 or more well-de ned inputs. ● Output − An algorithm should have 1 or more well-de ned outputs and should match the desired output. ● Finiteness − Algorithms must terminate after a nite number of steps. ● Feasibility − This should be feasible with the available resources. ● Independent − An algorithm should have step-by-step directions, which should be independent of any programming code. Example: Step 1 − Start Step 2 − declare three integers x, y & z Step 3 − de ne values of x & y Step 4 − multiply values of x & y Step 5 − store the result of step 4 to z Step 6 − print z Step 7 − Stop The algorithm can be represented using a owchart or a pseudo-code. Flowchart: A owchart is a graphical representation of an algorithm. Example of owcharts: 1. Add two numbers entered by the user.
  • 15. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 14/105 2. Find the largest among three different numbers entered by the user. Pseudo-Code: A pseudo-code is an intermediate between human language and a programming language. Examples: If the student's grade is greater than or equal to 60 Print "passed" or else Print "failed"
  • 16. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 15/105 Programming Basics C programming: ● C language combines the power of a low-level language and a high-level language. ● C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. ● low-level languages are used for system programming, while high-level languages are used for application programming. ● It is because such languages are exible and easy to use. ● The features of C programming make it possible to use the language for system programming, development of interpreters, compilers, operating systems, graphics, general utilities, etc. ● C is also used to write other applications, such as databases, compilers, word processors, and spreadsheets. First C Program: 1. #include <stdio.h> 2. int main(){ 3. printf("Hello Edu Desire"); 4. return 0; 5. } #include <stdio.h> includes the standard input-output library functions. The printf() function is de ned in stdio.h. int main() The main() function is the entrypoint of every program in the c language. printf() The printf() function is used to print data on the console. return 0 The return 0 statement, returns the execution status to the OS. The 0 value is used for successful execution and 1 for unsuccessful execution. Basic Structure of the C program: A C program is divided into six sections: Documentation, Link, De nition, Global Declaration, Main() Function, and Subprograms. Section Description Documentation The description of the program, programmer's name, and creation date. These are generally written in the form of comments. Link The preprocessor section contains all the header les used in a program. It informs the system to link the header les to the system libraries.
  • 17. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 16/105 De nition The de ne section comprises different constants declared using the de ne keyword. Global Declaration Includes declaration of global variables, function declarations, static global variables, and functions. Main Function For every C program, the execution starts from the main() function. It is mandatory to include a main() function in every C program. Subprograms Include all user-de ned functions (functions the user provides). They can contain inbuilt functions. Example 1: To nd the sum of two numbers given by the user 1. /* Sum of two numbers */ 2. #include<stdio.h> 3. int main() 4. { 5. int a, b, sum; 6. printf("Enter two numbers to be added "); 7. scanf("%d %d", &a, &b); 8. // calculating sum 9. sum = a + b; 10. printf("%d + %d = %d", a, b, sum); 11. return 0; // return the integer value in the sum 12. } Output: Enter two numbers to be added 3 5 3+5=8 Programming Error in C: These errors are detected either during the time of compilation or execution. Thus, the errors must be removed from the program for the successful execution of the program. There are mainly ve types of errors that exist in C programming: ● Syntax error ● Run-time error ● Linker error ● Logical error ● Semantic error Syntax Error: Syntax errors are also known as compilation errors as they occurred at the compilation time. These errors mainly occurred due to mistakes while typing when the programmer does not follow the grammar rule of the programming language. These errors can be easily corrected.
  • 18. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 17/105 For example: 1. If we want to declare the variable of type integer, 2. int a; // this is the correct form 3. Int a; // this is an incorrect form. Commonly occurred syntax errors are: ● If we miss the parenthesis (}) while writing the code. ● Displaying the value of a variable without its declaration. ● If we miss the semicolon (;) at the end of the statement. Logical Error: The logical error is an error that leads to an undesired output. These errors produce incorrect output, but they are error-free, known as logical errors. The occurrence of these errors mainly depends upon the logical thinking of the developer. Source Code: Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension. Object Code: Object code is the output of a compiler after it processes the source code. The object code is usually a machine code, also called machine language, which can be understood directly by a speci c type of CPU. Executable Code: Executable (also called the Binary) is the output of a linker after it processes the object code. A machine code le can be immediately executable, or it might require linking with other object code les (e.g. libraries) to produce a complete executable program. Component of C Program: You have seen the basic structure of a C program, so it will be easy to understand other basic building blocks of the C programming language. Token: A C program consists of various tokens and a token is either a keyword, an identi er, a constant, a string literal, or a symbol. Semicolons: In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. Given below are two different statements − printf("Hello, World! n"); return 0; Comments: Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below −
  • 19. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 18/105 /* my rst program in C */ Identi ers: ● A C identi er is a name used to identify a variable, function, or any other user-de ned item. ● An identi er starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9). ● C does not allow punctuation characters such as @, $, and % within identi ers. ● C is a case-sensitive programming language. Thus, X and x are two different identi ers in C. Keywords: The followinglist shows the reservedwords in C. These reserved words may not beused as constants or variables or any other identi er names. auto else long switch break enum register typedef case extern return union char oat short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _Packed double Whitespace in C: A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Variable in C: ● A variable is the name of the memory location. ● It is used to store data. ● Its value can be changed, and it can be reused many times. Rules for de ning variables: ● A variable can have alphabets, digits, and underscore. ● A variable name can start with the alphabet, and underscore only. It can't start with a digit. ● No whitespace is allowed within the variable name. ● A variable name must not be any reserved word or keyword, e.g. int, oat, etc. Types of Variables in C: There are many types of variables in c 1. local variable 2. global variable 3. static variable
  • 20. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 19/105 4. automatic variable 5. external variable Local Variable: A variable that is declared inside the function or block is called a local variable. 1. void function1(){ 2. int x=10;//local variable 3. } Global Variable: A variable that is declared outside the function or block is called a global variable. 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 a 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. } 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 les by using an external variable. To declare an external variable, you need to use the extern keyword. 1. extern int x=10;//external variable (also global) Data Type In C: A data type speci es the type of data that a variable can store such as integer, oating, character, etc. There are the following data types in the C language. Type Data Type Basic Data Type They are arithmetic types and are further classi ed into (a) integer types and (b) oating-point types. ● int, char, oat, double
  • 21. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 20/105 Derived Data Type They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types, and (e) Function types. Enumeration Data Type They are again arithmetic types and they are used to de ne variables that can only assign certain discrete integer values throughout the program. ● enum Void Data Type The type speci er void indicates that no value is available. Let's see the basic data types. Its size is given according to 32-bit architecture. Integer Types: The following table provides the details of standard integer types with their storage sizes and value ranges − Data Type Memory Size Range char 1 byte −128 to 127 signed char 1 byte -128 to 127 unsigned char 1 byte 0 to 255 int 2 byte −32,768 to 32,767 signed int 2 byte -32768 to 32767 unsigned int 2 byte 0 to 65,535 signed short int 2 byte −32,768 to 32,767 unsigned short int 2 byte 0 to 65,535 signed Long int 4 byte -2,147,483,648 to 2,147,483,647 unsigned Long int 4 byte 0 to 4,294,967,295 Floating-Point Types: The following table provide the details of standard oating-point types with storage sizes and value ranges and their precision − Data Type Memory Size Range oat 4 byte 1.2E-38 to 3.4E+38 double 8 bytes 2.3E-308 to 1.7E+308
  • 22. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 21/105 long double 10 bytes 3.4E-4932 to 1.1E+4932 The void Type: The void type speci es that no value is available. It is used in three kinds of situations − ● Function returns as void ● Function arguments as void ● Pointers to void Storage Classes: Storage classes in C are used to determine thelifetime, visibility, memory location, and initial value of a variable. There are four types of storage classes in C ● Automatic ● External ● Static ● Register Storage Classes Storage Place Value Scope Lifetime auto RAM Garbage Value Local Within the function extern RAM Zero Global Till the end of the main program Maybe declared anywhere in the program static RAM Zero Local Till the end of the main program, Retains value between multiple functions call register Register Garbage Value Local Within the Function The Automatic Storage Class: ● Automatic variables are allocated memory automatically at runtime. ● The visibility of the automatic variables is limited to the block in which they are de ned. ● The keyword used for de ning automatic variables is auto. ● Every local variable is automatic in C by default. Example #include <stdio.h> int main() { int a; //auto
  • 23. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 22/105 char b; oat c; printf("%d %c %f", a,b,c); // printing initial default value of automatic variables a, b, and c. return 0; } Output: garbage garbage garbage Static Storage Class: ● The variables de ned as static speci er can hold their value between the multiple function calls. ● Static local variables are visible(scope) only to the function or the block in which they are de ned. ● A same static variable can be declared many times but can be assigned at only one time. ● The keyword used to de ne static variable is static. Example #include<stdio.h> void sum() { static int a = 10; static int b = 24; printf("%d %d n",a,b); a++; b++; } void main() { int i; for(i = 0; i< 3; i++) { sum(); // The static variables hold their value between multiple function calls. } } Output: 10 24 11 25 12 26 Register Storage Class: ● The variables de ned as the register is allocated the memory into the CPU registers depending upon the size of the memory remaining in the CPU. ● The access time of the register variables is faster than the automatic variables. ● The initial default value of the register local variables is 0. ● We can store pointers in the register, i.e., a register can store the address of a variable.
  • 24. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 23/105 Example 1 #include <stdio.h> int main() { register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0. printf("%d", a); } Output: 0 External Storage Class: ● The external storage class is used to tell the compiler that the variable de ned as extern is declared with an external linkage elsewhere in the program. ● The variables declared as extern are not allocated any memory. ● The default initial value of the external integral type is 0 otherwise null. ● We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block or method. ● An external variable can be declared many times but can be initialized only once. Example 1. #include <stdio.h> 2. int a; 3. int main() 4. { 5. extern int a; // variable a is de ned globally, the memory will not be allocated to a 6. printf("%d", a); 7. } Output: 0 SIT Sitmarhi Desire The More You Practice, The Better You Get.
  • 25. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 24/105 Arithmetic Expressions and Precedence Operators in C: An operator is a symbol that tells the compiler to perform speci c mathematical or logical functions. There are the following types of operators to perform different types of operations in C language. ● Arithmetic Operators ● Relational Operators ● Logical Operators ● Bitwise Operators ● Assignment Operators ● Misc Operators Arithmetic Operators: Arithmetic Operators are the operators which are used to perform mathematical calculations. Assume variable A holds 10 and variable B holds 20 then − Operator Description Example + Adds two operands. A + B = 30 - Subtracts the second operand from the rst. A - B = -10 * Multiplies both operands. A * B = 200 / Divides numerator by de-numerator. B / A = 2 % Modulus Operator and the remainder after an integer division. B % A = 0 ++ Increment operator increases the integer value by one. A++ = 11 - - Decrement operator decreases the integer value by one. A- - = 9 Relational Operator: Relational operators are speci cally used to compare two quantities or values in a program. It checks the relationship between two operands. If the given relation is true, it will return 1 and if the relation is false, then it will return 0. Assume variable A holds 10 and variable B holds 20 then −
  • 26. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 25/105 Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true. > Checks if the value of the left operand is greater than the value of the right operand. (A > B) is not true. < Checks if the value of the left operand is less than the value of the right operand. (A > B) is true. >= Checks if the value of the left operand is greater than or equal to the value of the right operand. (A >= B) is not true. <= Checks if the value of the left operand is less than or equal to the value of the right operand. (A <= B) is true. Logical Operator: In the C programming language, we have three logical operators when we need to test more than one condition to make decisions. Assume variable A holds 1 and variable B holds 0, then − Operator Description Example && Called Logical AND operator. If both operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. !(A && B) is true. Bitwise Operator: ● Bitwise operators are the operators which work on bits and perform the bit-by-bit operation. ● Bitwise operators are especially used in C programming for performing bit-level operations. ● C programming language supports a special operator for bit operation between two variables. The truth tables for &, |, and ^ are as follows −
  • 27. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 26/105 p q p & q P | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 Here, we will assume that A = 50 and B = 25 in binary format as follows. A = 00110010 B = 00011001 ----------------- A&B = 00010000 A|B = 00111011 A^B = 00101011 ~A = 11001101 The table provided below demonstrates the bitwise operators supported by C. Assume variable 'A' holds 50 and variable 'B' holds 25. Operator Description Example & Binary AND Operator. It copies a bit to the result if it exists in both operands. (A & B) = 16, i.e. 00010000 | Binary OR Operator. It copies a bit if and only if it exists in either operand (A | B) = 59, i.e. 00111011 ^ Binary XOR Operator. It copies the bit only if it is set in one operand but not both. (A ^ B) = 43, i.e. 00101011 ~ Binary One's Complement Operator. It is unary and has the effect of ' ipping' bits. (~A ) = ~(50), i.e,. -0111101 << Binary Left Shift Operator. The value of the left operands is moved left by the number of bits speci ed by the right operand. A << 2 = 200 i.e. 11001000 >> Binary Right Shift Operator. The value of the left operands is moved right by the number of bits speci ed by the right operand. A >> 2 = 12 i.e., 00001100 Assignment Operator: An assignment operator is mainly responsible for assigning a value to a variable in a program.
  • 28. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 27/105 Operator Description Example = Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C += Add AND assignment operator. It adds the right operand to the left operand and assigns the result to the left operand. C += A is equivalent to C = C + A -= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A *= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A <<= Left shift AND assignment operator. C <<= 2 is the same as C = C << 2 >>= Right shift AND assignment operator. C >>= 2 is the same as C = C >> 2 &= Bitwise AND assignment operator. C &= 2 is the same as C = C & 2 ^= Bitwise exclusive OR and assignment operator. C ^= 2 is the same as C = C ^ 2 |= Bitwise inclusive OR and assignment operator. C |= 2 is the same as C = C | 2
  • 29. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 28/105 Misc Operator: Besides all the other operators discussed above, the C programming language also offers a few other important operators including sizeof, comma, pointer(*), and conditional operator (?:). Operator Description Example sizeof() Returns the size of a variable. sizeof(a), where a is an integer, will return 4. & Returns the address of a variable. &a; returns the actual address of the variable. * Pointer to a variable. *a; ?: Conditional Expression. If Condition is true? then value X: Otherwise, value Y Precedence of Operators in C: The precedence of operator species that which operator will be evaluated rst and next. The associativity speci es the operator directly to be evaluated; it may be left to right or right to left. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it rst gets multiplied with 3*2 and then adds into 7. Category Operator Associativity Post x () [] ->. ++ - - Left to Right Unary + - ! ~ ++ - - (type)* & sizeof Right to Left Multiplication * / % Left to Right Additive + - Left to Right Category Operator Associativity Shift << >> Left to Right Relational < <= > >= Left to Right Equality == != Left to Right Bitwise AND & Left to Right Bitwise OR | Left to Right
  • 30. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 29/105 Bitwise XOR ^ Left to Right Logical AND && Left to Right Logical OR || Left to Right Conditional ?: Right to Left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to Left Comma , Left to Right Type Conversion: Type conversion is the method to convert one data type into another data type. When we write a C program, we declare some variables and constants, if we perform some operation or write some expression, the result of that expression may be of some other type. So we need to do typecasting or type conversion in C programming. Example: #include <stdio.h> int main() { oat a = 12.3; int b = (int) a + 3; //typecasting oat to int printf("The value of b is: %d", b); return 0; } Output: The value of b is: 15 ‘C’ programming provides two types of type conversion operations: Implicit type Conversion: ● The implicit type conversion takes place when more than one data type is present in an expression. ● It is done by the compiler itself it is also called automatic type conversion. ● Here the automatic type conversion takes place in order to prevent data loss, as the datatypes are upgraded to the variable with the datatype having the largest value.
  • 31. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 30/105 Example 1 int a = 20; double b = 20.5; a + b; Here, the rst operand is int type and the other is of type double. So, as per rule 2, the variable a will be converted to double. Therefore, the nal answer is double a + b = 40.500000. Example 2 char ch='a'; int a =13; a + c; Here, the rst operand is char type and the other is of type int. So, as per rule 1, the char variable will be converted to int type during the operation and the nal answer will be of type int. We know the ASCII value for ch is 97. Therefore, the nal answer is a + c = 97 + 13 = 110. Explicit Type Conversion: ● It refers to the type conversion performed by a programmer by modifying the data type of an expression using typecasting. ● It is also Called casting in another language. It is done by a programmer. Let's start with an example. If we perform an arithmetic operation on two same types of datatype variables so the output will be in the same data type. But there are some operations like the division that can give us output in oat or double. a = 3; (int) b = 20; (int) c = b/a = 6 Here the expected output was 6.66 but a and b were integers so the output come as 6 integers. But if we need 6.66 as output we need explicit type conversion. Example: #include<stdio.h> Int main() { int a = 3; int b = 20;
  • 32. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 31/105 oat X = b/a; // without explicit type conversion printf(“without explicit type conversionL:%fn”, x); x = b/( oat)a; //with explicit type conversion printf(“with explicit type conversionL:%fn”, x); return 0; } Output: without explicit type conversion: 6.000000 without explicit type conversion: 6.666667 Conditional Branching Conditions statement: The if-else statement in C is used to perform the operations based on some speci c condition. The operations speci ed in the if block is executed if and only if the given condition is true. There are the following variants of if statement in C language. ● If statement ● If-else statement ● If else-if ladder Statement ● Nested if ● Switch statement If Statement: ● It is one of the powerful conditional statements. ● The if statement is used to check some given condition and perform some operations depending upon the correctness of that condition. ● The condition evaluates to either true or false. True is always a non-zero value, and false is a value that contains zero. The syntax of the if statement is given below. if(expression){ //code to be executed } Flowchart of if statement in C
  • 33. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 32/105 Let's see a simple example of C language if statement. #include<stdio.h> int main(){ int number=0; printf("Enter a number:"); scanf("%d",&number); if(number%2==0){ printf("%d is even number", number); } return 0; } Output Enter a number: 4 4 is even number Program to nd the largest number of the three. #include <stdio.h> int main() { int a, b, c; printf("Enter three numbers?"); scanf("%d %d %d",&a,&b,&c); if(a>b && a>c) { printf("%d is largest",a); } if(b>a && b > c) { printf("%d is largest",b);
  • 34. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 33/105 } if(c>a && c>b) { printf("%d is largest",c); } if(a == b && a == c) { printf("All are equal"); } } Output Enter three numbers? 12 23 34 34 is the largest If-else Statement: ● The if-else statement is used to perform two operations for a single condition. ● If the given condition is true, then program control goes inside the if block and executes the Statement. ● The condition is false, then program control goes inside the else block and executes the corresponding Statement. Syntax of if-else Statement if(expression){ //code to be executed if a condition is true } else{ //code to be executed if a condition is false } Flowchart of the if-else statement in C Let's see the simple example to check whether a number is even or odd using if-else statement in C language.
  • 35. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 34/105 #include<stdio.h> int main(){ int number=0; printf("enter a number:"); scanf("%d",&number); if(number%2==0){ printf("%d is even number", number); } else{ printf("%d is odd number", number); } return 0; } Output: Enter a number: 4 4 is even number Enter a number: 5 5 is odd number Program to check whether a person is eligible to vote or not. #include <stdio.h> int main() { int age; printf("Enter your age?"); scanf("%d",&age); if(age>=18) { printf("You are eligible to vote..."); } else { printf("Sorry ... you can't vote"); } } Output: Enter your age?18 You are eligible to vote... Enter your age?13 Sorry ... you can't vote If else-if ladder Statement: ● The if-else-if conditional Statement in c is used to execute one code from multiple conditions.
  • 36. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 35/105 ● In the if-else-if ladder statement, if a condition is true then the statements de ned in the if block will be executed, otherwise if some other condition is true then the statements de ned in the else-if block will be executed, at the last if none of the condition is true then the statements de ned in the else block will be executed. ● There are multiple else-if blocks possible. ● It is similar to the switch case statement. Syntax of If- else-if Ladder Statement if(condition1){ //code to be executed if condition1 is true } else if(condition2){ //code to be executed if condition2 is true } else if(condition3){ //code to be executed if condition3 is true } ... else { //code to be executed if all the conditions are false } Flowchart of else-if ladder statement in C Program to calculate the grade of the student according to the speci ed marks.
  • 37. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 36/105 #include <stdio.h> int main() { int marks; printf("Enter your marks?"); scanf("%d",&marks); if(marks > 85 && marks <= 100) { printf("Congrats ! you scored grade A ..."); } else if (marks > 60 && marks <= 85) { printf("You scored grade B + ..."); } else if (marks > 40 && marks <= 60) { printf("You scored grade B ..."); } else if (marks > 30 && marks <= 40) { printf("You scored grade C ..."); } else { printf("Sorry you are fail ..."); } } Output: Enter your marks?10 Sorry you are fail ... Enter your marks?40 You scored grade C ... Enter your marks?90 Congrats! you scored grade A ... Nested If-else Statements ● A nested if-else statement is used to check more than one condition. ● Nested if-else is also known as a multi-way selection statement. ● if the result of the given condition is True, then the Statement inside the if block is executed. ● If the given condition is false, then it will check the rst else if part, and if the condition of is true then the statements related to else if are Executed otherwise the pointer goes to the next else if, and this process is contained And if the result of the all the else if a condition is false then the pointer is automatically going to else part and the Statement of the else automatically executed. Syntax ofNested if-else Statement if(expression) { Statement
  • 38. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 37/105 } else if { // Statement } else if { //Statement } else { // Statement } Following the program to nd the greatest number among the three numbers. #include<stdio.h> #include<conio.h> void main( ) { int a,b,c; clrscr(); printf(“Please Enter three number”); scanf(“%d%d%d”,&a,&b,&c); if(a>b) { if(a>c) { printf(“a is greatest number”); } else { printf(“c is greatest number”); } } else { if(b>c) { printf(“b is greatest number”); } else { printf(“c is greatest”); } } getch(); } Output: Please Enter three number 10
  • 39. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 38/105 18 5 b is greatest Switch Case Statement: ● A switch case statement in C Programming tests the value of a choice variable and compares it with multiple cases. ● When the case match is found, a block of statements associated with that speci c case is executed. ● If a case match is not found, then the default statement is executed, and the control goes out of the switch block. The syntax of switch statement switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; } Rules for switch statement: ● Case labels must have constants or constant expressions. ● Case label must be of integral Type (Integer, Character). ● Case label should not be ‘ oat type. ‘ ● Switch case should have at most one default label ● The default label is Optional ● The default can be placed anywhere in the switch ● Break Statement takes control out of the switch ● Two or more cases may share one break statement. Flowchart of a switch statement in C
  • 40. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 39/105 Let's see a simple example of c language switch statement. #include<stdio.h> int main(){ int number=0; printf("enter a number:"); scanf("%d",&number); switch(number){ case 10: printf("number equals to 10"); break; case 50: printf("number is equal to 50"); break; case 100: printf("number is equal to 100"); break; default: printf("number is not equal to 10, 50 or 100"); } return 0; } Output: enter a number: 4 number is not equal to 10, 50 or 100 enter a number: 50 number is equal to 50
  • 41. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 40/105 SIT Sitamarhi Desire The More You Practice, The Better You Get. Iteration and Loops Loops: A loop statement allows us to execute a statement or group of statements multiple times. ● It provides code reusability. ● Using loops, we do not need to write the same code again and again. ● Using loops, we can traverse over the elements of data structures (array or linked lists). Types of C Loops: There are three types of loops. ● While loop ● Do while loop ● For loop while loop: ● While loop is also known as a pre-tested loop. ● While loop allows a part of the code to be executed multiple times depending upon a given boolean condition. ● The while loop is mostly used in cases where the number of iterations is not known in advance.
  • 42. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 41/105 The syntax of a while loop in c language is given below: while(condition){ //code to be executed } Flowchart of while loop in C Let's see the simple program of while loop that prints table of 1. #include<stdio.h> int main(){ int i=1; while(i<=10){ printf("%d n",i); i++; } return 0; } Output: 1 2 3 4 5 6 7 8 9 10 Example: #include<stdio.h> void main ()
  • 43. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 42/105 { int j = 1; while(j+=2,j<=10) { printf("%d ",j); } printf("%d",j); } Output: 3 5 7 9 11 Example: #include<stdio.h> void main () { int x = 10, y = 2; while(x+y-1) { printf("%d %d",x--,y--); } } Output: In nite loop do while loop: ● The do-while loop is a post-tested loop. ● Using the do-while loop, we can repeat the execution of several parts of the statements. ● The do-while loop is mainly used in the case where we need to execute the loop at least once. ● A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. The syntax of the C language do-while loop is given below: do{ //code to be executed } while(condition); Flowchart of do while loop
  • 44. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 43/105 Program to print table for the given number using do while loop #include<stdio.h> int main(){ int i=1,number=0; printf("Enter a number: "); scanf("%d",&number); do{ printf("%d n",(number*i)); i++; } while(i<=10); return 0; } Output: Enter a number: 2 2 4 6 8 10 12 14 16 18 20 for loop: ● The for loop in C language is used to iterate the statements or a part of the program several times. ● It is frequently used to traverse the data structures like the array and linked list. ● A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a speci c number of times. The syntax of for loop in c language is given below:
  • 45. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 44/105 for(Expression 1; Expression 2; Expression 3) { //code to be executed } Or for ( init; condition; increment ) { statement(s); } Flowchart of for loop in C Example: #include <stdio.h> int main () { int a; /* for loop execution */ for( a = 10; a < 20; a = a + 1 ){ printf("value of a: %dn", a); } return 0; } Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of
  • 46. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 45/105 a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 Nested Loops: ● C programming allows to use one loop inside another loop. ● Any number of loops can be de ned inside another loop, i.e., there is no restriction for de ning any number of loops. ● The nesting level can be de ned at n times. You can de ne any type of loop inside another loop; for example, you can de ne a 'while' loop inside a 'for' loop. Syntax of Nested loop Outer_loop { Inner_loop { // inner loop statements. } // outer loop statements. } The syntax for a nested for loop statement for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } The syntax for a nested while loop statement while(condition) { while(condition) { statement(s); } statement(s); } The syntax for a nested do...while loop statement do { statement(s); do { statement(s); }while( condition ); }while( condition );
  • 47. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 46/105 Example: Uses a nested loop to nd the prime numbers from 2 to 20 − Live Demo #include <stdio.h> int main () { /* local variable de nition */ int i, j; for(i = 2; i<20; i++) { for(j = 2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is primen", i); } return 0; } Output: 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 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 statements. ● The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop rst and then proceeds to the outer loops. The break statement in C can be used in the following two scenarios: 1. With switch case 2. With loop Syntax: //loop or switch case break; Flowchart of a break in c
  • 48. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 47/105 Consider the following example to use break statement inside while loop. #include<stdio.h> void main () { int i = 0; while(1) { printf("%d ",i); i++; if(i == 10) break; } printf("came out of while loop"); } Output: 0 1 2 3 4 5 6 7 8 9 come out of while loop 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: //loop statements continue; //some lines of the code which is to be skipped Continue statement example #include<stdio.h> int main(){ int i=1; //initializing a local variable //starting a loop from 1 to 10 for(i=1;i<=10;i++){ if(i==5){//if the value of i is equal to 5, it will continue the loop continue; } printf("%d n",i); }//end of for loop return 0; } Output: 1 2 3 4 6 7 8 9 10
  • 49. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 48/105 As you can see, 5 is not printed on the console because the loop is continued at i==5. Goto statement: ● The goto statement is known as a jump statement in C. ● The goto statement can be used to repeat some part of the code for a particular condition. ● It can also be used to break 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 complicated. Syntax: label: //some part of the code; goto label; Example: #include <stdio.h> int main() { int num,i=1; printf("Enter the number whose table you want to print?"); scanf("%d",&num); table: printf("%d x %d = %dn", num,i,num*i); i++; if(i<=10) goto table; } 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 Arrays ● Arrays a kind of data structure that can store a xed-size sequential collection of elements of the same type. ● An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. The array contains the following properties. ● Each element of an array is of the same data type and carries the same size, i.e., int = 4 bytes. ● Elements of the array are stored at contiguous memory locations where the rst element is stored at the smallest memory location.
  • 50. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 49/105 ● 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: ● Code Optimization: Less code to access the data. ● Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. ● Ease of sorting: To sort the elements of the array, we need a few lines of code only. ● Random Access: We can access any element randomly using the array. Type of Array: ● 1D Array ● 2D Array ● Multi-Dimensional Array One-Dimensional Arrays: ● A one-dimensional array in C is a list. ● Each element of the list contains only one value, whether that value be an int, char, or oat. ● To declare an array, three values are typically needed: the data type, the name of the array, and the number of elements to be contained in the array. We can declare an array in the c language in the following way. data_type array_name[array_size]; Example to declare the array 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. marks[0]=80;//initialization of array marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75; Array Example: #include<stdio.h> int main(){ int i=0; int marks[5];//declaration of array marks[0]=80;//initialization of array marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75; //traversal of an array for(i=0;i<5;i++){ printf("%d n", marks[i]); }//end of for loop
  • 51. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 50/105 return 0; } Output: 80 60 70 85 75 Two-dimensional Arrays: ● The simplest form of multidimensional array is the two-dimensional array. ● The two-dimensional array can be de ned as an array of arrays. ● The 2D array is organized as matrices which can be represented as a collection of rows and columns. ● To declare a two-dimensional integer array of size [x][y], you would write something as follows − type arrayName [ x ][ y ]. Declaration of two dimensional Array: data_type array_name[rows][columns]; Consider the following example. Column-0 Column-1 Column-2 Column-3 Row-0 A[0] [0] A[0] [1] A[0] [2] A[0] [3] Row-1 A[1] [0] A[1] [1] A[1] [2] A[1] [3] Row-2 A[2] [0] A[2] [1] A[2] [2] A[2] [3] int twodimen[3][4]; Here, 3 is the number of rows, and 4 is the number of columns. Initializing Two-Dimensional Arrays: Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; Two-dimensional array example #include<stdio.h> int main(){ int i=0,j=0; int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; //traversing 2D array for(i=0;i<4;i++){ for(j=0;j<3;j++){ printf("arr[%d] [%d] = %d n", i,j , arr[i][j]);
  • 52. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 51/105 }//end of j }//end of i return 0; } 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 Multi dimensional Arrays: C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration − type name[size1][size2]...[sizeN]; For example, the following declaration creates a three-dimensional integer array − int threedim[5][10][4]; Passing Array to Function: If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Consider the following syntax to pass an array to the function. functionname(arrayname);//passing array There are 3 ways to declare the function which is intended to receive an array as an argument. Way-1: Formal parameters as a pointer − void myFunction(int *arrayname) { . } Way-2: Formal parameters as a sized array − void myFunction(int arrayname[Size]) { . } Way-3: Formal parameters as an unsized array − void myFunction(int arrayname[]) { . }
  • 53. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 52/105 Passing an array to function example #include<stdio.h> int minarray(int arr[], int size){ int min=arr[0]; int i=0; for(i=1;i<size;i++){ if(min>arr[i]){ min=arr[i]; } }//end of for return min; }//end of function int main(){ int i=0,min=0; int numbers[]={4,5,7,3,8,9};//declaration of array min=minarray(numbers,6);//passing array with size printf("minimum number is %d n", min); return 0; } Output: Minimum number is 3 SIT Sitamarhi Desire The More You Practice, The Better You Get.
  • 54. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 53/105 Functions C Functions: ● In c, we can divide a large program into the basic building blocks known as functions. ● 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. ● A function is a group of statements that together perform a task. ● Every C program has at least one function, which is main(), and all the most trivial programs can de ne additional functions. Advantages of functions in C: There are the following advantages of C functions. ● By using functions, we can avoid rewriting the same logic/code again and again in a program. ● We can call C functions any number of times in a program and from any place in a program. ● We can track a large C program easily when it is divided into multiple functions. ● Reusability is the main achievement of C functions. Here are all the parts of a function − ● Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. ● Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. ● Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as an actual parameter or argument. The parameter list refers to the type, order, and a number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. ● Function Body: The function body contains a collection of statements that de ne what the function does. Function Aspects: There are three aspects of a C function. ● 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. Syntax: return_type function_name (argument_list); ● Function call: The function can be called from anywhere in the program. We must pass the same number of functions as it is declared in the function declaration. Syntax: function_name (argument_list); ● Function de nition: It contains the actual statements which are to be executed. Syntax: return_type function_name (argument_list){function_body}; Types of Functions: There are two types of functions in C programming:
  • 55. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 54/105 ● Library Functions: are the functions which are declared in the C header les such as scanf(), printf(), gets(), puts(), ceil(), oor(), etc. ● User-de ned 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. Example for Function without argument and return value Example 1 #include<stdio.h> void printName(); void main () { printf("Hello "); printName(); } void printName() { printf("Edu Desire"); } Output: Hello Edu Desire Example 2 #include<stdio.h> void sum(); void main() { printf("nGoing to calculate the sum of two numbers:"); sum(); } void sum() { int a,b; printf("nEnter two numbers"); scanf("%d %d",&a,&b); printf("The sum is %d",a+b); } Output: Going to calculate the sum of two numbers: Enter two numbers 20 24 The sum is 44 Example for Function with argument and without return value Example 1: a program to calculate the average of ve numbers.
  • 56. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 55/105 #include<stdio.h> void average(int, int, int, int, int); void main() { int a,b,c,d,e; printf("nGoing to calculate the average of ve numbers:"); printf("nEnter ve numbers:"); scanf("%d %d %d %d %d",&a,&b,&c,&d,&e); average(a,b,c,d,e); } void average(int a, int b, int c, int d, int e) { oat avg; avg = (a+b+c+d+e)/5; printf("The average of given ve numbers: %f",avg); } Output: Going to calculate the average of ve numbers: Enter ve numbers: 10 20 30 40 50 The average of given ve numbers: 30.000000 C 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 speci c operations. For example, printf is a library function used to print on the console. The list of the most used header les is given in the following table. Header File Description stdio.h This is a standard input/output header le. It contains all the library functions regarding standard input/output. conio.h This is a console input/output header le. string.h It contains all string related library functions like gets(), puts(),etc. math.h This header le contains all the math operations related functions like sqrt(), pow(), etc. time.h This header le contains all the time-related functions.
  • 57. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 56/105 ctype.h This header le contains all character handling functions. locale.h This le contains locale functions. stdlib.h This header le contains all the general library functions like malloc(), calloc(), exit(), etc. There are two methods to pass the data into the function in C language, i.e., ● call by value ● call by reference Call by value: ● The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. ● In other words, we can say that the value of the variable is used in the function call in the call by value method. ● In call by value method, we can not modify the value of the actual parameter by the formal parameter. ● 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. Example: #include<stdio.h> void change(int num) { printf("Before adding value inside function num=%d n", num); num=num+100; printf("After adding value inside function num=%d n", num); } int main() { int x=100; printf("Before function call x=%d n", x); change(x);//passing value in function printf("After function call x=%d n", x); return 0; } 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 Now, let us call the function swap() by passing actual values as in the following example −
  • 58. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 57/105 #include <stdio.h> /* function declaration */ void swap(int x, int y); int main () { /* local variable de nition */ int a = 100; int b = 200; printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); /* calling a function to swap the values */ swap(a, b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ return; } Output: Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 100 After swap, value of b : 200 Call by reference: ● In call by reference, the address of the variable is passed into the function call as the actual parameter. ● The value of the actual parameters can be modi ed by changing the formal parameters since the address of the actual parameters is passed. ● The memoryallocation 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 modi ed value gets stored at the same address. Example:
  • 59. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 58/105 #include<stdio.h> void change(int *num) { printf("Before adding value inside function num=%d n",*num); (*num) += 100; printf("After adding value inside function num=%d n", *num); } int main() { int x=100; printf("Before function call x=%d n", x); change(&x);//passing reference in function printf("After function call x=%d n", x); return 0; } 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 Let us now call the function swap() by passing values by reference as in the following example − Live Demo #include <stdio.h> int main () { /* local variable de nition */ int a = 100; int b = 200; printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); /* calling a function to swap the values */ swap(&a, &b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } void swap(int *x, int *y) { int temp; temp = *x; /* save the value of x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */
  • 60. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 59/105 return; } Output: Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100 Difference between call by value and call by reference in c Call by value Call by reference A copy of the value is passed into the function An address of value is passed into the function Actual and formal arguments are created at the different memory location Actual and formal arguments are created at the same memory location Original value not modi ed. The original value is modi ed. Values of variables are passed using a straightforward method. Pointer variables are required to store the address of variables. Does not allow you to make any changes in the actual variables. Allows you to make changes in the values of variables by using function calls. Default in many programming languages like C++.PHP. Visual Basic NET, and C#. It is supported by most programming languages like JAVA, but not as default. Recursion Functions: ● 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. ● while using recursion, programmers need to be careful to de ne an exit condition from the function, otherwise, it will go into an in nite loop. ● Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating the Fibonacci series, etc. Syntax: void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); } Example: Recursion is used to calculate the factorial of a number.
  • 61. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 60/105 #include <stdio.h> int fact (int); int main() { int n,f; printf("Enter the number whose factorial you want to calculate?"); scanf("%d",&n); f = fact(n); printf("factorial = %d",f); } int fact(int n) { if (n==0) { return 0; } else if ( n == 1) { return 1; } else { return n*fact(n-1); } } Output: Enter the number whose factorial you want to calculate?5 factorial = 120 Example: To nd the nth term of the Fibonacci series. Concept: b(5) / b(4) b(3) / / b(3) b(2) b(2) b(1) / / / b(2) b(1) b(1) b(0) b(1) b(0) / b(1) b(0) #include<stdio.h> int bonacci(int); void main () { int n,f;
  • 62. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 61/105 printf("Enter the value of n?"); scanf("%d",&n); f = bonacci(n); printf("%d",f); } int bonacci (int n) { if (n==0) { return 0; } else if (n == 1) { return 1; } else { return bonacci(n-1)+ bonacci(n-2); } } Output: Enter the value of n? 9 4 Basic Searching and Sorting Algorithms Searching Algorithm: ● The searching algorithms are used to search or nd one or more than one element from a dataset. ● These types of algorithms are used to nd elements from speci c data structures. ● Searching may be sequential or not. ● If the data in the dataset are random, then we need to use sequential searching. Otherwise, we can use other different techniques to reduce the complexity. In this Section, We are going to cover ● Linear Search ● Binary Search Linear Search Algorithm: ● It is the simplest searching algorithm. ● Linear search is a sequential searching algorithm where we start from one end and check every element of the list until the desired element is found. It is the simplest search algorithm.
  • 63. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 62/105 Working of Linear Search: ● Search for an element k = 1 in the given list. 8 5 1 14 10 24 ● Start from the rst element, compare k with each element x. k != 8 k != 5 k = 1 ● If x == k, return the index. ● Else, return not found. Algorithm: LinearSearch(array, key) for each item in the array if item == value returns its index Example: // Linear Search in C #include <stdio.h> int search(int array[], int n, int x) { // Going through array sequentially for (int i = 0; i < n; i++) if (array[i] == x) return I; return -1; } int main() { int array[] = {8, 5, 1, 14, 10, 24}; int x = 1; int n = sizeof(array) / sizeof(array[0]); int result = search(array, n, x); (result == -1)? printf("Element not found"): printf("Element found at index: %d", result); } Binary Search Algorithm: ● Binary Search is a search algorithm for nding the position of an element in a sorted 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 rst. ● In this approach, the element is always searched in the middle of a portion of an array. The Binary Search Algorithm can be implemented in two ways: ● The recursive method follows the divide and conquers approach. ● Iterative Method ● Example: Let x = 4 be the element to be searched in the given Array.
  • 64. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 63/105 5 8 7 4 3 6 Step 1: First we need to sort this array 3 4 5 6 7 8 Step 2: Set two pointers low and high at the lowest and the highest positions respectively. ● Low = 3 ● Hingh = 8 Step 3: Find the middle element mid of the array ie. arr[(low + high)/2] = 5 or 6, let mid = 6 Step 4: ● If x == mid, then return mid. ● If x > mid, then set the value of low = mid + 1. ● If x < mid, then set the value of high = mid - 1. Now Low = 3 High = 5 Mid = 4 Repeat Step 2 to Step 4 Mid = 4 x = 4 is found Algorithm: 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 right side return binarySearch(arr, x, low, mid - 1) Sorting Algorithm: Sorting is the process of arranging the elements of an array so that they can be placed either in ascending or descending order. Consider an array; int A[10] = { 5, 4, 10, 2, 30, 45, 34, 14, 18, 9 ) The Array sorted in ascending order will be given as; A[] = { 2, 4, 5, 9, 10, 14, 18, 30, 34, 45 } In this Section, We are going to cover
  • 65. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 64/105 ● Bubble Sort ● Insertion Sort ● Selection Sort Bubble Sort: ● It is inspired by observing the behavior of air bubbles over foam. ● Bubble sort is the easiest sorting algorithm to implement. ● It is an in-place sorting algorithm. Step-by-Step Process: ● Select the rst element of the list (i.e., the Element at the rst position in the list). ● Compare the selected element with all the other elements in the list. ● In every comparision, if any element is found smaller than the selected element (for Ascending order), then both are swapped. ● Repeat the same procedure with the element in the next position in the list till the entire list is sorted. Bubble Sort Algorithm: begin BubbleSort(arr) for all array elements if arr[i] > arr[i+1] swap(arr[i], arr[i+1]) end if end for return arr end BubbleSort Example: Consider the following unsorted list of element..? 13 32 26 35 10 First Pass: Sorting will start from the initial two elements. Let's compare them to check which is greater. 13 32 26 35 10 Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26. 13 32 26 35 10 Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like this. 13 26 32 35 10 Now, compare 32 and 35. 13 26 32 35 10 Here, 35 is greater than 32. So, there is no swapping required as they are already sorted. Now, the comparison will be between 35 and 10. 13 26 32 35 10 Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach the end of the array. After the rst pass, the array will be - 13 26 32 10 35 Now, move to the second iteration.
  • 66. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 65/105 Second Pass The same process will be followed for the second iteration. 13 26 32 10 35 13 26 32 10 35 Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be - 13 26 10 32 35 Now, move to the third iteration. Third Pass The same process will be followed for the third iteration. 13 26 10 32 35 13 26 10 32 35 Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be - 13 10 26 32 35 13 10 26 32 35 13 10 26 32 35 Now, move to the fourth iteration. The fourth pass Similarly, after the fourth iteration, the array will be - 13 10 26 32 35 Here, 10 is smaller than 13. So, swapping is required. After swapping, the array will be - 10 13 26 32 35 Hence, there is no swapping required, so the array is completely sorted. Program: Write a program to implement bubble sort in C language.
  • 67. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 66/105 #include<stdio.h> void print(int a[], int n) //function to print array elements { int i; for(i = 0; i < n; i++) { printf("%d ",a[i]); } } void bubble(int a[], int n) // function to implement bubble sort { int i, j, temp; for(i = 0; i < n; i++) { for(j = i+1; j < n; j++) { if(a[j] < a[i]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } void main () { int i, j, temp; int a[5] = { 10, 35, 32, 13, 26}; int n = sizeof(a)/sizeof( a[0]); printf("Before sorting array elements are - n"); print(a, n); bubble(a, n); printf("nAfter sorting array elements are - n"); print(a, n); } Output: Before sorting array element are - 10 35 32 13 26 After sorting array element is 10 13 26 32 35 Insertion Sort: ● Insertion sort is an in-place sorting algorithm. ● It is inspired by the way in which we sort playing cards. ● In the insertion sort algorithm, every iteration moves an element from the unsorted portion to the sorted portion until all the elements are sorted in the list.
  • 68. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 67/105 Step-by-Step Process: ● Assume that the rst element in the list is in the sorted portion and all the remaining elements are in the unsorted portion. ● Take the rst element from the unsorted portion and insert that element into the sorted portion in the order speci ed. ● Repeat the above process until all the elements from the unsorted portion are moved into the sorted portion. Working of Insertion sort Algorithm: Now, let's see the working of the insertion sort Algorithm. Let the elements of the array be - 12 31 25 8 32 17 Initially, the rst two elements are compared in insertion sort. 12 31 25 8 32 17 Here, 31 is greater than 12. That means both elements are already in ascending order. So, for now, 12 is stored in a sorted sub-array. 12 31 25 8 32 17 Now, move to the next two elements and compare them. 12 31 25 8 32 17 Here, 25 is smaller than 31. So, 31 is not in the correct position. Now, swap 31 with 25. Along with swapping, For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence, the sorted array remains sorted after swapping. 12 25 31 8 32 17 Now, two elements in the sorted array are 12 and 25. Move forward to the next elements which are 31 and 8. 12 25 31 8 32 17 Both 31 and 8 are not sorted. So, swap them. 12 25 8 31 32 17 Now, elements 12 & 25, and 8 are unsorted. So, swap them. 8 12 25 31 32 17 Now, the sorted array has three items that are 8, 12, and 25. Move to the next items that are 31 and 32. 8 12 25 31 32 17
  • 69. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 68/105 Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31. Move to the next elements which are 32 and 17. 8 12 25 31 32 17 17 is smaller than 32, 31 & 25. So, swap them. 8 12 17 25 32 32 Now, the array is completely sorted. Program: Write a program to implement insertion sort in C language. #include <stdio.h> void insert(int a[], int n) /* function to sort an aay with insertion sort */ { int i, j, temp; for (i = 1; i < n; i++) { temp = a[i]; j = i - 1; while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead from their current position*/ { a[j+1] = a[j]; j = j-1; } a[j+1] = temp; } } void printArr(int a[], int n) /* function to print the array */ { int i; for (i = 0; i < n; i++) printf("%d ", a[i]); } int main() { int a[] = { 12, 31, 25, 8, 32, 17 }; int n = sizeof(a) / sizeof(a[0]); printf("Before sorting array elements are - n"); printArr(a, n); insert(a, n); printf("nAfter sorting array elements are - n"); printArr(a, n); return 0; } Output: Before sorting array element are -
  • 70. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 69/105 12 31 25 8 32 17 After sorting array element are 8 12 17 25 31 32 Selection Sort: ● It is also the simplest algorithm. ● It is an in-place comparison sorting algorithm. ● In this algorithm, the array is divided into two parts, the rst is the sorted part, and another one is the unsorted part. ● Initially, the sorted part of the array is empty, and the unsorted part is the given array. ● Sorted part is placed at the left, while the unsorted part is placed at the right. Step-by-step Process: ● It nd the rst smallest element. ● It swaps it with the rst element of the unordered list. ● It nd the second smallest element. ● It swaps it with the second element of the unordered list. ● Similarly, it continues to sort the given elements. Working of Selection sort Algorithm: Let the elements of the array be - 12 29 25 8 32 17 40 At present, 12 is stored at the rst position, after searching the entire array, it is found So, swap 12 with 8. After the rst iteration, 8 will appear at the rst position in the sorted array. 8 29 25 12 32 17 40 At present, 29 is stored at the second position, after searching the entire array, it is found that 12 is the second smallest value. 8 29 25 12 32 17 40 Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the sorted array. 8 12 25 29 32 17 40 The same process is applied to the rest of the array elements. Now, we are showing a pictorial representation of the entire sorting process. 8 12 25 29 32 17 40 8 12 17 29 32 25 40 8 12 17 29 32 25 40
  • 71. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 70/105 8 12 17 25 32 29 40 8 12 17 25 32 29 40 8 12 17 25 29 32 40 8 12 17 25 29 32 40 8 12 17 25 29 32 40 8 12 17 25 29 32 40 Now, the array is completely sorted. Program: Write a program to implement selection sort in C language. #include <stdio.h> void selection(int arr[], int n) { int i, j, small; for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray { small = i; //minimum element in unsorted array for (j = i+1; j < n; j++) if (arr[j] < arr[small]) small = j; // Swap the minimum element with the rst element int temp = arr[small]; arr[small] = arr[i]; arr[i] = temp; } } void printArr(int a[], int n) /* function to print the array */ { int i; for (i = 0; i < n; i++) printf("%d ", a[i]); } int main() { int a[] = { 12, 29, 25, 8, 32, 17, 40 }; int n = sizeof(a) / sizeof(a[0]); printf("Before sorting array elements are - n"); printArr(a, n); selection(a, n);
  • 72. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 71/105 printf("nAfter sorting array elements are - n"); printArr(a, n); return 0; } Output: Before sorting array elements are - 12 29 25 8 32 17 40 After sorting array elements are - 8 12 17 25 29 32 40 SIT Sitamarhi Desire The More You Practice, The Better You Get. Pointers Pointers: ● The pointer in C language is a variable which stores the address of another variable. ● This variable can be of type int, char, array, function, or any other pointer. ● The size of the pointer depends on the architecture. However, in 32-bit architecture, the size of a pointer is 2 byte. ● The asterisk * used to declare a pointer is the same asterisk used for multiplication.
  • 73. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 72/105 Example: To de ne a pointer that stores the address of an integer. int n = 10; int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer. Declaring a pointer: The pointer in c language can be declared using * (asterisk symbol). It is also known as an indirection pointer used to dereference a pointer. int *a;//pointer to int char *c;//pointer to char Advantage of Pointer: ● Pointers in C Programming are helpful to access a memory location ● Pointers are an effective way to access the array structure elements ● Pointers are used for the allocation of dynamic memory. ● Pointers are used to build complicated data structures like a linked list, graph, trees, etc Application of Pointer: ● To pass arguments by reference. ● For accessing array elements. ● To return multiple values. ● Dynamic memory allocation. ● To implement data structures. ● To do system-level programming where memory addresses are useful. Example An example of using pointers to print the address and value is given below. As you can see in the above gure, the pointer variable stores the address of the number variable, i.e., fff4. The value of the number variable is 50. But the address of pointer variable p is aaa3. With the help of * (indirection operator), we can print the value of the pointer variable p. Let's see the example as explained in the above gure. #include<stdio.h> int main(){ int number=50; int *p; p=&number;//stores the address of number variable printf("Address of p variable is %x n",p); // p contains the address of the number, therefore, printing p gives the address of number.
  • 74. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 73/105 printf("Value of p variable is %d n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p. return 0; } Output: Address of number variable is fff4 Address of p variable is fff4 Value of p variable is 50 Type of Pointer: There are majorly four types of pointers, they are: ● Null Pointer: If you assign a NULL value to a pointer during its declaration, it is called Null Pointer. ● Void Pointer: When a pointer is declared with a void keyword, then it is called a void pointer. To print the value of this pointer, you need to typecast it. ● Wild Pointer: A wild pointer is only declared but not assigned an address of any variable. They are very tricky, and they may cause segmentation errors. ● Dangling Pointer: Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this memory, then this p is called a dangling pointer. You can deallocate memory using a free() function. There are two types of memory in our machine● Static Memory ● Dynamic Memory Both memories are managed by our Operating System. Our operating system helps us in the allocation and deallocation of memory blocks either during compile-time or during the run-time of our program. Static Memory Allocation: When the memory is allocated during compile-time it is stored in the Static Memory and it is known as Static Memory Allocation,
  • 75. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 74/105 Dynamic Memory Allocation: when the memory is allocated during run-time it is stored in the Dynamic Memory and it is known as Dynamic Memory Allocation. Differences between Static Memory Allocation and Dynamic Memory Allocation. Static Memory Allocation Dynamic Memory Allocation Memory is allocated at compile time. Memory is allocated at run time. Memory can't be increased while executing a program Memory can be increased while executing the program Used in the array. Used in link-list. Stack space is used in Static Memory Allocation. Heap space is used in Dynamic Memory Allocation. We can't allocate or deallocate a memory block during run-time. We can allocate and deallocate a memory block during run-time. It doesn't provide reusability of memory while the program is running. So, it is less efficient. It provides reusability of memory while the program is running. So, it is more efficient. Dynamic memory allocation in C: The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header le. ● malloc() ● calloc() ● realloc() ● free() malloc() function: ● The malloc() function allocates single block of requested memory. ● It doesn't initialize memory at execution time, so it has a garbage value initially. ● It returns NULL if memory is not sufficient. Syntax: ptr=(cast-data-type*)malloc(byte-size) Or int *ptr = (int *)malloc(sizeof(int)); Example: #include<stdio.h> #include<stdlib.h> int main(){ int n,i,*ptr,sum=0; printf("Enter a number of elements: "); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc if(ptr==NULL)
  • 76. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 75/105 { printf("Sorry! unable to allocate memory"); exit(0); } printf("Enter elements of an array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d", sum); free(ptr); return 0; } Output: Enter the a number of elements: 3 Enter elements of an array: 10 10 10 Sum = 30 calloc() function: ● The calloc() function allocates multiple blocks of requested memory. ● It initially initialize all bytes to zero. ● It returns NULL if memory is not sufficient. Syntax: ptr=(cast-data-type*)calloc(number, byte-size) Example: #include<stdio.h> #include<stdlib.h> int main(){ int n, i,*ptr,sum=0; printf("Enter a number of elements: "); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc if(ptr==NULL) { printf("Sorry! unable to allocate memory"); exit(0); } printf("Enter elements of an array: "); for(i=0; i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d", sum); free(ptr); return 0; }
  • 77. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 76/105 Output: Enter elements of an array: 3 Enter elements of an array: 10 10 10 Sum = 30 realloc() function: ● If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. ● “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. ● If the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. Syntax: ptr=realloc(ptr, new-size) Example: #include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Addresses of previously allocated memory:n"); for(i = 0; i < n1; ++i) printf("%pcn", ptr + i); printf("nEnter the new size: "); scanf("%d", &n2); // rellocating the memory ptr = realloc(ptr, n2 * sizeof(int)); printf("Addresses of newly allocated memory:n"); for(i = 0; i < n2; ++i) printf("%pcn", ptr + i); free(ptr); return 0; } Output: Enter size: 2 Addresses of previously allocated memory: 26855472 26855476
  • 78. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 77/105 Enter the new size: 4 Addresses of newly allocated memory: 26855472 26855476 26855480 26855484 free() function: ● The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until the program exit. Syntax: free(ptr) String: ● The string can be de ned as the one-dimensional array of characters terminated by a null ('0'). ● The character array or the string is used to manipulate text such as words or sentences. ● Each character in the array occupies one byte of memory, and the last character must always be 0. ● The termination character ('0') is important in a string since it is the only way to identify where the string ends. There are two ways to declare a string in c language. 1. By char array 2. By string literal Example of declaring string by char array in C language. While declaring a string, size is not mandatory. So we can write the code. char ch[10]={'e', 'd', 'u', 'd', 'e', 's', 'i', 'r', 'e', '0'}; As we know, array index starts from 0, so it will be represented as in the gure given below. Index-> 0 1 2 3 4 5 6 7 8 9 String-> e d u d e s i r e 0 We can also de ne the string by the string literal in C language. For example: char ch[]="edudesire"; In such case, '0' will be appended at the end of the string by the compiler. Difference between char array and string literal Char array String literal We need to add the null character '0' at the end of the array. In such a case, '0' will be appended at the end of the string by the compiler. we can reassign the characters of the array. We cannot be reassigned to another set of characters Simple example where a string is declared and being printed. The '%s' is used as a format speci er for the string in the c language.
  • 79. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 78/105 #include<stdio.h> #include <string.h> int main(){ char ch[10]={'e', 'd', 'u', 'd', 'e', 's', 'i', 'r', 'e', '0'}; char ch2[10]="edudesire"; printf("Char Array Value is: %sn", ch); printf("String Literal Value is: %sn", ch2); return 0; } Output: Char Array Value is: edudesire String Literal Value is: edudesire Traversing String: ● Traversing the string is one of the most important aspects in any of the programming languages. ● We may need to manipulate a very large text which can be done by traversing the text. There are two ways to traverse a string. 1. By using the length of string 2. By using the null character. Using the length of the string: Example of counting the number of vowels in a string. #include<stdio.h> void main () { char s[10] = "edudesire"; int i = 0; int count = 0; while(i<10) { if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o') { count ++; } i++; } printf("The number of vowels %d", count); } Output The number of vowels 5 Using the null character:
  • 80. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 79/105 Example of counting the number of vowels by using the null character. #include<stdio.h> void main () { char s[10] = "edudesire"; int i = 0; int count = 0; while(s[i] != NULL) { if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o') { count ++; } i++; } printf("The number of vowels %d", count); } Output The number of vowels 4 Pointers with strings: We have used pointers with the array, functions, and primitive data types so far. However, pointers can be used to point to the strings. The following example is to access the string via the pointer. #include<stdio.h> void main () { char s[10] = "edudesire"; char *p = s; // pointer p is pointing to string s. printf("%s",p); // the string edudesire is printed if we print p. }
  • 81. Follow me Sit Desire ) YouTube Facebook Instagram Telegram Page 80/105 Output: edudesire Index-> 0 1 2 3 4 5 6 7 8 9 Value-> e d u d e s i r e 0 Address-> 50 51 52 53 54 55 56 57 58 59 String Functions: There are many important string functions de ned in "string.h" library. String Length: strlen() The stredudesirelen() function returns the length of the given string. It doesn't count the null character '0'. #include<stdio.h> #include <string.h> int main(){ char ch[20]={'e', 'd', 'u', 'd', 'e', 's', 'i', 'r', 'e', '0'}; printf("Length of string is: %d",strlen(ch)); return 0; } Output: Length of string is: 9 Copy String: strcpy() The strcpy(destination, source) function copies the source string in the destination. #include<stdio.h> #include <string.h> int main(){ char ch1[20]={'e', 'd', 'u', 'd', 'e', 's', 'i', 'r', 'e', '0'}; char ch2[20]; strcpy(ch2,ch1); printf("Value of second string is: %s",ch2); return 0; } Output: Value of second string is: edudesire String Concatenation: strcat() Variable-> ptr Value-> 50 Address-> 101