0% found this document useful (0 votes)
14 views

c Textbook

Uploaded by

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

c Textbook

Uploaded by

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

INDEX

Unit I: Introduction to Computers and Basic Programming Concepts 3 - 30

• Introduction to Computers

o Definition, History, Generations of Computers 3 - 5

o Components of a Computer (ALU, Input/Output, Memory, 5 - 7

Program Counter)

o Basics of Programming Languages 8 - 11

(Low-Level vs. High-Level Languages)

o Compilation and Execution Process 11 - 15

o Basic Data Types, Variables, and Constants 15 - 17

o Keywords and Basic Input/Output in C 17 - 30

Unit II: Control Flow 31 - 53

• Conditional Statements

o if, if-else, nested if, switch 31 - 39

• Loops 39 - 47

o for, while, do-while

o Nested loops

• Control Statements 47 - 53

o break, continue, goto

Unit III: Arrays and Strings 54 - 68

• Introduction to Arrays

o Declaration, Initialization, Access, and 54 - 57

Modification of Arrays

C Programming 1
o Traversal and Manipulation of Array Elements

• Types of Arrays 57 - 63

o One-Dimensional, Multidimensional Arrays

o Memory Layout of Arrays

• Introduction to Strings 64 - 68

o String Manipulation, Common String Functions (strlen, strcpy, strcat,


strcmp)

Unit IV: Pointers and User-Defined Data Types 69 - 95

• Pointers

o Declaration, Initialization, Dereferencing, 69 - 84

Pointer Arithmetic

o Arrays and Pointers, Multidimensional Arrays 84 - 88

with Pointers

o Dynamic Memory Allocation

• User-Defined Data Types 88 - 95

o Structures

o Unions

Unit V: Functions 96 - 117

• Introduction to Functions

o Function Declaration and Definition 96 - 97

o Function Calls, Return Types, and Arguments 97 - 102

o Files, types of files , Formatted files I/O function , 102 - 117

Unformatted files I/O function

Common Errors in C Programming and How to Rectify Them 118 - 123

C Programming 2
UNIT – I
What is Computer?
A computer is an electronic device that manipulates information, or data. It has the ability to store,
retrieve, and process data. You may already know that you can use a computer to type documents, send
email, play games, and browse the Web. You can also use it to edit or create spreadsheets,
presentations, and even videos.

History of Computers
The history of computers dates back to ancient times with the development of early counting tools and
progresses through various stages of mechanical and electronic innovations to the sophisticated digital
computers of today. Here's a detailed overview:

Abacus

The abacus, dating back to around 2400 BC, is one of the earliest known tools for computing. It consists
of a series of rods with beads that can be moved to perform arithmetic operations. The abacus is still in
use today in some parts of the world.

Mechanical Calculators

In the 17th century, inventors like Blaise Pascal and Gottfried Wilhelm Leibniz developed mechanical
calculators capable of performing basic arithmetic operations. Pascal's calculator, known as the
Pascaline, used a series of gears and wheels, while Leibniz's Step Reckoner could perform multiplication
and division in addition to addition and subtraction.

Analytical Engine

Charles Babbage, an English mathematician, designed the Analytical Engine in the 1830s. It is considered
the first concept of a general-purpose computer. The Analytical Engine had components similar to
modern computers, such as an arithmetic logic unit (ALU), control flow in the form of conditional
branching and loops, and memory. However, it was never completed during Babbage's lifetime.

First Generation Computers (1940-1956)

The first generation of computers used vacuum tubes for circuitry and magnetic drums for memory.
These machines were enormous, taking up entire rooms, and were very expensive to operate. They
relied on machine language, the lowest-level programming language understood by computers.

C Programming 3
Key examples include:

• ENIAC (Electronic Numerical Integrator and Computer): Developed in 1945, it was the first
general-purpose electronic digital computer.
• UNIVAC I (Universal Automatic Computer): Delivered in 1951, it was the first commercial
computer produced in the United States.

Second Generation Computers (1956-1963)

Transistors replaced vacuum tubes and ushered in the second generation of computers. Transistors
were smaller, faster, cheaper, and more reliable than vacuum tubes. High-level programming languages
like COBOL and FORTRAN were developed during this period. Notable examples include:

• IBM 7094: A powerful second-generation mainframe computer introduced in the 1960s.


• CDC 1604: One of the first computers to use transistors, developed by Control Data Corporation.

Third Generation Computers (1964-1971)

The third generation of computers saw the development of integrated circuits (IC’s), which placed
multiple transistors on a single chip, significantly increasing the power and efficiency of computers while
reducing their cost and size. Key developments included:

• IBM System/360: A mainframe computer system family that spanned a wide range of
applications and introduced the concept of computer family compatibility.
• DEC PDP-8: The first commercially successful minicomputer, which made computing more
accessible to smaller businesses and organizations.

Fourth Generation Computers (1971-Present)

The development of the microprocessor marked the beginning of the fourth generation of computers.
Microprocessors contain the entire central processing unit (CPU) on a single chip, leading to the
development of personal computers (PCs). Significant milestones include:

• Intel 4004: The first commercially available microprocessor, released in 1971.


• IBM PC: Introduced in 1981, it became the standard for personal computers.
• Apple Macintosh: Launched in 1984, it popularized the graphical user interface (GUI).

Modern Developments: Advances in artificial intelligence (AI), cloud computing, and quantum
computing continue to drive innovation in the computing field.

Fifth Generation Modern Era

In the modern era, computers have become ubiquitous and integral to almost every aspect of daily
life. Key trends and technologies include:

C Programming 4
• Artificial Intelligence (AI): Machine learning, natural language processing, and robotics are
advancing rapidly, enabling computers to perform tasks that previously required human
intelligence.
• Cloud Computing: Provides scalable and flexible resources over the internet, transforming how
data is stored and accessed.
• Quantum Computing: Explores the use of quantum-mechanical phenomena to perform
computation, promising exponential increases in processing power for certain tasks.

Basic Organization of a Computer


A computer system consists of various components that work together to perform tasks. These
components can be broadly categorized into the following units:

1.ALU-Arithmetic logic unit

2.Input/Output units

3.Memory

4.Program counter

C Programming 5
1. Arithmetic Logic Unit (ALU)

The Arithmetic Logic Unit is a critical component of the CPU (Central Processing Unit). It performs all
arithmetic and logical operations. The operations include addition, subtraction, multiplication, division,
and logical operations like AND, OR, NOT, and XOR.

• Arithmetic Operations: These include basic operations such as addition, subtraction,


multiplication, and division.
• Logical Operations: These operations include comparison operations (greater than, less than,
equal to) and logical operations (AND, OR, NOT, XOR).

The ALU receives input data from the CPU registers, performs the necessary operations, and then sends
the results back to the CPU registers for further processing or storage.

2. Input-Output Units (I/O Units)

Input-Output units are responsible for communication between the computer and the external
environment. Input devices allow users to input data into the computer, while output devices allow the
computer to communicate the results of its computations to the user.

• Input Devices: Examples include keyboards, mice, scanners, and microphones. These devices
convert user actions or data into a format that the computer can process.
• Output Devices: Examples include monitors, printers, and speakers. These devices convert the
computer's processed data into a format that humans can understand or utilize.

I/O units often work through specific interfaces and protocols to ensure correct and efficient data
transfer between the computer and peripheral devices.

3. Memory
C Programming 6
Memory is where the computer stores data and instructions. It is divided into primary memory (RAM
and ROM) and secondary memory (hard drives, SSDs).

• Primary Memory: This type of memory is essential for the computer's operation and is used to
store data temporarily while the computer is running.
• RAM (Random Access Memory): Volatile memory that temporarily holds data and instructions
that the CPU is currently processing. Data in RAM is lost when the computer is turned off.
• ROM (Read-Only Memory): Non-volatile memory that stores critical data needed to boot the
computer and perform fundamental operations. Data in ROM is not lost when the computer is
turned off.
• Secondary Memory: This type of memory provides long-term storage for data and programs. It
is non-volatile, meaning data is retained even when the computer is powered down
• Hard Disk Drives (HDD): Traditional storage devices that use spinning disks to read/write data.
• Solid State Drives (SSD): Modern storage devices that use flash memory to store data, offering
faster read/write speeds than HDDs.

4. Program Counter (PC)

The Program Counter is a register within the CPU that holds the address of the next instruction to be
executed. It plays a crucial role in the execution of programs by ensuring the CPU processes instructions
in the correct sequence.

• Function: After fetching the current instruction, the CPU increments the Program Counter to
point to the next instruction in the sequence. If the current instruction is a jump or branch
instruction, the Program Counter is updated to reflect the address of the target instruction,
enabling non-sequential execution when necessary.

• Importance: The Program Counter helps maintain the flow of control in the program, ensuring
instructions are executed in the proper order and enabling complex control flow structures like
loops and conditionals.

C Programming 7
Introduction to Programming Languages

Programming languages are formal languages comprised of sets of instructions that produce various
kinds of output. They are used in computer programming to implement algorithms and manipulate data.
Programming languages enable humans to communicate with computers in a more understandable
way.

Types of Programming Languages

Low-Level Languages
• Machine Language: The lowest-level programming language, consisting of binary code that the
computer's CPU can execute directly. Each instruction performs a very specific task, such as loading
data into a register or adding numbers.
• Assembly Language: A slight abstraction above machine language, assembly language uses
mnemonic codes to represent machine-level instructions, making it easier for humans to
understand. Each assembly language instruction corresponds to a specific machine language
instruction.

High-Level Languages
These languages are more abstract and easier for humans to read and write. They enable programmers
to write instructions in a syntax that is closer to human language. Examples include C, C++, Java, Python,
and JavaScript. High-level languages need to be compiled or interpreted into machine language for
execution by the computer.

