c Textbook
c Textbook
• Introduction to Computers
Program Counter)
• Conditional Statements
• Loops 39 - 47
o Nested loops
• Control Statements 47 - 53
• Introduction to Arrays
Modification of Arrays
C Programming 1
o Traversal and Manipulation of Array Elements
• Types of Arrays 57 - 63
• Introduction to Strings 64 - 68
• Pointers
Pointer Arithmetic
with Pointers
o Structures
o Unions
• Introduction to Functions
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.
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.
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:
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.
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:
Modern Developments: Advances in artificial intelligence (AI), cloud computing, and quantum
computing continue to drive innovation in the computing field.
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.
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.
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.
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.
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.
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.
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.
• 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.
Flowcharts
Definition: A graphical representation of an algorithm.
Symbols:
Oval: Start/End
Rectangle: Process
Parallelogram: Input/Output
Diamond: Decision
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
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.
Example:
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.
• 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.
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.
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.
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.
Any change in the source program during the translation does not require retranslation of the
entire code.
The Interpreter works by line working of Code, that’s why Optimization is a little slower compared
to Compilers.
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:
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.
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.
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 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:
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.
data_type variable_name;
Example:
int count;
float temperature;
char initial;
Variable Initialization:
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.
Example:
#define PI 3.14159
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
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);
• %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:
Here is an example program that uses both input and output functions to create a simple calculator:
C Programming 20
C Programming 21
Operators, Type Conversion, and Casting:
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;
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) {
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
Example:
int a = 1, b = 0;
if (a && b) {
} else {
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 (>>)
C Programming 23
int c = a & b; // 0001 in binary, c = 1
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:
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.
Example:
int a = 10;
float b = 5.5;
Example:
int a = 10;
float b = 5.5;
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'
C Programming 27
In the above program:
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-
• 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-
• When stubs are located far from the top level module, choosing test cases and designing stubs
become more challenging.
Example:
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-
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 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
C Programming 30
Unit-II
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.
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){
}else{
Flow chart:
C Programming 33
Example Program:
Output:
i is greater than 15
Syntax:
if(condition){
if(condition){
else{
C Programming 34
}
else{
if(condition){
else{
Flow chart:
C Programming 35
Sample program:
Output:
i is smaller than 15
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.
Using Loops :
1.For Loops
2.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){
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
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
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;
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
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
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
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
----------------------------
. | .
. | .
. | .
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.
or
The C arrays are static in nature, i.e., they are allocated memory at the compile time.
int arr_int[5];
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.
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.
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.
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.
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.
array_name[i] = value i;
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];
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_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:
Multidimensional Arrays
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
Syntax of 2D Array in C
array_name[size1] [size2];
Here,
• 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
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:
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.
In this example:
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:
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.
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}
};
C Programming 59
Address Value
0x2000 1
0x2004 2
0x2008 3
0x200C 4
0x2010 5
0x2014 6
Example Program
Here is an example program demonstrating the memory layout and accessing elements:
Output:
C Programming 60
Base address of arr: 0x7ffee2c4b6a0
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.
data_type array_name[rows][columns];
int two_dimen[4][3];
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:
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.
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
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.
• By char array
• By string literal
• By using string pointer
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:
• 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.
C Programming 64
You can use functions like scanf, printf, gets, and puts to handle string input and output.
Using fgets :
C Programming 66
strcmp: Compares two strings.
C Programming 67
Array programs with integers
1.Initializing and Printing an Array
Strings:
1.String input, traversing, printing
2. Reverse a String
7. Copy a String
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.
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
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.
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.
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 the num is 10 and the memory location of the variable 'num' is displayed on the screen.
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 Programming 74
OUTPUT:
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
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.
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
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.
OUTPUT:
C Programming 78
OUTPUT:
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:
C Programming 79
OUTPUT:
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
OUTPUT:
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
C Programming 82
OUTPUT:
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
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.
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};
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.
C Programming 86
C Programming 87
OUTPUT:
How many Elements:4
Enter Elements one by one23
67
45
15
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:
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;
};
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.
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.
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.
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.
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.
• 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.
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.
• 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.
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 .
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
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 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
Note:
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
They take minimum effort to maintain, are easily readable, and provide least security and takes
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:
Declaration of a file
When working with files, you need to declare a pointer of type file. This declaration is needed
C Programming 104
Syntax
FILE *fp;
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.
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.
Example:
fprintf(fp1, “%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()
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)
C Programming 108
Unformatted File I/O Functions
fputc() function
putc ( ):- Putting a character in to the file. It works with only character data type. One character
Example
file1.txt
fgetc() function
The fgetc() function returns/read a single character from the file. It gets a character from the
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.
ch = getc (fp);
Example:
C Programming 109
myfile.txt
fputs()
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
Ex: int x = 5;
putw(x,fp);
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
syntax:
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
Eg:
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
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.
Example:
File: file.txt
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
syntax:
n = ftell(fp);
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.
getche() Reads a character from keyboard and echoes to the output screen.
C Programming 116
printf() Writes formatted data to screen.
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();
}
```
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;
}
```
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;
```
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