Problem Solving Using C Notes 1
Problem Solving Using C Notes 1
Department of CSE
Darshan Institute of Engineering & Technology, Rajkot
[Link]
srinivascsedept@[Link]
+91 9347556447
Outline
• Introduction to components of a computer system:
Looping
ÊDisks, primary and secondary memory,
ÊProcessor, operating system, compilers,
ÊCreating, compiling and executing a program etc.,
• Number systems and Introduction to Algorithms:
Êsteps to solve logical and numerical problems.
ÊRepresentation of Algorithm, Flowchart/Pseudo code with examples,
ÊProgram design and structured programming.
• Introduction to C Programming Language:
ÊSimple input and output with scanf and printf, variables
ÊSyntax and Logical Errors in compilation, object and executable code,
ÊOperators, expressions and precedence, Expression evaluation,
ÊType conversion
• Conditional Branching and Loops:
ÊWriting and evaluation of conditionals and consequent branching with if, if-else,
Êswitch-case,
Êternary operator, goto, break
ÊIteration with for, while, do- while loops
Chapter - 1
Computer
The word computer comes from the word “compute”, which means, “to calculate”.
A computer is an electronic device that can perform arithmetic operations at high speed and
it can process data, pictures, sound and graphics.
It can solve highly complicated problems quickly and accurately.
A computer is an electronic device or programmable machine which takes the input (Data)
from input devices, process it and generate the output(Information) on output devices.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 5
Disadvantages of Computer
Lake of intelligence
Ê It can not think while doing work.
Ê It does not have natural intelligence.
Ê It can not think about properness, correctness or effect of work it is doing.
Unable to correct mistake
Ê It can not correct mistake by itself.
Ê So if we provide wrong or incorrect data then it produces wrong result or perform wrong calculations.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 6
Computer System
ØA computer system consists of hardware ,software and Users.
ØHardware
Ø refers to any physical, electrical components of the computer.
Ø For example keyboard, mouse, cabinet of computer is considered as hardware.
ØSoftware
Ø refers to a program or set of instructions that is written to achieve a specified task.
ØUsers
Ø refers to persons or machenies who operate the computer.
Computer System
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 7
Block Diagram of Computer
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 9
Block Diagram of Computer
Input Devices:
ÊThe input device is used to enter data into a computer.
ÊThe devices like keyboard, mouse and scanner are commonly used input devices.
Central Processing Unit:
ÊIt is the main part of the computer.
ÊIt’s main function is to execute programs stored in the main memory.
ÊIt consists of three functional units: ALU, CU and MU.
¨Arithmetic and Logic Unit (ALU):
ÊIt performs arithmetic and logical operations on the data.
¨Control Unit:
ÊIt controls the overall activities of the components of the computer.
¨Memory Unit:
ÊIt is used to hold the waiting data to be processed.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 10
Block Diagram of Computer
Memory: There are two types of memories.
•Volatile Memory
•Non-volatile Memory
•Volatile Memory: It means that the information present in these types of memory devices is
deleted as soon as the power is switched off.
•Non-volatile Memory: It means that the information present in these types of memory devices
is not lost as soon as the power is switched off.
Types of Storage Devices:
•Primary Storage or Main Memory.
•Auxiliary Storage or Secondary Storage
•Cache memory
•Registers
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 11
Block Diagram of Computer
Types of Storage Devices:
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 12
Block Diagram of Computer
Primary Storage/Main Memory:
ØThis is the place where the data is stored temporarily during processing.
ØPrimary memory (main memory) is available in two forms: RAM and ROM.
Output Devices:
Ø It is used to display or print the result.
Ø Monitor, printer and plotter are commonly used output devices.
Ø If output is shown on the screen it is called soft copy. If it is printed on the paper is called hard
copy.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 14
Computer Software
Software refers to a program or set of instructions that is written to achieve a specified task.
Ê These instructions need to be written in a programming language that the computer can understand.
Programming Language: An artificial set of rules, vocabulary and syntax used to instruct the computer to execute
certain tasks.
Software is mainly categorized into two groups.
Ø System Software
Ø Application Software
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 15
System Software
System Software consists of programs that manage the hardware resources of a computer and perform
required information processing tasks.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 17
Programming Languages
A program’s instructions need to be written in a programming language that the computer can
understand.
The first programming language is machine language.
Computer languages were evolved from machine language to natural language (like English language).
Computer Languages are basically divided into three categories:
Ê Machine language
Ê Symbolic language
Ê High level languages
Step 2
1 Compiling Source Code Press
Alt + F9
Step 3
1 Linking with Library
Press
Alt + F9
Step 4
1
Press
Executing Source Code Ctrl + F9
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 22
C Program Execution Process
Source Code Compiler Object Code Linker Executable Code User Screen
CPU
[Link] [Link]
Sample.c
stdio.h
List of ERRORS
Header Files
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 23
C Program Execution Process
1. Writing and Editing the program
Ê Software used to write programs is known as a text editor, where you can type, edit and store the data.
Ê You can write a C program in text editor and save that file on to the disk with “.c” extension. This file is
called source file.
2. Compiling Program
Ê Compiler is used to convert High Level Language instructions into the Machine Language instructions.
Ê It could complete its task in two steps.
i) Preprocessor
ii) Translator
Preprocessor:
§ It reads the source file and checks for special commands known as preprocessor commands ( instructions which
starts with # symbols ).
§ The result of preprocessor is called as translation unit.
§ Preprocessor processes the source file before compilation only.
Translator:
§ It is a program which reads the translation unit and converts the program into machine language and gives the
object module.
§ This module is not yet ready to run because it does not have the required C and other functions included.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 24
C Program Execution Process
3. Linking a program with required library functions
Ê C program is made up of different functions in which some functions can be written by the programmer,
other functions like input/output functions and mathematical library functions, that exist elsewhere and
must be attached to our program.
Ê The linker assembles all of these functions and produces the executable file which is ready to run on the
computer.
4. Executing the program.
Ê Once a program has been linked, it is ready for execution.
Ê Now, you can execute the program by using the run command.
Ê Loader is a program which is used to load the program from the disk to main memory.
1. Write a program (source code) using vi editor and save it with .c extension. Ex: $vi sample.c
2. Run the compiler to convert a program into to “binary” code. Ex: $cc sample.c
3. Compiler gives errors and warnings if any, then edit the source file, fix it, and re-compile.
4. Run it and see the output. Ex: $ ./[Link]
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 25
Translators
A program written in high-level language is called as source code. To convert the source code
into machine code, translators are needed.
A translator takes a program written in source language as input and converts it into a program
in target language as output.
It also detects and reports the error during translation.
Roles of translator are:
Ê Translating the high-level language program input into an equivalent machine language program.
Ê Providing diagnostic messages wherever the programmer violates specification of the high-level language
program.
Different type of translators
The different types of translator are as follows:
Ê Compiler
Ê Interpreter
Ê Assembler
Error Message
Interpreter Code
Ê Interpreter is a translator which is used to convert programs in high-level language to low-level language.
Interpreter translates line by line and reports the error once it encountered during the translation process.
Ê It directly executes the operations specified in the source program when the input is given by the user.
Ê It gives better error diagnostics than a compiler.
Input
Examples
of
Operating
System
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 30
Computer System Structure
Computer system can be divided into four components:
Ê Hardware – provides basic computing resources
§ CPU, memory, I/O devices
Ê Operating system
§ Controls and coordinates use of hardware among various applications and users
Ê Application programs – define the ways in which the system resources are used to solve
the computing problems of the users
§ Word processors, compilers, web browsers, database systems, video games
Ê Users
§ People, machines, other computers
[Link],
Prof. [Link],
Firoz Asst.
Asst.
A Sherasiya Professor,CSE
Professor,CSE Unit-1
Unit-1
Introduction
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to Operating
to C Programming
System Systems Language 31
Four Components of a Computer System
Users
Web E-mail Music
browser reader player
Application Programs
User
Mode
Software User Program
Operating Systems
Kernal
Operating System Mode
Hardware Hardware
[Link],
Prof. [Link],
Firoz Asst.
Asst.
A Sherasiya Professor,CSE
Professor,CSE Unit-1
Unit-1
Introduction
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to Operating
to C Programming
System Systems Language 32
Functions of Operating system
1. Booting
Ê Booting is a process of starting the computer operating system starts the computer to work. It checks the
computer and makes it ready to work.
2. Memory Management
Ê The memory cannot be managed without operating system.
Ê Different programs and data execute in memory at one time. if there is no operating system, the programs
may mix with each other. The system will not work properly.
3. Loading and Execution
Ê A program is loaded in the memory before it can be executed. Operating system provides the facility to load
programs in memory easily and then execute it.
4. Data security
Ê Data is an important part of computer system. The operating system protects the data stored on the
computer from illegal use, modification or deletion.
5. Disk Management
Ê Operating system manages the disk space. It manages the stored files and folders in a proper way.
[Link],
Prof. [Link],
Firoz Asst.
Asst.
A Sherasiya Professor,CSE
Professor,CSE Unit-1
Unit-1
Introduction
#3140702 (OS) Unit 1 – Introduction to Introduction
to Operating
to C Programming
Operating System Systems Language 33
Functions of Operating system
6. Process Management
Ê CPU can perform one task at one time. if there are many tasks, operating system decides which task should
get the CPU.
7. Device Controlling
Ê operating system also controls all devices attached to computer. The hardware devices are controlled with
the help of small software called device drivers..
8. Providing interface
Ê User interface controls how you input data and instruction and how information is displayed on screen.
Ê The operating system offers two types of the interface to the user:
§ 1. Graphical-line interface: It interacts with of visual environment to communicate with the computer. It uses windows,
icons, menus and other graphical objects to issues commands.
§ 2. Command-line interface: it provides an interface to communicate with the computer by typing commands.
[Link],
Prof. [Link],
Firoz Asst.
Asst.
A Sherasiya Professor,CSE
Professor,CSE Unit-1
Unit-1
Introduction
#3140702 (OS) Unit 1 – Introduction to Introduction
to Operating
to C Programming
Operating System Systems Language 34
Chapter - 2
Decimal, Binary, Octal, Hexa Decimal
Number Systems
Ê A number is a mathematical value used for counting and measuring objects, and for performing arithmetic
calculations.
Ê A number system is defined as the representation of numbers by using digits or other symbols in a
consistent manner.
Types of Number Systems
There are different types of number systems in which the four main types are:
Ê Binary number system (Base - 2)
Ê Octal number system (Base - 8)
Ê Decimal number system (Base - 10)
Ê Hexadecimal number system (Base – 16)
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 36
Decimal, Binary, Octal, Hexa Decimal
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 37
Binary Number System
Binary Number System
Ê The binary number system uses only two digits: 0 and 1.
Ê The numbers in this system have a base of 2.
Ê Digits 0 and 1 are called bits and 8 bits together make a byte.
Ê For example: 100012, 1111012, 10101012 are some examples of numbers in the binary number system.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 38
Octal Number System
Octal Number System
Ê The octal number system uses eight digits: 0,1,2,3,4,5,6 and 7 with the base of 8.
Ê The advantage of this system is that it has lesser digits when compared to several other systems, hence,
there would be fewer computational errors.
Ê Digits like 8 and 9 are not included in the octal number system.
Ê Just as the binary, the octal number system is used in minicomputers but with digits from 0 to 7.
Ê For example: 358, 238, 1418 are some examples of numbers in the octal number system.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 39
Decimal Number System
Decimal Number System
Ê The decimal number system uses ten digits: 0,1,2,3,4,5,6,7,8 and 9 with the base number as 10.
Ê The decimal number system is the system that we generally use to represent numbers in real life.
Ê If any number is represented without a base, it means that its base is 10.
Ê For example: 72310, 3210, 425710 are some examples of numbers in the decimal number system.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 40
Hexadecimal Number System
Hexadecimal Number System
Ê The hexadecimal number system uses sixteen digits/alphabets: 0,1,2,3,4,5,6,7,8,9 and A,B,C,D,E,F with the
base number as 16.
Ê Here, A-F of the hexadecimal system means the numbers 10-15 of the decimal number system respectively.
Ê This system is used in computers to reduce the large-sized strings of the binary system.
Ê For example: 7B316, 6F16, 4B2A16 are some examples of numbers in the hexadecimal number system.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 41
Chapter - 3
Program Development
It is a multistep process that requires that:
Ê 1. Understand the problem
Ê 2. Develop Solution
§ 1. Structure Chart
§ 2. Algorithm / Pseudo code
§ 3. Flowchart
Ê 3. Write the program
Ê 4. Test the program
1. Understand the Problem
Ê The first step in solving any problem is to understand it.
Ê To solve any problem first you must understand the problem by reading the requirements of the
problem.
Ê Once you understand it, review with user(customer) and system analyst.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 43
Program Development
2. Develop the Solution
Ê To develop a solution to a problem the following tools are needed.
1. Structure Chart:
Ê It is also known as a hierarchy chart, shows the functional flow through your program.
Ê It shows how the problem is broken into logical steps, each step will be a separate module.
Ê It also shows the interaction between all the parts of your program.
Ê It is like the architect’s blueprint.
The below two are used to design the individual parts of the program.
1. Algorithm / Pseudo Code
2. Flowchart
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 44
Example Structure Chart
Buy a
Computer
Desktop Laptop
DELL HP DELL HP
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 45
Algorithm
Algorithm: It is an ordered sequence of unambiguous and well-defined instructions that performs
some task and halts in finite time.
Let's examine the four parts of this definition more closely.
1. Ordered Sequence: You can number the step.
2. Unambiguous and well defined instructions: Each instruction should be clear, well understand.
3. Performs some task
4. Halts in finite time: Algorithm must terminate at some point.
Properties of an Algorithm:-
1. Finiteness: An algorithm must terminate in a finite number of steps.
2. Definiteness: Each step of an algorithm must be precisely and unambiguously stated.
3. Effectiveness: Each step must be effective, and can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself.
5. Input/Output: Each algorithm must take zero, one or more inputs and produces one or more output.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 46
Algorithm
Three Categories of Algorithmic Operations
Ê An algorithm must have the ability to alter the order of its instructions. An instruction that alters
the order of an algorithm is called a control structure.
Three categories of an algorithmic operations:
1. Sequential operations: Instructions are executed in order
2. Conditional/Selection ("question asking") Operations: A control structure that asks a true/false
question and then selects the next instruction based on the answer.
3. Iterative Operations (loops): A control structure that repeats the execution of a block of instructions.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 47
Pseudo Code
Definition: English-like statements that follow a loosely defined syntax and are used to convey the
design of an algorithm.
Example1: To determine whether a student is passed or not
Algorithm:
Pseudo Code:
Begin
1. If student's grade is greater than or equal to 60
1. If grade >= 60
1.1 Print "passed"
1.1 Print
2. else "passed"
2.1 Print "failed" 2. else
2.1 Print
"failed”
End
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 48
Pseudo Code
Example 2: Write an algorithm to determine a student’s final grade and indicate whether it is passing or
failing. The final grade is calculated as the average of four marks.
Pseudo Code: Algorithm:
1. Input set of 4 marks Begin
2. Calculate their average by summing and Step 1: Input M1,M2,M3,M4
dividing by 4 Step 2: GRADE
3. if average is below 50 (M1+M2+M3+M4)/4
4. Print “FAIL” Step 3: if (GRADE < 50) then
5. else Step 4: Print “FAIL”
6. Print “PASS” Step 5: else
Step 6: Print “PASS”
Step 7: endif
End
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 49
Flow chart
Flowchart: Pictorial representation of an algorithm is called flowchart.
or
A diagram that uses graphic symbols to depict the nature and flow of the steps in a process.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 50
Flow chart
Example: Addition of two numbers Algorithm
Start:
Start
Step 1: Read a, b values
Step 2: Sum of a,b
Accept a, b Step 3: Print “C”.
Stop:
c=a+b
Display C
End
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 51
Flow chart
Example: Number is positive or negative Algorithm
Start Start:
Step 1: Read no.
Read no Step 2: If no is greater than equal zero, go
to step 4.
True
Step 3: Print no is a negative number, go to
False
Is no >= 0 step 5.
Step 4: Print no is a positive number.
Step 5: Stop.
Print no is Print no is
Positive Negative Stop:
End
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 52
Flow chart
Example: Largest number from 3 numbers (Flowchart) Algorithm
Start
Read a, b, c
True False
Is a>b
Stop
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 53
Flow chart
Example: Largest number from 3 numbers (Algorithm)
Start:
Step 1: Read a, b, c.
Step 2: If a>b, go to step 5.
Step 3: If b>c, go to step 8.
Step 4: Print c is largest number, go to step 9.
Step 5: If a>c, go to step 7.
Step 6: Print c is largest number, go to step 9.
Step 7: Print a is largest number, go to step 9.
Step 8: Print b is largest number.
Stop:
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 54
Flow chart
Example: Print 1 to 10 Algorithm
Start Start:
Step 1: Initialize a to 1.
Step 2: Print a.
Step 3: Repeat step 2 until a<=10.
a=1
Step 3.1: a=a+1.
Stop:
a=a+1 Print a
Is a<=10
Stop
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 55
Differences between Flowchart and Algorithm
Flowchart Algorithm
Easy to show branching and looping. Difficult to show branching and looping.
Flowchart for big problem is impractical. Algorithm can be written for any problem.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 56
Chapter - 4
C History
ALGOL was the first computer language.
In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming
Language) at University of Cambridge primarily, for writing system software.
‘B’ was used to create early versions of UNIX operating system at Bell Laboratories.
In 1988 C language was standardized by ANSI as ANSI C (ANSI- American National Standards
Institute).
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 58
C Features
The increasing popularity of C is due to its various features:
Robust: C is a robust language with rich set of built-in functions and operators to write any complex
programs.
C compilers combines the capabilities of low level languages with features of high level language.
Therefore it is suitable for writing the system software, application software and most of the
compilers of other languages also developed with C language.
Efficient and Fast: Programs written in C are efficient and fast. This is due to its variety of data types.
Portable: C program written on one computer can also run on the other computer with small or no
modification.
Example: C program written in windows can also run on the Linux operating system.
Structured Programming: Every program in C language is divided into small modules or functions so
that it makes the program much simple, debugging, and also maintenance of the program is easy.
Ability to extend itself: A C program is basically a collection of various functions supported by C
library (also known as header files). We can also add our own functions to the C library. These
functions can be reused in other applications or programs.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 59
Structure of C Program
Include
information
about standard
library
Main calls
library function
printf to print
this message.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 60
Preprocessor directives
The preprocessor directives provide instructions to the preprocessor, to include functions from the
system library, to define the symbolic constants and macro.
The preprocessor command always starts with symbol #.
Example: #include<stdio.h>
Header file contains a collection of library files.
#include<stdio.h> includes the information about the standard input/output library.
The variables that are used in common by more than one function are called Global Variables and are
declared in global declaration section.
Every C program must have one main() function. All the statements of main are enclosed in braces.
The program execution begins at main() function and ends at closing brace of the main function.
C program can have any number of user-defined functions and they are generally placed immediately
after the main () function, although they may appear in any order.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 61
Preprocessor directives
All sections except the main () function may be absent when they are not required.
In the previous program, main() function returns an integer value to the operating system.
Each statement in C program must end with ; specifies that the instruction is ended.
A function can be called by it’s name, followed by a parenthesized list of arguments and ended
with semicolon.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 62
Comments
To make the program more readable use the comments.
They may used to make the program easier to understand.
Two types of comments
Ê 1. Block comment
Ê 2. Line comment
[Link] comment :
Ê Any characters between /* and */ are ignored by the compiler.
Ê Comments may appear anywhere in a program.
Ê /* and */ is used to comment the multiple lines of code which is ignored by the compiler.
Ê Nested block comments are invalid like /* /* */
Ê Ex:/* Write a program to add two integer numbers */
2. Line comment
Ê To comment a single line use two slashes //
int a=10,b=20,c; // Variables declaration & initialization
c=a+b; // Adding two numbers
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 63
C Token
In a passage of text, individual words and punctuation marks are called as tokens.
The compiler splits the program into individual units, are known as C tokens. C has six types of
tokens.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 64
C Token
Characters are used to form words, numbers and expressions.
Characters are categorized as
Ê Letters
Ê Digits
Ê Special characters
Ê White spaces.
Letters(26+26): (Upper Case and Lower Case)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Digits(10): 0123456789
Special Characters(36):
’"()*+-/:= !&$;<>%?,. ˆ#@˜‘{}[]\|
White Spaces(5): Blank Space, Horizontal Space, Carriage Return, New Line.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 65
A. Identifiers
Identifiers are names given to various programming elements such as variables, constants, and
functions.
It should start with an alphabet or underscore, followed by the combinations of alphabets and
digits.
No special character is allowed except underscore.
An Identifier can be of arbitrarily long. Some implementation of C recognizes only the first 8
characters and some other recognize first 32 Characters.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 66
A. Identifiers Cont…
Identifier Legality
Percent Legal
y2x5__fg7h Legal
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 67
Variables
Variable is a valid identifier which is used to store the value in the memory location, that value varies
during the program execution.
Types of variables:
Ê Global Variables
Ê Local Variables
Global Variable: The variables which are declared at the starting of the program are called as global
variable. They are visible to all the parts of the program.
Local Variable: The variables which are declared in a function are called local variables to that function.
These variables visible only within the function.
Variable Declaration & Definition:
Ê Each variable in your program must be declared and defined.
Ê In C, a declaration is used to name an object, such as a variable. Definitions are used to create the object.
Ê When you create variables, the declaration gives them a symbolic name and the definition reserves memory for them.
Ê A variable’s type can be any of the data types, such as character, integer or real except void.
Ê C allows multiple variables of the same type to be defined in one statement.
Ê Example: int a, b;
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 68
Variable Cont..
Variable Initialization:
Ê You can initialize a variable at the same time that you declare it by including an initializer.
Ê To initialize a variable when it is defined, the identifier is followed by the assignment operator and then the initializer.
Ê Example: int count = 0;
Variable
Variabledeclaration
declarationand
anddefinition:
definition:
Example:
Example:int
inta;a; Variable initialization:
a Variable name datatype identifier = initial value;
Examples:
int a=10;
23456 Garbage value float b=2.1;
float pi=3.14;
1000 Address of the variable char ch=‘A’;
When you want to process some information, you can save the values temporarily in variables.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 69
Variables Cont…
There are some restrictions on the variable names (same as identifiers):
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 71
[Link]
Constants are data values that cannot be changed during the program execution.
Like variables, constants have a type.
Types of constants:
Ê Boolean constants:
§ A Boolean data type can take only two values true and false.
Ê Character constants
§ Single character constants
§ string constants.
Ê Numeric constants.
§ integer constant
§ real constants.
Type qualifier const
Ø One way to use the constant is with memory constants. Memory constants use a C type qualifier; const.
Ø This indicates that the data cannot be changed.
Ê const type identifier= value;
Ê const float pi=3.14;
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 72
D. Strings
Single character constants
Ê A single character constants are enclosed in single quotes.
Ê Example: ‘1’ ‘X’ ‘%’ ‘ ‘
Ê Character constants have integer values called ASCII values.
char ch=‘A’;
printf(“%d”,ch); Output: 65
similarly printf(“%c”,65) Output: A
String Constants
Ê String is a collection of characters or sequence of characters enclosed in double quotes.
Ê The characters may be letters, numbers, special characters and blank space.
Ê Example: “JNTUH” “2011” “A”.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 73
Backslash \ escape characters
Backslash characters are used in output functions. constant meaning
These backslash characters are preceded with the \ symbol.
‘\a’ Alert(bell)
‘\b’ Back space
Numeric Constants ‘\f’ Form feed
Ê integer constant:
‘\n’ New line
§ It is a sequence of digits that consists numbers from 0to 9.
Ê Example: 23 -678 0 +78 ‘\r’ Carriage return
Mantissa e exponent
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 76
[Link]
C supports a rich set of operators.
An operator is a symbol that tells the computer to perform mathematical or logical operations.
Operators are used in C to operate on data and variables.
expression
X=Y+Z
Operators: =, + Operands: x, y, z
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 77
Operators Cont…
Types of Operators:
C operators can be classified into a number of categories.
They include:
Ê Arithmetic Operators
Ê Relational Operators
Ê Logical Operators
Ê Assignment Operator
Ê Increment and Decrement Operators
Ê Conditional Operators
Ê Bitwise Operators
Ê Special Operators
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 78
[Link] Operators
Arithmetic operators are used for mathematical calculation.
a b a&&b a||b
0 0 0 0 a !a
0 1 0 1
0 1
1 0 0 1
Syntax: operand1 logical operator operand2 1 0
or 1 1 1 1
logical operator operand
Example: (x<y) && (x= = 8)
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 81
4. Assignment Operators
ØAssignment operators are used to assign the result of an expression to a variable.
Ø Assignment Operator is =
Syntax: variable = expression;
Ø Types of assignment:
Ê Single Assignment Ex: a = 10;
Ê Multiple Assignment Ex: a=b=c=0;
Ê Compound Assignment Ex: c = a + b;
Operator Meaning Example Equivalent
+= Addition with assignment a +=5 a= a+5
-= Subtraction with assignment a –=6 a=a-6
*= Multiplication with assignment a *=5 a=a*5
/= Division with assignment a /=5 a=a/5
%= Remainder with assignment a %=5 a=a%5
Syntax: operand1 arithmetic assigntment operator operand2
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 82
5. Increment and Decrement Operators
Ê We can add or subtract 1 to or from variables by using increment (++) and decrement (--)
operators.
Ê The operator ++ adds 1 to the operand and the operator – – subtracts 1.
Ê They can apply in two ways: postfix and prefix.
Ê Syntax: increment or decrement operator operand
operand increment or decrement operator
Ê Prefix form: Variable is changed before expression is evaluated
Ê Postfix form: Variable is changed after expression is evaluated.
Operator Meaning Example Equivalent
++ Prefix or Pre Increment ++i i=i+1; i+=1
++ Postfix or Post Increment i++ i=i+1; i+=1
-- Prefix or Pre Decrement --i i=i-1; i-=1
-- Postfix or Pot Decrement i-- i=i-1; i-=1
Operator Description
Pre increment operator (++x) value of x is incremented before assigning it to the variable on the left
Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the variable on the left
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 84
6. Conditional (ternary)Operators ( ?: )
C’s only conditional (or ternary) operator requires three operands.
Syntax: conditional expression? expression1: expression2;
The conditional expression is any expression that results in a true (nonzero) or false (zero).
If the result is true then expression1 executes, otherwise expression2 executes.
Example: a=1;
b=2;
x = (a<b)?a:b;
This is like
if(a<b)
x=a;
else
x=b;
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 85
7. Bitwise Operators
Ø C has a special operator known as Bitwise operator for manipulation of data at bit level.
Ø Bitwise operator may not be applied for float and [Link] the data which is in binary form.
Ø Syntax: operand1 bitwise operator operand2
Operator Meaning Example
A B A&B A|B A^B
& bitwise AND a&b
0 0 0 0 0
| bitwise OR a|b 0 1 0 1 1
^ bitwise exclusive OR a^b 1 0 0 1 1
<< shift left (shift left means multiply by 2) a<< 2 1 1 1 1 0
>> shift right (shift right means divide by 2) a>>2
Ø Examples:
& Bitwise AND 0110 & 0011 0010
| Bitwise OR 0110 | 0011 0111
^ Bitwise XOR 0110 ^ 0011 0101
<< Left shift 01101110 << 2 10111000
>> Right shift 01101110 >> 3 00001101
~ One's complement ~0011 1100
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 86
7. Bitwise Operators Cont…
ØShift right:
Ø>> is a binary operator that requires two integral operands. the first one is value to be shifted, the
second one specifies number of bits to be shifted.
Ø The general form is as follows:
variable >> expression;
Ø When bits are shifted right, the bits at the rightmost end are deleted.
Ø Shift right operator divides by a power of 2. I.e. a>>n results in a/2n, where n is number of bits to be
shifted.
Example: a=8;
b=a>>1; // assigns 4 after shift right operation
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 87
7. Bitwise Operators Cont…
Ø Shift left:
Ø << is a binary operator that requires two integral operands. the first one is value to be shifted, the second one
specifies number of bits to be shifted.
Ø The general form is as follows:
variable << expression;
Ø When bits are shifted left, the bits at the leftmost end are deleted.
Example: a=8;
b=a<<1; // assigns 16 after left shift operation
Ø Shift left operator multiply by a power of 2, a<<n results in a*2n, where n is number of bits to be shifted.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 88
[Link] Operators
Operator Meaning
& Address operator, it is used to determine address of the variable.
* Pointer operator, it is used to declare pointer variable and to get value from it.
, Comma operator. It is used to link the related expressions together.
sizeof It returns the number of bytes the operand occupies.
. member selection operator, used in structure.
-> member selection operator, used in pointer to structure.
comma operator :
Ø It doesn’t operate on data but allows more than one expression to appear on the same line.
Example: int i = 10, j = 20; printf (%d %.2f %c”, a,f,c);
j = (i = 12, i + 8); //i is assigned 12 added to 8 produces 20
sizeof Operator :
Ø It is a unary operator (operates on a single value).
Ø Produces a result that represent the size in bytes.
Syntax: sizeof(datatype);
Example: int a = 5; sizeof (a); //produces 2
sizeof(char); // produces 1
sizeof(int); // produces 2
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 89
Data types
Data types are used to indicate the type of value represented or stored in a variable, the number
of bytes to be reserved in memory, the range of values that can be represented in memory, and
the type of operation that can be performed on a particular data value.
ANSI C supports 3 categories of data types:
Ê Built-in data types
Ê Derived data types
Ê User Defined data types
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 90
Data types Cont…
Built-in data types:
Ê Built-in data types are also known as primitive data types. C uses the
Ê following primitive data types.
int integer quantity
char character (stores a single character)
float floating point number
double floating point number
[Link] data type:
Ê An integer number (also called whole number) has no fractional part or decimal point.
Ê The keyword int is used to specify an integer variable.
Ê It occupies 2 bytes (16 bits) or 4 bytes (32 bits), depending on the machine architecture.
Ê 16-bit integer can have values in the range of -32768 to 32767
Ê One bit is used for sign.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 91
Data types Cont…
[Link] data type:
Ê Defines an empty data type which can then be associated with some data types. It is useful with pointers.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 92
Data types Cont…
[Link] Data Type :
Ê The shortest data type is character.
Ê The keyword char is used to declare a variable of a character type.
Ê It is stored in 1 byte in memory.
Ê Corresponding integer values for all characters are defined in ASCII (American Standard Code for
Information Interchange).
Ê Example: character constant ‘a’ has an int value 97, ‘b’ has 98, ‘A’ has 65 etc.
Ê Character can have values in the range of -128 to 127.
Character Types
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 93
Data types Cont…
4. floating point data type:
Ê The keyword float is used to declare a variable of the type float.
Ê The float type variable is usually stored in 32 bits, with 6 digits of precision.
Ê A float variable can have values in the range of 3.4E-38 to 3.4 E+38.
5. double data type:
Ê A floating point number can also be represented by the double data type.
Ê The data type double is stored on most machines in 64 bits which is about 15 decimal places of accuracy.
Ê To declare a variable of the type double, use the keyword double.
Ê A double variable can have values in the range of 1.7E-308 to +1.7E+308.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 96
Precedence and Associativity
Ø Precedence is used to determine the order in which different operators in a complex expression are evaluated.
Ø Associativity is used to determine the order in which operators with the same precedence are valuated in a
complex expression.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 97
Precedence and Associativity
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 98
Expression Evaluation
A side effect is an action that results from the evaluation of an expression.
For example, in an assignment, C first evaluates the expression on the right of the assignment operator and then
places the value in the left variable.
Changing the value of the left variable is a side effect.
Left-to-Right Associativity
Right-to-Left Associativity
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 99
Expression
ØExpression
ÊAn expression is a sequence of operands and operators that reduces to a single value.
Ê Expressions can be simple or complex.
Ê An operator is a syntactical token that requires an action be taken.
Ê An operand is an object on which an operation is performed; it receives an operator’s action.
ØPrimary Expression:
ÊThe most elementary type of expression is a primary expression.
Ê It consists of only one operand with no operator.
Ê In C, the operand in the primary expression can be a name, a constant,or a parenthesized expression.
Ê Name is any identifier for a variable, a function, or any other object in the language.
Ê The following are examples of primary expressions:
ÊExample: a price sum max
Ê Literal Constants is a piece of data whose value can’t change during the execution of the program.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 100
Expression
ØThe following are examples of literal constants used in primary expression:
Example: ‘A’ 56 98 12.34
Ø Any value enclosed in parentheses must be reduced in a single value is called as primary expression.
Ø The following are example of parentheses expression:
Example: (a*x + b) (a-b*c) (x+90)
Post fix expression:
ØIt is an expression which contains operand followed by one operator.
Example: a++; a- -;
Ø The operand in a postfix expression must be a variable.
Ø (a++) has the same effect as (a = a + 1)
Ø If ++ is after the operand, as in a++, the increment takes place after the expression is evaluated.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 101
Expression
In the following figure:
1. Value of the variable a is assigned to x #include<stdio.h>
2. Value of the a is incremented by 1. void main()
{
a=10;
x=a++;
printf(“x=%d, a=%d”,x,a);
}
Output:
x=10, a=11
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 102
Expression
Pre fix expression:
Ê It is an expression which contains operator followed by an operand.
ÊExample: ++a; - -a;
Ê The operand of a prefix expression must be a variable.
Ê (++a) has the same effect as (a = a + 1)
Ê If ++ is before the operand, as in ++a, the increment takes place before the expression is evaluated.
#include<stdio.h>
void main()
{ a=10;
x=++a;
printf(“x=%d, a=%d”,x,a);
}
Output:
x=11, a=11
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 103
Expression
Unary expression:
Ê It is an expression which consists of unary operator followed by the operand
Binary Expressions:
ÊIn binary expression operator must be placed in between the two operands.
ÊBoth operands of the modulo operator (%) must be integral types.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 104
Type conversion
Up to this point, we have assumed that all of our expressions involved data of the same type.
But, what happens when we write an expression that involves two different data types, such as
multiplying an integer and a floating-point number?
To perform these evaluations, one of the types must be converted.
Type Conversion: Conversion of one data type to another data type.
Type conversions are classified into:
ÊImplicit Type Conversion
ÊExplicit Type Conversion (Cast)
Ø Implicit Conversion:
ØIn implicit type conversion, if the operands of an expression are of different types, the lower data type
is automatically converted to the higher data type before the operation evaluation.
Ø The result of the expression will be of higher data type.
Ø The final result of an expression is converted to the type of the variable on the LHS of the assignment
statement, before assigning the value to it.
Ø Conversion during assignments:
char c = 'a‘; int i;
i = c; /* i is assigned by the ascii of ‘a’ */
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 105
Type Conversion Cont…
Ê Arithmetic Conversion: If two operands of a binary operator are not the same type, implicit conversion
occurs:
int i = 5 , j = 1;
float x = 1.0, y;
y = x / i; /* y = 1.0 / 5.0 */
y = j / i; /* y = 1 / 5 so y = 0 */
Explicit Conversion or Type Casting:
ÊIn explicit type conversion, the user has to enforce the compiler to convert one data type to another data
type by using typecasting operator.
Ê This method of typecasting is done by prefixing the variable name with the data type enclosed within
parenthesis.
(data type) expression
Ê Where (data type) can be any valid C data type and expression is any variable, constant or a combination of
both.
ÊExample: int x;
x=(int)7.5;
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 106
Type Conversion Cont…
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 107
Chapter - 5
Computer
ØStatements
Ê A statement causes an action to be performed by the program.
Ê It translates directly into one or more executable computer instructions.
Ê Generally statement is ended with semicolon.
Ê Most statements need a semicolon at the end; some do not. Compound statements are used to group the
statements into a single executable unit.
Ê It consists of one or more individual statements enclosed within the braces { }
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 Unit-1 Introduction
– Introduction to C System
to Operating Programming Language 109
Decision Control Structures
ØThe decision is described to the computer as a conditional statement that can be answered
either true or false.
ØIf the answer is true, one or more action statements are executed.
ØIf the answer is false, then a different action or set of actions is executed.
Types of decision control structures:
Ê if
Ê if..else
Ê nested if…else
Ê else if ladder
Ê dangling else
Ê switch statement
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-1
#3140702 (OS) Unit 1 – Introduction Introduction
to Cyber Security
Operating to C Programming Language
System 110
Decision Control Statement: if..else
The general form of a simple if statement is: Enter
if (condition)
{ Condition
statement-block;
} ELSE Statement
else IF Statement
{
Statement-block;
} Exit
Rules:
Ê The expression or condition which is followed by if statement Example:
must be enclosed in parenthesis. main()
Ê No semicolon is needed for an if…else statement. { int a=10,b=20;
Ê Both the true and false statements can be any statement (even if(a>b)
another if…else)
{printf(“%d”,a);}
Ê Multiple statements under if and else should be enclosed
between curly braces. else
Ê No need to enclose a single statement in curly braces. {printf(“%d”,b);}
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 111
Decision Control Statement: else if Ladder
Rules:
if (condition1)
Ê The conditions are evaluated from the top to statements1;
down.
else if (condition2)
Ê As soon as a true condition is found the statements2;
statement associated with it is executed and
else if (condition3)
the control is transferred to the statement x
by skipping the rest of the ladder. statements3;
else if (condition4)
Ê When all n conditions become false,final
else containing default_statementthat will statements4;
be executed ……
else if(conditionn)
statementsn;
else
default_statement;
statement x;
[Link],
Prof. [Link],
Firoz Asst.
Asst.
A Sherasiya Professor,CSE
Professor,CSE Unit-1
Unit-1
Introduction
#3140702 (OS) Unit 1 – Introduction to Introduction
to Operating
to C Programming
Operating System Systems Language 112
Dangling else
else is always paired with the most recent unpaired if. To avoid dangling else problem place the inner if statement with in
the curly braces.
[Link],
Prof. [Link],
Firoz Asst.
Asst.
A Sherasiya Professor,CSE
Professor,CSE Unit-1
Unit-1
Introduction
#3140702 (OS) Unit 1 – Introduction to Introduction
to Operating
to C Programming
Operating System Systems Language 113
Decision Control Statement: switch
Ê It is a multi-way conditional statement generalizing the if…else statement.
Ê It is a conditional control statement that allows some particular group of statements to be chosen from
several available groups.
Ê A switch statement allows a single variable to be compared with several possible case labels, which are
represented by constant values.
Ê If the variable matches with one of the constants, then an execution jump is made to that point.
Ê A case label cannot appear more than once and there can only be one default expression.
Ê Note: switch statement does not allow less than ( < ), greater than ( > ).
Ê ONLY the equality operator (==) is used with a switch statement.
Ê The control variable must be integral (int or char) only.
Ê When the switch statement is encountered, the control variable is evaluated.
Ê Then, if that evaluated value is equal to any of the values specified in a case clause, the statements
immediately following the colon (“:”) begin to run.
Ê Default case is optional and if specified, default statements will be executed, if there is no match for the
case labels.
Ê Once the program flow enters a case label, the statements associated with case have been executed, the
program flow continues with the statement for the next case. (if there is no break statement after case
label.)
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 114
Decision Control Statement: switch
General format of switch:
Ê If you want to execute only one case-label, C provides
break statement.
Ê It causes the program to jump out of the switch
statement, that is go to the closing braces (}) and
continues the remaining code of the program.
Ê If we add break to the last statement of the case, the
general form of switch case is as follows:
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 115
Loops in C
Ê C has three loop statements: the while, the for, and the do…while. The first two are pretest loops, and the
third is a post-test loop.
Ê We can use all of them for event-controlled and counter-controlled loops.
Ê A looping process, in general, would include the following four steps:
Ê Before a loop start, the loop control variable must be initialized; this should be done before the first
execution of loop body.
Ê Test for the specified condition for execution of the loop, known as loop control expression.
Ê Executing the body of the loop, known as actions.
Ê Updating the loop control variable for performing next condition checking.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 116
Loops in C
while
Ê The "while" loop is a generalized looping structure that employs a variable or expression for testing the
condition.
Ê It is a repetition statement that allows an action to be repeated while some conditions remain true.
Ê The body of while statement can be a single statement or compound statements.
Ê It doesn’t perform even a single operation if condition fails.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 118
Loops in C Cont…
do-while
Ê The “do while" loop is a repetition statement that allows an action to be done at least once and then
condition is tested.
Ê On reaching do statement, the program proceeds to evaluate the body of the loop first.
Ê At the end of the loop, condition statement is evaluated.
Ê If the condition is true, it evaluates the body of the loop once again.
Ê This process continues up to the condition becomes false.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 119
Loops in C Cont…
Example 3: To print fibonacci sequence for the given Example 4: To print multiplication table for 5.
number.
#include <stdio.h>
#include<stdio.h> void main()
main() {
{ int i = 1, n=5;
int a=0,b=1,c,i; do
i=1; {
printf("%d%d",a,b); printf(“ %d * %d = %d “, n, i, n*i);
do i = i + 1;
{ } while ( i<= 5);
c=a+b; }
i++;
printf("%3d",c);
a=b;
b=c;
}while(i<=10);
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 120
Loops in C Cont…
for
Ê A for loop is used when a loop is to be executed a known number of times.
Ê We can do the same thing with a while loop, but the for loop is easier to read and more natural for counting
loops.
Ê General form of the for is:
for( initialization; test-condition; updation)
{
Body of the loop
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 121
Loops in C Cont…
Compare between while and for loops
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 122
Loops in C Cont…
Ê Option 3: The infinite loop
Ê One of the most interesting uses of the for loop is the creation of the infinite loop. Since none of the three expressions
that form the for loop are required, it is possible to make an endless loop by leaving the conditional expression empty.
Ê For example: for (; ;)
printf(“The loop will run forever\n”);
Ê Actually the for (; ;) construct does not necessarily create an infinite loop because C’s break statement, when
encountered anywhere inside the body of a loop, causes immediate termination of the loop.
Ê Program control then picks up the code following the loop, as shown here:
for (; ;)
{
ch = getchar( ); /* get a character */
if (ch = = ‘A’)
break ;
}
printf (“you typed an A”);
Ê This loop will run until A is typed at the keyboard.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 123
Loops in C Cont…
Ê Option 3: For loop with no body
Ê A statement, as defined by the C syntax, may be empty.
Ê This means that the body of the for may also be empty.
Ê This fact can be used to improve the efficiency of certain algorithms as well as to create time delay loops.
Ê The following statement shows how to create a time delay loop using a for loop:
for (t = 0; t < SOME VALUE; t++);
Ê The operator comma , is used to separate the more than one expressions.
Ê A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the type
and value of the right operand.
Ê Thus, in a for statement, it is possible to place multiple expressions in the various parts.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 124
Others statements/Jumping Statements
1. break
Ê When a break statement is enclosed inside a block or loop, the loop is immediately exited and program continues with the
next statement immediately following the loop.
Ê When loop are nested break only exit from the inner loop containing it.
Ê The format of the break statement is: Example 6: Program to demonstrate break
statement.
#include<stdio.h>
main()
{
int i;
i=1;
while(i<=10)
{
if(i==8)
break;
printf(“%d”,i);
i=i+1;
}
printf(“\n Thanking You”);
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 125
Others statements /Jumping Statements
2. Continue
Ê When a continue statement is enclosed inside a block or loop, the loop is to be continued with the next
iteration.
Ê The continue statement tells the compiler, skip the following statements and continue with the next iteration.
Ê The format of the continue statement is: Example 5: Program to demonstrate
continue statement.
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;i++)
{
if(i = = 3)
continue;
printf(" %d",i);
}
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 126
Others statements/Jumping Statements
3. goto
Ê goto is an unconditional statement used to transfer the control from one statement to another statement in
the program.
Ê Syntax: Example 5: Program to demonstrate goto
Label: Statements; goto label; statement.
#include <stdio.h>
Ê The format of the gotostatement is:
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf("%d ", i);
if(i==5)
goto end;
}
end:
printf("\nEnd of the program");
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya Unit-1
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Security
Operating to C Programming Language
System 127
Programming for Problem Solving(PPS)
Thank
You
D. SRINIVAS
ComputerInstitute
Darshan Scienceofand Engineering
Engineering DepartmentRajkot
& Technology,
srinivascsedept@[Link]
+91-9347556447
Programming for Problem Solving (PPS)
Department of CSE
Darshan Institute of Engineering & Technology, Rajkot
[Link]
srinivascsedept@[Link]
+91 9347556447
Outline
Looping
• Arrays:
Êone- and two-dimensional arrays,
Êcreating, accessing and manipulating elements of arrays.
• Strings:
ÊIntroduction to strings,
Êhandling strings as array of characters,
ÊBasic string functions available in C (strlen, strcat, strcpy, strstr etc.),
Êarrays of strings.
• Structures:
ÊDefining structures, initializing structures,
Êunions,
ÊArray of structures
• Pointers:
ÊIdea of pointers, defining pointers,
ÊPointers to Arrays and Structures,
ÊUse of Pointers in self- referential structures,
Êusage of self-referential structures in linked list (no implementation),
ÊEnumeration data type.
Chapter - 1
Arrays in C
How to create an array:
Ê Creation of an consists two things: Element Type and Array Size.
Ê Element Type: What kind of data an array can hold?
An array can hold any one of the following data:
integer, double, character data.
Ê Array Size: How many elements an array can contain?
Once an array size is defined it cannot be changed at run-time
Using arrays in C:
Ê In C, arrays can be classified based on how the data items are arranged for human understanding. Arrays are
broadly classified into three categories,
1. One Dimensional Arrays
2. Two Dimensional Arrays
3. Multi Dimensional Arrays
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 132
Arrays in C
One Dimensional Arrays:
Ê One dimensional array is a linear list consisting of related and similar Data items.
Ê In memory all the data items are stored in contiguous memory locations one after the other.
Ê Syntax for declaring One Dimensional Arrays:
elementType arrayName[size];
Ê Where elementType specifies data type of each element in the array,arrayName specifies name of the
variable you are declaring and size specifies number of elements allocated for this array.
Ê To declare regular variables we just specify a data type and a unique name.
Ê Example: int number;
Ê To declare an array, we just add an array size.
Example: int temp[5]; //Creates an array of 5 integer elements.
Example: double stockprice[31]; //Creates an array of 31 double elements.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 133
Arrays in C
Initializing One Dimensional Arrays:
Ê If array is not initialized it contain garbage values.
Ê Types of array initializations:
Option 1: Initializing all memory locations
Option 2: Initialization without size
Option 3: Partial array initialization
Option 4: Initializing an entire array with zero.
Option 1: Initializing all memory locations:
Ê If you know all the data at compile time, you can specify all your data within brackets:
int temp [5] = {75, 79, 82, 70, 68};
Ê During compilation, 5 contiguous memory locations are reserved by the compiler for the variable temp and
all these locations are initialized as shown below.
Ê If the size of integer is 2 bytes, 10 bytes will be allocated for the variable temp.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 134
Arrays in C
Option 2: Initialization without size:
Ê If you omit the size of an array, but specify an initial set of data, then the compiler will automatically
determine the size of an array.
int temp [] = {75, 79, 82, 70, 68};
Ê In the above declaration, even though you have not specified exact number of elements to be used in array
temp, the array size will be set with the total number of initial values specified.
Ê Here, the compiler creates an array of 5 elements. The array temp is initialized as shown below.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 135
Arrays in C
Option 3 Partial Array Initialization:
Ê If the number of values to be initialized is less than the size of the array, then the elements are initialized in
the order from 0th location.
Ê The remaining locations will be initialized to zero automatically.
int temp [5] = {75, 79, 82};
Ê Even though compiler allocates 5 memory locations, using the above declaration statement, the compiler
initializes first three locations with 75, 70 and 82, and the next set of memory locations are automatically
initialized to 0’s by the compiler as shown below.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 136
Arrays in C
Option 4: Initializing an entire array with zero:
Ê If you do not know any data ahead of time, but you want to initialize everything to 0, just use 0 within { }. For
example:
int temp [5] = {0};
Ê This will initialize every element within the array to 0 as shown below.
Ê Example:
int temp [5] = {5};
Ê The first value is supplied in the first element memory location, remaining all elements are placed with zero.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 137
Arrays in C
Accessing elements of one dimensional array:
Ê You know how to declare and initialize an array. Now lets understand, how to access an array elements.
Ê To access an array element use name of the array with the subscript in brackets.
Ê Suppose you have an array called temperature, for storing temperature in a year.
Ê Then the subscripts would be 0,1,…,364.
Ê For example to access temperature of fifth day:
temperature [4]
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 139
Arrays in C
#include <stdio.h>
void main()
{
int a[10];
int i, size, total=0;
printf(“ Enter the size of the array : ");
scanf("%d", &size);
printf(“ Enter the elements of an array : ");
for (i = 0; i < size ; i++)
scanf("%d",&a[i]);
for (i = 0; i < size ; i++)
total += a[i];
printf(“Sum of all array elements: %d", total);
}
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 140
Arrays in C
Two Dimensional Arrays:
Ê Two-dimensional array are those type of array, which has finite number of rows and finite number of
columns.
Ê An array of array is called a two-dimensional array and can be represented as a table with rows and
columns.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 144
Arrays in C
Multi Dimensional Arrays:
Ê C allows three or more dimensions. The exact limit is determined by the compile.
Ê The general form of multidimensional array is
elementType arrayName [s1][s2][s3]…[sm];
Ê Where si is the size of the ith dimension.
Ê Array declarations read right-to-left
Ê For Example: int a[3][5][4];
Ê It is represented as “an array of ten arrays of three arrays of two ints”
Ê In memory the elements are stored as shown in below figure.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 145
Arrays in C
Example:
int table[3][5][4] = {
{
{000,001,002,003},
{010,011,012,013},
{020,021,022,023},
{030,031,032,033},
{040,041,032,043}
},
{
{100,101,102,103},
{110,111,112,113},
{120,121,122,123},
{130,131,132,133},
{140,141,142,143}
},
{
{200,201,202,203},
{210,211,212,213},
{220,221,222,223},
{230,231,232,233},
{240,241,242,243}
}
};
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 146
Arrays in C
Inter-function communication (Functions with Arrays):
Ø Like the values of variable, it is also possible to pass values of an array to a function.
Ø There are two types of passing an array to the function:
Ø 1. Passing Individual Elements
Ø 2. Passing the whole array
1. Passing Individual Elements:
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 147
Arrays in C
2. Passing the whole array:
Ê To pass an array to a called function, it is sufficient to list the name of the array, without any subscripts, and
the size of the array as arguments.
Ê For example, the function call findMax(a, n); will pass all the elements contained in the array a of size n.
Ê The called function expecting this must be appropriately defined.
Ê The findMax function header looks like: int findMax(int x[], int size)
Ê The pair of brackets informs the compiler that the argument x is an array of numbers. It is not necessary to
specify the size of the array here.
Ê The function prototype takes of the form
int findMax (int [], int );
int findMax (int a [], int );
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 148
Arrays in C
//Program to read an array of elements and find max value. int findMax(int x[],int size)
#include<stdio.h> {
int findMax(int[],int); int temp;
void main() temp=x[0];
{ for(i=1;i<size; i++)
int a[10], n ,i , max; {
printf(“\n Enter the size of the array “); if(x[i]>temp)
scanf(“%d”,&n); {
printf(‘\n Enter the elements of the array : “); temp=x[i];
for(i=0;i<n;i++) }
scanf(“%d”,&a[i]); }
max=findMax(a, n); return temp;
printf(“\n The Maximum value =%d”, max); }
}
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 149
Chapter - 2
Strings
Character Arrays and Strings:
Ê String is a sequence of characters.
Ê If ‘\0’ is present after a series of characters in an array, then that array becomes a string otherwise it is a
character array.
Ê Example:
char arr[] = {'a', 'b', 'c'}; //This is an array
char arr[] = {'a', 'b', 'c', ‘\0’ }; //This is a string
Strings:
Ê A C string is a variable-length array of characters that is delimited by the null character.
Ê A string is a sequence of characters.
Ê A string literal is enclosed in double quotes.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 151
Strings
Declaring And Initializing String Variables
Declaring a String:
Ê A string variable is a valid C variable name and always declared as an array.
Ê The general form of declaration of a string variable is,
char string name [size];
Ê The size determines the number of characters in the string name.
Ê When the compiler assigns a character string to a character array, it automatically supplies a null
character(‘\0’) at the end of the string.
Ê The size should be equal to the maximum number of characters in the string plus one.
Initializing a String: This can be done in two ways.
1. char str1[7]=“Welcome”;
2. char str2[8]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’,’\0’};
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 153
Strings Munipulation Functions
The C Library provides a rich set of string handling functions that are placed under the header
file <string.h> and <ctype.h>.
Ê Some of the string handling functions are (string.h):
strlen() strcat() strcpy() strrchr()
strcmp() strstr() strchr() strrev()
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 154
Strings Munipulation Functions
strlen () function:
Ê This function counts and returns the number of characters in a string. It takes the form
Syantax: int n=strlen(string);
Ê Where n is an integer variable, which receives the value of the length of the string. The counting ends at the first null
character.
strcat () function:
Ê The strcat function joins two strings together.
Ê It takes of the following form:
strcat(string1,string2);
Ê string1 and string2 are character arrays.
Ê When the function strcat is executed, string2 is appended to string1.
Ê It does so by removing the null character at the end of string1 and placing string2 from there.
Ê strcat function may also append a string constant to a string variable. The following is valid.
strcat(part1,”Good”);
Ê C permits nesting of strcat functions.
Ê Example:
strcat(strcat(string1,string2),string3);
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 155
Strings Munipulation Functions
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 156
Strings Munipulation Functions
strcmp () function:
Ê The strcmp function compares two strings, it returns the value 0 if they are equal.
Ê If they are not equal, it returns the numeric difference between the first non matching characters in the
strings.
Ê It takes the following form:
strcmp(str1,str2);
Ê returning value less than 0 means ''str1'' is less than ''str2'‘
Ê returning value 0 means ''str1'' is equal to ''str2'‘
Ê returning value greater than 0 means ''str1'' is greater than ''str2''
Ê string1 and string2 may be string variables or string constants.
Ê Example:
strcmp(name1,name2);
strcmp(name1,”John”);
strcmp(“their” ,”there”);
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 157
Strings Munipulation Functions
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 158
Strings Munipulation Functions
strcpy () function:
Ê It copies the contents of one string to another [Link] takes the following form:
strcpy(string1,string2);
Ê The above function assign the contents of string2 to string1.
Ê string2 may be a character array variable or a string constant.
Ê Example: strcpy(city ,”Delhi”);
strcpy(city1,city2):
strrev() function:
Ê Reverses the contents of the string. It takes of the form
strrev(string); Example:
#include<stdio.h>
#include<string.h>
void main(){
char s[]=”hello”;
strrev(s);
puts(s);
}
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 159
Strings Munipulation Functions
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 160
Strings Munipulation Functions
strstr () function:
Ê It is a two-parameter function that can be used to locate a sub-string in a string.
Ê It takes the form:
Ê strstr (s1, s2);
Ê Example: strstr (s1,”ABC”);
Ê The function strstr searches the string s1 to see whether the string s2 is contained in [Link] yes, the function
returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL pointer.
strchr() function:
Ê It is used to determine the existence of a character in a string.
Ê Example: strchr (s1,’m’); //It locates the first occurrence of the character ‘m’.
Ê Example: strrchr(s2,’m’); //It locates the last occurrence of the character ‘m’.
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 161
Strings Munipulation Functions
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 162
Strings Munipulation Functions
strcat () function:
Ê It is used to join only two Strings at a time.
Ê It takes the form:
Ê strcat (s1, s2);
Ê Example: strcat (s1,”CAT”);
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 163
Strings Munipulation Functions
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 164
Strings Munipulation Functions
Ê The basic string span function, strspn, searches the string, spanning characters that are in the set and
stopping at the first character that is not in the set.
Ê They return the number of characters that matched those in the set.
Ê If no characters match those in the set, they return zero.
Ê The function declaration is shown below:
int strspn(const char* str, const char* set);
Ê The second function, strcspn, is string complement span; its functions stop
Ê at the first character that matches one of the characters in the set.
int strcspn(const char* str, const char* ste);
String Span
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 165
String Example program
/*Define functions- length of a string, copy, concatenate, convert into uppercase letters, compare two strings for
alphabetical order- over strings and implement in a program*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
main() {
char str1[15],str2[15],str3[10];
int n,c,len,i;
printf("\n Enter the string1 ");
gets(str1);
puts(str1);
printf("\n Enter the string2 ");
gets(str2);
puts(str2);
printf("Enter the string 3 ");
scanf("%s",str3);
printf("%s",str3);
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 166
String Example program
printf("\n***************************");
printf("\n 1. String Length ");
printf("\n 2. String Copy ");
printf("\n 3. String Comparison ");
printf("\n 4. String Concat ");
printf("\n 5. UpperCase ");
printf("\n***************************");
printf("\n Enter the choice u want to perform");
scanf("%d",&n);
switch(n)
{
case 1: len=strlen(str1);
printf("\n The length of the string entered is %d",len);
break;
case 2: strcpy(str1,str2);
printf("\n 1st string =%s,2nd string=%s",str1,str2);
break;
case 3: c=strcmp(str1,str2);
if(c==0)
printf("\n Both are equal");
else
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 167
String Example program
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-2
#3140702 (OS) Unit 1 – Introduction to Cyber
Arrays,
Security
Operating Strings,
System Structures and Pointers 168
Chapter - 3
The Type Definition (typedef)
typedef :
Ê A type definition, typedef, gives a name to a data type by creating a new type that can then be used anywhere
a type is permitted.
Ê Its purpose is to redefine the name of an existing variable type.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 172
What is Structure?
Structure is a collection of logically related data items of different datatypes grouped together
under single name.
Structure is a user defined datatype.
Structure helps to build a complex datatype which is more meaningful than an array.
But, an array holds similar datatype record, when structure holds different datatypes records.
Two fundamental aspects of Structure:
Ê Declaration of Structure Variable
Ê Accessing of Structure Member
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 173
Syntax to Define Structure
To define a structure, we need to use struct keyword.
This keyword is reserved word in C language. We can only use it for structure and its object
declaration.
Syntax structure_name is name of custom type
1 struct structure_name
2 {
3 member1_declaration;
4 member2_declaration; memberN_declaration is individual member
5 . . . declaration
6 memberN_declaration;
7 };
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 174
Create Structure variable
A data type defines various properties about data stored in memory.
To use any type we must declare its variable.
Hence, let us learn how to create our custom structure type objects also known as structure
variable.
In C programming, there are two ways to declare a structure variable:
1. Along with structure definition
2. After structure definition
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 175
Create Structure Variable – Cont.
1. Declaration along with the structure definition
Syntax Example
1 struct structure_name 1 struct student
2 { 2 {
3 member1_declaration; 3 char name[30]; // Student Name
4 member2_declaration; 4 int roll_no; // Student Roll No
5 . . . 5 float CPI; // Student CPI
6 memberN_declaration; 6 int backlog; // Student Backlog
7 } structure_variable; 7 } student1;
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 176
Create Structure Variable – Cont.
2. Declaration after Structure definition
Syntax
1 struct structure_name structure_variable;
Example
1 struct student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 };
8 struct student student1; // Declare structure variable
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 177
Access Structure member (data)
Structure is a complex data type, we cannot assign any value directly to it using assignment
operator.
We must assign data to individual structure members separately.
C supports two operators to access structure members, using a structure variable.
1. Dot/period operator (.)
2. Arrow operator (->)
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 178
Access Structure member (data) – Cont.
1. Dot/period operator (.)
Ê It is known as member access operator. We use dot operator to access members of simple structure variable.
Syntax Example
1 structure_variable.member_name; 1 // Assign CPI of student1
2. Arrow operator (->)
2 [Link] = 7.46;
Ê In C language it is illegal to access a structure member from a pointer to structure variable using dot
operator.
Ê We use arrow operator to access structure member from pointer to structure.
Syntax Example
1 pointer_to_structure->member_name; 1 // Student1 is a pointer to student type
2 student1 -> CPI = 7.46;
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 179
Write a program to read and display student information using structure.
Program Output
1 #include <stdio.h> Enter Student Name:aaa
2 struct student Enter Student Roll Number:111
3 {
4 char name[40]; // Student name Enter Student CPI:7.89
5 int roll; // Student enrollment Enter Student Backlog:0
6 float CPI; // Student mobile number
7 int backlog; Student using simple structure variable.
8 };
9 int main()
Student name: aaa
10 { Student Enrollment: 111
11 struct student student1; // Simple structure variable Student CPI: 7.890000
12 // Input data in structure members using dot operator Student Backlog: 0
13 printf("Enter Student Name:");
14 scanf("%s", [Link]);
15 printf("Enter Student Roll Number:");
16 scanf("%d", &[Link]);
17 printf("Enter Student CPI:");
18 scanf("%f", &[Link]);
19 printf("Enter Student Backlog:");
20 scanf("%d", &[Link]);
21 // Display data in structure members using dot operator
22 printf("\nStudent using simple structure variable.\n");
23 printf("Student name: %s\n", [Link]);
24 printf("Student Enrollment: %d\n", [Link]);
25 printf("Student CPI: %f\n", [Link]);
26 printf("Student Backlog: %i\n", [Link]);
27 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 180
Write a program to declare time structure and read two different time period and display sum of it.
Program
1 #include<stdio.h> 27 scanf ("%d",&[Link]);
2 struct time { 28 printf ("The Time is
3 int hours; 29 %d:%d:%d",[Link],[Link],[Link]
4 int minutes; 30 ds);
5 int seconds; 31 h = [Link] + [Link];
6 }; 32 m = [Link] + [Link];
7 int main() { 33 s = [Link] + [Link];
8 struct time t1,t2; 34 printf ("\nSum of the two time's is
9 int h, m, s; 35 %d:%d:%d",h,m,s);
10 //1st time 36 return 0;
11 printf ("Enter 1st time."); 37 }
12 printf ("\nEnter Hours: ");
13 scanf ("%d",&[Link]);
14 printf ("Enter Minutes: "); Output
15 scanf ("%d",&[Link]); Enter 1st time.
16 printf ("Enter Seconds: "); Enter Hours: 1
17 scanf ("%d",&[Link]); Enter Minutes: 20
18 printf ("The Time is Enter Seconds: 20
19 %d:%d:%d",[Link],[Link],[Link]); The Time is 1:20:20
20 //2nd time
21 printf ("\n\nEnter the 2nd time."); Enter the 2nd time.
22 printf ("\nEnter Hours: "); Enter Hours: 2
23 scanf ("%d",&[Link]); Enter Minutes: 10
24 printf ("Enter Minutes: "); Enter Seconds: 10
25 scanf ("%d",&[Link]); The Time is 2:10:10
26 printf ("Enter Seconds: "); Sum of the two time's is 3:30:30
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 181
Structure using Pointer
Reference/address of structure object is passed as function argument to the definition of function.
Program Output
1 #include <stdio.h> Enter Name: ABC
2 struct student {
3 char name[20]; Enter RollNo: 121
4 int rollno; Enter CPI: 7.46
5 float cpi;
6 };
7 int main() Student Details:
8 { Name: ABC
9 struct student *studPtr, stud1;
10 studPtr = &stud1; RollNo: 121
11 printf("Enter Name: "); CPI: 7.460000
12 scanf("%s", studPtr->name);
13 printf("Enter RollNo: ");
14 scanf("%d", &studPtr->rollno);
15 printf("Enter CPI: ");
16 scanf("%f", &studPtr->cpi);
17 printf("\nStudent Details:\n");
18 printf("Name: %s\n", studPtr->name);
19 printf("RollNo: %d", studPtr->rollno);
20 printf(”\nCPI: %f", studPtr->cpi);
21 return 0;
22 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 182
Nested Structure
When a structure contains another structure, it is called nested structure.
For example, we have two structures named Address and Student. To make Address nested to Student,
we have to define Address structure before and outside Student structure and create an object of
Address structure inside Student structure.
Syntax
1 struct structure_name1
2 {
3 member1_declaration;
4 member2_declaration;
5 ...
6 memberN_declaration;
7 };
8 struct structure_name2
9 {
10 member1_declaration;
11 member2_declaration;
12 ...
13 struct structure1 obj;
14 };
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 183
Write a program to read and display student information using nested of structure.
Program
1 #include<stdio.h> 27 printf("\n\tEnter Student City : ");
2 struct Address 28 scanf("%s",[Link]);
3 { 29 printf("\n\tEnter Student Pincode : ");
4 char HouseNo[25]; 30 scanf("%s",[Link]);
5 char City[25]; 31 printf("\nDetails of Students");
6 char PinCode[25]; 32 printf("\n\tStudent Name : %s",[Link]);
7 }; 33 printf("\n\tStudent Roll Number :
8 struct Student 34 %d",[Link]);
9 { 35 printf("\n\tStudent CPI : %f",[Link]);
10 char name[25]; 36 printf("\n\tStudent House No :
11 int roll; 37 %s",[Link]);
12 float cpi; 38 printf("\n\tStudent City :
13 struct Address Add; 39 %s",[Link]);
14 }; 40 printf("\n\tStudent Pincode :
15 int main() 41 %s",[Link]);
16 { 42 return 0;
17 int i; 43 }
18 struct Student s;
19 printf("\n\tEnter Student Name : "); Output
20 scanf("%s",[Link]); Details of Students
21 printf("\n\tEnter Student Roll Number : "); Student Name : aaa
22 scanf("%d",&[Link]); Student Roll Number : 111
23 printf("\n\tEnter Student CPI : "); Student CPI : 7.890000
24 scanf("%f",&[Link]); Student House No : 39
25 printf("\n\tEnter Student House No : "); Student City : rajkot
26 scanf("%s",[Link]); Student Pincode : 360001
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 184
Array of Structure
It can be defined as the collection of multiple structure variables where each variable contains
information about different entities.
The array of structures in C are used to store information about multiple entities of different
data types.
Syntax
1 struct structure_name
2 {
3 member1_declaration;
4 member2_declaration;
5 ...
6 memberN_declaration;
7 } structure_variable[size];
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 185
Write a program to read and display N student information using array of structure.
Program
1 #include<stdio.h> Output
2 struct student {
3 char name[20]; Enter how many records u want to store : 3
4 int rollno;
5 float cpi; Enter 1 record :
6 }; Enter Name : aaa
7 int main( ) { Enter RollNo. : 111
8 int i,n; Enter CPI : 7.89
9 printf("Enter how many records u want to store : ");
10 scanf("%d",&n); Enter 2 record :
11 struct student sarr[n]; Enter Name : bbb
12 for(i=0; i<n; i++) Enter RollNo. : 222
13 {
Enter CPI : 7.85
14 printf("\nEnter %d record : \n",i+1);
15 printf("Enter Name : ");
16 scanf("%s",sarr[i].name); Enter 3 record :
17 printf("Enter RollNo. : "); Enter Name : ccc
18 scanf("%d",&sarr[i].rollno); Enter RollNo. : 333
19 printf("Enter CPI : "); Enter CPI : 8.56
20 scanf("%f",&sarr[i].cpi);
21 } Name RollNo Marks
22 printf("\n\tName\tRollNo\tMarks\t\n"); aaa 111 7.89
23 for(i=0; i<n; i++) { bbb 222 7.85
24 printf("\t%s\t\t%d\t\t%.2f\t\n", sarr[i].name, ccc 333 8.56
25 sarr[i].rollno, sarr[i].cpi);
26 }
27 return 0;
28 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 186
Write a program to declare time structure and read two different time period and display sum of it using function.
Program
1 #include<stdio.h> Output
2 struct Time {
3 int hours; Enter Hours: 1
4 int minutes; Enter Minutes: 20
5 int seconds; Enter Seconds: 20
6 };
7 struct Time input(); // function declaration Hours : Minutes : Seconds
8 int main() 1 : 20 : 20
9 {
10 struct Time t;
11 t=input();
12 printf("Hours : Minutes : Seconds\n %d : %d :
13 %d",[Link],[Link],[Link]);
14 return 0;
15 }
16 struct Time input() // function definition
17 {
18 struct Time tt;
19 printf ("Enter Hours: ");
20 scanf ("%d",&[Link]);
21 printf ("Enter Minutes: ");
22 scanf ("%d",&[Link]);
23 printf ("Enter Seconds: ");
24 scanf ("%d",&[Link]);
25 return tt; // return structure variable
26 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 187
Unions
Ê Union can be defined as a user-defined data type which is a collection of different variables of different data
types in the same memory location.
Ê The union can also be defined as many members, but only one member can contain a value at a particular
point in time.
Ê Union is a user-defined data type, but unlike structures, they share the same memory location.
Syntax
1 union structure_name1
2 {
3 member1_declaration;
4 member2_declaration;
5 ...
6 memberN_declaration;
7 };
8 union structure_name2
9 {
10 member1_declaration;
11 member2_declaration;
12 ...
13 union structure1 obj;
14 };
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 188
Unions
Access members of a union
Ê We use the . operator to access members of a union.
Ê And to access pointer variables, we use the -> operator..
In the above example,
Ê To access price for car1, [Link] is used.
Ê To access price using car3, either (*car3).price or car3->price can be used.
Syntax
1 union car
2 {
3 char name[50];
4 int price;
5 } car1, car2, *car3;
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 189
Difference between unions and structures
Program
differences between structures and unions
1 #include <stdio.h>
Ê Here, the size of sJob is 40 bytes because 2 union unionJob
§ the size of name[32] is 32 bytes 3 {
4 char name[32];
§ the size of salary is 4 bytes 5 float salary;
§ the size of workerNo is 4 bytes 6 int workerNo;
7 } uJob;
8
9 struct structJob
10 {
11 char name[32];
12 float salary;
13 int workerNo;
14 } sJob;
Output
15 void main()
size of union = 32 16 {
size of structure = 40 17 printf("size of union = %d bytes",
18 sizeof(uJob));
19 printf("\nsize of structure = %d
20 bytes", sizeof(sJob));
21 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 190
Differences between Structures and Unions
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 191
Chapter - 4
What is Pointer?
A normal variable is used to store value.
A pointer is a variable that store address / reference of another variable.
Pointer is derived data type in C language.
A pointer contains the memory address of that variable as their value. Pointers are also
called address variables because they contain the addresses of other variables.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 193
Advantages and Disdvantages of pointers :
Advantages (Benefits) of pointers :
Ê Pointers provide direct access to memory
Ê Pointers provide a way to return more than one value to the functions
Ê Reduces the storage space and complexity of the program
Ê Reduces the execution time of the program
Ê Provides an alternate way to access array elements
Ê Pointers can be used to pass information back and forth between the calling function and called function.
Ê Pointers allows us to perform dynamic memory allocation and deallocation.
Ê Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.
Ê Pointers allows us to resize the dynamically allocated memory block.
Ê Addresses of objects can be extracted using pointers
Disadvantages (Drawbacks) of pointers :
Ê Uninitialized pointers might cause segmentation fault.
Ê Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
Ê Pointers are slower than normal variables.
Ê If pointers are updated with incorrect values, it might lead to memory corruption.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 194
Declaration & Initialization of Pointer
Syntax Output
1 datatype *ptr_variablename; 10 10 5000
Example
1 void main()
2 { Variable Value Address
3 int a=10, *p; // assign memory address of a
4 to pointer variable p a 10 5000
5 p = &a;
6 printf("%d %d %d", a, *p, p); p 5048
5000
7 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 196
Pointer to Pointer – Double Pointer
Pointer holds the address of another variable of same type.
When a pointer holds the address of another pointer then such type of pointer is known
as pointer-to-pointer or double pointer.
The first pointer contains the address of the second pointer, which points to the location that
contains the actual value.
Syntax
Pointer Pointer Variable
1 datatype **ptr_variablename;
address address value
Example
1 int **ptr;
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 197
Write a program to print variable, address of pointer variable and pointer to pointer variable.
Program
1 #include <stdio.h>
2 int main () {
3 int var;
4 int *ptr;
5 int **pptr;
6 var = 3000;
7 ptr = &var; // address of var
8 pptr = &ptr; // address of ptr using address of operator &
9 printf("Value of var = %d\n", var );
10 printf("Value available at *ptr = %d\n", *ptr );
11 printf("Value available at **pptr = %d\n", **pptr);
12 return 0;
13 }
Output
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 198
Relation between Array & Pointer
When we declare an array, compiler allocates continuous blocks of memory so that all the
elements of an array can be stored in that memory.
The address of first allocated byte or the address of first element is assigned to an array name.
Thus array name works as pointer variable.
The address of first element is also known as base address.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 199
Relation between Array & Pointer – Cont.
Example: int a[10], *p;
a[0] is same as *(a+0), a[2] is same as *(a+2) and a[i] is same as *(a+i)
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 200
Array of Pointer
As we have an array of char, int, float etc, same way we can have an array of pointer.
Individual elements of an array will store the address values.
So, an array is a collection of values of similar type. It can also be a collection of references of
similar type known by single name.
Syntax
1 datatype *name[size];
Example
1 int *ptr[5]; //declares an array of integer pointer of size 5
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 201
Array of Pointer – Cont.
An array of pointers ptr can be used to point to different rows of matrix as follow:
Example
1 for(i=0; i<5; i++)
2 {
3 ptr[i]=&mat[i][0];
4 }
ptr 0 1 2
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]
By dynamic memory allocation, we do not require to declare two-dimensional array, it can be
created dynamically using array of pointers.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 202
Write a program to swap value of two variables using pointer / call by reference.
Program
1 int main()
2 {
3 int num1,num2;
4 printf("Enter value of num1 and num2: ");
5 scanf("%d %d",&num1, &num2);
6
7 //displaying numbers before swapping
8 printf("Before Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
9
10 //calling the user defined function swap()
11 swap(&num1,&num2);
12
13 //displaying numbers after swapping
14 printf("After Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
15 return 0;
16 }
Output
Enter value of num1 and num2: 5
10
Before Swapping: num1 is: 5, num2 is: 10
After Swapping: num1 is: 10, num2 is: 5
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 203
Pointer and Function
Like normal variable, pointer variable can be passed as function argument and function can
return pointer as well.
There are two approaches to passing argument to a function:
Ê Call by value
Ê Call by reference / address
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 204
Call by Value
In this approach, the values are passed as function argument to the definition of function.
Program Output
1 #include<stdio.h> Values before calling 10, 20
2 void fun(int,int); Values after calling 10, 20
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
7 fun(A,B); Address 48252 24688
8 printf("\nValues after calling %d, %d",A,B);
9 return 0; Value 10 20 10 11 20 22
10 }
11 void fun(int X,int Y) Variable A B X Y
12 {
13 X=11;
14 Y=22;
15 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 205
Call by Reference / Address
In this approach, the references / addresses are passed as function argument to the definition
of function.
Program
Output
1 #include<stdio.h>
Values before calling 10, 20
2 void fun(int*,int*); Values after calling 11, 22
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
7 fun(&A,&B); Address 24688
48252
8 printf("\nValues after calling %d, %d",A,B);
9 return 0; Value 10 11 20 22 48252 24688
10 }
11 void fun(int *X,int *Y) Variable A B *X *Y
12 {
13 *X=11;
14 *Y=22;
15 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 206
Pointer to Function
Every function has reference or address, and if we know the reference or address of function,
we can access the function using its reference or address.
This is the way of accessing function using pointer.
Syntax
1 return-type (*ptr-function)(argument list);
return-type: Type of value function will return.
argument list: Represents the type and number of value function will take, values are sent by
the calling statement.
(*ptr-function): The parentheses around *ptr-function tells the compiler that it is pointer to
function.
If we write *ptr-function without parentheses then it tells the compiler that ptr-function is a
function that will return a pointer.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 207
Write a program to sum of two numbers using pointer to function.
Program
1 #include<stdio.h> Output
2 int Sum(int,int); Enter 1st number : 5
3 int (*ptr)(int,int);
4 int main() Enter 2nd number : 10
5 {
6 int a,b,rt; The sum is : 15
7 printf("\nEnter 1st number : ");
8 scanf("%d",&a);
9 printf("\nEnter 2nd number : ");
10 scanf("%d",&b);
11 ptr = Sum;
12 rt = (*ptr)(a,b);
13 printf("\nThe sum is : %d",rt);
14 return 0;
15 }
16 int Sum(int x,int y)
17 {
18 return x + y;
19 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 208
Enumerated Types
Enum:
Ê The enumerated type is a user-defined type based on the standard integer type.
Ê In an enumerated type, each integer value is given an identifier called an enumeration constant.
Ê Declaring an Enumerated Type:
Ê To declare an enumerated type, we must declare its identifier and its values. Because it is derived from
integer type, its operations are the same as for integers.
Ê Syntax for defining an enumerated type is as follows,
enum typeName
{
member1;
member2;
….
….
};
Ê Where enum is the keyword that tells the compiler about enumerated type definition, enum type_Name
together represent the user defined data type and member1, member2… are integer constants but
represented using descriptive names. These are called enumerator constants or enumerators.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 209
Enumerated Types
Enum:
Ê The definition is terminated with a semicolon.
Ê The syntax for declaring the variables are shown below:
enum typeName var;
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 210
Enumerated Types
Assigning Values to Enumerated Types
Ê After an enumerated variable has been declared, we can store values in it.
Ê While, the compiler automatically assigns values to enumerated types starting with 0, the next values are
initialized with a value by adding 1 to previous value.
Ê For example,
enum color {RED, BLUE, GREEN, WHITE};
Ê Here red representing the value 0, blue is 1, green is 2, white is 3.
Ê You can also create variables from the enumerated type.
Ê For example, enum color skyColor;
Ê We can override it and assign our own values.
Ê For example, to make JAN start with 1 we could use the following declaration.
Ê enum month
{
JAN=1, FEB, MAR, APR, MAY,JUN, JUL, AUG, SEP, OCT, NOV, DEC
}m1;
Ê Note that we need not to assign every enumerator constant value. If we omit the initializes, the complier assigns the next
value by adding 1.
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 211
Enumerated Types
Assigning Values to Enumerated Types
Ê Consider the following enumerated declaration,
enum days
{ //Example program to demonstrate enum
sun=3, mon, tue, wed=0, thu, fri, sat #include<stdio.h>
main()
} d1, d2; {
enum color
{
RED,
GREEN,
BLUE
}c1;
printf("%d %d%d",RED,GREEN,BLUE);
Output: c1 = BLUE;
0 1 2 printf("\n%d ",c1);
2 }
[Link],
Prof. Firoz A Asst. Professor,CSE
Sherasiya Unit-2 Arrays,
#3140702 (OS) Unit 1 – Introduction Strings,System
to Operating Structures and Pointers 212
Programming for Problem Solving(PPS)
Thank
You
D. SRINIVAS
ComputerInstitute
Darshan Scienceofand Engineering
Engineering DepartmentRajkot
& Technology,
srinivascsedept@[Link]
+91-9347556447
Programming for Problem Solving (PPS)
Department of CSE
Darshan Institute of Engineering & Technology, Rajkot
[Link]
srinivascsedept@[Link]
+91 9347556447
Outline
Looping
• Preprocessor:
ÊIntroduction to Preprocessors
ÊTypes of Preprocessors
ÊCommonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef.
• Files:
ÊText and Binary files,
ÊCreating and Reading and writing text and binary files,
ÊAppending data to existing files,
ÊWriting and reading structures using binary files,
ÊRandom access using fseek, ftell and rewind functions
Chapter - 1
Preprocessor
The C compiler is made of two functional parts: a preprocessor and a translator.
The preprocessor is a program which processes the source code before it passes through the
compiler.
The translator is a program which converts the program into machine language and gives the
object module.
There are 4 main types of preprocessor directives:
Ê Macros
Ê File Inclusion
Ê Conditional Compilation
Ê Other directives
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 217
Types of Pre-processors
1. Macros:
Ê Macros are a piece of code in a program which is given some name.
Ê Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code.
Ê The ‘#define’ directive is used to define a macro.
Ê [Link] by Symbolic Constants as macro:
§ Macro definition without arguments is referred as a constant.
§ The body of the macro definition can be any constant value including integer, float, double, character, or string.
§ However, character constants must be enclosed in single quotes and string constants in double quotes.
§ Example:
#define PI 3.14159
§ Here “PI” replaces with "3.14159“.
Ê [Link] by Function macro:
§ C handles function macros by simply rescanning a line after macro expansion.
§ Therefore, if an expansion results in a new statement with a macro ,the second macro will be properly expanded.
§ For Example:
#define sqre(a) (a*a)
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 218
Types of Preprocessors
Ê Program
#include<stdio.h>
#define square(x) (x*x) /* macro definition */
void main()
{
int a=10;
printf("The square of %d=%d", a, square(a));
}
OUTPUT:
The square of 5 = 25
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 219
Types of Pre-processors
Ê C. Predefined Macros
§ ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros
should not be directly modified.
Ê Program:
[Link]. Macro & Description
#include <stdio.h> 1. __DATE__ The current date as a character literal
void main() in "MMM DD YYYY" format.
{
printf("File :%s\n", __FILE__ ); 2. __TIME__ The current time as a character literal
printf("Date :%s\n", __DATE__ ); in "HH:MM:SS" format.
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ ); 3. __FILE__ This contains the current filename as a
printf("ANSI :%d\n", __STDC__ ); string literal.
}
Ê Output: 4. __LINE__ This contains the current line number
as a decimal constant.
File :test.c
Date :April 1 2022 5. __STDC__ Defined as 1 when the compiler
Time :03:36:24
complies with the ANSI standard.
Line :8
ANSI :1
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 220
Types of Pre-processors –Cont…
[Link] Inclusion:
Ê This type of preprocessor directive tells the compiler to include a file in the source code program.
Ê There are two types of files which can be included by the user in the program:
Ê A. Header File or Standard files:
§ These files contains definition of pre-defined functions like printf(), scanf() etc.
§ These files must be included for working with these functions.
§ It is used to direct the preprocessor to include header files from the system library.
Ê Syntax:
§ #include< file-name >
Ê B. User defined files:
§ When a program becomes very large, it is good practice to divide it into smaller files and include whenever needed.
§ These types of files are user defined files.
§ It is used to direct the preprocessor look for the files in the current working directory and standard library.
§ These files can be included as:
Ê Syntax:
§ #include"filename”
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 221
Types of Pre-processors –Cont…
[Link] Compilation:
Ê Conditional Compilation directives are type of directives which helps to compile a specific portion of the
program or to skip compilation of some specific part of the program based on some conditions.
Ê It allows us to control the compilation process by including or excluding statements.
Ê Cast expressions, size of, enumeration constants cannot be evaluated in preprocessor directives.
Ê Its structure is similar to if statement.
Ê This can be done with the help of two preprocessing commands ‘ifdef‘ and ‘endif‘.
Ê Syntax for conditional compilation:
§ #if expression1
code to be included for true
§ #elif expression2
code to be included for true
§ #else
code to be included false
§ #endif
§ #if !defined( NULL )
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 222
Types of Pre-processors –Cont…
4. Other Directives:
Ê Apart from the above directives there are two more directives which are not commonly used.
Ê These are:
Ê #undef Directive:
§ The #undef directive is used to undefine an existing macro.
§ This directive works as:
§ first job of a preprocessor is file inclusion that is copying of one or more files into programs.
§ The files are usually header files and external files containing functions and data declarations.
Ê Syntax:
§ #undef LIMIT
Ê #pragma Directive:
§ This directive is a special purpose directive and is used to turn on or off some features.
§ #pragma startup and #pragma exit:
§ These directives helps us to specify the functions that are needed to run before program startup( before the control
passes to main()) and just before program exit (just before the control returns from main()).
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 223
Types of Pre-processors –Cont…
Preprocessor Syntax/Description
Syntax: #define
Macro
This macro defines constant value and can be any of the basic data types.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 224
Chapter - 2
Files
FILE:
Ê A file is an external collection of related data treated as a unit.
Ê The primary purpose of a file is to keep a record of data.
Ê Record is a group of related fields. Field is a group of characters they convey meaning.
Ê Files are stored in auxiliary or secondary storage devices. The two common forms of secondary storage are
disk (hard disk, CD and DVD) and tape.
Ê Each file ends with an end of file (EOF) at a specified byte number, recorded in file structure.
Ê C has predefined structure to hold this information.
Ê The stdio.h header file defines this file structure; its name is FILE.
File Name
Ê File name is a string of characters that make up a valid filename.
Ê Every operating system uses a set of rules for naming its files.
Ê When we want to read or write files, we must use the operating system rules when we name a file.
Ê The file name may contain two parts, a primary name and an optional period with extension.
Ê Example: [Link]
program.c
[Link],
[Link],
Prof. Firoz Asst.
[Link],CSE
A Sherasiya Professor,CSE Unit-1
Unit-3
#3140702 (OS) Unit 1 – Introduction to Cyber
Introduction
Preprocessors
Security
Operating to C and
System Programming
Files Language 226
File Management
In real life, we want to store data permanently so that later we can retrieve it and reuse it.
A file is a collection of characters stored on a secondary storage device like hard disk, or pen
drive.
There are two kinds of files that programmer deals with:
Ê Text Files are human readable and it is a stream of plain English characters
Ê Binary Files are computer readable, and it is a stream of processed characters and ASCII symbols
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 227
Text Files And Binary Files:
Text File:
Ê It is a file in which data are stored using only characters; a text file is written using text stream.
Ê Non-character data types are converted to a sequence of characters before they are stored in the file.
Ê In the text format, data are organized into lines, terminated by newline character.
Ê The text files are in human readable form and they can be created and read using any text editor.
Ê Text files are read and written using input / output functions that convert characters to data types: scanf and
printf, getchar and putchar, fgets and fputs.
The following figure shows the data transfer in text file:
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 228
File Opening Modes
Ê We can perform different operations on a file based on the file opening modes
Binary
Text Mode Description
Mode
Open the file for reading only. If it exists, then the file is opened with the current contents;
r rb
otherwise an error occurs.
Open the file for writing only. A file with specified name is created if the file does not
w wb
exists. The contents are deleted, if the file already exists.
Open the file for appending (or adding data at the end of file) data to it. The file is opened
a ab with the current contents safe. A file with the specified name is created if the file does not
exists.
r+ r+b The existing file is opened to the beginning for both reading and writing.
w+ w+b Same as w except both for reading and writing.
a+ a+b Same as a except both for reading and writing.
Note: The main difference is w+ truncate the file to zero length if it exists or create a new file if it doesn't. While r+
neither deletes the content nor create a new file if it doesn't exist.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 229
Text Files And Binary Files:
Binary File:
Ê A binary file is a collection of data stored in the internal format of the computer.
Ê The binary files are not in human readable form.
Ê There are no lines or newline characters.
Ê Binary files are read and written using binary streams known as block input / output functions.
Ê The following figure shows the data transfer in binary file:
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 230
Text Files And Binary Files:
Differences between Text File and Binary File
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 231
File Handling Functions or Operations
In general, there are five steps to processing a file.
Ê 1. Creating a file
Ê 2. Opening a file
Ê 3. Reading a file
Ê 4. Writing a file
Ê 5. Closing a file
[Link] a file (fopen):
Ê The function that prepares a file for processing is fopen.
Ê It does two things: First, it makes the connection between the physical file and the file stream in the program.
Ê Second, it creates a program file structure to store the information needed to process the file.
Ê To open a file, we need to specify the physical filename and its mode.
Ê Syntax:
fopen (“filename”, “mode”);
Ê The file mode is a string that tells C compiler how we intend to use the file: reading, writing or append.
Ê For example: fptr1 = fopen (“mydata", "r”);
Ê Once the files are open, they stay open until you close them or end the program.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 232
File Handling Functions or Operations
[Link] a file (fopen):
Ê This function used to open existing file with respective mode.
Ê The function that prepares a file for processing is fopen.
Ê It does two things: First, it makes the connection between the physical file and the file stream in the program.
Ê Second, it creates a program file structure to store the information needed to process the file.
Ê To open a file, we need to specify the physical filename and its mode.
Ê Syntax:
fopen (“filename”, “mode”);
Ê The file mode is a string that tells C compiler how we intend to use the file: reading, writing or append.
Ê For example: fptr1 = fopen (“mydata", "r”);
Ê Once the files are open, they stay open until you close them or end the program.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 233
File Handling Functions or Operations
[Link] a file :
Read a character: getc () and fgetc ()
Ê The getc functions read the next character from the stream, which can be a user-defined stream or stdin, and converts it
in to an integer.
Ê This function has one argument which is the file pointer declared as FILE or stdin (in case of standard input stream).
Ê If the read detects an end of file, the function returns EOF, EOF is also returned if any error occurs.
Ê The functionality of getc / fgetc is same.
Ê Syntax:
int getc (FILE *spIn); or int getc(stdin);
int fgetc (FILE *spIn); or int fgetc(stdin);
Read a string: gets () and fgets ()
Ê The gets functions read the string from the file, which can be a user-defined stream or stdin.
Ê This function has one argument which is the file pointer declared as FILE or stdin (in case of standard input stream).
Ê If the read detects an end of file, the function returns EOF, EOF is also returned if any error occurs.
Ê The functionality of gets / fgets is same.
Ê Syntax:
int gets (FILE *spIn); or int gets(stdin);
int fgets(FILE *spIn); or int fgets(stdin);
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 234
File Handling Functions or Operations
Read an integer: getw () and fgetw ()
Ê The getc functions read the next interger from the stream, which can be a user-defined stream or stdin.
Ê This function has one argument which is the file pointer declared as FILE or stdin (in case of standard input stream).
Ê If the read detects an end of file, the function returns EOF, EOF is also returned if any error occurs.
Ê The functionality of getw / fgetw is same.
Ê Syntax:
int getw (FILE *spIn); or int getw(stdin);
int fgetw (FILE *spIn); or int fgetw(stdin);
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 235
File Handling Functions or Operations
[Link] a file :
Formatted input -fscanf ():
Ê It is used to read data from a user-specified stream.
Ê The general format of fscanf() is:
fscanf (stream-pointer, ”format string”, list);
Ê The first argument is the stream pointer, it is the pointer to the streams that has been declared and associated with a text
file. Remaining is same as scanf function arguments.
Ê The following example illustrates the use of an input stream.
int a, b;
FILE *fptr1;
fptr1 = fopen (“mydata", "r”);
fscanf (fptr1, "%d %d", &a, &b);
Ê The fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b.
Ê The only difference between scanf and fscanf is that scanf reads data from the stdin (input stream) and fscanf reads
input from a user specified stream(stdin or file).
Ê The following example illustrates how to read data from keyboard using fscanf,
fscanf (stdin,”%d”, &a);
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 236
File Handling Functions or Operations
[Link] a file :
Writing a character: putc () and fputc ()
Ê The putc function writes a character to the stream which can be a user-defined stream, stdout, or stderr.
Ê The functionality of putc/ fputc is same.
Ê The functions, putc or fputc takes two arguments.
Ê The first parameter is the character to be written and the second parameter is the file.
Ê The second parameter is the file pointer declared as FILE or stdout or stderr.
Ê If the character is successfully written, the function returns it. If any error occurs, it returns EOF.
Ê Syntax:
int putc (char, *fp);
int fputc (char, *fp);
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 237
File Handling Functions or Operations
Read an integer: getw () and fgetw ()
Ê The getc functions read the next interger from the stream, which can be a user-defined stream or stdin.
Ê This function has one argument which is the file pointer declared as FILE or stdin (in case of standard input stream).
Ê If the read detects an end of file, the function returns EOF, EOF is also returned if any error occurs.
Ê The functionality of getw / fgetw is same.
Ê Syntax:
int getw (FILE *spIn); or int getw(stdin);
int fgetw (FILE *spIn); or int fgetw(stdin);
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 238
File Handling Functions or Operations
Formatted Output -Writing to Files: fprintf ()
Ê It can handle a group of mixed data simultaneously.
Ê The first argument of these functions is a file pointer which specifies the file to be used.
Ê The general form of fprintf is:
fprintf (stream-pointer, ”format string”, list);
Ê Where stream-pointer is a file pointer associated with a file that has been opened for writing.
Ê The format string contains output specifications for the items in the list.
Ê The list may include variables, constants and strings.
Ê The following example illustrates the use of an Output stream.
int a = 5, b = 20;
FILE *fptr2;
fptr2 = fopen (“results", "w”);
fprintf (fptr2, "%d %d", a, b) ;
Ê The fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2.
Ê fprintf function works like printf except that it specifies the file in which the data will be displayed.
Ê The file can be standard output (stdout) or standard error (stderr) also.
Ê Example,
fprintf (stdout,”%d”,45);
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 239
File Handling Functions or Operations
[Link] a file (fclose):
Ê When we no longer need a file, we should be close it to free system resources, such as buffer space.
Ê Closing a file ensures that all outstanding information associated with the file is flushed out from the buffers
and all links to the file are broken.
Ê Another instance where we have to close a file is to reopen the same file in a different mode.
Ê A file is closed using the close function, fclose.
Ê Syntax:
fclose (file-pointer);
Ê fclose () returns 0 on success (or) -1 on error.
Ê Once a file is closed, its file pointer can be reused for another file.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 240
Programs
Write a C program to fprintf() and fscanf() a text file.
Program
Program
#include <stdio.h>
#include <stdlib.h> #include <stdio.h>
#include <stdlib.h>
int main()
{ int main()
int num; {
FILE *fptr; int num;
fptr = fopen("C:\\[Link]","w"); FILE *fptr;
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 241
File Handling Functions or Operations
Reading And Writing binary Functions:
Ê C language uses the block input and output functions to read and write data to binary files.
Ê As we know that data are stored in memory in the form of 0’s and 1’s.
Ê When we read and write the binary files, the data are transferred just as they are found in memory and hence there are no
format conversions.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 242
File Handling Functions or Operations
File Write: fwrite ()
Ê It writes specified number of items to a binary file.
Ê The function declaration is as follows,
int fwrite (void *pOutArea, int elementSize, int count, FILE *sp);
Ê The parameters for file write correspond exactly to the parameters for the file read function.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 243
Programs
Write a C program to fread() and fwrite() a binary file.
Program
Program
#include <stdio.h>
#include <stdlib.h> #include <stdio.h>
struct threeNum #include <stdlib.h>
{ struct threeNum
int n1, n2, n3; {
}; int n1, n2, n3;
void main() };
{ void main()
int n; {
struct threeNum num; int n;
FILE *fptr; struct threeNum num;
if ((fptr = fopen("C:\\[Link]","wb")) == NULL){ FILE *fptr;
printf("Error! opening file"); if ((fptr = fopen("C:\\[Link]","rb")) == NULL){
exit(1); printf("Error! opening file");
} exit(1);
for(n = 1; n < 5; ++n) }
{
num.n1 = n; for(n = 1; n < 5; ++n)
num.n2 = 5*n; {
num.n3 = 5*n + 1; fread(&num, sizeof(struct threeNum), 1, fptr);
fwrite(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2,
} num.n3);
fclose(fptr); }
} fclose(fptr);
}
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 244
Programs
Write a C program to copy a given file.
Program
#include <stdio.h>
void main()
{
FILE *fp1, *fp2; //p and q is a FILE type pointer
char ch; //ch is used to store temporary data
fp1 = fopen("file1.c","r"); //open file “file1.c” in read mode
fp2 = fopen("file2.c","w"); //open file “file2.c” in write mode
do { //repeat step 9 and 10 until EOF is reached
ch = getc(fp1); //get character pointed by p into ch
putc(ch, fp2); //print ch value into file, pointed by pointer q
}while(ch != EOF); //condition to check EOF is reached or not
fclose(fp1); //free up the file pointer p
fclose(fp2); //free up the file pointer q
printf("File copied successfully...");
}
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 245
Programs- Cont…
Write a C program to merge the two files
Program Program (contd.)
#include <stdio.h>
printf("Merged [Link] and
void main()
[Link] into [Link]");
{
fclose(fp1);
FILE *p1,*p2,*p3;
fclose(fp2);
char ch;
fclose(fp3);
p1 = fopen(“[Link]","r");
return 0;
p2 = fopen(“[Link]","r");
}
p3 = fopen(“[Link]",“w");
if (fp1 == NULL || fp2 == NULL)
{
puts("Could not open files");
exit(0); Output
} Merged [Link] and [Link] into
while ((c = fgetc(fp1)) != EOF) [Link]
{
fputc(c, fp3);
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 246
Programs- Cont…
Write a C program to count lines, words, tabs, and characters
Progra Program
m (contd.)
#include <stdio.h> c+
void main() +;
{
FILE *p; ch = getc(p);
char ch; }
int ln=0,t=0,w=0,c=0; fclose(p);
p = fopen("[Link]","r"); printf("Lines = %d, tabs = %d, w
ch = getc(p); ords = %d, characters = %d\n",ln,
while (ch != EOF) { t, w, c);
if (ch == '\n') }
ln++; Output
else if(ch == '\t')
t++; Lines = 22, tabs = 0, words = 152,
characters = 283
else if(ch == ' ')
w++;
else
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 247
Random Access File Functions
Rewind File (rewind):
Ê It simply sets the file position indicator to the beginning of the file.
Ê Syntax:
void rewind(FILE *stream);
Ê It helps us in reading a file more than once, without having to close and open the file.
Ê A common use of the rewind function is to change a work file from a write state to a read state.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 248
Random Access File Functions
Current Location (ftell):
Ê It reports the current position of the file marker in the file, relative to the beginning of the file.
Ê It measures the position in the file by the number of bytes, relative to zero, from the beginning of the file.
Ê Syntax:
int pos=long int ftell(FILE *stream);
Ê It also returns the number of bytes from the beginning of the file.
Ê If ftell encounters an error, it returns -1.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 249
Random Access File Functions
Re Position: (fseek):
Ê It is used to move the file position to a desired location within the file.
Ê Syntax:
int fseek(FILE *stream, long offset, int wherefrom);
Ê The offset specifies the number of positions to be moved from the location specified by position.
Ê The position can take one of the following three values:
Value Meaning
0 Beginning of file.
1 Current position.
2 End of file.
Ê The offset may be positive( means forward), or negative (means backward).
Ê When the operation is successful, fseek returns a zero.
Ê If we attempt to move the file pointer beyond the file boundaries, an error occurs and fseek returns -1.
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 250
Random Access File Functions
Operations of the fseek function
Statement Meaning
fseek(fp,0L,0); Go to the beginning.
fseek(fp,0L,1); Stay at the current position.
fseek(fp,0L,2); Go to the end of the file, past the last character
of the file.
fseek(fp,m,0) Move to (m+1)th byte in the file.
fseek(fp,m,1); Go forward by m bytes.
fseek(fp,-m,1); Go backward by m bytes from the current
position.
fseek(fp,-m,2); Go backward by m bytes from the end. (positions
the file to the character from the end.)
[Link],
Prof. Firoz A SherasiyaAsst. Professor,CSE Unit-3
#3140702 (OS) Unit 1 – Introduction Preprocessors
to Operating System and Files 251
Programming for Problem Solving(PPS)
Thank
You
D. SRINIVAS
ComputerInstitute
Darshan Scienceofand Engineering
Engineering DepartmentRajkot
& Technology,
srinivascsedept@[Link]
+91-9347556447
Programming for Problem Solving (PPS)
Department of CSE
Darshan Institute of Engineering & Technology, Rajkot
[Link]
srinivascsedept@[Link]
+91 9347556447
Outline
Looping
• Functions:
ÊDesigning structured programs,
ÊDeclaring a function, Signature of a function,
ÊParameters and return type of a function,
Êpassing parameters to functions,
Êcall by value Passing arrays to functions,
Êpassing pointers to functions, idea of call by reference,
ÊSome C standard functions and libraries
• Recursion:
ÊSimple programs,
Êsuch as Finding Factorial,
ÊFibonacci series etc.,
ÊLimitations of Recursive functions
• Dynamic memory allocation:
ÊAllocating and freeing memory,
Ê Allocating memory for arrays of different datatypes.
Chapter - 1
Function
A function is a group of programming statements that perform a specific task.
It divides a large program into smaller parts.
A function is something like hiring a person to do a specific job for you.
Every C program can be thought of as a collection of these functions.
Program execution in C language starts from the main function.
Syntax
void main()
{
// body part
}
Why function ?
Ê Avoids rewriting the same code over and over.
Ê Using functions it becomes easier to write programs and keep track of what they doing.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 256
Advantages of Function
Using function we can avoid rewriting the same logic or code again and again in a program.
We can track or understand large program easily when it is divide into functions.
It provides reusability.
It help in testing and debugging because it can be tested for errors individually in the easiest
way.
Reduction in size of program due to code of a function can be used again and again, by calling
it.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 257
Types of Functions
Function
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 258
Program Structure for Function
When we use a user-defined function program structure is divided into three parts.
Function Structure
void func1(); Function Prototype
void main()
{
....
func1(); Function call
}
void func1()
{
.... Function definition
//function body
....
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 259
Function Phototype
A function Prototype also know as function declaration.
A function declaration tells the compiler about a function name and how to call
the function.
It defines the function before it is being used or called.
A function prototype needs to be written at the beginning of the program.
Syntax Example
return-type function-name (arg-1, arg 2, …); void addition(int, int);
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 260
Function Definition
A function definition defines the functions header and body.
A function header part should be identical to the function prototype.
Ê Function return type
Ê Function name
Ê List of parameters
A function body part defines function logic.
Ê Function statements
Syntax Example
return-type function-name (arg-1, arg 2, …) void addition(int x, int y)
{ {
//... Function body printf("Addition
} is=%d“,(x+y)); }
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 261
Program on Function
WAP to add two number using add(int, int) Function
Output
Program
Addition is = 11
#include <stdio.h>
void add(int, int); // function declaration
void main()
{
int a = 5, b = 6;
add(a, b); // function call
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 262
Actual parameters and Formal parameters
Values that are passed to the called function from the main function are known as Actual
parameters.
The variables declared in the function prototype or definition are known as Formal parameters.
When a method is called, the formal parameter is temporarily "bound" to the actual parameter.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 263
Programs on Functions
WAP to find Factorial of a Number.
Program Output
#include <stdio.h> Enter the number :
int fact(int); 5
int main() factorial = 120
{
int n, f;
printf("Enter the number :\n");
scanf("%d", &n);
f = fact(n);
printf("factorial = %d", f);
}
int fact(int n)
{
int i, fact = 1;
for (i = 1; i <= n; i++)
fact = fact * i;
return fact;
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 264
Programs on Functions
WAP to check Number is Prime or not
Program Program contd.
#include <stdio.h> int checkPrime(int n1)
int checkPrime(int); {
void main() int i = 2;
{ while (i <= n1 / 2)
int n1, prime; {
printf("Enter the number :"); if (n1 % i == 0)
scanf("%d", &n1); return 0;
prime = checkPrime(n1); else
if (prime == 1) i++;
printf("The number %d is a prime }
number.\n", n1); return 1;
else }
printf("The number %d is not a
prime number.\n", n1);
}
Output
Enter the number :7
The number 7 is a prime number.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 265
Category of Function
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 266
Category of Function cont…
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 267
Passing Parameters to Functions
There are two ways of passing parameters to the functions.
1. Call by value and 2. Call by reference
Call by value:
Ê When a function is called with actual parameters, the values of actual parameters are copied into the formal
parameters.
Ê If the values of the formal parameters changes in the function, the values of the actual parameters are not
changed.
Ê This way of passing parameters is called call by value (pass by value).
Ê In the below example, the values of the arguments to swap () 10 and 20 are copied into the parameters x and
y.
Ê Note that the values of x and y are swapped in the function.
Ê But, the values of actual parameters remain same before swap and after swap.
Note: In call by value any changes done on the formal parameter will not affect the actual
parameters.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 268
Example Program on call by value
#include<stdio.h>
void swap (int , int ); /*function prototype */
void main ()
{ int a=10, b=20;
swap (a, b); /*function calling*/
printf (“From main The Values of a and b a=%d, b=%d “, a, b);
}
void swap (int x, int y) /* function definition */
{ int temp;
temp=x;
x=y;
y=temp;
printf (“\n The Values of a and b after swapping a=%d, b =%d”, x, y);
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 269
Passing Parameters to Functions
Call by reference:
Ê When a function is called with actual parameters, the values of actual parameters are copied into the formal
parameters.
Ê If the values of the formal parameters changes in the function, the values of the actual parameters are not
changed.
Ê This way of passing parameters is called call by reference (pass by address).
Ê In the below example, the values of the arguments to swap () 10 and 20 are copied into the parameters x and
y.
Ê Note that the values of x and y are swapped in the function.
Ê But, the values of actual parameters remain same before swap and after swap.
Note: In call by reference any changes done on the formal parameter will affect the actual
parameters.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 270
Example Program on call by reference
#include<stdio.h>
void swap (int * , int * ); /*function prototype */
void main ()
{ int a=10, b=20;
swap (&a, &b); /*function calling*/
printf (“From main The Values of a and b a=%d, b=%d “, a, b);
}
void swap (int *x, int *y) /* function definition */
{ int temp;
temp=*x;
*x=*y;
*y=temp;
printf (“\n The Values of a and b after swapping a=%d, b =%d”, x, y);
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 271
Differences between Call by Value and Call by Reference
Formal parameters contain the value of Formal parameters contain the address of
actual parameters. actual parameters.
Change of formal parameters in the function The actual parameters are changed since
will not affect the actual parameters in the the formal parameters indirectly manipulate
calling function the actual parameters
Execution is slower since all the values have Execution is faster since only addresses are
to be copied into formal parameters. copied.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 272
Chapter - 2
Recursion
Any function which calls itself is called recursive function and such function calls are called
recursive calls.
Recursion cannot be applied to all problems, but it is more useful for the tasks that can be
defined in terms of a similar subtask.
It is idea of representing problem a with smaller problems.
Any problem that can be solved recursively can be solved iteratively.
When recursive function call itself, the memory for called function allocated and different copy
of the local variable is created for each function call.
Some of the problem best suitable for recursion are
Ê Factorial
Ê Fibonacci
Ê Tower of Hanoi
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 274
Working of Recursion
Working
void func1();
void main()
{
....
func1();
.... Function
} call
void func1()
{ Recursive
.... function call
func1();
....
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 275
Properties Recursion
A recursive function can go infinite like a loop. To avoid infinite running of recursive function,
there are two properties that a recursive function must have.
Base Case or Base criteria
Ê It allows the recursion algorithm to stop.
Ê A base case is typically a problem that is small enough to solve directly.
Progressive approach
Ê A recursive algorithm must change its state in such a way that it moves forward to the base case.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 276
Programs on Recursion
Factorial of a Number using Recursion Fibonacci Series of a Number using Recursion
Program Output Program int fibonacci(int n)
#include <stdio.h> Enter the number: #include <stdio.h> {
int fact(int); 5 int fibonacci(int); if (n == 0 || n == 1)
void main() factorial = 120
{ void main() return n;
int n, f; { else
printf("Enter the int n, m = 0, i; return
number:\n"); printf("Enter (fibonacci(n - 1) +
scanf("%d", &n); Total terms\n"); fibonacci(n - 2));
f = fact(n); scanf("%d", &n); }
printf("factorial = %d", f); printf("Fibonacci
}
series\n"); Output
int fact(int n)
{ for (i = 1; i <= Enter Total terms
if (n == 0) n; i++) 5
return 1; { printf("%d ", Fibonacci series
else if (n == 1) fibonacci(m)); 0 1 1 2 3
return 1; m++;
else }
return n * fact(n - 1); }
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 277
Iteration vs Recursion
ITERATION RECURSION
Iteration explicitly uses repetition structure. Recursion achieves repetition by calling the same
function repeatedly.
Iteration is terminated when the loop condition Recursion is terminated when base case is
fails satisfied.
May have infinite loop if the loop condition never Recursion is infinite if there is no base case or if
fails base case never reaches.
Iterative functions execute much faster and Recursive functions are slow and takes a lot of
occcupy less memory space. memory space compared to iterative functions
No. of CPU Cycles repeated No. of times Function executed
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 278
Chapter - 2
Dynamic Memory Allocation(DMA)
If memory is allocated at runtime (during execution of program) then it is called
dynamic memory.
It allocates memory from heap (heap: it is an empty area in memory)
Memory can be accessed only through a pointer.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 280
[Link]() Function
malloc () is used to allocate a fixed amount of memory during the execution of a program.
malloc () allocates size_in_bytes of memory from heap, if the allocation succeeds, a
pointer to the block of memory is returned else NULL is returned.
Allocated memory space may not be contiguous.
Each block contains a size, a pointer to the next block, and the space itself.
The blocks are kept in ascending order of storage address, and the last block points to the first.
The memory is not initialized.
Syntax Description
ptr_var = (cast_type *) This statement returns a pointer to size_in_bytes of uninitialized storage, or
malloc (size_in_bytes); NULL if the request cannot be satisfied.
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 281
Write a C program to allocate memory using malloc.
Program
#include <stdio.h>
void main()
{
int *fp; //fp is a pointer variable
fp = (int *)malloc(sizeof(int)); //returns a pointer to int size storage
*fp = 25; //store 25 in the address pointed by fp
printf("%d", *fp); //print the value of fp, i.e. 25
free(fp); //free up the space pointed to by fp
}
Output
25
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 282
[Link]() function
calloc() is used to allocate a block of memory during the execution of a program
calloc() allocates a region of memory to hold no_of_blocks of size_of_block each,
if the allocation succeeds then a pointer to the block of memory is returned else NULL is
returned.
The memory is initialized to ZERO.
Syntax Description
ptr_var = (cast_type *) This statement returns a pointer to no_of_blocks of size size_of_blocks, it
calloc (no_of_blocks, returns NULL if the request cannot be satisfied.
size_of_block);
Example:
int n = 20;
fp = (int *)calloc(n, sizeof(int));
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 283
Write a C program to allocate memory using calloc.
Program
#include <stdio.h>
void main()
{
int i, n; //i, n are integer variables
int *fp; //fp is a pointer variable
printf("Enter how many numbers: ");
scanf("%d", &n);
fp = (int *)calloc(n, sizeof(int)); //calloc returns a pointer to n blocks
for(i = 0; i < n; i++) //loop through until all the blocks are read
{
scanf("%d",fp); //read and store into location where fp points
fp++; //increment the pointer variable
}
free(fp); //frees the space pointed to by fp
}
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 284
[Link]() function
realloc() changes the size of the object pointed to by pointer fp to specified size.
The contents will be unchanged up to the minimum of the old and new sizes.
If the new size is larger, the new space will be uninitialized.
realloc() returns a pointer to the new space, or NULL if the request cannot be satisfied, in
which case *fp is unchanged.
Syntax Description
ptr_var = (cast_type *) This statement returns a pointer to new space, or NULL if the request cannot be
realloc (void *fp, satisfied.
size_t);
Example: fp = (int *)realloc(fp,sizeof(int)*20);
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 285
Write a C program to allocate memory using realloc.
Program
#include <stdio.h>
void main()
{
int *fp; //fp is a file pointer
fp = (int *)malloc(sizeof(int)); //malloc returns a pointer to int size storage
*fp = 25; //store 25 in the address pointed by fp
fp =(int *)realloc(fp, 2*sizeof(int)); //returns a pointer to new space
printf("%d", *fp); //print the value of fp
free(fp); //free up the space pointed to by fp
}
Output
25
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 286
[Link]() function
Free() deallocates the space pointed to by fp.
It does nothing if fp is NULL.
fp must be a pointer to space previously allocated by calloc, malloc or realloc.
Syntax Description
void free(void *); This statement free up the memory not needed anymore.
Example: free(fp);
[Link],
Prof. Asst. Professor,CSE
Firoz A Sherasiya Unit-4
#3140702 (OS) Unit Functionstoand
1 – Introduction Dynamic
Operating Memory Allocations
System 287
Programming for Problem Solving(PPS)
Thank
You
D. SRINIVAS
ComputerInstitute
Darshan Scienceofand Engineering
Engineering DepartmentRajkot
& Technology,
srinivascsedept@[Link]
+91-9347556447
Programming for Problem Solving (PPS)
Department of CSE
Darshan Institute of Engineering & Technology, Rajkot
[Link]
srinivascsedept@[Link]
+91 9347556447
Outline
Looping
• Algorithms:
ÊAlgorithms for finding roots of a quadratic equations, finding minimum and maximum
numbers of a given set, finding if a number is prime number, etc.
•Sorting:
ÊBasic searching in an array of elements (linear and binary search techniques),
ÊBasic algorithms to sort array of elements (Bubble, Insertion and Selection sort
algorithms),
ÊBasic concept of order of complexity through the example programs
Chapter - 1
Algorithms
Algorithm: It is an ordered sequence of unambiguous and well-defined instructions that
performs some task and halts in finite time.
Let's examine the four parts of this definition more closely.
1. Ordered Sequence: You can number the step.
2. Unambiguous and well defined instructions: Each instruction should be clear, well understand.
3. Performs some task
4. Halts in finite time: Algorithm must terminate at some point.
Properties of an Algorithm:-
1. Finiteness: An algorithm must terminate in a finite number of steps.
2. Definiteness: Each step of an algorithm must be precisely and unambiguously stated.
3. Effectiveness: Each step must be effective, and can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself.
5. Input/Output: Each algorithm must take zero, one or more inputs and produces one or more output.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 292
Algorithm to find all the roots of a quadratic equation
Start:
Step1: Input the value of a, b, c.
Step2: Calculate d = b*b - 4*a*c
Step3: If (d < 0)
Step3.1:Display "Roots are Imaginary “ calculate r1 = (-b +i sqrt(d) )/ 2a and r2 =(b + i
sqrt(d) )/ 2a.
Step4:else if (d = 0)
Step4.1:Display "Roots are Equal" and calculate r1 = r2 = (-b / 2*a)
Step5:else
Step5.1:Display "Roots are real” and
calculate r1 = -b + sqrt(d) / 2*a and r2 = -b - sqrt(d) / 2*a
Step4: Print r1 and r2.
Stop:
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 293
Algorithm to find the minimum and maximum numbers in a given set of numbers
Start:
Step1: Initialize two variables "min" and "max" to the first element in the set.
Step2: Iterate through the rest of the set, comparing each element to the current
values of "min" and "max".
Step3: If the current element is smaller than "min", set "min" to the current element.
Step4: If the current element is larger than "max", set "max" to the current element.
Step5: After iterating through the entire set, "min" and "max" will contain the minimum
and maximum values, respectively.
Stop:
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 294
Algorithm to Find Prime Number
Start:
Step1:Take num as input.
STEP 2: Initialize a variable temp to 0.
STEP 3: Iterate a “for” loop from 2 to num/2.
STEP 4: If num is divisible by loop iterator, then increment temp.
STEP 5: If the temp is equal to 0,
Return “Num IS PRIME”.
Step6: Else,
Return “Num IS NOT PRIME”.
Stop:
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 295
Chapter - 1
SEARCHING
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 297
Linear Search
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 298
Linear Search
Example
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 299
Linear Search
Linear search is a very basic and simple search algorithm. In Linear search, we search an
element or value in a given array by traversing the array from the starting, till the desired
element or value is found.
It compares the element to be searched with all the elements present in the array and when the
element is matched successfully, it returns the index of the element in the array, else it return -1.
Linear Search is applied on unsorted or unordered lists, when there are fewer elements in a list.
Algorithm Linear Search ( Array A, Value x) Step 6: Print Element x Found at index i
Step 1: Set i to 1 and go to step 8
Step 2: if i > n then go to step 7 Step 7: Print element not found
Step 3: if A[i] = x then go to step 6
Step 8: Exit
Step 4: Set i to i + 1
Step 5: Go to Step 2
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 300
Write a C program to find key element in the list using Linear Search.
Program
#include <stdio.h>
int main() Output
{
int a[10], i, item,n; Enter number of elements of an
printf("\nEnter number of elements of an array:\n"); array:
scanf("%d",&n); 8
printf("\nEnter elements: \n");
for (i=0; i<n; i++) Enter elements:
scanf("%d", &a[i]); 23578641
printf("\nEnter item to search: ");
scanf("%d", &item);
Enter item to search: 1
for (i=0; i<=9; i++)
if (item == a[i])
{ Item found at location 8
printf("\nItem found at location %d", i+1);
break;
}
if (i > 9)
printf("\nItem does not exist.");
return 0;
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 301
Binary Search
Binary Search is used with sorted array or list.
In binary search, we follow the following steps:
Ê 1. We start by comparing the element to be searched with the element in the
middle of the list/array.
Ê 2. If we get a match, we return the index of the middle element.
Ê 3. If we do not get a match, we check whether the element to be searched is
less or greater than in value than the middle element.
Ê 4. If the element/number to be searched is greater in value than the middle
number, then we pick the elements on the right side of the middle element(as
the list/array is sorted, hence on the right, we will have all the numbers greater
than the middle number), and start again from the step 1.
Ê 5. If the element/number to be searched is lesser in value than the middle
number, then we pick the elements on the left side of the middle element, and
start again from the step 1.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 302
Binary Search
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 303
Binary Search
Example
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 304
Write a C program to find key element in the list using Binary Search.
Program
#include<stdio.h>
else
#include<conio.h>
last = middle-1;
int main()
middle = (first+last)/2;
{
}
int i, arr[10], search, first, last, middle;
if(first>last)
printf("Enter 10 elements (in ascending order): ");
printf("\nThe number, %d is not found in given
for(i=0; i<10; i++)
Array", search);
scanf("%d", &arr[i]);
getch();
printf("\nEnter element to be search: ");
return 0;
scanf("%d", &search);
}
first = 0;
last = 9;
middle = (first+last)/2;
while(first <= last)
{ Output
if(arr[middle]<search) Enter 10 elements (in ascending order): 1 5 8 9 10 15 20
first = middle+1; 21 25 28
else if(arr[middle]==search)
Enter element to be search: 15
{
printf("\nThe number, %d found at Position The number, 15 found at Position 6
%d", search, middle+1);
break;
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 305
Sorting Algorithms
A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most
used orders are numerical order and lexicographical order.
Efficient sorting is important to optimizing the use of other algorithms that require sorted
lists to work correctly and for producing human - readable input. Sorting algorithms are often
classified by :
Ê * Computational complexity (worst, average and best case) in terms of the size of the
list (N). For typical sorting algorithms good behaviour is O(NlogN) and worst case
behaviour is O(N2 ) and the average case behaviour is O(N).
Ê * Memory Utilization
Ê * Stability - Maintaining relative order of records with equal keys.
Ê * No. of comparisions.
Ê * Methods applied like Insertion, exchange, selection, merging etc. Sorting is a process
of linear ordering of list of objects.
Ê Sorting techniques are categorized into
§ Internal Sorting: takes place in the main memory of a computer.
• Ex. eg : - Bubble sort, Insertion sort, Shell sort, Quick sort, Heap sort, etc.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 306
Sorting Algorithms
§ External Sorting: takes place in the secondary memory of a computer, Since the
number of objects to be sorted is too large to fit in main memory.
• eg : - Merge Sort, Multiway Merge, Polyphase merge.
Sorting Techniques
Ê Bubble Sort
Ê Selection Sort
Ê Insertion Sort
Ê Merge Sort
Ê Quicksort
Ê Counting Sort
Ê Radix Sort
Ê Bucket Sort
Ê Heap Sort
Ê Shell Sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 307
Bubble Sort
Bubble sort is a simple sorting algorithm that repeatedly iterates through the list,
compares adjacent elements and swaps them if they are in the wrong order. The
algorithm continues until no more swaps are needed.
The basic steps of the bubble sort algorithm are as follows:
Ê Start at the beginning of the list.
Ê Compare the first two elements. If the first element is greater than the second element,
swap them.
Ê Move to the next pair of adjacent elements and repeat step 2.
Ê Continue this process until the end of the list is reached.
Ê If any swaps were made during the previous iteration, repeat steps 2-4 until no swaps are
made.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 308
Bubble Sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 309
Write a C program to sort elements in the list using Bubble Sort.
Program
#include <stdio.h> }
int main()
{ printf("Sorted list in ascending order:\n");
int array[100], n, i, j, swap;
printf("Enter number of elements\n"); for (i = 0; i < n; i++)
scanf("%d", &n); printf("%d\n", array[i]);
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 310
Bubble Sort
Advantages:
Ê Bubble sort is easy to understand and implement.
Ê Bubble sort is a stable sorting algorithm, meaning that it preserves the relative order of
equal elements in the input list.
Ê Bubble sort has a space complexity of O(1), meaning that it does not require any additional
memory beyond the input list.
Disadvantages:
Ê Bubble sort has a time complexity of O(n^2), where n is the number of elements in the
input list. This means that as the size of the list increases, the time taken to sort the list
increases exponentially. For large lists, bubble sort is much slower than other sorting
algorithms with better time complexity, such as merge sort or quicksort.
Ê Bubble sort is not adaptive, meaning that it does not take advantage of the fact that the
input list may already be partially sorted. Even if the input list is nearly sorted, bubble sort
still requires O(n^2) time to sort the list.
Ê Bubble sort is not efficient for large lists, and it is generally only used for educational
purposes or for sorting small lists with few elements.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 311
Selection Sort
Selection sort is a simple sorting algorithm that works by repeatedly selecting the
smallest element from the unsorted portion of the list and swapping it with the
first element of the unsorted portion.
The algorithm proceeds as follows:
1. Find the smallest element in the unsorted portion of the list.
2. Swap the smallest element with the first element of the unsorted portion of the list.
3. Move the boundary between the sorted and unsorted portions of the list one element to
the right.
4. Repeat steps 1-3 until the entire list is sorted.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 312
Selection Sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 313
Write a C program to sort elements in the list using Slection Sort.
Program
printf("Sorted list in ascending order:\n");
#include <stdio.h> for (c = 0; c < n; c++)
int main() printf("%d\n", array[c]);
{ return 0;
int array[100], n, c, d, position, t; }
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0; c < (n - 1); c++)
{ Output
position = c;
for (d = c + 1; d < n; d++)
Enter number of elements
{ 5
if (array[position] > array[d]) Enter 5 integers
position = d; 8
} 2
if (position != c) 1
{ 0
t = array[c];
array[c] = array[position];
40
array[position] = t; Sorted list in ascending order:
} 0 1 2 8 40
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 314
Selection Sort
Advantages:
Ê Selection sort is easy to understand and implement.
Ê Selection sort is a stable sorting algorithm, meaning that it preserves the relative order of
equal elements in the input list.
Ê Selection sort has a space complexity of O(1), meaning that it does not require any
additional memory beyond the input list.
Disadvantages:
Ê Selection sort has a time complexity of O(n^2), where n is the number of elements in the
input list. This means that as the size of the list increases, the time taken to sort the list
increases exponentially. For large lists, selection sort is much slower than other sorting
algorithms with better time complexity, such as merge sort or quicksort.
Ê Selection sort is not adaptive, meaning that it does not take advantage of the fact that the
input list may already be partially sorted. Even if the input list is nearly sorted, selection
sort still requires O(n^2) time to sort the list.
Ê Selection sort is not efficient for large lists, and it is generally only used for educational
purposes or for sorting small lists with few elements.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 315
Insertion Sort
Insertion sort works similar to the sorting of playing cards in hands. It is assumed that
the first card is already sorted in the card game, and then we select an unsorted card. If
the selected unsorted card is greater than the first card, it will be placed at the right
side; otherwise, it will be placed at the left side. Similarly, all unsorted cards are taken
and put in their exact place.
The algorithm proceeds as follows:
Ê Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Ê Step2 - Pick the next element, and store it separately in a key.
Ê Step3 - Now, compare the key with all elements in the sorted array.
Ê Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.
Ê Step 5 - Insert the value.
Ê Step 6 - Repeat until the array is sorted.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 316
Insertion Sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 317
Write a C program to sort elements in the list using Insertion Sort.
Program
#include <stdio.h> printf("Sorted list in ascending order:\n");
int main() for (c = 0; c <= n - 1; c++) {
{ printf("%d\n", array[c]);
int n, array[1000], c, d, t, flag = 0; }
printf("Enter number of elements\n");
scanf("%d", &n); return 0;
printf("Enter %d integers\n", n); }
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 1 ; c <= n - 1; c++) {
t = array[c]; Output
for (d = c - 1 ; d >= 0; d--) {
if (array[d] > t) {
Enter number of elements
array[d+1] = array[d]; 5
flag = 1; Enter 5 integers
} 6
else 8
break; 0
} 1
if (flag)
array[d+1] = t;
30
} Sorted list in ascending order:
0 1 6 8 30
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 318
Insertion Sort
Advantages:
Ê Simple implementation
Ê Efficient for small data sets
Ê Adaptive, i.e., it is appropriate for data sets that are already substantially sorted.
Disadvantages:
Ê The disadvantage of the insertion sort is that it does not perform as well as other, better
sorting algorithms
Ê With n-squared steps required for every n element to be sorted, the insertion sort does not
deal well with a huge list.
Ê The insertion sort is particularly useful only when sorting a list of few items.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 319
Quick Sort
Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot'
element from the array and partitioning the other elements into two sub-arrays
such that each element in the left sub-array is less than or equal to the pivot
element and each element in the right sub-array is larger than the pivot element.
The algorithm proceeds as follows:
Ê It picks an element as a pivot and partitions the given array around the picked pivot. There
are many different versions of quick Sort that pick pivot in different ways.
Ê Always pick the first element as a pivot.
Ê Always pick the last element as a pivot
Ê Pick a random element as a pivot.
Ê Pick median as the pivot.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 320
Quick Sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 321
Write a C program to sort elements in the list using Quick Sort.
Program
printf("arr[%d]: ", i);
#include <stdio.h> scanf("%d", &arr[i]);
#include <stdlib.h> }
int quickSort(int *arr, int low, int high) int low = 0;
{ int high = n - 1;
int i = low, j = high; int pivot = arr[high];
int pivot = arr[(low + high) / 2];
int k = low - 1;
while (i <= j)
{ for (int j = low; j < high; j++)
while (arr[i] < pivot) {
i++; if (arr[j] <= pivot)
while (arr[j] > pivot) {
j--; k++;
if (i <= j) int temp = arr[k];
{ arr[k] = arr[j];
int temp = arr[i]; arr[j] = temp;
arr[i] = arr[j]; }
arr[j] = temp;
}
i++;
j--; int temp = arr[k + 1];
} arr[k + 1] = arr[high];
} arr[high] = temp;
if (low < j) int pi = k + 1;
quickSort(arr, low, j); quickSort(arr, low, pi - 1);
if (i < high) quickSort(arr, pi + 1, high);
quickSort(arr, i, high); puts("The sorted array is: ");
return 0; for (int i = 0; i < n; i++)
} {
void main(void)
printf("%d ", arr[i]);
{
puts("Enter the number of elements in the array: "); }
int n; }
scanf("%d", &n);
int arr[n];
puts("Enter the elements of the array: ");
for (int i = 0; i < n;i++)
{
[Link], Asst. Professor,CSE
Firoz A Sherasiya #3140702 (OS) Unit 1 –Unit-5 Algorithms,
Introduction Searching
to Operating Systemand Sortings 322
Quick Sort
Advantages:
Ê The quick sort is regarded as the best sorting algorithm.
Ê It is able to deal well with a huge list of items.
Ê Because it sorts in place, no additional storage is required as well
Disadvantages:
Ê The slight disadvantage of quick sort is that its worst-case performance is similar to
average performances of the bubble, insertion or selections sorts.
Ê If the sorting element is integers than radix sort is more efficient than quick sort.
Ê If the list is already sorted than bubble sort is much more efficient than quick sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 323
Merge Sort
Merge sort is a popular sorting algorithm that works by dividing the input array
into two halves, recursively sorting each half, and then merging the two sorted
halves back together.
The basic steps of the merge sort algorithm are as follows:
Ê Divide the input array into two halves, roughly equal in size.
Ê Recursively sort each half of the array using merge sort.
Ê Merge the two sorted halves back together into a single sorted array.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 324
Merge Sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 325
Write a C program to sort elements in the list using Merge Sort.
else {
Program
return;
#include <stdio.h> }
#define max 10 }
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 }; int main() {
int b[10]; int i;
void merging(int low, int mid, int high) { printf("List before sorting\n");
int l1, l2, i; for(i = 0; i <= max; i++)
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; printf("%d ", a[i]);
i++) { sort(0, max);
if(a[l1] <= a[l2]) printf("\nList after sorting\n");
b[i] = a[l1++]; for(i = 0; i <= max; i++)
else printf("%d ", a[i]);
b[i] = a[l2++]; }
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high) Output
b[i++] = a[l2++];
List before sorting
for(i = low; i <= high; i++)
a[i] = b[i]; 10 14 19 26 27 31 33 35 42 44 0
} List after sorting
void sort(int low, int high) { 0 10 14 19 26 27 31 33 35 42 44
int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 326
Merge Sort
Advantages:
Ê It can be applied to files of any size.
Ê Reading of the input during the run-creation step is sequential ==> Not much seeking.
Ê If heap sort is used for the in-memory part of the merge, its operation can be overlapped
with I/O
Disadvantages:
Ê Requires extra space »N
Ê Merge Sort requires more space than other sort.
Ê Merge sort is less efficient than other sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 327
Heap Sort
Heap sort is a popular sorting algorithm that works by creating a binary heap data
structure from the array to be sorted, and then repeatedly removing the largest
element from the heap and adding it to the sorted portion of the array.
The basic steps of the heap sort algorithm are as follows:
Ê Build a binary heap from the array to be sorted.
Ê Repeatedly extract the maximum element from the heap and place it in the sorted portion
of the array.
Ê Continue this process until all elements have been extracted and the array is sorted.
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 328
Heap Sort
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 329
Write a C program to sort elements in the list using Heap Sort.
if(current!=largest ){
Program swap(&arr[current], &arr[largest]);
#include<stdio.h> heapify(arr, size, largest);
void heapify(int arr[], int size, int current); }
void heapSort(int arr[], int size); void heapSort(int arr[], int size){
void swap(int* a, int* b); for(int i= (size/2)-1;i>=0;i--){
int main(){ heapify(arr, size, i);
int arr[]= {12,6,10,5,1,9}; }
int size= sizeof(arr)/sizeof(arr[0]); for(int i=size-1;i>=0;i--){
heapSort(arr, size); swap(&arr[0], &arr[i]);
}
printf("Sorted array is:\n"); heapify(arr, i, 0 );
for (int i = 0; i < size; i++) }
{ }
printf("%d\t", arr[i]); void swap(int* a, int* b){
} int t= *a;
} *a=*b;
void heapify(int arr[], int size, int current){ *b=t;
int largest = current; }
int left= 2*current+1;
int right= 2*current+2;
Output
if(left<size && arr[left]>arr[largest]){
largest=left; Sorted array is:
} 1 5 6 9 10 12
if(right<size && arr[right]>arr[largest]){
largest=right;
}
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 330
Heap Sort
Advantages:
Ê The Heap sort algorithm is widely used because of its efficiency.
Ê The Heap sort algorithm can be implemented as an in-place sorting algorithm
Ê its memory usage is minimal
Disadvantages:
Ê Heap sort requires more space for sorting
Ê Heap sort make a tree of sorting elements.
Ê Quick sort is much more efficient than Heap in many cases
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 331
Time and Space Complexity of all Sorting Algorithms
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 332
Chapter - 3
Storage Classes
Storage class decides the scope, lifetime and memory allocation of variable.
Scope of a variable is the boundary within which a variable can be used.
Storage Initial
Storage Scope Life Example
Specifier Value
Auto int a;
Stack Garbage Within block End of block
{auto} auto int a;
Static Data Zero Within block Till end of program static extern int var;
{static} segment static int var;
[Link],
Prof. Firoz Asst. Professor,CSE
A Sherasiya #3140702 (OS) Unit 1 – Unit-5 Algorithms,
Introduction Searching
to Operating System and Sortings 334
Programming for Problem Solving(PPS)
Thank
You
D. SRINIVAS
ComputerInstitute
Darshan Scienceofand Engineering
Engineering DepartmentRajkot
& Technology,
srinivascsedept@[Link]
+91-9347556447