C Programming 8
Characteristics of Programming Languages
• Syntax: The set of rules that defines the combinations of symbols that are considered to be
correctly structured programs in a language.
• Semantics: The meaning of the symbols, characters, and statements in a programming language.
• Abstraction: The process of reducing complexity by focusing on the high-level overview of
operations while ignoring the low-level details.
• Portability: The ease with which programs can be transferred from one computer system to
another.
• Efficiency: How well a programming language translates into machine code and performs its
operations.
• Readability: The ease with which a human can read and understand the source code of a
program.

Examples of High-Level Programming Languages

1. C Programming Language
➢ Developed in the early 1970s by Dennis Ritchie at Bell Labs.
➢ Known for its efficiency and control over system resources.
➢ Commonly used for system programming, developing operating systems, and embedded
systems.

2. Python
➢ An interpreted, high-level, and general-purpose programming language created by Guido van
Rossum.
➢ Known for its readability and simplicity, making it a popular choice for beginners.
➢ Widely used in web development, data science, artificial intelligence, and automation.

3. Java
➢ A high-level, class-based, object-oriented programming language designed to have as few
implementation dependencies as possible.
➢ Widely used in enterprise environments, web development, and Android app development.

Importance of Programming Languages

• Programming languages are essential tools for creating software applications, solving complex
problems, and automating tasks. They enable developers to:
• Write programs that perform specific tasks.
• Communicate instructions to a computer.
• Develop software that can be used in various fields such as business, science, education, and
entertainment.

C Programming 9
Basics of a Computer Program
Algorithms
Definition: A step-by-step procedure or formula for solving a problem.

Characteristics:
- Definiteness: Clear and unambiguous steps.
- Effectiveness: Each step is simple enough to be carried out.
- Finiteness: The algorithm must terminate after a finite number of steps.
- Input/Output: An algorithm takes input and produces output.

Example: Algorithm to find the largest of three numbers:


1. Start
2. Read numbers A, B, C
3. If A > B and A > C, then A is the largest
4. Else if B > C, then B is the largest
5. Else C is the largest
6. End

Flowcharts
Definition: A graphical representation of an algorithm.

Symbols:
Oval: Start/End
Rectangle: Process
Parallelogram: Input/Output
Diamond: Decision

Example Using Dia Tool:


- Create a flowchart for the above algorithm to find the largest of three numbers.

Pseudo Code
Definition: A high-level description of an algorithm using a mix of natural language and programming
constructs.

Writing Conventions: Simple and readable, avoids syntactical details of a specific programming
language.

C Programming 10
Example:
BEGIN
READ A, B, C
IF A > B AND A > C THEN
PRINT A is the largest
ELSE IF B > C THEN
PRINT B is the largest
ELSE
PRINT C is the largest
END IF
END

Introduction to Compilation and Execution

In the world of programming, writing code is just the beginning. To make a program run, it needs to go
through a series of steps involving compilation and execution. Understanding these steps is crucial for
effective programming.

Compilation
Compilation is the process of converting the source code written in a high-level programming
language into machine code (binary code) that the computer's CPU can understand and execute. This
process is carried out by a compiler.

C Programming 11
Steps in Compilation:

1. Source File:

o The process starts with a source file, which is the C code written by the programmer with a
.c extension.

2. Preprocessor:

o The preprocessor handles directives like #include, #define, and macros. It processes these
directives and generates a pre-processed file, often with a .i extension. This file contains the
expanded code with all macros replaced and header files included.

3. Compiler:

o The compiler takes the pre-processed file and translates it into assembly code, which is a
lower-level, machine-readable language. The output is an assembly file with a .s extension.

4. Assembler:

o The assembler converts the assembly code into object code, which consists of machine code
instructions. The result is an object file with a .o extension. This object file is not yet
executable; it might still depend on other object files or libraries.

5. Linker:

o The linker takes one or more object files and combines them, resolving references between
them to produce a single executable file. It handles linking libraries and ensuring that all
external references (like function calls to libraries) are properly resolved. The final output is
an executable file.

This sequence of steps transforms human-readable C code into a machine-executable program.

Example:

For a C program, the typical compilation command might be:

GCC -o myprogram myprogram.c

This command tells the GCC compiler to compile myprogram.c into an executable named myprogram.

C Programming 12
Execution

Execution is the process of running the compiled program on the computer. This involves loading the
executable file into memory and the CPU executing its instructions

Steps in Execution:

• Loading: The operating system loads the executable file into memory.
• Linking: Dynamic linking may occur at this stage if the program relies on shared libraries.
• Execution: The CPU begins executing the program’s instructions starting from the entry point,
typically the main function in C.
• Runtime: During execution, the program may perform various operations such as input/output,
calculations, and interactions with system resources.
• Termination: Once the program completes its task, it terminates, freeing up the resources it was
using.

Example:
After compiling myprogram.c into myprogram, you can execute it by simply typing:
./myprogram
This runs the executable and begins the program’s operation.

Compilers vs. Interpreters


Compilers: Translate the entire source code into machine code before execution. This results in a
standalone executable file.
Steps of Programming:

• Program Creation.
• Analysis of language by the compiler and throws errors in case of any incorrect statement.
• In case of no error, the Compiler converts the source code to Machine Code.
• Linking of various code files into a runnable program.
• Finally runs a Program.

Compiled codes run faster than Interpreter.

The compiler generates an output in the form of (.exe).

Any change in the source program after the compilation requires recompiling the entire code.

Errors are displayed in Compiler after Compiling together at the current time.

C Programming 13
The compiler can see code upfront which helps in running the code faster because of performing
Optimization.

It does not require source code for later execution.

Execution of the program takes place only after the whole program is compiled.

Compilers more often take a large amount of time for analyzing the source code.

C,C++,C# etc are programming languages that are compiler-based.

Interpreters: Translate and execute the source code line-by-line at runtime. No standalone
executable is produced, and the interpreter must be present to run the program
Steps of Programming:

• Program Creation.
• Linking of files or generation of Machine Code is not required by Interpreter.
• Execution of source statements one by one.

Interpreted codes run slower than Compiler.

The interpreter does not generate any output.

Any change in the source program during the translation does not require retranslation of the
entire code.

Errors are displayed in every single line.

The Interpreter works by line working of Code, that’s why Optimization is a little slower compared
to Compilers.

It requires source code for later execution.

Execution of the program happens after every line is checked or evaluated.

In comparison, Interpreters take less time for analyzing the source code.

Ruby, Python, Perl, SNOBOL,MATLAB etc are programming languages that are interpreter

Example Languages:

• Compiled Languages: C, C++, Rust


• Interpreted Languages: Python, JavaScript, Ruby

C Programming 14
Benefits and Drawbacks

Compiled Languages:

Benefits: Faster execution, better optimization, and no need for the source code to be present at
runtime.

Drawbacks: Compilation can be time-consuming, and debugging is often more complex.

Interpreted Languages:

Benefits: Easier debugging, platform independence, and more flexible during development.

Drawbacks: Slower execution and the need for the interpreter to be present at runtime.

Primitive Data Types, Variables, and Constants:

Understanding primitive data types, variables, and constants is essential for programming. These
concepts form the foundation of how data is stored, manipulated, and accessed in a program.

Primitive Data Types:

Primitive data types are the most basic data types available in a programming language. They represent
simple values and are typically built into the language. In C programming, the primitive data types
include:

1. Integer Types:
• int: Used to represent whole numbers. Size is typically 4 bytes.
• short: A smaller integer type, usually 2 bytes.
• long: A larger integer type, typically 4 or 8 bytes.
• long long: An even larger integer type, usually 8 bytes.

2. Floating-Point Types:
• float: Used to represent single-precision floating-point numbers. Typically 4 bytes.
• double: Used to represent double-precision floating-point numbers. Typically 8 bytes.
• long double: Extended precision floating-point numbers. Size varies by platform.

C Programming 15
3. Character Type:
• char: Used to represent single characters. Typically 1 byte.

4. Void Type:
• void: Used to specify that no value is available. Often used in function declarations.

5. Boolean Type:
• _Bool: Represents boolean values (true/false). Typically 1 byte.

Example:

int age = 25;

float salary = 50000.50;

char grade = 'A';

Variables:
A variable is a storage location identified by a name (an identifier) used to store data that can be
modified during program execution. Variables must be declared before use, specifying the type of data
they will hold.

Syntax for Declaring Variables:

data_type variable_name;

Example:

int count;

float temperature;

char initial;

Variable Initialization:

Variables can be initialized at the time of declaration:

int count = 10;

float temperature = 36.5;

char initial = 'J';

C Programming 16
Constants:
A constant is a value that, once defined, cannot be altered by the program during its execution.
Constants are used to define values that should remain the same throughout the program.

Syntax for Declaring Constants:

1. Using #define Preprocessor Directive:

#define CONSTANT_NAME value

2. Using const keyword

Const data_type CONSTANT_NAME(variable_name) =value;

Example:

#define PI 3.14159

const int DAYS_IN_WEEK = 7;

Differences Between Variables and Constants

Variables: Their values can be changed during program execution.

Constants: Their values remain fixed throughout the program.

Example Program Illustrating Variables and Constants:

C Programming 17
In this example, PI is a constant defined using #define, and radius is a constant defined using the const
keyword. The variable area is used to store the computed area of a circle.

Key words:
Keywords are predefined or reserved words that have special meanings to the compiler. These are

part of the syntax and cannot be used as variables or identifiers in the program. A list of keywords

in C or reserved words in the C programming language are mentioned below:

Break case char const continue default do double else enum


extern float for goto if int Long register return short signed sizeof
static struct switch typedef union unsigned void volatile while auto

Basic Input and Output


In C programming, input and output operations are essential for interacting with users and displaying
results. These operations are primarily handled using standard input and output functions provided by
the C Standard Library.

Basic Input

The scanf function is used to read formatted input from the standard input (usually the keyboard). It
can read multiple values of various data types.

scanf("format_specifier", &variable);

Common Format Specifiers:

• %d for integers
• %f for floats
• %c for characters
• %s for strings

C Programming 18
Example :

Basic Output :

The printf function is used to write formatted output to the standard output (usually the screen).

Syntax:

printf("format_specifier", variable);

C Programming 19
Example:-

This C program declares three variables: age (integer), salary (float), and grade (character). It then prints
their values using printf, formatting the output for each type: %d for integer, %.2f for float with two
decimal places, and %c for character. The program ends with return 0, indicating successful execution

Detailed Example:

Simple Calculator Program

Here is an example program that uses both input and output functions to create a simple calculator:

in the below program

The user inputs two numbers and an operator.

The program performs the specified operation.

The result is displayed using printf

C Programming 20
C Programming 21
Operators, Type Conversion, and Casting:

Operations are fundamental to programming, allowing manipulation and computation of data.


Understanding operations, type conversion, and casting is essential for writing effective programs in C.

Operators
Operations in C can be categorized into various types:

Arithmetic Operations:
Arithmetic operations are basic mathematical calculations involving numbers, including addition (+),
subtraction (-), multiplication (*), division (/), and modulus (%). These operations are fundamental to
many programming and mathematical tasks, enabling the manipulation and analysis of numerical data.

➢ Addition (+)
➢ Subtraction (-)
➢ Multiplication (*)
➢ Division (/)
➢ Modulus (%)

Example:

int a = 10, b = 5;

int sum = a + b; // sum = 15

int difference = a - b; // difference = 5

int product = a * b; // product = 50

int quotient = a / b; // quotient = 2

int remainder = a % b; // remainder = 0

Relational Operations:
Relational operations are used to compare two values or expressions, returning a boolean result (either
true or false). The primary relational operators include:

➢ Equal to (==)
➢ Not equal to (!=)
➢ Greater than (>)
➢ Less than (<)
➢ Greater than or equal to (>=)
➢ Less than or equal to (<=)

C Programming 22
Example:

int x = 10, y = 5;

if (x > y) {

printf("x is greater than y\n");

Logical Operations:
Logical operators are used to combine multiple boolean expressions or values and return a boolean
result (true or false). The primary logical operators include

➢ Logical AND (&&)


➢ Logical OR (||)
➢ Logical NOT (!)

Example:

int a = 1, b = 0;

if (a && b) {

printf("Both are true\n");

} else {

printf("At least one is false\n");

Bitwise Operations:
Bitwise operations are used to perform operations on individual bits of integer values. These operations
are often used in low-level programming, data manipulation, and performance optimization. The
primary bitwise operators include:

➢ AND (&)
➢ OR (|)
➢ XOR (^)
➢ NOT (~)
➢ Left shift (<<)
➢ Right shift (>>)

int a = 5; // 0101 in binary

int b = 3; // 0011 in binary

C Programming 23
int c = a & b; // 0001 in binary, c = 1

int d = a | b; // 0111 in binary, d = 7

Assignment Operations:
Assignment operations are used to assign a value to a variable in programming. The most common
assignment operator is the equal sign (=), which assigns the value on the right-hand side to the variable
on the left-hand side. In addition to the basic assignment, there are compound assignment operators
that combine arithmetic operations with assignment. The primary assignment operators include:

Simple assignment (=)

Compound assignment (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=)

Example:

int a = 10;

a += 5; // a = 15

a*= 2; // a = 30

C Programming 24
C Programming 25
Type Conversion

Type conversion is the process of converting one data type to another. It can be implicit or explicit.

Implicit Type Conversion (Automatic Type Conversion):

The compiler automatically converts one data type to another.

This occurs in expressions where operands of different types are combined.

Example:

int a = 10;

float b = 5.5;

float result = a + b; // int 'a' is implicitly converted to float

Explicit Type Conversion (Casting):

The programmer manually converts one data type to another.

This is done using casting.

Example:

int a = 10;

float b = 5.5;

float result = (float)a + b; // explicit casting of 'a' to float

Casting

Casting is used to explicitly convert one data type to another. It is useful when you need to override
the default type conversion rules.

Syntax:

(data_type)expression

C Programming 26
Examples of Casting:

• Integer to Float:
int a = 10;
float b = (float)a; // b = 10.0

• Float to Integer:
float a = 5.75;
int b = (int)a; // b = 5, fractional part is discarded

• Character to Integer:
char c = 'A';
int ascii = (int)c; // ascii = 65, ASCII value of 'A'

Example Program Illustrating Type Conversion and Casting

C Programming 27
In the above program:

Implicit and explicit type conversions are demonstrated.

Casting a float to an integer and a character to its ASCII value is shown.

Problem-Solving Strategies

Top-Down Approach
Breaking down a complex problem into smaller, more manageable sub-problems.

In this approach We focus on breaking up the problem into smaller parts.This approach is mainly used
by structured programming language such as COBOL, FORTRAN, C, etc.Each part is programmed
separately therefore contain redundancy.In this approach the communications is less among modules.It
is also used in debugging, module documentation, etc.In top down approach, decomposition takes
place.In this top function of system might be hard to identify.

Pros-

• Easier isolation of interface errors

• It benefits in the case error occurs towards the top of the program.

• Defects in design get detected early and can be corrected as an early working module of the
program is available.

Cons-

• Difficulty in observing the output of test case.

• Stub writing is quite crucial as it leads to setting of output parameters.

• When stubs are located far from the top level module, choosing test cases and designing stubs
become more challenging.

Example:

Developing software by dividing it into modules and further into sub-modules.

Bottom-Up Approach
Starting with solving the smallest parts of the problem and integrating them to solve the larger
problem.

In bottom up approach, we solve smaller problems and integrate it as whole and complete the
solution.This approach is mainly used by object oriented programming language such as C++, C#,
Python.Redundancy is minimized by using data encapsulation and data hiding.In this module must

C Programming 28
have communication.It is basically used in testing.In bottom up approach composition takes place.In
this sometimes we can not build a program from the piece we have started.

Pros-

• Easy to create test conditions

• Test results are easy to observe

• It is suited if defects occur at the bottom of the program.

Cons-

• There is no representation of the working model once several modules have been constructed.

• There is no existence of the program as an entity without the addition of the last module.

• From a partially integrated system, test engineers cannot observe system-level functions. It
can be possible only with the installation of the top-level test driver.

Example: Building individual functions and combining them to create a complete program.

Time and Space Complexities of Algorithms:


Understanding time and space complexities is crucial for designing efficient algorithms and software
systems. These concepts help developers analyze the performance and scalability of their code,
ensuring optimal resource utilization.

Time Complexity
Definition: Amount of time taken by an algorithm to run as a function of the length of the input.

Time complexity is defined in terms of how many times it takes to run a given algorithm, based on the
length of the input. Time complexity is not a measurement of how much time it takes to execute a
particular algorithm because such factors as programming language, operating system, and processing
power are also considered.Time complexity is a type of computational complexity that describes the
time required to execute an algorithm. The time complexity of an algorithm is the amount of time it
takes for each statement to complete. As a result, it is highly dependent on the size of the processed
data. It also aids in defining an algorithm's effectiveness and evaluating its performance
Big O Notation: Represents the upper bound of the time complexity.
- Example: O(n), O(log n), O(n^2)

C Programming 29
Space Complexity
Definition: Amount of memory space required by an algorithm as a function of the length of the input.

When an algorithm is run on a computer, it necessitates a certain amount of memory space. The
amount of memory used by a program to execute it is represented by its space complexity. Because a
program requires memory to store input data and temporal values while running, the space
complexity is auxiliary and input space.
Big O Notation: Represents the upper bound of the space complexity.
- Example: O(1), O(n), O(n^2)

Example Programs in C

Example 1: Basic Input and Output

Example 2: Type Conversion

C Programming 30
Unit-II

Simple Sequential Programs:


Sequential programs in C are those that execute instructions in a linear, step-by-step manner, from the
beginning of the program to the end. Each statement in the program is executed exactly once, in the
order in which they appear. This is the simplest type of control flow in programming.

Example of a Sequential Program:

Conditional Statements:
The conditional statements such as if, if else, switch, etc. are used for decision-making purposes in C
programs. They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not.

Following are the decision-making statements available in C:

1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement

C Programming 31
if Statements:
if statement is the simple decision making statement. Based on the condition mention in the if block,
the decision is going to be made. If the condition is satisfied then the if block is executed other wise it
comes out of the if block.

Syntax :
If(condition){

//condition is true

//block of code

Flow chart :

Example Program:

C Programming 32
Output:
I am Not in if

if-else Statement:
The if-else statement contains two blocks one for is statement and other for else. First the condition in
the if block is checked if condition satisfies the if block is executed other wise the else block is executed.
No condition is specified for else block.

Syntax:
if(condition){

//if block is executed

}else{

//else block is executed

Flow chart:

C Programming 33
Example Program:

Output:
i is greater than 15

Nested if-else Statement:


The nested if statement is same like simple if statement but the difference is another if condition is
mentioned in if block. If the main if block condition satisfies it checks for inner if condition and then the
inside if block code is executed.

Syntax:
if(condition){

//outside if condition true

if(condition){

//outside if condition true

else{

//inside if false condition

C Programming 34
}

else{

if(condition){

//else block if condition true

else{

//inside else block

Flow chart:

C Programming 35
Sample program:

Output:
i is smaller than 15

i is smaller than 12 too

if-else ladder:
The if else if statements are used when the user has to decide among multiple options. An if-else ladder
in C is a way to execute one block of code among multiple options based on certain conditions. It uses
multiple ‘if’ and ‘else if’ statements to check various conditions sequentially. When a condition
evaluates to true, the corresponding block of code is executed, and the rest of the ladder is skipped.

C Programming 36
Syntax:
if (condition)

statement;

else if (condition)

statement;

else

statement;

Flow chart:

Example Program:

C Programming 37
Output:
i is 20

Switch Statement:
The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement. The switch block
consists of cases to be executed based on the value of the switch variable. In switch statement the
default block is executed if all the other cases fails the condition.

NOTE:
The switch expression should evaluate to either integer or character. It cannot evaluate any other data
type.

Syntax:
switch (expression) {

case value1:

statements;

case value2:

statements;

....

....

....

default:

statements;

C Programming 38
Flow chart:

Example Program:

Output:
Case 2 is executed

C Programming 39
Loops:
Loops are used to repeat a block of code until the specified condition is met. A loop statement allows
programmers to execute a statement or group of statements multiple times without repetition of
code.

How do you print the hello world programs ten times?

Using Loops :

There are three types of loops:

1.For Loops

2.While Loops

3.Do While Loops

C Programming 40
For Loops:
For Loop and While Loop are Entry-controlled loops. In Entry controlled loops the test condition is
checked before entering the main body of the loop. For loops allows programmers to write a loop that
will be executed a specific number of times. For loop enables programmers to perform n number of
steps together in a single line.

Syntax:
for(initialization expression; test expression; update expression){

// body of the loop

In for loop, a loop variable is used to control the loop. Firstly we initialize the loop variable with some
value, then check its test condition. If the statement is true then control will move to the body and the
body of for loop will be executed. Steps will be repeated till the exit condition becomes true. If the test
condition will be false then it will stop.

Flow Diagram:

C Programming 41
Example Program:

Output:

Hello World

Hello World

Hello World

Hello World

Hello World

Nested For Loops:


A nested loop means a loop statement inside another loop statement. That is why nested loops are also
called “loop inside loops“. We can define any number of loops inside another loop.Nested for loop refers
to any type of loop that is defined inside a ‘for’ loop.

C Programming 42
Flow Diagram:

Program:

C Programming 43
Output:
1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

Same as for while and do – while loops.

While Loop:
While loop does not depend upon the number of iterations. In for loop the number of iterations was
previously known to us but in the While loop, the execution is terminated on the basis of the test
condition. If the test condition will become false then it will break from the while loop else body will be
executed.

Syntax:
Initialization expression;

while (test expression) {

// body of the loop

Updation expression;

Firstly we initialize the loop variable with some value. Then it enters the while loop and checks for the
condition, if the condition is true further steps will be executed and it updates the variable. Steps will
be repeated till the condition becomes true. If the test condition will be false then it will stop.

C Programming 44
Flow Diagram:

Program:

Output:
Hello World

Hello World

Hello World

Hello World

C Programming 45
do-while Loop:
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition
which is tested at the end of the body. In the do-while loop, the loop body will execute at least
once irrespective of the test condition.

Syntax:
initialization_expression;

do

// body of do-while loop

update_expression;

} while (test_expression);

Firstly, we initialize the loop variable with some value. Then it enters the do block and executes the
body of the loop, updating the variable. After executing the loop body, it checks the condition. If the
condition is true, the steps are repeated. This process continues until the condition becomes false. The
do-while loop guarantees that the loop body is executed at least once, even if the test condition is
initially false.

Flow Diagram:

C Programming 46
Program:

Output:
Hello World

Hello World

Hello World

Hello World

Hello World

Loops Control Statements:


Loop control statements in C programming are used to change execution from its normal sequence.

Types:
1.Break Statement

2.Continue Statement

3.Goto Statement

C Programming 47
1.Break Statement:
The break in C is a loop control statement that breaks out of the loop when encountered. It can be used
inside loops or switch statements to bring the control out of the block. The break statement can only
break out of a single loop at a time.

Syntax:
break;

Program

NOTE:

C Programming 48
Break statement only breaks out of one loop at a time. So if in nested loop, we have used break in
inner loop, the control will come to outer loop instead of breaking out of all the loops at once. We will
have to use multiple break statements if we want to break out of all the loops.

Output:
break in for loop

12

break in while loop

12

2.Continue Statement:
The C continue statement resets program control to the beginning of the loop when encountered. As a
result, the current iteration of the loop gets skipped and the control moves on to the next iteration.
Statements after the continue statement in the loop are not executed.

Syntax:
continue;

Program:

C Programming 49
Output:
1235

1235

3.Goto Statement:
The C goto statement is sometimes also referred to as an unconditional jump statement. The goto
statement can be used to jump from anywhere to anywhere within a function.

Syntax1 | Syntax2

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

goto label; | label:

. | .

. | .

. | .

label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label.
Here, the label is a user-defined identifier that indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the
‘goto label;’ statement in the above syntax.

C Programming 50
Example-1:

Output:
26 is even

C Programming 51
Example-2:

Output:
1 2 3 4 5 6 7 8 9 10

Practice Programs
1. Write a program to find the given number is even or odd.
2. Write a program to find the largest of two numbers.
3. Write a program to find whether the person is eligible to vote or not.
4. Write a program that takes a student's score (integer) as input and prints the grade based on
the following scale using if-else if statements.
5. Write a program that takes a year as input from the user and checks if it is a leap year or not.
6. Write a program that takes an integer (1-7) from the user and prints the corresponding day of
the week using a switch statement. (1 for Monday, 2 for Tuesday, ..., 7 for Sunday).
7. Write a program that takes an integer from the user and determines if it is positive, negative,
or zero using if-else statements.

C Programming 52
8. Write a program that takes the age of a person as input and classifies them into one of the
following age groups using if-else if statements.
9. Write a program to find whether the character is vowel or consonant.
10. Find largest among three numbers.
11. Write a program to print numbers from 1 to 10 using a for loop?
12. Write a program to print the first 10 odd numbers using a for loop?
13. Write a program to count down from 10 to 1 using a while loop?
14. Write a program to find the sum of the first N natural numbers. The value of N should be given
by the user?
15. Write a program to calculate the factorial of a given number using a while loop?
16. Write a program to print the multiplication table of a given number using a for loop?
17. Write a program to reverse a given number using a while loop. For example, if the input is
12345, the output should be 54321.
18. Write a program to count the number of digits in a given number using a while loop?
19. Write a program to print all even numbers between 1 and 50 using a for loop?
20. Write a program to calculate the sum of the digits of a given number using a while loop. For
example, if the input is 123, the output should be 6 (1+2+3).

C Programming 53
UNIT-3 Arrays

What is Array in C?

Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing
multiple values under a single name. An array in C is a fixed-size collection of similar data items stored
in contiguous memory locations. It can be used to store the collection of primitive data types such as
int, char, float, etc., and also derived and user-defined data types such as pointers, structures, etc.

In C, we have to declare the array like any other variable before using it. We can declare an array by
specifying its name, the type of its elements, and the size of its dimensions. When we declare an array
in C, the compiler allocates the memory block of the specified size to the array name.

Syntax of Array Declaration:


data_type array_name [size];

or

data_type array_name [size1] [size2]...[size N];

The C arrays are static in nature, i.e., they are allocated memory at the compile time.

// declaring array of integers

int arr_int[5];

// declaring array of characters

char arr_char[5];

C Programming 54
Array indexing :
Indexing of arrays in C refers to accessing or referring to individual elements within an array using an
integer index. The index allows you to retrieve or modify the value stored at a specific position within
the array.

❖ Key Points about Array Indexing:


Zero-based Indexing: In C, array indexing starts from 0. This means the first element of the array is
accessed using index 0, the second element using index 1, and so on.

Syntax: The syntax for accessing an array element is:

arrayName[index]

where arrayName is the name of the array and index is an integer expression.

Bounds: The valid index range for an array of size n is from 0 to n-1. Accessing an index outside this range
results in undefined behavior. C does not perform bounds checking on arrays. This means that accessing
an array with an out-of-bounds index will not result in an error but will lead to undefined behavior.
Always ensure your index is within the valid range.

➢ C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is declared
or allocated memory, the elements of the array contain some garbage value. So, we need to initialize
the array to some meaningful value. There are multiple ways in which we can initialize an array in C.

1. Array Initialization with Declaration

In this method, we initialize the array along with its declaration. We use an initializer list to initialize
multiple elements of the array. An initializer list is the list of values enclosed within braces { } separated
b a comma.

data_type array_name [size] = {value1, value2, ... value N};

2. Array Initialization with Declaration without Size

If we initialize an array using an initializer list, we can skip declaring the size of the array as the compiler
can automatically deduce the size of the array in these cases. The size of the array in these cases is equal
to the number of elements present in the initializer list as the compiler can automatically deduce the
size of the array.

C Programming 55
data_type array_name[] = {1,2,3,4,5};

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)

We initialize the array after the declaration by assigning the initial value to each element individually.
We can use for loop, while loop, or do-while loop to assign the value to each element of the array.

for (int i = 0; i < N; i++) {

array_name[i] = value i;

A.Access Array Elements

We can access any element of an array in C using the array subscript operator [ ] and the index value i
of the element. One thing to note is that the indexing in the array always starts with 0, i.e., the first
element is at index 0 and the last element is at N – 1 where N is the number of elements in the array.

array_name [index];

B.Update Array Element

We can update the value of an element at the given index i in a similar way to accessing an element by
using the array subscript operator [ ] and assignment operator =.

array_name[i] = new_value;

C.Array Traversal

Traversal is the process in which we visit every element of the data structure. For C array traversal, we
use loops to iterate through each element of the array.

Array Traversal using for Loop

for (int i = 0; i < N; i++) {

array_name[i];

C Programming 56
D. Modifying Elements:

Elements of the array can be modified by assigning new values to specific indices. Here, the first element
is changed to 100 and the fifth element is changed to 500.

arr[0] = 100;

arr[4] = 500;

❖ Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as follows:

One Dimensional Arrays (1D Array)

Multidimensional Arrays

1. One Dimensional Array in C

The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.

Syntax of 1D Array in C

array_name [size];

2. Multidimensional Array in C

Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the popular
multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with more dimensions than
3d arrays but they are avoided as they get very complex and occupy a large amount of space.

A. Two-Dimensional Array in C

• A Two-Dimensional array or 2D array:


In C is an array that has exactly two dimensions. They can be visualized in the form of rows and columns
organized in a two-dimensional plane.

Syntax of 2D Array in C

array_name[size1] [size2];

Here,

size1: Size of the first dimension.

size2: Size of the second dimension.

• B. Three-Dimensional Array in C:

C Programming 57
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A 3D array
has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked on top of each
other to create the third dimension.

Syntax of 3D Array in C

array_name [size1] [size2] [size3];

ARRAYS-MEMORY MODEL
In C, arrays have a simple and efficient memory model where elements are stored in contiguous memory
locations. This contiguous allocation allows for easy and fast access to any element using its index. Here’s
a detailed look at the memory model of arrays in C:

Memory Layout of Arrays

When an array is declared, the compiler allocates a block of memory large enough to hold all the
elements of the array. The size of the memory block is the product of the number of elements and the
size of each element.

Example: Consider an example where an array of integers is declared:

int arr[5] = {10, 20, 30, 40, 50};

In this example:

The array arr has 5 elements.

Each element is of type int, typically 4 bytes on most systems.

The total memory allocated for arr is 5 * 4 = 20 bytes.

Contiguous Memory Allocation


The elements are stored in contiguous memory locations. If the base address of the array (address of
arr[0]) is 0x1000, the memory layout would look like this:

Address Value

0x1000 10

0x1004 20

0x1008 30

0x100C 40

0x1010 50

Accessing Elements

C Programming 58
The address of any element arr[i] can be calculated using the formula:

Address of arr[i] = base_address + i * sizeof(element_type)

For example, the address of arr[2]:

Address of arr[2] = 0x1000 + 2 * 4 = 0x1008

Pointer Arithmetic
In C, you can also use pointers to access array elements. Since array elements are stored contiguously,
pointer arithmetic can be used to traverse the array.

int *ptr = arr; // ptr points to the first element of arr

// Access elements using pointer arithmetic

int firstElement = *(ptr); // 10

int secondElement = *(ptr + 1); // 20

int thirdElement = *(ptr + 2); // 30

Multi-dimensional Arrays
For multi-dimensional arrays, the memory layout is still contiguous but follows a row-major order. This
means that the elements of each row are stored in contiguous memory locations.

Consider a 2D array:

int matrix[2][3] = {

{1, 2, 3},

{4, 5, 6}

};

The memory layout would be:

C Programming 59
Address Value

0x2000 1

0x2004 2

0x2008 3

0x200C 4

0x2010 5

0x2014 6

➢ Accessing Elements in 2D Arrays


For a 2D array matrix with n rows and m columns, the address of element matrix[i][j] can be calculated
as:

Address of matrix[i][j] = base_address + (i * m + j) * sizeof(element_type)

For example, the address of matrix[1][2]:

Address of matrix[1][2] = 0x2000 + (1 * 3 + 2) * 4 = 0x2014

Example Program

Here is an example program demonstrating the memory layout and accessing elements:

Output:

C Programming 60
Base address of arr: 0x7ffee2c4b6a0

Address of arr[0]: 0x7ffee2c4b6a0, Value: 10

Address of arr[1]: 0x7ffee2c4b6a4, Value: 20

Address of arr[2]: 0x7ffee2c4b6a8, Value: 30

Address of arr[3]: 0x7ffee2c4b6ac, Value: 40

Address of arr[4]: 0x7ffee2c4b6b0, Value: 50

Using pointer arithmetic:

Value at ptr + 0: 10

Value at ptr + 1: 20

Value at ptr + 2: 30

Value at ptr + 3: 40

Value at ptr + 4: 50

This example shows how array elements are stored in contiguous memory locations, how to access them
using array indexing and pointer arithmetic, and how to print their addresses and values.

❖ Two Dimensional Array in C


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

Declaration of two dimensional Array in C

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

data_type array_name[rows][columns];

Consider the following example.

int two_dimen[4][3];

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

Initialization of 2D Array in C

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

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

example:

Output:

arr[0][0] = 1

arr[0][1] = 2

arr[0][2] = 3

arr[1][0] = 2

arr[1][1] = 3

arr[1][2] = 4

arr[2][0] = 3

arr[2][1] = 4

arr[2][2] = 5

arr[3][0] = 4

arr[3][1] = 5

arr[3][2] = 6

C Programming 62
Accessing Elements in a Two-Dimensional Array
You can access elements of a two-dimensional array using the row and column indices. The indices are
zero-based, meaning the first element is at [0][0].

Example:

int value = matrix[1][2];

Memory Layout
In memory, a two-dimensional array is stored in a row-major order. This means that all elements of the
first row are stored in contiguous memory locations, followed by the elements of the second row, and
so on.

For the matrix[3][4] example:

Address Value

0x1000 1

0x1004 2

0x1008 3

0x100C 4

0x1010 5

0x1014 6

0x1018 7

0x101C 8

0x1020 9

0x1024 10

0x1028 11

0x102C 12

Pointer Arithmetic with Two-Dimensional Arrays


You can also use pointers to access elements in a two-dimensional array. The array name acts as a
pointer to the first element.

Example:

C Programming 63
❖ Introduction to Strings:
The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The
character array or the string is used to manipulate text such as word or sentences. Each character in the
array occupies one byte of memory, and the last character must always be 0. The termination character
('\0') is important in a string since it is the only way to identify where the string ends. When we define a
string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

• By char array
• By string literal
• By using string pointer

Let's see the example of declaring string by char array in C language.

char ch[10]={'g', 'p', 'c', 'e', 't', 'k', 'u', 'r', 'n', 'o', 'o', 'l','\0'};

We can also define the string by the string literal in C language. For example:

char ch[]="GPCET";

Using a pointer:

char *str = "Hello";

• We need to add the null character '\0' at the end of the array by ourself whereas, it is appended
internally by the compiler in the case of the character array.
• The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.

Accepting string as the input and printing output

C Programming 64
You can use functions like scanf, printf, gets, and puts to handle string input and output.

Using scanf and printf:

Using gets and puts:

Using fgets :

Common String Functions


C Programming 65
C provides a set of library functions to manipulate strings. These functions are declared in the string.h
header file.

strlen: Computes the length of a string.

strcpy: Copies one string to another.

strcat: Concatenates two strings.

C Programming 66
strcmp: Compares two strings.

strchr: Finds the first occurrence of a character in a string

strstr: Finds the first occurrence of a substring in a string.

C Programming 67
Array programs with integers
1.Initializing and Printing an Array

2. Finding the Maximum and Minimum Values in an Array

3. Calculating the Sum and Average of Array Elements

4. Reversing the Elements of an Array

5. Searching for an Element in an Array

6. Sorting an Array in Ascending Order (Bubble Sort)

7. Inserting elements in an array (starting, ending, at specific index)

8. Deleting elements in an array (starting, ending, at specific index)

Strings:
1.String input, traversing, printing

2. Reverse a String

3.check if the string is palindrome or not

4. Count the Number of Vowels and Consonants

5. Find the Length of a String

6. Concatenate Two Strings

7. Copy a String

8. Convert a String to Uppercase

9. Convert a String to Lowercase

C Programming 68
UNIT-4

Pointers & User Defined Data types: Pointers, dereferencing and address
operators, pointer and address arithmetic, array manipulation using pointers, User-
defined data types-Structures and Unions.

Pointers:
Pointers are one of the core components of the C programming language.
A pointer can be used to store the memory address of other variables, functions, or even other pointers.
The use of pointers allows low-level memory access, dynamic memory allocation, and many other
functionality in C.
Like any variable or constant, we must declare a pointer before using it to store any variable
address.

Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.

datatype * ptr;
where:
➢ ptr is the name of the pointer.
➢ datatype is the type of data it is pointing to.

C Programming 69
Implementing the pointers (Using of pointers)
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing

1. Pointer Declaration:
In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer,
we use the * dereference operator before its name.

Syntax : data_type *pointer_name;


Example: int *p;
float *x;
Example: int *ptr;
The pointer declared here will point to some random memory address as it is not
initialized.Such pointers are called wild pointers.

1. Pointer Initialization:
Pointer initialization is the process where we assign some initial value to the pointer variable.
We generally use the & address of operator to get the memory address of a variable and then
store it in the pointer variable.

Making a pointer variable to point other variables by providing address of that variable to thepointer
is known as referencing of pointer.
It is also known as initialization of pointers. For proper use of pointer, pointer variables mustpoint to
some valid address and it is important to note that without referencing, pointer variables are meaningless.
General syntax for referencing of pointer / initializing the pointer is:

pointer_variable = &normal_variable;
Here pointer_variable and normal_variable must be of the same data types.

int a=5;
int *ptr;
ptr = &a;

C Programming 70
Here pointer ptr got address of variable a so, pointer ptr is now pointing to variable a.
float val=5.5;
float *p;

p = &val;
Here pointer p got address of variable val so, pointer p is now pointing to variable val.
But!

float x=30.4;
int *iptr;

iptr = &x;
is invalid!!! Because pointer iptr cannot store address of float variable.

Other Example
int var = 10;int *
ptr; ptr = &var;

We can also declare and initialize the pointer in a single step. This method is called pointer
definition as the pointer is declared and initialized at the same time.

Example

int *ptr = &var;

Note: It is recommended that the pointers should always be initialized to some value
beforestarting using it. Otherwise, it may lead to number of errors.

C Programming 71
2. Pointer Dereferencing:
When indirection operator (*) is used with the pointer variable, then it is known as
dereferencing a pointer. When we dereference a pointer, then the value of the variable
pointedby this pointer will be returned.

The *pointer_variable after referencing instructs compilers that go to the memory


address stored by pointer_variable and get value from that memory address.

Dereferencing a pointer is the process of accessing the value stored in the memory
address specified in the pointer. We use the same * dereferencing operator that we used in
the pointer declaration.

Use of dereferencing pointer:


Dereference a pointer is used because of the following reasons:
➢ It can be used to access or manipulate the data stored at the memory location, which is
pointed by the pointer.
➢ Any operation applied to the dereferenced pointer will directly affect the value of the variable
that it points to.
Steps to dereference a pointer:
1) First, we declare the integer variable to which the pointer points.
int x =9;
2) Now, we declare the integer pointer variable.
int *ptr;
3) After the declaration of an integer pointer variable, we store the address of 'x' variable to the
pointer variable 'ptr'.
ptr=&x;

4) We can change the value of 'x' variable by dereferencing a pointer 'ptr' as given below:
*ptr =8;
The above line changes the value of 'x' variable from 9 to 8 because 'ptr' points to the 'x'location
and dereferencing of 'ptr', i.e., *ptr=8 will update the value of x.

C Programming 72
Let's combine all the above steps:

OUTPUT:
value of x at beginning: 9
value of x after dereferencing: 8

Address operator:

The Address Operator in C also called a pointer. This address operator is denoted by “&”. This &
symbol is called an ampersand. The purpose of this address operator or pointer is used to return the
address of the variable.

Syntax: &variable_name;

C Programming 73
OUTPUT:

The value of num is: 10


The address of num is: 0x7fff5fbff7ac

The value of the num is 10 and the memory location of the variable 'num' is displayed on the screen.

Address Operator Uses:


1. Passing Pointers as Function Arguments
2. Dynamic Memory Allocation:

1) Passing pointers as function parameters is one of the address operator's main applications. Pointers
are variables that keep track of other variables' memory addresses. The original value of a variable in
the calling function can be changed by supplying the variable's address as a function argument.

C Program to swap two numbers by using pointers.

C Programming 74
OUTPUT:

Before swapping: x = 10, y = 20

After swapping: x = 20, y = 10

The function "swap" declared in the above program, and it accepts two integer pointers as
inputs. We have accessed the values of the variables that the pointers pointed to within the function
using the address operator. After that, using a temporary variable, we switched the variables' values.
Two integer variables named 'x' and 'y' have been defined in the main function, and they have
each been given an initial value of 10 and 20 respectively. The values of the variablesboth
before and after using the 'swap' function were printed using the printf( ) function. The
'swap' function has been given the addresses of 'x' and 'y' as arguments.

C Programming 75
2. Dynamic Memory Allocation:
The address operator is also used in dynamic memory allocation. Using the malloc()
function, dynamic memory allocation enables run-time memory allocation. The address operator can
be used to access the memory block that was allocated using the pointer that the malloc( ) function
returns.

Here we have declared variables 'n' and 'i' as well as a pointer 'arr' of integer type. The user
will be prompted to provide the array's element count using the printf( ) method.
We used the malloc( ) function to allocate memory to the reference "arr". The size of each
integer element in the array is specified by the 'sizeof(int)' option. The program exits after displaying
an error message if the memory allocation fails.

C Programming 76
OUTPUT:
Enter the number of elements: 5

Enter element 1: 10

Enter element 2: 20

Enter element 3: 30

Enter element 4: 40

Enter element 5: 50

The elements of the array are: 10 20 30 40 50

To read the array's elements from the user, we utilized a for loop. Each element of the array
can be accessed using the address operator. We utilized another for loop to print the array's
elements on the screen.

Pointer Arithmetic in C:
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers.
The pointer variables store the memory address of another variable. It doesn’t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language.
The C pointer arithmetic operations are slightly different from the general mathematical calculations.

Pointer arithmetic operations are:

1) Increment/Decrement of a Pointer
2) Addition of integer to a pointer
3) Subtraction of integer from a pointer
4) Subtracting two pointers of the same type
5) Comparison of pointers

1) Pointer increment and decrement:


Pointer increment operation increments pointer by one. Causing it to point to a memory
location skipping N bytes (where N is size of pointer data type). This is somewhat different from the
general arithmetic since the value of the pointer will get increased by the size of the data type to which
the pointer is pointing.

C Programming 77
We can traverse an array by using the increment operation on a pointer which will keep
pointing to every next element of the array, perform some operation on that, and update itself in a
loop.

The Rule to increment the pointer is given below:


new_address= current_address + i * size_of(data type)

Here i is the number by which the pointer get increased.


32-bit
For 32-bit int variable, it will be incremented by 2 bytes.
64-bit
For 64-bit int variable, it will be incremented by 4 bytes.
Let's see the example of incrementing pointer variable on 64-bit architecture.

OUTPUT:

Address of p variable is 3214864300

After increment: Address of p variable is 3214864304

C Programming 78
OUTPUT:

printing array elements...1 2 3 4 5

2) Decrementing Pointer in C:
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing
to the previous location. The formula of decrementing the pointer is given below:

new_address= current_address - i * size_of(data type)


32-bit
For 32-bit int variable, it will be decremented by 2 bytes.
64-bit
For 64-bit int variable, it will be decremented by 4 bytes.
Let's see the example of decrementing pointer variable on 64-bit OS.

C Programming 79
OUTPUT:

Address of p variable is 3214864300


After decrement: Address of p variable is 3214864296

C Programming 80
3) Addition of Integer to Pointer:
When a pointer is added with an integer value, the value is first multiplied by the size of the
data type and then added to the pointer.

Example: Consider the ptr is an integer pointer that stores 1000 as an address. If we add integer
5 to it using the expression, ptr = ptr + 5, then, the final address stored in the ptr will be

ptr = 1000 + sizeof(int) * 5 = 1020.

OUTPUT:

Pointer ptr2 before Addition:


0x7ffca373da9cPointer ptr2 after Addition:
0x7ffca373daa8

C Programming 81
4) Subtraction of Integer to Pointer:
When a pointer is subtracted with an integer value, the value is first multiplied by the size of
the data type and then subtracted from the pointer similar to addition.

Example:
Consider the example as above where the ptr is an integer pointer that stores 1000 as an
address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final
address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980

Example of Subtraction of Integer from Pointer

C Programming 82
OUTPUT:

Pointer ptr2 before Subtraction: 0x7ffd718ffebc


Pointer ptr2 after Subtraction: 0x7ffd718ffeb0

5) Subtraction of Two Pointers:


The subtraction of two pointers is possible only when they have the same data type. The result is
generated by calculating the difference between the addresses of the two pointers and calculating
how many bits of data it is according to the pointer data type. The subtraction of two pointers gives
the increments between the two pointers.

Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted. The difference
between addresses is 4 bytes. Since the size of int is 4 bytes, therefore the increment between ptr1
and ptr2 is given by (4/4) = 1.

C Programming 83
OUTPUT:
ptr1 = 2715594428, ptr2 = 2715594424

Subtraction of ptr1 & ptr2 is 1

6) Comparison of Pointers:
We can compare the two pointers by using the comparison operators in C. We can implement
this by using all operators >, >=, <, <=, ==, !=. It returns true for the valid condition and returns false
for the unsatisfied condition.
Step 1: Initialize the integer values and point these integer values to the pointer.
Step 2: Now, check the condition by using comparison or relational operators on pointer
variables.
Step 3: Display the output.

Example of Pointer Comparison:

OUTPUT:
Pointer to Array Name and First Element are Equal.

C Programming 84
Array manipulation using pointers:

Using pointers, we can access and manipulate array elements. Dereferencing the pointer gives
the value of the element it points to. By incrementing or decrementing the pointer, we can traverse
the array. Using pointers we can access array elements and we can also manipulate them whenever
we required.
Simple Example to understand:
int arr[3] = {10, 20, 30};

int *ptr = arr;

printf("%d", *ptr); // Outputs 10


ptr++;

printf("%d", *ptr); // Outputs 20

Pointer Arithmetic with Arrays:


Pointer arithmetic allows for efficient traversal of arrays. When you increment a pointer pointing to
an array element, it moves to the next element. The pointer advances by the size of the array's data
type.
int arr[3] = {10, 20, 30};

int *ptr = arr;


ptr += 2;

printf("%d", *ptr); // Outputs 30

Multidimensional Arrays and Pointers:


For multidimensional arrays, pointers can be a bit more complex. For a two-dimensional array, we
use a pointer to a pointer. This allows you to access elements in both dimensions.

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

int (*ptr)[3] = arr; // Pointer to an array of 3 integers


printf("%d", ptr[1][2]); // Outputs 6

C Programming 85
C Program to Swap Elements in an Array using Pointers:
This is a C Program to accept an array & swap elements using pointers.

This program will implement an array and will swap the elements of the array. Swapping isdone
using pointers.

Problem Solution / Algorithm steps:

1. Declare an array and define all its elements.


2. Create a function with two parameters i.e. two pointer variables.
3. Inside this function, first create a temporary variable. Then this temporary variable is
assigned the value at first pointer.
4. Now, value at first pointer changes to the value at second pointer.
5. And value at second pointer changes to the value of temporary variable.
6. This way swapping is done and in main( ) function, we need to pass two pointer variables
pointing the element which we need to swap.

C program for Array manipulation using pointers:

C Programming 86
C Programming 87
OUTPUT:
How many Elements:4
Enter Elements one by one23
67
45
15

Resultant Array: X[0] = 23.000000


X[1] = 67.000000
X[2] = 15.000000
X[3] = 45.000000

User-defined data types:


The data types defined by the user them self are referred to as user-defined data types. These data
types are derived from the existing data types.
Need of User-Defined Data types:
➢ It enables customization in the code. User can define his/her own data types.
➢ Users can write more efficient and flexible code.
➢ Provides abstraction.
Types of User-Defined Data Types:
There are 4 types of user-defined data types in C. They are

1. Structure
2. Union

3. Enum
4. Typedef
1. Structure:
Structure is a user-defined data type in a programming language that stores different data types'
valuestogether. The struct keyword is used to define a structure data type in a program. The struct
data type stores one or more than one data element of different kinds in a variable.
Suppose that if we want to store the data of employee in our C/C++ project, where we have
tostore the following different parameters:
• Id
• Name
• Department

C Programming 88
• Email Address
One way to store 4 different data by creating 4 different arrays for each parameter, such as id[ ],
name[ ], department[ ], and email[ ]. Using array id[i] represents the id of the ith employee.
Similarly, name[i] represents the name of ith employee (name). Array element department[i] and
email[i] represent the ith employee's department and email address.
Syntax of struct:

struct [structure_name]

{
type member_1;type
member_2;

...
type member_n;

};

C Programming 89
Let's see the another example to define a structure for an entity employee in c.
struct employee

{ int id;

char name[20];

float salary;

};

The following image shows the memory allocation of the structure employee that is defined in the

above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are
the members or fields of the structure. Let's understand it by the diagram given above:

Declaring structure variable:


We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:

1. By struct keyword within main( ) function


2. By declaring a variable at the time of defining the structure.
1st way:

Let's see the example to declare the structure variable by struct keyword. It should be declared within
the main function.

C Programming 90
struct employee

{ int id;

char name[50];
float salary;

};

Now write given code inside the main( ) function.

struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2
canbe treated in the same way as the objects in C++ and Java.

2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Here, e1 and e2 can be treated as the objects.

If the number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare
the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main()
function.

Accessing members of the structure

C Programming 91
There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)
Let's see the code to access the id member of p1 variable by. (member) operator.

Example program to illustrate structure concept.

C Programming 92
OUTPUT:
Employee 1 id : 101
Employee 1 name : Sonoo Jaiswal
Employee 1 salary : 56000.000000
Employee 2 id : 102
Employee 2 name : James Bond
Employee 2 salary : 126000.000000

Union in C:

Union is a special data type available in C that allows storing different data types in the same memory
location. We can define a union with many members, but only one member can contain a value at
any given time. Unions provide an efficient way of using the same memory location for multiple
purposes.

Compiler allocate the memory, by considering the size of the largest memory. So size of unionis equal
to the largest member.

Unlike structures, Union can share the same memory location.


Syntax of Declaring Union

union [name of union]


{
type member1;
type member2;
type member3;
};

Union is declared using the union keyword and name of union. Number 1, number 2,
number 3 are individual members of union. The body part is terminated with a semicolon;.

C Programming 93
Example of Union in C Programming

Output:
1101109601
20.199892
a

In the above program, you can see that the values of x and y gets corrupted. Only variable ch
prints the expected result. It is because, in union, the memory location is shared among all member
data types.

Therefore, the only data member whose value is currently stored, will occupy memory space.The
value of the variable ch was stored at last, so the value of the rest of the variables is lost.

C Programming 94
C Programming 95
UNIT – V
INTRODUCTION TO FUNCTIONS:
Functions are essential in C programming because they help break down complex problems into smaller,
more manageable tasks. Each function performs a specific task, and by combining these tasks, you can
solve the overall problem. Functions also promote code reuse, as you can use the same function
multiple times without rewriting the code.

Example:

In this example, the square function calculates the square of a number. You can reuse the square
function whenever you need to find the square of a number.

Function Declaration and Definition


A function declaration (also called a function prototype) is a statement that tells the compiler about a
function's name, return type, and parameters. It does not contain the function body. The function
definition, on the other hand, includes the actual code that specifies what the function does.

Example:

C Programming 96
In this example, the divide function is declared before main and defined later. The function divides two
integers and returns the result as a float.

Function Call, Return Types, and Arguments


• Function Call: When you use a function in your code, you call it by using its name followed by
parentheses, which may contain arguments. The function is then executed, and control returns
to the point after the call once it’s done.

• Return Types: The return type of a function is the data type of the value that the function
returns to the caller. If a function doesn’t need to return a value, you use void as the return
type.

• Arguments: These are values you pass to a function when you call it. The function uses these
values to perform its task.

Example:

C Programming 97
Here, the max function returns the maximum of two numbers. The return type is int, and the function
is called in main.

Modifying Parameters Inside Functions Using Pointers


Passing parameters by value means that the function works with a copy of the data, so any changes
made inside the function don’t affect the original value. To modify the original value, you pass the
address of the variable using pointers, which allows the function to work directly with the original data.

C Programming 98
Example:

In this example, the increment function takes a pointer to an integer and increments the value it
points to. This modifies the original variable passed to the function.

Arrays as Parameters
Arrays can be passed to functions just like variables. However, when passing arrays, the base address

of the array is passed, meaning that the function can access and modify the elements of the original
array.

C Programming 99
Example:

In this example, the sumArray function calculates the sum of elements in an array. The array is passed
by reference, allowing the function to access the actual elements.

Scope and Lifetime of Variables


The scope of a variable determines where it can be accessed in the code. Variables can be local
(accessible only within the block they are declared) or global (accessible throughout the program). The
lifetime of a variable is how long it exists in memory during the program's execution.

• Local Variables: Exist only during the execution of the block or function where they are
declared. Once the block ends, the variable is destroyed.

• Global Variables: Declared outside all functions, they remain in memory for the program's
entire duration and can be accessed by any function.

C Programming 100
Example:

In this example, globalVar is a global variable, accessible in both main and demoFunction. However,
localVar is a local variable, accessible only within demoFunction.

Command Line Arguments


Command line arguments are inputs provided to a program when it is executed from the command line.
They are useful for customizing the behavior of a program without modifying the code.

C Programming 101
Example:

Here, argc counts the number of command line arguments, and argv is an array of strings representing
the arguments. The program calculates the sum of two integers provided as command line arguments .

Why files are needed?


• When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
• You can easily move your data from one computer to another without any changes.

File I/O:-
Sometimes it is necessary to store the data in a manner that can be later retrieved and displayed

C Programming 102
either in a part or in whole. This medium is usually a “file” on the disk. File I/O can be handled

by using different functions.

a) Formatted functions:- The file input function fscanf( ) and the file output function fprintf( )
are called formatted file I/O functions.

b)Unformatted functions:- The input functions like getc( ), getw( ), and fread( ) are called
unformatted file input functions and putc( ), putw( ), and fwrite( ) functions are unformatted file

output functions. Each and every function is having its own syntax and meaning.

File streams:- Stream is either reading or writing of data. The streams are designed to allow the
user to access the files efficiently. A stream is a file or physical device like key board, printer, monitor,
etc., The FILE object uses these devices. When a C program is started, the operating system is
responsible for opening three streams:

standard input stream (stdin),

standard output stream (stdout),

standard error(stderr).

Normally the stdin is connected to the keyboard, the stdout and stderr are connected to the monitor.

Files
File is a collection of bytes that is stored on secondary storage devices like Hard disk.

OR

A file represents a sequence of bytes on the disk where a group of related data is stored. File is

created for permanent storage of data. It is a ready made structure.

Note:

All files related function are available in stdio.h header file.

Types of Files :
When dealing with files, there are two types of files you should know about:

C Programming 103
1. Text files

2. Binary files

1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text

editors.

When you open those files, you'll see all the contents within the file as plain text. You can easily

edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide least security and takes

bigger storage space.

2. Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store it
in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better security than text
files.

File Operations
In C, you can perform four major operations on the file, either text or binary:

• Naming a file/Creation of new file


• Opening an existing file
• Reading data from file
• Writing data into file
• Closing a file

Steps for processing a file

➢ Declare a file pointer


➢ open a file using fopen() function
➢ Process the file using suitable file functions.
➢ close the file using fclose() function.

Declaration of a file
When working with files, you need to declare a pointer of type file. This declaration is needed

for communication between the file and program.

C Programming 104
Syntax

FILE *fp;

Opening a file - for creation and edit


The fopen() function is used to create a new file or to open an existing file.

General Syntax :

fp = fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

Closing a File
The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using library function fclose().

fclose(fptr); //fptr is the file pointer associated with file to be closed.

File Opening Modes:


Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode

Difference between Append and Write Mode


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to

write in a file. In both the modes, new file is created if it doesn't exists already.

C Programming 105
The only difference they have is, when you open a file in the write mode, the file is reset,

resulting in deletion of any data already present in the file. While in append mode this will not

happen. Append mode is used to append or add data to the existing data of file(if any). Hence,

when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the
file.

Formatted File I/O Functions


Syntax of fprintf is

fprintf (fp, “control string”, list);

Example:
fprintf(fp1, “%s %d”, name, age);

Syntax of fscanf is,

fscanf(fp, “control string”, list);

Example: fscanf(fp, “%s %d”, name, & age);

Note:
➢ fscanf is used to read list of items from a file
➢ fprintf is used to write a list of items to a file.

Note:

EOF – End of file (when EOF encountered the reading / writing should be terminated) .

Example:

C Programming 106
Example 1: Write to a text file using fprintf()

Example 2: Read from a text file using fscanf()

C Programming 107
Input/Output Operation on files
S.No Function Operation Syntax
1 getc() Read a character from a file getc( fp)
2 putc() Write a character in file putc(c, fp)

3 fprintf() To write set of data in file fprintf(fp, "control string", list)


4 fscanf() To read set of data from file. fscanf(fp, "control string", list)
5 getw() To read an integer from a file. getw(fp)
6 putw() To write an integer in file. putw(integer, fp)

C Programming 108
Unformatted File I/O Functions
fputc() function

The fputc() function is used to write a single character into file.

putc ( ):- Putting a character in to the file. It works with only character data type. One character

at a time can write into a file.

Ex: char ch =‟a‟;

putc (ch, fp);

Example

file1.txt

fgetc() function

The fgetc() function returns/read a single character from the file. It gets a character from the

stream. It returns EOF at the end of file.

getc ( ): getting a character from the file, or reading the file information character by character at a
time, upto the end of the file by using this function.

Ex: char ch;

ch = getc (fp);

Example:

C Programming 109
myfile.txt

this is simple text message.

fputs()

The fputs() function writes a line of characters into file

Example:

myfile2.txt

hello c programming

fgets()

C Programming 110
The fgets() function reads a line of characters from file.

Example:

Output:

hello c programming

The getw and putw functions:


These are integer oriented functions. These are similar to above functions and are used to read and
write integer values. These are useful when we deal with only integer data. The general format is

putw ( ): putting or writing of an integer value to a file.

putw (integer , fp);

Ex: int x = 5;

putw(x,fp);

getw ( ): getting or reading integer value from a file.

Ex: int x;

x = getw (fp);

C Programming 111
File Positioning Functions
fseek()

The fseek() function is used to set the file pointer to the specified offset. It is used to write data

into file at desired location.

syntax:

fseek(FILE * stream, long int offset, int whence)

The first parameter stream is the pointer to the file. The second parameter is the position of the record
to be found, and the third parameter specifies the location where the offset starts.

Whence Meaning
SEKK_SET Starts the offset from the beginning of the file.
SEKK_END Starts the offset from the end of the file.
SEKK_CUR Starts the offset from the current location of the cursor in the file.

or

fseek(file pointer, offset, position);

• file pointer is a pointer to the concerned file.


• Offset is a number or variable of type long, it specifies the number of positions (bytes) to be
moved from the location specified. If offset is positive number, then moving forward or negative
meaning move backwards.
• Position is a n integer number and it specifies from which position the file pointer to be moved.
Position can take one of the following three values.
➢ 0 beginning of file
➢ 1 current position
➢ 2 end of file

Eg:

fseek (fp, 0L,0); - go to the beginning of the file. (Similar to rewind).

C Programming 112
fseek (fp, 0L,1); - Stay at current position (Rarely used)

fseek (fp, 0L,2); -go to the end of the file, past the last character of the file.

Example:

myfile.txt

This is sonoo Jaiswal

rewind() :This function places the file pointer to the beginning of the file, irrespective of where it is
present right now. It takes file pointer as an argument.

Syntax: rewind( fp);

Example:

File: file.txt

this is a simple text

Example:

C Programming 113
Output:
this is a simple textthis is a simple text As you can see, rewind() function moves the file pointer at
beginning of the file that is why "this is simple text" is printed 2 times. If you don't call rewind() function,
"this is simple text" will be printed only once.

ftell()

The ftell() function returns the current file position of the specified stream. We can use ftell()

function to get the total size of a file after moving file pointer at the end of file. We can use

SEEK_END constant to move the file pointer at the end of file.

syntax:

n = ftell(fp);

n would give the relative offset(in bytes).

Example:

C Programming 114
Output:
Size of file: 21 bytes

C Programming 115
INBUILT FUNCTIONS FOR FILE HANDLING IN C LANGUAGE:

Function Description
fopen() Creates a new file or opens an existing file.

fclose() Closes an opened file.

getw() Reads an integer from file.

putw() Writes an integer to file.

fgetc() Reads a character from file.


fputc() Writes a character to file.

gets() Reads a line from keyboard.

puts() Writes a line to the output screen.

fgets() Reads a string from a file, one line at a time.

fputs() Writes a string to a file.

feof() Checks for the end of file.

fgetchar() Reads a character from keyboard.

fprintf() Writes formatted data to a file.

fscanf() Reads formatted data from a file.

fputchar() Writes a character to the output screen from keyboard input.

fseek() Moves file pointer position to a given location.

SEEK_SET Moves file pointer position to the beginning of the file.

SEEK_CUR Moves file pointer position to a given location.

SEEK_END Moves file pointer position to the end of file.

ftell() Gives the current position of the file pointer.

rewind() Moves file pointer position to the beginning of the file.

getc() Reads a character from file.

getch() Reads a character from keyboard.

getche() Reads a character from keyboard and echoes to the output screen.

getchar() Reads a character from keyboard.

putc() Writes a character to file.

putchar() Writes a character to screen.

C Programming 116
printf() Writes formatted data to screen.

sprintf() Writes formatted output to a string.

scanf() Reads formatted data from keyboard.

sscanf() Reads formatted input from a string.

remove() Deletes a file.

fflush() Flushes a file.

C Programming 117
Common Errors in C Programming and How to Rectify Them

This section of the book covers common errors that occur while programming in C, with examples and
guidance on how to identify and fix them. Each error type is illustrated with multiple examples to help
beginners understand not only the error but also how to rectify it.

1. Syntax Errors
Syntax errors occur when the code violates the language's grammar rules. These errors are detected
by the compiler during the compilation phase. Examples include missing semicolons, unmatched
parentheses, and incorrect use of language constructs.

Examples:
1. Missing semicolon:
Incorrect:
```c
int x = 5 // Error: Missing semicolon
```
Correct:
```c
int x = 5;
```

2. Unmatched parentheses:
Incorrect:
```c
if (x > 5 {
printf("x is greater than 5");
}
```
Correct:
```c
if (x > 5) {
printf("x is greater than 5");
}
```

2. Semantic Errors
Semantic errors occur when the syntax is correct but the program's meaning or logic is wrong. These
errors can result in incorrect outputs, even though the program compiles and runs.

C Programming 118
Examples:
1. Uninitialized variables:
Incorrect:
```c
int x;
printf("%d", x); // Error: 'x' is used without initialization
```
Correct:
```c
int x = 0;
printf("%d", x);
```

2. Type mismatch:
Incorrect:
```c
int x = 5.5; // Warning or Error: Assigning a float to an integer
```
Correct:
```c
float x = 5.5;
```

3. Logical Errors
Logical errors occur when the program runs but produces incorrect results because the logic is flawed.
These errors are not caught by the compiler, and they require debugging to resolve.

Examples:
1. Incorrect operator use:
Incorrect:
```c
if (a = 5) { // Error: Assignment operator used instead of comparison operator
// Logic flaw
}
```
Correct:
```c
if (a == 5) { // Correct comparison operator
}
```

2. Infinite loop:
Incorrect:

C Programming 119
```c
while (i != 0) {
// Some code
} // Error: If 'i' is never modified, this becomes an infinite loop
```
Correct:
```c
while (i != 0) {
i--; // Modify the loop variable
}
```

4. Linker Errors
Linker errors occur during the linking stage of the compilation process. These errors usually arise due
to missing external dependencies or unresolved references.

Examples:
1. Undefined reference:
Incorrect:
```c
int main() {
foo(); // Error: Undefined reference to 'foo'
}
```
Correct:
```c
void foo() {
// Function definition
}
int main() {
foo();
}
```

2. Missing library linkage:


```bash
$ gcc program.c -o program // Error: Missing library
```
Correct:
```bash
$ gcc program.c -o program -lm // Correct: Link with the math library
```

C Programming 120
5. Runtime Errors
Runtime errors occur during program execution and are often caused by invalid memory access,
division by zero, or other issues that lead to program crashes or abnormal behavior.

Examples:
1. Division by zero:
Incorrect:
```c
int a = 5, b = 0;
int c = a / b; // Error: Division by zero
```
Correct:
```c
int a = 5, b = 1;
if (b != 0) {
int c = a / b;
}
```

2. Null pointer dereference:


Incorrect:
```c
int *ptr = NULL;
*ptr = 5; // Error: Dereferencing a null pointer
```
Correct:
```c
int *ptr = malloc(sizeof(int));
if (ptr != NULL) {
*ptr = 5;
}
```

6. Memory Errors
Memory errors occur due to improper handling of dynamically allocated memory. These errors can
lead to memory leaks, segmentation faults, and undefined behavior.

Examples:
1. Memory leak:
Incorrect:
```c
int *ptr = malloc(10 * sizeof(int)); // Error: Memory not freed
```

C Programming 121
Correct:
```c
int *ptr = malloc(10 * sizeof(int));
free(ptr); // Correct: Freeing memory
```

2. Double free:
Incorrect:
```c
int *ptr = malloc(10 * sizeof(int));
free(ptr);
free(ptr); // Error: Double free
```
Correct:
```c
int *ptr = malloc(10 * sizeof(int));
free(ptr); // Correct
```

7. Type Errors
Type errors occur when there is a mismatch between the expected and actual data types. These often
lead to warnings but can also result in errors.

Examples:
1. Implicit type conversion:
Incorrect:
```c
int x = 5.7; // Error: Assigning a float to an integer
```
Correct:
```c
float x = 5.7;
```

2. Incorrect format specifier:


Incorrect:
```c
int a = 5;
printf("%f", a); // Error: Wrong format specifier
```
Correct:
```c
int a = 5;

C Programming 122
printf("%d", a); // Correct format specifier
```

Conclusion
Understanding the common errors in C programming and knowing how to fix them is crucial for
beginners. With practice and attention to detail, these mistakes can be avoided, and debugging skills
will improve.

C Programming 123
C Programming 124

You might also like