KEMBAR78
CS25C01 Computer Programming C | PDF | Computer Program | Programming
100% found this document useful (1 vote)
210 views98 pages

CS25C01 Computer Programming C

About Computer Programming C

Uploaded by

mohanapriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
210 views98 pages

CS25C01 Computer Programming C

About Computer Programming C

Uploaded by

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

CS25C01 Computer Programming: C

Introduction to C
1. PROBLEM SOLVING
1.1. Introduction to Problem Solving
Problem solving is the process of finding a solution to a given problem. In programming, it
involves:
1. Understanding the problem.
2. Breaking it into smaller steps.
3. Designing a logical solution.
4. Implementing it using a programming language (like C).
5. Testing and refining the solution.
Problem solving is not just coding—it’s thinking logically and systematically.
1.2. Steps in Problem Solving
The general steps are:
Step 1: Understanding the Problem
 Read and analyze the problem carefully.
 Identify inputs (what is given) and outputs (what needs to be produced).
 Determine any constraints or special conditions.
Example:
Problem: Find the sum of two numbers.
 Inputs: Two numbers (say a and b)
 Output: Their sum (a + b)
Step 2: Breaking the Problem into Steps (Algorithm Design)
 Create an algorithm: step-by-step instructions to solve the problem.
 Use pseudo-code if needed (plain English instructions before coding).
Algorithm Example: Sum of Two Numbers
1. Start
2. Read the first number a
3. Read the second number b
4. Calculate sum = a + b
5. Print sum
6. End
Step 3: Choosing the Right Data and Tools
 Identify variables and their types:
o Integer, Float, Character, etc.
 Decide which operators or functions will be needed.
Example:
 a and b → int
 sum → int
 Operator → +
Step 4: Implementation in C
 Translate the algorithm into C code.
#include <stdio.h>
int main() {
int a, b, sum;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
Explanation of Code:
 #include <stdio.h> → Includes standard input-output functions.
 int main() → Entry point of the program.
 scanf() → Reads input from user.
 printf() → Displays output.
 sum = a + b; → Performs the calculation.
Step 5: Testing and Debugging
 Check the program with different inputs.
 Correct any errors (syntax, logic, runtime).
Example:
Input: 5 and 10 → Output should be 15
Input: -3 and 7 → Output should be 4
1.3. Types of Problems In C
1. Simple Arithmetic Problems – sum, difference, multiplication.
2. Decision Making Problems – using if, else, switch.
3. Looping Problems – using for, while, do-while.
4. Array and String Problems – finding maximum, sorting, searching.
5. Function Problems – breaking code into reusable blocks.
Here’s a detailed explanation of the types of problems in C programming, along with examples
and subcategories for clarity:
A. Simple Arithmetic Problems
These are the most basic problems where you perform mathematical calculations using C
operators.
Key Focus: +, -, *, /, % operators, and basic input/output.
Examples:
 Sum of two numbers
 Average of numbers
 Area of a circle, rectangle, or triangle
 Conversion between units (e.g., Celsius to Fahrenheit)

Sample Code: Sum of Two Numbers


#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d\n", a + b);
return 0;
}
B. Decision-Making Problems
These problems require the program to make choices based on certain conditions.
Key Focus: if, if-else, nested if, switch-case.
Subtypes:
1. Single Condition: Check one condition.
o Example: Check if a number is positive.
2. Multiple Conditions: Nested or combined conditions.
o Example: Find the largest among three numbers.
3. Switch Cases: Handle multiple discrete values.
o Example: Display name of the day based on a number (1-7).

Sample Code: Largest of Three Numbers


#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if(a > b && a > c)
printf("Largest = %d\n", a);
else if(b > c)
printf("Largest = %d\n", b);
else
printf("Largest = %d\n", c);
return 0;
}

C. Looping Problems
These problems involve repetition of actions until a condition is met.
Key Focus: Loops – for, while, do-while.
Subtypes:
1. Fixed Iteration: Number of times is known.
o Example: Print first 10 natural numbers (for loop)
2. Conditional Iteration: Repeat until a condition is false.
o Example: Sum numbers until the user enters zero (while loop)
3. Do-While Loop: Execute at least once before checking the condition.
Sample Code: Print first 10 natural numbers
#include <stdio.h>
int main() {
for(int i=1; i<=10; i++)
printf("%d ", i);
return 0;
}
D. Array and String Problems
These involve storing multiple values and performing operations on collections of data.
Key Focus: Arrays, Strings, Indexing, Loops.
Subtypes:
1. Array Problems:
o Find sum/average of array elements
o Find largest/smallest element
o Sort an array (ascending/descending)
2. String Problems:
o Count characters, words, or vowels
o Reverse a string
o Compare two strings

Sample Code: Sum of Array Elements


#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
for(int i=0; i<n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Sum = %d\n", sum);
return 0;
}
E. Function Problems
These problems use functions to make code modular, reusable, and organized.
Key Focus: Function declaration, definition, calling, return type, parameters.
Subtypes:
1. Simple Function: Performs a single task.
o Example: Function to calculate factorial.
2. Function with Parameters: Input values passed to function.
o Example: Function to add two numbers.

3. Function Returning Value: Function returns a result to main program.


o Example: Function to check if a number is prime.

Sample Code: Function to Find Factorial


#include <stdio.h>
int factorial(int n) {
int fact = 1;
for(int i=1; i<=n; i++)
fact *= i;
return fact;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial = %d\n", factorial(num));
return 0;
}
F. Pointer Problems
Pointers are used for direct memory access and efficient handling of arrays, strings, and functions.
Key Focus: * (dereference), & (address-of), pointer arithmetic.
Examples:
 Access array elements using pointers
 Swap two numbers using pointers
 Dynamic memory allocation

G. File Handling Problems


These problems involve reading from or writing to files.
Key Focus: fopen, fclose, fprintf, fscanf, fread, fwrite.
Examples:
 Store student records in a file
 Read numbers from a file and find sum

H. Structure and Union Problems


Used for grouping different types of data together.
Key Focus: struct, union, typedef.
Examples:
 Store details of a student (name, roll number, marks)
 Manage employee records

I. Advanced C Problems
 Recursion: Functions calling themselves (factorial, Fibonacci series)
 Dynamic Memory Allocation: Using malloc, calloc, free
 Linked Lists, Stacks, Queues: Basic data structures in C
✅ Summary Table of Problem Types
Type Focus Examples
Arithmetic Calculations Sum, Average, Area
Decision Making Conditions Largest number, Grade
Looping Repetition Print series, Sum until zero
Array & String Collection & Manipulation Sum, Reverse, Sort
Function Modular Programming Factorial, Prime check
Pointer Memory Access Swap numbers, Array via pointer
File Handling File I/O Read/Write student records
Structure & Union Grouped Data Employee details
Advanced Data structures, Recursion Linked list, Fibonacci
Here's a clear mind map/flowchart structure for types of C problems and how they relate.
C Programming Problems

├─ 1. Simple/Basic Problems
│ ├─ Input/Output operations
│ ├─ Arithmetic calculations
│ └─ Variable manipulation

├─ 2. Conditional Problems
│ ├─ if / else statements
│ ├─ Nested if
│ ├─ switch-case
│ └─ Decision-making problems

├─ 3. Looping Problems
│ ├─ for loop problems
│ ├─ while loop problems
│ ├─ do-while loop problems
│ └─ Nested loops

├─ 4. Function-based Problems
│ ├─ Simple function calls
│ ├─ Recursive functions
│ └─ Parameter passing & return values

├─ 5. Array Problems
│ ├─ 1D arrays
│ ├─ 2D arrays / matrices
│ ├─ Searching (linear, binary)
│ └─ Sorting (bubble, selection, insertion)

├─ 6. String Problems
│ ├─ String manipulation
│ ├─ Palindrome / Anagram checks
│ ├─ Concatenation / Copy / Compare
│ └─ Pattern printing

├─ 7. Pointer Problems
│ ├─ Pointer arithmetic
│ ├─ Pointer to pointer
│ ├─ Dynamic memory allocation
│ └─ Array & function pointers

├─ 8. Structure & Union Problems
│ ├─ Structure declaration & usage
│ ├─ Nested structures
│ └─ Union manipulation

├─ 9. File Handling Problems
│ ├─ File read / write
│ ├─ Append / Modify file
│ └─ File error handling

└─ 10. Advanced/Complex Problems
├─ Data structures (stack, queue, linked list)
├─ Algorithm implementation
└─ Combined problems (arrays + functions + pointers)
1.4. Key Problem-Solving Concepts in C
Concept Description Example
Variables Storage for data int age = 20;
Data Types Type of data int, float, char
Operators Perform operations +, -, *, /
Conditional Statements Decision making if (a > b)
Loops Repetition of steps for(i=0;i<10;i++)
Functions Modular programming int sum(int x, int y)
1.5. Tips for Effective Problem Solving in C
1. Always understand the problem before coding.
2. Break large problems into smaller sub-problems.
3. Use pseudo-code or flowcharts for planning.
4. Test with multiple cases, including edge cases.
5. Keep your code simple and readable.
1.6. Example Problem: Finding the Largest of Three Numbers
Algorithm:
1. Start
2. Read a, b, c
3. If a > b and a > c → a is largest
4. Else if b > c → b is largest
5. Else c is largest
6. Print the largest number
7. End
C Code:
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if(a > b && a > c)
printf("Largest = %d\n", a);
else if(b > c)
printf("Largest = %d\n", b);
else
printf("Largest = %d\n", c);
return 0;
}
2. PROBLEM ANALYSIS CHART
A Problem Analysis Chart is a diagrammatic or tabular representation of a problem, showing its
inputs, processes, outputs, and constraints. It is used to break down a problem logically and
ensure nothing is missed during coding.
2.1. Purpose of a Problem Analysis Chart
 To understand the problem clearly before writing code.
 To identify inputs and outputs.
 To outline the processing steps logically.
 To help in designing algorithms and flowcharts.
 To reduce errors and improve problem-solving efficiency.
2.2. Components of a Problem Analysis Chart
Component Description Example
A concise description of what needs
Problem Statement Find the sum of two numbers
to be solved
Data required from the user or another
Inputs Two numbers a and b
source
Logical steps or calculations to
Processing / Steps Sum = a + b
transform input into output
Outputs Results produced by the program Display sum of two numbers
Constraints / Numbers can be negative or positive;
Any limits, rules, or special cases
Conditions output should handle integers
2.3. How to Construct a Problem Analysis Chart
1. Identify the Problem
o Clearly define what you are trying to solve.
2. List Inputs
o All required data, including type and range.
3. Determine Processing Steps
o Break the solution into sequential steps (algorithm).
4. Define Outputs
o Specify what results need to be displayed.
5. Check Constraints / Assumptions
o Any special rules or edge cases to consider.

2.4. Example: Sum of Two Numbers


Component Details
Problem Statement Calculate the sum of two numbers entered by the user
Inputs int a, b (from user)
Processing 1. Read numbers a and b 2. sum = a + b 3. Display sum
Outputs Display sum of a and b
Constraints Numbers can be negative or zero; only integers considered
2.5. Example: Largest of Three Numbers
Component Details
Problem
Find the largest number among three given numbers
Statement
Inputs int a, b, c
1. Read numbers a, b, c 2. Compare numbers using if-else 3. Determine largest 4.
Processing
Display the largest number
Outputs Largest of the three numbers
Constraints Numbers can be equal or negative; program should handle ties
2.6. Benefits of a Problem Analysis Chart
1. Clarity – Shows problem structure clearly.
2. Planning – Helps in designing algorithms and flowcharts.
3. Error Reduction – Early identification of missing inputs or steps.
4. Documentation – Serves as a reference for coding and testing.
5. Communication – Easy to explain problem solution to others.

2.7. Visual Representation (Optional)


Problem: Find sum of two numbers
INPUTS: a, b
PROCESSING:
1. Read a, b
2. sum = a + b
OUTPUT: Display sum
CONSTRAINTS: Only integers; negative values allowed
Or as a flow-like table:
Input Processing Steps Output
a, b sum = a + b sum

3. DEVELOPING AN ALGORITHM
An algorithm is a step-by-step procedure to solve a problem or perform a computation. It is a
blueprint before coding, helping programmers logically structure their solutions.
3.1. Definition of Algorithm
An algorithm is:
 A finite set of well-defined instructions.
 It solves a specific problem.
 It guarantees a correct result in finite steps.
Characteristics:
1. Finiteness – Must terminate after a finite number of steps.
2. Definiteness – Each step should be clear and unambiguous.
3. Input – Zero or more inputs can be provided.
4. Output – At least one output should result.
5. Effectiveness – Steps must be basic enough to be executed manually or by a machine.
3.2. Importance of Algorithm Development
 Helps in structured problem solving.
 Makes coding easier and more organized.
 Reduces errors and debugging time.
 Provides a clear plan for translating logic into a program.
 Can be tested independently of programming language.
3.3. Steps to Develop an Algorithm
Step 1: Understand the Problem
 Read the problem statement carefully.
 Identify:
o Input – Data provided to solve the problem.
o Output – Expected results.
o Constraints – Any limitations or rules.
Example: Problem: Find the largest of three numbers.
 Input: a, b, c
 Output: largest number
 Constraints: numbers can be equal or negative

Step 2: Break the Problem into Sub-Problems


 Divide the main problem into smaller, manageable tasks.
 Focus on logical sequence of operations.
Example:
1. Read three numbers: a, b, c
2. Compare a with b and c
3. Compare b with c if necessary
4. Determine and display the largest number

Step 3: Choose Data and Operations


 Decide variables and data types.
 Identify operators needed (arithmetic, logical, relational).
Example:
 Variables: int a, b, c, largest
 Operators: >, &&

Step 4: Write the Algorithm in Steps


 Use plain English or pseudo-code.
 Ensure sequence, conditions, and loops are clear.
 Avoid ambiguity.
Algorithm Example: Largest of Three Numbers
1. Start
2. Read numbers a, b, c
3. If a > b and a > c → largest = a
4. Else if b > c → largest = b
5. Else → largest = c
6. Print largest
7. End

Step 5: Test the Algorithm


 Use sample input and check if the output is correct.
 Modify the algorithm if it fails for any scenario.
Example:
 Input: 5, 10, 7 → Output: 10 ✅
 Input: -3, -7, -1 → Output: -1 ✅

Step 6: Convert Algorithm to Flowchart (Optional)


 Flowcharts provide a visual representation of the algorithm.
 Helps in better understanding and communication.
Basic Symbols:
 Oval → Start/End
 Parallelogram → Input/Output
 Rectangle → Processing
 Diamond → Decision

3.4. Example: Algorithm for Sum of N Numbers


Problem Statement: Find the sum of N numbers entered by the user.
Algorithm:
1. Start
2. Read integer n (number of elements)
3. Initialize sum = 0
4. For i = 1 to n:
o Read number num
o sum = sum + num
5. Print sum
6. End

3.5. Guidelines for Developing a Good Algorithm


1. Each step must be simple and clear.
2. Avoid unnecessary steps; keep it efficient.
3. Consider all possible inputs, including edge cases.
4. Use loops and conditions appropriately.
5. Ensure algorithm is language-independent.

3.6. Benefits of Developing an Algorithm


 Provides a clear plan before coding.
 Improves program efficiency.
 Facilitates debugging and testing.
 Makes collaboration easier, as algorithms are understandable by others.

4.FLOWCHART AND PSEUDOCODE


4.1 FLOWCHART
A flowchart is a graphical representation of an algorithm or process. It uses symbols and arrows
to depict the flow of steps in solving a problem.
4.1.1 Purpose of Flowchart
 Visualizes the logical sequence of a program.
 Helps in planning and designing algorithms.
 Makes problem solving easier to understand and communicate.
 Useful for debugging and identifying logical errors.
4.1.2 Basic Flowchart Symbols
Symbol Name Purpose
Oval / Ellipse Start/End Indicates the beginning or end of the program
Parallelogram Input/Output Represents data input or output
Rectangle Process Represents a computation or assignment
Diamond Decision Represents a decision point (Yes/No, True/False)
Arrow Flow Line Shows the direction of process flow
4.1.3 Example Flowchart
Problem: Find the sum of two numbers
Steps:
1. Start
2. Read a and b
3. sum = a + b
4. Print sum
5. End
Flowchart Representation:
[Start]
|
[Read a, b]
|
[sum = a + b]
|
[Print sum]
|
[End]
Decision Flowchart Example: Find the largest of two numbers
[Start]
|
[Read a, b]
|
[Is a > b?] ----No----> [Largest = b]
|Yes
[Largest = a]
|
[Print Largest]
|
[End]
4.2 PSEUDOCODE
Pseudocode is a plain-language description of the steps in an algorithm. It is not actual
programming code, but it resembles code and is easy to convert into any programming language.
4.2.1 Purpose of Pseudocode
 Helps in thinking logically before coding.
 Language-independent: can be understood by anyone.
 Makes writing programs easier.
 Serves as a bridge between algorithm and code.
4.2.2 Rules for Writing Pseudocode
1. Use simple, clear, and concise language.
2. Focus on steps rather than syntax.
3. Avoid using specific programming language constructs.
4. Use indentation to show hierarchy and loops.
5. Include input, processing, and output clearly.
4.2.3 Example Pseudocode
Problem: Find the sum of two numbers
Start
Read number A
Read number B
SUM = A + B
Print SUM
End

Problem: Find the largest of three numbers


Start
Read numbers A, B, C
If A > B and A > C then
LARGEST = A
Else if B > C then
LARGEST = B
Else
LARGEST = C
End If
Print LARGEST
End

Problem: Sum of N numbers


Start
Read N
SUM = 0
For I = 1 to N do
Read NUMBER
SUM = SUM + NUMBER
End For
Print SUM
End

4.3. Comparison: Flowchart vs Pseudocode


Feature Flowchart Pseudocode
Representation Graphical Textual
Purpose Visualize process flow Describe logical steps
Easy to Understand Yes Yes, but text-based
Easy to Modify Can be complex Simple to edit
Use Beginners, debugging Planning and coding
Best For Complex decisions with multiple paths Step-by-step sequential logic
4.4. Best Practices
 Keep flowcharts simple and clean, avoid crossing arrows.
 Use meaningful symbols and labels.
 Indent pseudocode properly to show loops and decisions.
 Use pseudocode for algorithm planning and flowcharts for visualizing logic.
 Test logic using sample inputs before coding.
4.5. Summary
 Algorithm → Pseudocode → Flowchart → Code is a standard problem-solving
approach.
 Pseudocode focuses on logic in text, flowchart focuses on logic visually.
 Both help in reducing errors, improving clarity, and making coding easier.
5. PROGRAM STRUCTURE IN C
A program structure refers to the organization and sequence of statements in a C program. A
well-structured program ensures clarity, readability, and correctness.
C programs generally follow a standard structure to make them understandable and executable by
the compiler.
5.1. Basic Components of a C Program
A typical C program consists of the following sections:
1. Preprocessor Directives
2. Global Declarations (Optional)
3. Function Definitions
4. Main Function (main())
5. Local Declarations and Statements
6. Comments (Optional, for readability)
5.2. Detailed Explanation of Components
5.2.1 Preprocessor Directives
 These lines start with # and are executed before compilation.
 Common directives:
o #include <stdio.h> → Include standard input/output library.
o #define → Define constants or macros.
Example:
#include <stdio.h>
#define PI 3.14
Purpose: Allows the program to access library functions and predefined constants.
5.2.2 Global Declarations (Optional)
 Variables declared outside all functions are called global variables.
 Accessible by all functions in the program.
Example:
int total; // Global variable
Note: Use global variables carefully to avoid conflicts.
5.2.3 Function Definitions
 A function is a block of code that performs a specific task.
 C programs have a main function, and may include user-defined functions.
Function Structure:
return_type function_name(parameters) {
// body of function
}
Example:
int add(int a, int b) {
return a + b;
}
5.2.4 Main Function
 Every C program must have a main() function, which is the entry point.
 The operating system executes statements starting from main().
Syntax:
int main() {
// program statements
return 0;
}
Explanation:
 int → Main function returns an integer value to OS.
 return 0; → Program executed successfully.
5.2.5 Local Declarations and Statements
 Variables declared inside functions are local variables.
 Accessible only within the function.
 Program statements include:
o Input/output statements (scanf, printf)
o Assignment statements
o Decision-making (if, switch)
o Loops (for, while)
o Function calls
Example:
int main() {
int a, b, sum; // local variables
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
5.2.6 Comments (Optional)
 Comments are used to explain code, ignored by compiler.
 Two types:
o Single-line comment: // This is a comment
o Multi-line comment: /* This is a comment */
Purpose: Improves readability and documentation.

5.3. Flow of a C Program


1. Preprocessor directives executed first.
2. Global variables initialized.
3. Program execution starts from main().
4. Statements in main() or called functions are executed sequentially.
5. Program terminates and returns control to the operating system.
Flow Diagram (Simplified):
[Preprocessor Directives]
|
[Global Declarations]
|
main()
|
[Local Declarations]
|
[Statements Execution]
|
return 0

5.4. Example of Complete C Program


#include <stdio.h> // Preprocessor directive
// Global variable
int count = 0;
// Function definition
int add(int x, int y) {
return x + y;
}
int main() {
// Local variables
int a, b, sum;
// Input
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
// Processing using function
sum = add(a, b);
// Output
printf("Sum = %d\n", sum);
return 0; // End of program
}

5.5. Rules for Writing a C Program


1. Every C program must have a main() function.
2. Statements must end with a semicolon (;).
3. Preprocessor directives do not end with a semicolon.
4. Use curly braces {} to group statements.
5. Variable names must follow naming rules: letters, digits, underscore; cannot start with a
digit.
6. Comments can improve readability.
5.6. Summary of Program Structure
Component Purpose
Preprocessor Directives Include libraries and macros
Global Declarations Variables accessible throughout program
Functions Modular blocks performing specific tasks
Main Function Entry point; program execution starts here
Local Declarations Variables for use within a function
Statements Instructions: input, output, calculations, loops, decisions
Comments Explain code, improve readability

6. COMPILATION & EXECUTION PROCESS


6.1. Introduction
When you write a C program, it is written in high-level language which cannot be directly
executed by a computer. It needs to be translated into machine language.
The process of transforming a C program into an executable form is called Compilation and
Execution.
6.2. Steps in Compilation & Execution
The process can be divided into four main steps:
1. Preprocessing
2. Compilation
3. Assembly
4. Linking
5. Execution
6.2.1 Preprocessing
 Preprocessing is the first step performed by the preprocessor.
 It handles preprocessor directives like #include, #define, #ifdef, etc.
 It prepares the source code for compilation.
Tasks Performed:
1. Include header files (#include <stdio.h>)
2. Replace constants or macros (#define PI 3.14)
3. Conditional compilation (#ifdef, #ifndef)
Output: Preprocessed code file (usually with extension .i)
6.2.2 Compilation
 The compiler translates the preprocessed code into assembly or intermediate code.
 It checks for syntax errors during this stage.
Tasks Performed:
1. Syntax analysis
2. Semantic checks
3. Conversion into assembly/machine-like code
Output: Object file (usually with .obj or .o extension)
Note: If there are syntax errors, compilation fails, and errors are reported.
6.2.3 Assembly
 The assembler converts assembly code into machine code (binary code).
 Machine code is CPU-readable instructions.
Output: Object code (binary instructions)
6.2.4 Linking
 The linker combines object files and library files into a single executable.
 It resolves references to functions and variables used in the program.
Output: Executable file (.exe in Windows, no extension in Linux)
Example: Linking with standard library printf() from stdio.h
6.2.5 Execution (Running the Program)
 The CPU loads the executable file into memory.
 The program starts execution from the main() function.
 The program performs input, processing, and output as per the instructions.
Output: The final result of the program displayed to the user.
6.3. Flow of Compilation and Execution
Source Code (program.c)
|
Preprocessor
Preprocessed Code (.i)
|
Compiler
Assembly Code
Assembler
Object Code (.o/.obj)
|
Linker
Executable Program (.exe)
|
Execution
Output on Screen
6.4. Example
C Program: Sum of Two Numbers
#include <stdio.h>
int main() {
int a, b, sum;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
Steps During Compilation & Execution:
Step What Happens
Preprocessing #include <stdio.h> replaced with actual library code
Compilation Syntax checked, converted to assembly
Assembly Converted to machine code (.o/.obj)
Linking Links printf, scanf from standard library to create .exe
Execution CPU runs program, user inputs numbers, output displayed
6.5. Errors During Compilation & Execution
Error Type Stage Description
Syntax Error Compilation Incorrect use of language rules
Semantic Error Compilation Meaning of statement is invalid
Linker Error Linking Missing functions or libraries
Runtime Error Execution Errors like division by zero, memory issues
Logical Error Execution Program runs but gives wrong output
6.6. Summary
1. Preprocessing: Handles #include and macros.
2. Compilation: Converts code to assembly, checks syntax.
3. Assembly: Converts assembly to machine code.
4. Linking: Combines object code and libraries to executable.
5. Execution: Runs program, produces output.
Flow: Source Code → Preprocessor → Compiler → Assembler → Linker → Executable → Output

7. INTERACTIVE AND SCRIPT MODE IN C


7.1. Introduction
When running programs, there are generally two modes of execution:
1. Interactive Mode – Programs are executed line by line, taking input and giving output
immediately.
2. Script Mode (Batch Mode) – The entire program is written and saved in a file, then
compiled and executed as a whole.
Both modes are used in different scenarios depending on the type of task.
7.2. Interactive Mode
7.2.1 Definition
 In interactive mode, the programmer can type commands or statements one by one.
 The interpreter/compiler executes each statement immediately and returns the result.
Purpose:
 Useful for testing small code snippets.
 Helps beginners learn syntax and logic quickly.
 Good for debugging single statements or expressions.

7.2.2 Features
1. Commands executed immediately.
2. No need to save the program in a file.
3. Mostly used in interpreted languages, but some C compilers offer interactive shells.
4. Errors can be detected instantly.
7.2.3 Example
Imagine a C interactive shell (like an online C interpreter):
> int a = 5;
> int b = 10;
> int sum = a + b;
> printf("%d\n", sum);
15
 Each line is executed as soon as it is entered.
 Immediate feedback makes it easy to experiment with code.

7.3. Script Mode (Batch Mode)


7.3.1 Definition
 In script mode, the entire program is written in a source file (like program.c).
 The file is then compiled and executed as a whole.
Purpose:
 Used for larger programs that require multiple statements and functions.
 Suitable for production-level programming.

7.3.2 Features
1. Entire program is stored in a file.
2. Requires compilation before execution.
3. Output is generated only after executing the complete program.
4. Easier to maintain and reuse programs.

7.3.3 Example
program.c
#include <stdio.h>
int main() {
int a, b, sum;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
Execution Steps (Script Mode):
1. Save the program as program.c.
2. Compile: gcc program.c -o program
3. Run: ./program
4. Output appears after program executes.
7.4. Comparison: Interactive Mode vs Script Mode
Feature Interactive Mode Script Mode
Execution Line by line Whole program at once
Saving Not necessary Must be saved in file
Best For Learning, testing small code Full applications, reusable programs
Error Detection Immediate After compilation
Complexity Simple Can handle complex programs
Feedback Instant After execution
7.5. Advantages & Disadvantages
Interactive Mode
 Advantages: Quick testing, easy debugging, instant results.
 Disadvantages: Not suitable for large programs, cannot save code permanently.
Script Mode
 Advantages: Can handle large programs, reusable, maintainable, suitable for real-world
projects.
 Disadvantages: Requires compilation, feedback is not immediate.

7.6. Summary
 Interactive Mode: Immediate execution, best for learning and testing small code snippets.
 Script Mode: Full program execution after compilation, best for complete applications.
 Usage: Beginners often start with interactive mode, while professional programs are
developed in script mode.
8. COMMENTS
8.1 Definition
 Comments are non-executable statements used to explain code.
 They help programmers understand the code when revisiting it later.
 Ignored by the compiler, so they do not affect program execution.
8.2 Types of Comments
1. Single-line Comment:
o Syntax: // comment
o Used for brief explanations or notes.
o Example:
int a = 5; // variable a stores the value 5
2. Multi-line Comment:
o Syntax: /* comment */
o Can span multiple lines.
o Example:
/*
This program calculates the sum
of two numbers entered by the user
*/
8.3 Importance of Comments
 Improve readability of code.
 Help in documentation.
 Make team collaboration easier.
 Useful for debugging by temporarily disabling code.
9. INDENTATION IN C
9.1 Definition
 Indentation is adding spaces or tabs at the beginning of a line to show hierarchy or
structure in code.
 Though C compiler does not require indentation, it improves readability and
maintainability.
9.2 Rules for Proper Indentation
1. Indent code inside braces {}.
2. Align if, else, for, while blocks consistently.
3. Use 4 spaces or 1 tab per level (standard practice).
9.3 Example
#include <stdio.h>
int main() {
int a = 5, b = 10, sum;
// Calculate sum
sum = a + b;
if(sum > 0) {
printf("Sum is positive\n");
} else {
printf("Sum is non-positive\n");
}
return 0;
}
 Indentation makes blocks of code clear and logical flow easier to follow.
10. ERROR MESSAGES
10.1 Definition
 Errors are problems in the code that prevent it from executing correctly.
 The compiler generates error messages to help locate and fix mistakes.
10.2 Types of Errors
Type Description Example
Syntax Error Mistakes in C language rules Missing semicolon: int a = 5 (should be int a = 5;)
Semantic Using undeclared variable: sum = a + b; (a or b not
Incorrect meaning of code
Error declared)
Runtime Occurs during program
Division by zero: x/0
Error execution
Program runs but gives wrong
Logical Error Using a-b instead of a+b
output
10.3 How to Handle Errors
1. Read the error message carefully.
2. Check the line number indicated.
3. Correct the syntax or logic.
4. Recompile and test until the program runs correctly.
Example:
#include <stdio.h>
int main() {
int a, b, sum
sum = a + b;
printf("%d", sum);
return 0;
}
 Compiler Error: expected ';' before 'sum' → Missing semicolon after int a, b, sum.

11. BEST PRACTICES


 Always use comments for complex logic.
 Indent code properly to show hierarchy.
 Pay attention to compiler messages; they help identify errors.
 Debug logically: syntax → runtime → logical errors.
Summary
Topic Purpose
Comments Explain code, improve readability, document programs
Indentation Show code structure, make it readable, maintainable
Error Messages Identify mistakes, guide debugging, ensure correct execution
12. PRIMITIVE DATA TYPES
12.1 Definition
 Primitive data types are basic types of data that a C program can use to store values.
 They are built-in types and form the foundation of all variables.
12.2 Common Primitive Data Types in C
Data Type Size (typical) Range Description Example
Int 2 or 4 bytes -32,768 to 32,767 (16-bit) Stores integers int age = 25;
Float 4 bytes ±3.4e-38 Stores decimal numbers float pi = 3.14;
Stores double precision
double 8 bytes ±1.7e+308 double g = 9.81;
decimal
Char 1 byte -128 to 127 Stores a single character char grade = 'A';
Void 0 N/A Represents no value / empty void main()
Note: Size and range can vary depending on compiler and system architecture.
13. CONSTANTS
13.1 Definition
 Constants are fixed values that cannot be changed during program execution.
13.2 Types of Constants
1. Literal Constants – Directly written in code.
o Example: 100, 3.14, 'A'
2. Defined Constants – Using #define preprocessor directive.
o Example:
3. #define PI 3.14159
4. const Keyword – Declare variables whose value cannot change.
o Example:
5. const int DAYS = 7;
Importance:
 Prevent accidental modification of values
 Improves program clarity

14. VARIABLES
14.1 Definition
 Variables are named memory locations used to store data that can change during
program execution.
14.2 Rules for Naming Variables
1. Names must start with a letter or underscore (_).
2. Can contain letters, digits, or underscores.
3. Case-sensitive (a ≠ A).
4. Cannot be reserved keywords.
Examples:
int age; // valid
float salary; // valid
int 1stNum; // invalid
14.3 Variable Declaration & Initialization
 Declaration: Allocate memory and define type
int age;
float salary;
 Initialization: Assign initial value
int age = 25;
float salary = 5000.50;
15. RESERVED WORDS (KEYWORDS)
15.1 Definition
 Reserved words are predefined words in C with special meaning.
 They cannot be used as variable names.
15.2 Examples of Reserved Words
int, float, double, char, void, if, else, for, while, do,
switch, case, break, continue, return, const, sizeof, typedef
Purpose
 Define data types (int, float)
 Control program flow (if, for, while)
 Manage functions (return, void)
Summary Table
Concept Definition Example
Primitive Data Type Basic built-in data type to store values int a = 10;
Constant Fixed value that cannot change const int DAYS = 7;
Variable Named memory location for storing data float salary = 5000.50;
Reserved Word Predefined word in C with special meaning if, return, int
Example Program Using All Concepts
#include <stdio.h>
#define PI 3.14159 // Constant using #define
int main() {
int radius; // Variable declaration
const int MAX = 100; // Constant using const keyword
float area; // Variable declaration
printf("Enter radius: ");
scanf("%d", &radius);
area = PI * radius * radius; // Using constant PI
printf("Area of circle = %.2f\n", area);
return 0; // Reserved word
}
Explanation:
 int radius → variable to store radius
 const int MAX → constant that cannot be changed
 #define PI → constant value for PI
 return → reserved word to exit main function

16. ARITHMETIC OPERATORS


16.1 Definition
 Arithmetic operators are used to perform basic mathematical operations on numerical data.
16.2 List of Arithmetic Operators
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a % b
++ Increment by 1 a++ or ++a
-- Decrement by 1 a-- or --a
16.3 Example
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b);
a++;
printf("a++ = %d\n", a);
return 0;
}
17. RELATIONAL OPERATORS
17.1 Definition
 Relational operators compare two values and return 1 (true) or 0 (false).
17.2 List of Relational Operators
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
17.3 Example
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("a == b: %d\n", a == b); // 0
printf("a != b: %d\n", a != b); // 1
printf("a > b: %d\n", a > b); // 0
printf("a <= b: %d\n", a <= b); // 1
return 0;
}
18. LOGICAL OPERATORS
18.1 Definition
 Logical operators are used to combine conditional expressions and return true (1) or false
(0).
18.2 List of Logical Operators
Operator Description Example
&& Logical AND (a > 0 && b > 0)
` `
! Logical NOT !(a > 0)
18.3 Example

#include <stdio.h>
int main() {
int a = 5, b = 0;
printf("a > 0 && b > 0: %d\n", a > 0 && b > 0); // 0
printf("a > 0 || b > 0: %d\n", a > 0 || b > 0); // 1
printf("!(a > 0): %d\n", !(a > 0)); // 0
return 0;
}

19. BITWISE OPERATORS


19.1 Definition
 Bitwise operators perform operations on individual bits of integers.
 Useful for low-level programming, encryption, and optimization.
19.2 List of Bitwise Operators
Operator Description Example Result (a=5, b=3)
& AND a&b 1 (0101 & 0011 = 0001)
` ` OR `a
^ XOR a^b 6 (0101 ^ 0011 = 0110)
~ Complement ~a -6 (~0101 = 1010)
<< Left shift a << 1 10 (0101 << 1 = 1010)
>> Right shift a >> 1 2 (0101 >> 1 = 0010)
19.3 Example
#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("a << 1 = %d\n", a << 1);
printf("a >> 1 = %d\n", a >> 1);
return 0;
}
SUMMARY TABLE OF OPERATORS
Category Operators Purpose Example
Arithmetic + - * / % ++ -- Perform mathematical operations a + b
Relational == != ><>= <= Compare values, returns 1 or 0 a>b
Logical `&& !`
Category Operators Purpose Example
Bitwise `& ^ ~ <<>>` Operate on individual bits
Key Notes
 Arithmetic operators → work on numbers.
 Relational operators → used in decision making.
 Logical operators → combine multiple conditions.
 Bitwise operators → manipulate data at the bit level.
 Operator precedence matters; use parentheses () to avoid confusion.
20. INPUT/OUTPUT (I/O) FUNCTIONS IN C
20.1 Definition
 I/O functions allow a program to receive input from the user and display output to the
screen.
 In C, I/O functions are provided in the stdio.h library.
20.2 Input Functions
20.2.1 scanf()
Used to read input from the user.
 Syntax:
scanf("format_specifier", &variable);
Format Specifiers:
Data Type Specifier
Int %d
Float %f
double %lf
Char %c
string %s
Example:
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("Your age is %d\n", age);
return 0;
}
Notes:
 Use & before variable name to provide address for storing input.
 Can read multiple inputs:
int a, b;
scanf("%d %d", &a, &b);
20.3 Output Functions
20.3.1 printf()
 Used to display output on the screen.
 Syntax:
printf("format_specifier", variable);
Example:
#include <stdio.h>
int main() {
int a = 5;
float pi = 3.14;
printf("Value of a = %d\n", a);
printf("Value of pi = %.2f\n", pi);
return 0;
}
Notes:
 \n → newline character.
 %d → integer, %f → float, %c → character, %s → string.

20.4 Other Common I/O Functions


Function Purpose
getchar() Reads a single character from input
putchar() Prints a single character
gets()* Reads a string (deprecated, unsafe)
puts() Prints a string followed by newline
Example:
char ch;
ch = getchar(); // read character
putchar(ch); // print character
21. BUILT-IN FUNCTIONS IN C
21.1 Definition
 Built-in functions are predefined functions provided by C libraries to perform common
tasks.
 They save time and simplify programming.
21.2 Categories of Built-in Functions
Category Header File Example Functions
Math Functions math.h sqrt(), pow(), sin(), cos(), abs()
String Functions string.h strlen(), strcpy(), strcat(), strcmp()
Character Functions ctype.h isdigit(), isalpha(), toupper(), tolower()
Other Utility Functions stdlib.h rand(), exit(), malloc(), free()
Time Functions time.h time(), clock()
21.3 Example of Built-in Functions
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
// Math function
double num = 16.0;
printf("Square root of %.2f = %.2f\n", num, sqrt(num));
// String function
char str1[20] = "Hello";
char str2[20] = "World";
strcat(str1, str2); // concatenate
printf("Concatenated string: %s\n", str1);
return 0;
}
Explanation:
 sqrt() → calculates square root
 strcat() → concatenates two strings
Summary Table
Concept Function/Example Purpose
Input scanf(), getchar(), gets() Read data from user
Output printf(), putchar(), puts() Display data on screen
Math sqrt(), pow(), abs() Perform mathematical operations
String strlen(), strcpy(), strcmp() Perform string manipulation
Character isdigit(), toupper() Check or convert characters
Utility rand(), exit(), malloc() Miscellaneous tasks
Notes & Best Practices
1. Always include the correct header file for built-in functions.
2. Use scanf() carefully; provide correct format specifier.
3. Avoid using gets(); use fgets() instead.
4. Use built-in functions instead of writing your own for efficiency and reliability.
CONTROL STRUCTURES
1. if Control Structure in C:
1.1. Introduction to Control Structures
 Control structures control the flow of program execution based on conditions.
 They allow a program to make decisions and execute specific code blocks.
 Common control structures in C:
o Decision-making:if, if-else, nested if, switch
o Loops:for, while, do-while
o Jump statements:break, continue, goto, return

1.2. The if Statement


1.2.1 Definition
 The if statement is a decision-making control structure in C.
 It evaluates a condition (expression) and executes a block of code only if the
condition is true.
 If the condition is false, the block is skipped.
 It is the simplest form of decision-making in programming.
1.2.2 Syntax
if (condition) {
// statements to execute if condition is true
}
 condition → an expression that evaluates to true (non-zero) or false (zero).
 If the condition is true, the statements inside {} are executed.
 If the condition is false, the statements are skipped.

1.3. Flow of Execution


1. Condition evaluation: The expression is evaluated.
2. Decision making:
o True → Execute the block inside if.
o False → Skip the block or go to else/else if.
3. Program flow continues after the block.
Flow Diagram:
┌──────────────┐
│ Evaluate │
│ condition │
└───────┬──────┘

True ┌───┴───┐ False
│ │
Execute statements │ Skip block

Continue
1.4. Example 1 of Simple if
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0) {
printf("The number is positive.\n");
}
printf("End of program.\n");
return 0;
}
Explanation:
 If user enters 5 → Output: "The number is positive."
 If user enters -3 → Output: (skips if block) → "End of program."
Example 2
#include <stdio.h>
int main() {
int age;
printf("Enter age: ");
scanf("%d", &age);
if (age >= 18)
printf("Eligible to vote\n");
printf("End of program\n");
return 0;
}
 If age = 20 → Output: Eligible to vote
 If age = 15 → Output: End of program
2. if-else Statement
2.1 Definition used when there are two possible actions.
 Executes one block if true, another block if false.
2.2 Syntax
if (condition) {
// statements if condition is true
} else {
// statements if condition is false
}
2.3 Example 1
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num % 2 == 0) {
printf("Even number.\n");
} else {
printf("Odd number.\n");
}

return 0;
}

Example 2
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0)
printf("Positive\n");
else if (num < 0)
printf("Negative\n");
else
printf("Zero\n");
return 0;
}
3. Nested if Statement
3.1 Definition
 if statements can be nested inside another if to check multiple conditions.
3.2 Syntax
if (condition1) {
if (condition2) {
// statements
}
}
3.3 Example 1
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num > 0) {
if (num % 2 == 0) {
printf("Positive even number.\n");
} else {
printf("Positive odd number.\n");
}
} else {
printf("Number is not positive.\n");
}

return 0;
}

Example 2
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if (marks >= 0 && marks <= 100) {
if (marks >= 90)
printf("Grade A\n");
else if (marks >= 75)
printf("Grade B\n");
else
printf("Grade C\n");
} else {
printf("Invalid marks\n");
}
return 0;
}
3.4. Key Points
1. Condition must evaluate to true (non-zero) or false (zero).
2. Braces {} are optional if only one statement is inside the if.
3. if (num > 0)
4. printf("Positive\n"); // valid
5. Use nested if for multiple levels of decision-making.
6. Combine if with else if to check multiple conditions.
3.5. Best Practices
1. Always use braces {} even for single statements (prevents logical errors).
2. Ensure conditions are mutually exclusive when using else if.
3. Avoid deep nesting; consider using logical operators (&&, ||) to combine conditions.
4. Use clear indentation for readability.
5. Check for boundary conditions (like 0 or negative values).
3.6. Common Mistakes
Mistake Example Correct Approach
Add ; only after statement, not after if
Forgetting semicolon if(a>0) printf("Positive")
condition
Misusing = instead of
if(a=5) Use if(a==5)
==
Missing braces in nested Only first line executed
Use {} to group multiple statements
if unexpectedly

3.7. Summary Table


Feature Syntax Description
Simple if if(condition){...} Executes block if condition true
if-else if(condition){...} else {...} Executes one of two blocks
Nested if if(cond1){ if(cond2){...} } Checks multiple conditions
Single Statement if(condition) statement; {} optional for one statement

4. Switch-case Control Structure in C:


4.1. Introduction
 The switch-case statement is a decision-making control structure, similar to if-else.
 It is used when a variable needs to be compared with multiple constant values.
 More readable than multiple if-else if statements for discrete values.
4.2. Syntax
switch (expression) {
case constant1:
// statements executed if expression == constant1
break;
case constant2:
// statements executed if expression == constant2
break;
...
default:
// statements executed if expression doesn't match any case
}
4.3. Components of switch-case
Component Description
switch(expression) Evaluates the expression once; its value is compared with each case
case constant: Executes this block if expression matches the constant
break; Terminates the switch block; prevents fall-through to the next case
default: Executes if none of the cases match; optional
4.4. How It Works (Flow)
1. Evaluate the expression inside switch().
2. Compare it with each case value in order.
3. Execute statements in the matching case.
4. If a break is encountered, exit the switch.
5. If no case matches, execute default (if present).
Flow Diagram:
┌─────────────────┐
│ Evaluate expression │
└────────┬────────┘
Match?│
┌─────┴─────┐
Case1 → Yes → execute → break → exit

Case2 → Yes → execute → break → exit

...
No match → default (if exists) → execute → exit

4.5. Example of switch-case


#include <stdio.h>

int main() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);

switch(day) {
case 1:
printf("Sunday\n");
break;
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid day\n");
}

return 0;
}
Explanation:
 User enters 3 → Output: "Tuesday"
 If user enters 9 → Output: "Invalid day"
4.6. Important Points
1. Expression in switch(expression) must be of integer or character type.
2. Case values must be constants; cannot be variables or expressions.
3. Break statement is important to prevent fall-through.
4. default: is optional but recommended.
5. Multiple cases can execute the same block:
case 1:
case 2:
case 3:
printf("First three days\n");
break;

4.7. Advantages of switch-case


 More readable than multiple if-else if for discrete constant values.
 Reduces nested conditions.
 Easier to modify and maintain.

4.8. Common Mistakes


Mistake Explanation Correct Approach
Missing break; Causes fall-through to next case Always use break unless intentional
Using variable in case Case must be constant case 5: not case x:
Forgetting default No action if expression doesn't match Use default to handle unexpected input

4.9. Summary Table


Feature switch-case
Decision type Multi-way selection
Expression type Integer, char, or enum
Case values Must be constants
Default Optional, executes if no case matches
Break Prevents fall-through

5. while loop in C:
5.1. Introduction to Loops
 Loops allow repeated execution of a block of code until a condition is met.
 Types of loops in C:
1. while loop (entry-controlled)
2. do-while loop (exit-controlled)
3. for loop (counter-controlled)
The while loop is used when the number of iterations is not known in advance, and repetition
depends on a condition.

5.2. Syntax of while Loop


while (condition) {
// statements to be executed repeatedly
}
 condition: Boolean expression; loop continues while it is true (non-zero).
 statements: Executed repeatedly until the condition becomes false (0).

5.3. Flow of while Loop


1. Evaluate the condition.
2. If true, execute the statements inside the loop.
3. After executing, return to step 1.
4. If false, exit the loop and continue with the rest of the program.
Flow Diagram:
┌─────────────┐
│ Evaluate │
│ Condition │
└───────┬─────┘
True │ False
┌──────┴───────┐
│ Execute loop │
└──────┬───────┘
Back to condition

5.4. Example of while Loop


Example 1: Print numbers 1 to 5
#include <stdio.h>

int main() {
int i = 1; // initialization
while (i <= 5) { // condition
printf("%d\n", i);
i++; // increment to avoid infinite loop
}
return 0;
}
Output:
1
2
3
4
5

5.5. Key Points


1. Entry-controlled loop → Condition is checked before executing the loop body.
2. If the condition is false initially, the loop body may never execute.
3. Always ensure increment/decrement or some mechanism changes the condition, otherwise
infinite loop occurs.

5.6. Example: Sum of Numbers Using while


#include <stdio.h>

int main() {
int n, sum = 0, i = 1;
printf("Enter a positive number: ");
scanf("%d", &n);

while (i <= n) {
sum += i; // sum = sum + i
i++;
}

printf("Sum of 1 to %d = %d\n", n, sum);


return 0;
}
Explanation:
 User enters 5 → Output: Sum of 1 to 5 = 15
 Loop adds numbers from 1 to n.

5.7. Common Mistakes


Mistake Explanation Solution
Infinite loop Condition never becomes false Update variable inside loop
Condition always false Loop body never executes Check initialization and condition
Forgetting increment/decrement Loop runs forever Ensure loop variable changes
5.8. Best Practices
1. Initialize loop variables before the loop.
2. Update variables inside the loop to eventually break the loop.
3. Keep loop body minimal for readability.
4. Use break carefully if you want to exit the loop early.

5.9. Summary Table


Feature Description
Type Entry-controlled loop
Syntax while(condition) { statements; }
Execution Condition checked first; if true → execute, repeat; if false → exit
Infinite loop risk Yes, if condition never becomes false
Use When number of iterations is unknown

6. do-while loop in C:
6.1. Introduction to do-while Loop
 The do-while loop is an entry-exit-controlled loop in C.
 It is similar to the while loop but with one key difference: the loop body executes at least
once, even if the condition is false.
 Used when you want the loop to run at least once before checking the condition.

6.2. Syntax
do {
// statements to execute
} while (condition);
 statements: Executed repeatedly.
 condition: Boolean expression; loop continues while true (non-zero).
 Semicolon ; after while is mandatory.

6.3. Flow of do-while Loop


1. Execute the statements inside the loop.
2. Evaluate the condition.
3. If condition is true, repeat step 1.
4. If condition is false, exit the loop.
Flow Diagram:
┌──────────────┐
│ Execute loop │
└──────┬───────┘

┌──────┴───────┐
│ Evaluate cond│
└──────┬───────┘
True │ False
┌────┴─────┐
Repeat loop│ Exit

6.4. Example of do-while Loop


Example 1: Print numbers 1 to 5
#include <stdio.h>

int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);

return 0;
}
Output:
1
2
3
4
5
Note: Even if i started at 10, the loop executes once, then checks the condition.

6.5. Example: Sum of Numbers Using do-while


#include <stdio.h>

int main() {
int n, sum = 0, i = 1;
printf("Enter a positive number: ");
scanf("%d", &n);

do {
sum += i;
i++;
} while (i <= n);
printf("Sum of 1 to %d = %d\n", n, sum);
return 0;
}
 User enters 5 → Output: Sum of 1 to 5 = 15
 Ensures that the loop executes at least once, even if n <= 0.

6.6. Key Differences Between while and do-while


Feature while do-while
Loop Type Entry-controlled Exit-controlled
Condition Check Before executing loop body After executing loop body
Minimum Execution May execute 0 times Executes at least 1 time
Semicolon Not needed after while block Required after while(condition);
Use Case When execution depends on condition When at least one execution is needed

6.7. Common Mistakes


Mistake Explanation Solution
do { ... } while(condition)
Forgetting semicolon Add semicolon after while
requires ;
Infinite loop Condition never becomes false Ensure loop variable changes
Misplaced Causes wrong number of Place increment/decrement correctly
increment/decrement iterations inside loop

6.8. Best Practices


1. Use do-while for menu-driven programs or user input validation, where code must run at
least once.
2. Keep the loop body minimal and readable.
3. Always update variables that affect the condition to avoid infinite loops.

6.9. Example: Menu-Driven Program Using do-while


#include <stdio.h>

int main() {
int choice;
do {
printf("\nMenu:\n1. Add\n2. Subtract\n3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1: printf("Add selected\n"); break;
case 2: printf("Subtract selected\n"); break;
case 3: printf("Exiting...\n"); break;
default: printf("Invalid choice\n");
}
} while(choice != 3);

return 0;
}
Explanation:
 The menu appears at least once, and repeats until the user chooses 3.

6.10. Summary Table: while vs do-while


Feature while do-while
Entry/Exit Entry-controlled Exit-controlled
Condition Check Before loop body After loop body
Minimum Execution 0 1
Semicolon Optional Mandatory
Common Use Unknown iterations Menu/input validation

7. for loop in C:
7.1. Introduction to for Loop
 The for loop is a counter-controlled loop in C.
 It is mainly used when the number of iterations is known beforehand.
 Combines initialization, condition check, and increment/decrement in a single line.
7.2. Syntax of for Loop
for (initialization; condition; increment/decrement) {
// statements to execute repeatedly
}
Components
Component Description
initialization Sets the starting value of the loop control variable
condition Checked before each iteration; loop executes while true
increment/decrement Updates the loop control variable after each iteration
statements Code block executed repeatedly

7.3. Flow of Execution


1. Initialization: Executed once at the beginning.
2. Condition check: If true → execute loop body. If false → exit loop.
3. Execute statements inside the loop.
4. Increment/decrement the control variable.
5. Repeat from step 2 until condition is false.
Flow Diagram:
Initialization → Condition?
True ──> Execute loop → Increment → Condition?
False ─> Exit loop

7.4. Example of for Loop


Example 1: Print numbers 1 to 5
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
4
5
7.5. Example: Sum of First N Numbers
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter a positive number: ");
scanf("%d", &n);

for (int i = 1; i <= n; i++) {


sum += i; // sum = sum + i
}

printf("Sum of 1 to %d = %d\n", n, sum);


return 0;
}
Explanation:
 Loop runs from 1 to n
 Adds each number to sum

7.6. Key Points


1. Initialization occurs only once.
2. Condition is checked before each iteration.
3. Increment/decrement updates loop variable after executing the body.
4. Can have multiple initializations or increments using commas:
for (i = 0, j = 10; i < j; i++, j--) { ... }
5. Can omit any part of the for header (condition, increment, initialization), but must handle
carefully to avoid infinite loops.

7.7. Infinite for Loop Example


for (;;) {
printf("This will run forever!\n");
}
 Omitting all three parts creates an infinite loop.
 Useful in embedded systems or server programs, but usually controlled with a break
statement.

7.8. Best Practices


1. Keep loop body simple and readable.
2. Always ensure the loop variable changes to eventually terminate.
3. Prefer for when number of iterations is known.
4. Use meaningful loop variable names (i, j, k for counters; descriptive names for clarity).
7.9. Comparison with Other Loops
Feature for while do-while
Control type Counter-controlled Entry-controlled Exit-controlled
Known number of Unknown number of At least one execution
Use case
iterations iterations required
Syntax for(init; cond; incr) while(cond) do { } while(cond);

7.10. Example: Nested for Loop


Print a 5×5 multiplication table
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%3d ", i*j);
}
printf("\n");
}
return 0;
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
 Nested for loops are common for matrices, tables, and multi-dimensional arrays.

8. Nested Loops in C:
8.1. Introduction to Nested Loops
 Nested loops occur when one loop is placed inside another loop.
 Useful for repetitive tasks in multi-dimensional structures, such as matrices, tables, or
patterns.
 Can use any type of loop (for, while, do-while) inside another loop.
Structure:
Outer loop
{
Inner loop
{
// statements executed multiple times
}
}
 Inner loop executes completely for each iteration of the outer loop.

8.2. Syntax Example (Using for Loops)


for (initialization1; condition1; increment1) { // Outer loop
for (initialization2; condition2; increment2) { // Inner loop
// statements
}
}
8.3. How Nested Loops Work
1. Outer loop executes once → inner loop executes completely.
2. Outer loop increments → inner loop executes again completely.
3. Process repeats until outer loop condition is false.
Flow Diagram:
Outer Loop (i)
┌───────────────┐
│ i=1..n │
└─────┬─────────┘

Inner Loop (j)
┌───────────────┐
│ j=1..m │
└─────┬─────────┘
│ Execute statements
└───────────────> increment j
Repeat inner loop until j>m
Back to outer loop increment i
Repeat until i>n

8.4. Example 1: Printing a Pattern


Print a 5×5 star pattern
#include <stdio.h>

int main() {
int i, j;
for (i = 1; i <= 5; i++) { // Outer loop
for (j = 1; j <= 5; j++) { // Inner loop
printf("* ");
}
printf("\n"); // Newline after each row
}
return 0;
}
Output:
*****
*****
*****
*****
*****
 Inner loop prints 5 stars for each iteration of outer loop.

8.5. Example 2: Multiplication Table


#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%3d ", i * j);
}
printf("\n");
}
return 0;
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

8.6. Important Points


1. Inner loop executes fully for each iteration of outer loop.
2. Can nest any type of loop (for, while, do-while).
3. Keep track of loop variables to avoid confusion.
4. Nested loops can cause high time complexity if large ranges are used.
Example: Two loops with 1000 iterations each → 1,000,000 total iterations.

8.7. Nested Loops with Different Types


Example:for loop outer, while loop inner
#include <stdio.h>
int main() {
int i = 1;
while (i <= 3) { // Outer loop
for (int j = 1; j <= 3; j++) { // Inner loop
printf("%d ", j);
}
printf("\n");
i++;
}
return 0;
}
Output:
123
123
123
 Demonstrates that any combination of loops is valid.
8.8. Common Uses of Nested Loops
1. Printing patterns (*, numbers, letters).
2. Processing 2D arrays or matrices.
3. Generating tables (multiplication, truth tables).
4. Implementing complex algorithms (sorting, searching in grids).

8.9. Best Practices


1. Avoid too many levels of nesting; reduces readability.
2. Choose appropriate loop type for inner and outer loops.
3. Ensure inner loop variables are independent of outer loop variables.
4. Consider time complexity when working with large loops.

8.10. Summary Table


Feature Description
Definition A loop inside another loop
Execution Inner loop completes for each outer loop iteration
Use Cases Patterns, 2D arrays, tables
Loop Types Any combination (for, while, do-while)
Caution High time complexity if ranges are large
FUNCTIONS
1. Function Declaration in C:
1.1. Introduction to Functions in C
 A function is a block of code designed to perform a specific task.
 Functions help in:
1. Modularity – breaking program into smaller parts.
2. Reusability – use the same function multiple times.
3. Ease of debugging – easier to test small functions individually.
 In C, a function typically has three parts:
1. Function declaration (prototype)
2. Function definition
3. Function call

1.2. What is a Function Declaration?


 Also called a function prototype.
 Provides the compiler with information about the function before its use.
 Declares:
o Function name
o Return type
o Parameters (types only)
 Ensures that calls to the function match the definition.

1.3. Syntax of Function Declaration


return_type function_name(parameter_list);
Components
Component Description
return_type Type of value function returns (int, float, void, etc.)
function_name Identifier of the function
parameter_list Types (and optionally names) of arguments; empty () if none

1.4. Examples of Function Declarations


1. Function with no parameters and no return value:
void greet();
2. Function with parameters and return value:
int add(int, int);
3. Function with one parameter and no return value:
void printNumber(int);
1.5. Function Definition vs Declaration
Feature Declaration (Prototype) Definition
Purpose Tells compiler about function Actual code of function
Components Return type, name, parameter types Return type, name, parameters, body {}
Example int add(int, int); int add(int a, int b) { return a+b; }
Note: Function must be declared before it is called if it is defined after the main() function.

1.6. Example: Using Function Declaration


#include <stdio.h>
// Function declaration
int add(int, int);

int main() {
int result;
result = add(5, 10); // function call
printf("Sum = %d\n", result);
return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

Explanation:
1. Compiler knows about add() from declaration.
2. main() calls add().
3. Actual addition happens in definition.

1.7. Key Points About Function Declaration


1. Mandatory if function is defined after its call.
2. Specifies only types, not names (names are optional in declaration).
3. Helps type checking during compilation.
4. Can declare multiple functions at the top of the program for clarity.

1.8. Best Practices


 Always declare functions before main() or use header files.
 Keep function declarations consistent with definitions.
 Use void for functions that do not return any value.
 Use meaningful names for readability.
1.9. Example: Multiple Function Declarations
#include <stdio.h>
// Function declarations
void greet();
int multiply(int, int);
float divide(float, float);

int main() {
greet();
printf("Multiply: %d\n", multiply(3, 4));
printf("Divide: %.2f\n", divide(10.0, 2.0));
return 0;
}

// Function definitions
void greet() {
printf("Hello, welcome!\n");
}

int multiply(int a, int b) {


return a * b;
}

float divide(float a, float b) {


return a / b;
}

2. Function Definition and Function Calling in C:


2.1. Function Definition
 A function definition provides the actual body of the function, containing the statements
to perform a task.
 It follows the function declaration (prototype) if declared earlier.
 Contains:
1. Return type
2. Function name
3. Parameters (if any)
4. Body of statements enclosed in {}

2.1.1 Syntax of Function Definition


return_type function_name(parameter_list) {
// statements
return value; // if return type is not void
}
Components
Component Description
return_type Type of value the function returns (int, float, void)
function_name Identifier of the function
parameter_list List of parameters with type (optional if none)
Body {} Statements to execute when function is called
return Returns value if type is non-void

2.1.2 Examples of Function Definitions


1. Function with no parameters and no return value:
void greet() {
printf("Hello, World!\n");
}
2. Function with parameters and a return value:
int add(int a, int b) {
return a + b;
}

2.2. Function Calling


 Function call is the process of executing the function.
 When a function is called:
1. Control transfers to the function definition.
2. Statements inside function execute.
3. Control returns to the point after the function call.

2.2.1 Syntax of Function Call


function_name(arguments);
 arguments are the values passed to the function parameters.

2.2.2 Example: Function Calling


#include <stdio.h>
// Function declaration
int add(int, int);

int main() {
int sum;
sum = add(5, 10); // function call
printf("Sum = %d\n", sum);
return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

Explanation:
1. add(5, 10) → passes 5 and 10 to function parameters a and b.
2. Function executes return a+b;.
3. Returns 15 to the variable sum in main().
4. Program continues after the function call.

2.3. Types of Function Calls


1. Without arguments, without return value
void greet();
greet(); // just executes function
2. With arguments, without return value
void printNumber(int num);
printNumber(5);
3. Without arguments, with return value
int getRandomNumber();
int r = getRandomNumber();
4. With arguments, with return value
int add(int a, int b);
int sum = add(3, 4);

2.4. Key Points


1. Function must be declared before it is called, if definition appears after main().
2. Parameters in function definition receive arguments from the function call.
3. Function returns value only if return type is non-void.
4. Execution resumes after the function call.

2.5. Best Practices


 Keep function modular and single-purpose.
 Match function call arguments with parameters in type and number.
 Use meaningful names for readability.
 Avoid unnecessary deeply nested function calls for clarity.

2.6. Example: Multiple Functions with Calling


#include <stdio.h>
// Function declarations
void greet();
int multiply(int, int);
float divide(float, float);

int main() {
greet();
printf("Multiply: %d\n", multiply(3, 4));
printf("Divide: %.2f\n", divide(10.0, 2.0));
return 0;
}

// Function definitions
void greet() {
printf("Hello, welcome!\n");
}

int multiply(int a, int b) {


return a * b;
}

float divide(float a, float b) {


return a / b;
}
 main() calls all three functions.
 Each function performs its task independently.

3. Function Parameters and Return Types in C:


3.1. Function Parameters
 Function parameters are variables declared in the function definition to accept values
from the function call.
 They allow passing data to functions for processing.
 Parameters are sometimes called formal arguments.

3.1.1 Types of Function Parameters


1. No parameters
o Function does not take any input values.
void greet() {
printf("Hello!\n");
}
2. With parameters
o Function accepts one or more input values.
void printNumber(int num) {
printf("Number: %d\n", num);
}
3. Multiple parameters
o Pass multiple values separated by commas.
int add(int a, int b) {
return a + b;
}

3.1.2 Passing Methods


1. Call by Value (default in C)
o Passes copy of the value to the function.
o Changes inside function do not affect original variable.
void increment(int x) {
x = x + 1; // only local copy changes
}
2. Call by Reference (using pointers)
o Passes address of variable to function.
o Changes affect original variable.
void increment(int *x) {
*x = *x + 1; // original variable changes
}

3.2. Function Return Types


 Return type defines the type of value a function returns to the caller.
 It must match the type of the value returned by return statement.

3.2.1 Common Return Types


Return Type Description Example
void No value returned void greet()
int Returns integer int add(int a, int b)
float Returns floating-point number float divide(float a, float b)
char Returns a character char getGrade(int marks)
double Returns double-precision float double power(double x, double y)
3.2.2 Examples of Return Types
1. Void function (no return)
#include <stdio.h>

void greet() {
printf("Hello!\n");
}

int main() {
greet(); // call function
return 0;
}
2. Function with return value
#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int main() {
int sum = add(5, 10); // function returns value
printf("Sum = %d\n", sum);
return 0;
}

3.3. Function with Parameters and Return Value


#include <stdio.h>
float multiply(float x, float y) {
return x * y;
}

int main() {
float result = multiply(3.5, 2.0);
printf("Result = %.2f\n", result);
return 0;
}
 Parameters x and y receive values from the function call.
 Function returns product to the caller.
3.4. Key Points
1. Parameters allow functions to receive input values.
2. Return type allows functions to send results back.
3. void return type is used when no value needs to be returned.
4. Parameter types and return type must match function declaration.
5. Using pointers enables call by reference, allowing changes in original variables.

3.5. Example: Using Parameters and Return Types


#include <stdio.h>
// Function to calculate area of rectangle
float area(float length, float width) {
return length * width;
}

int main() {
float l = 5.0, w = 3.0;
float a = area(l, w); // call function with parameters
printf("Area = %.2f\n", a);
return 0;
}
Output:
Area = 15.00

3.6. Summary Table


Feature Description
Parameters Variables that receive input values in function
Return Type Type of value returned to caller
Void function Returns nothing
Call by value Passes copy of variable
Call by reference Passes address using pointers

4. Call by Value and Call by Reference in C:


4.1. Introduction
 In C, function parameters can be passed in two ways:
1. Call by Value
2. Call by Reference
 These determine whether changes to parameters inside a function affect the original
variables or not.
4.2. Call by Value
4.2.1 Definition
 Call by Value passes a copy of the variable’s value to the function.
 Changes made inside the function do not affect the original variable in the caller.

4.2.2 Syntax Example


#include <stdio.h>

void increment(int x) { // x is a copy of the value


x = x + 1;
printf("Inside function: x = %d\n", x);
}

int main() {
int a = 5;
increment(a); // call by value
printf("In main: a = %d\n", a); // original variable unchanged
return 0;
}
Output:
Inside function: x = 6
In main: a = 5
Explanation:
 x is a local copy of a.
 Modifying x does not affecta in main().

4.3. Call by Reference


4.3.1 Definition
 Call by Reference passes the address of the variable to the function.
 Changes made inside the function directly affect the original variable.
 Implemented using pointers in C.

4.3.2 Syntax Example


#include <stdio.h>
void increment(int *x) { // x is a pointer to the original variable
*x = *x + 1; // modify the original value
printf("Inside function: x = %d\n", *x);
}
int main() {
int a = 5;
increment(&a); // pass address of a
printf("In main: a = %d\n", a); // original variable changed
return 0;
}
Output:
Inside function: x = 6
In main: a = 6
Explanation:
 x points to a's memory location.
 *x modifies the value stored at that location.

4.4. Key Differences Between Call by Value and Call by Reference


Feature Call by Value Call by Reference
What is passed Copy of value Address of variable
Effect on original variable No change Value can be changed
Memory usage Extra memory for copy Efficient (no copy)
Safety Safer (original unchanged) Careful: modifying original
Syntax function(a) function(&a) with pointer parameter
Example increment(int x) increment(int *x)

4.5. When to Use


1. Call by Value
o When you don’t want to modify the original variable.
o Safer for primitive data types.
2. Call by Reference
o When you want to update the original variable.
o Useful for large data structures or arrays (avoid copying).

4.6. Example: Swapping Two Numbers


Using Call by Value (fails to swap)
#include <stdio.h>
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
printf("x = %d, y = %d\n", x, y); // values unchanged
return 0;
}
Output:
x = 5, y = 10

Using Call by Reference (works)


#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y); // values swapped
return 0;
}
Output:
x = 10, y = 5

4.7. Summary Table


Feature Call by Value Call by Reference
Passed to function Copy of variable Address of variable
Original variable Not affected Affected
Syntax function(a) function(&a) and pointer parameter
Memory More (copy) Less (pointer only)
Safety Safe Modify original data
Use case Read-only operations Modify original, large data structures

5. Recursive Functions in C:
5.1. Introduction to Recursive Functions
 A recursive function is a function that calls itself directly or indirectly.
 Useful for solving problems that can be broken down into smaller, similar sub-problems.
 Common examples: factorial calculation, Fibonacci series, tree traversal.
5.2. Characteristics of Recursive Functions
1. Base Case:
o A condition that stops the recursion.
o Prevents infinite recursion.
2. Recursive Case:
o Part where the function calls itself with modified parameters.
Recursion Formula Example:
Factorial(n) = n * Factorial(n-1), for n > 1
Base Case: Factorial(1) = 1

5.3. Syntax of a Recursive Function


return_type function_name(parameters) {
if (base_condition)
return value; // Base case
else
return function_name(modified_parameters); // Recursive call
}

5.4. Example 1: Factorial of a Number


#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}
int main() {
int num = 5;
printf("Factorial of %d = %d\n", num, factorial(num));
return 0;
}
Output:
Factorial of 5 = 120
Explanation:
 factorial(5) calls factorial(4) → factorial(3) → ... → factorial(1)
 Base case reached → recursion unwinds multiplying the values.

5.5. Example 2: Fibonacci Series


#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0; // Base case 1
else if (n == 1)
return 1; // Base case 2
else
return fibonacci(n-1) + fibonacci(n-2); // Recursive call
}
int main() {
int n = 7;
for (int i = 0; i < n; i++)
printf("%d ", fibonacci(i));
return 0;
}
Output:
0112358
 Each term is sum of the previous two terms.

5.6. Types of Recursion


1. Direct Recursion
o Function calls itself directly.
o Example: factorial() calls factorial().
2. Indirect Recursion
o Function A calls Function B, and Function B calls Function A.
3. Tail Recursion
o Recursive call is the last statement in the function.
o Optimized by some compilers.
4. Non-Tail Recursion
o Recursive call is not the last statement; requires stack to store intermediate
results.

5.7. Advantages of Recursive Functions


1. Simplifies code for problems with repetitive sub-structure.
2. Easy to understand for mathematical problems like factorial, Fibonacci, GCD.
3. Useful in data structures: trees, graphs, and linked lists.

5.8. Disadvantages / Limitations


1. Consumes more memory due to function call stack.
2. Slower compared to iterative solutions for some problems (e.g., Fibonacci).
3. Infinite recursion can cause stack overflow if base case is missing.
5.9. Best Practices
1. Always define a base case.
2. Avoid recursion for very large input sizes unless optimized.
3. Consider tail recursion for better compiler optimization.
4. For performance-critical problems, sometimes iteration is better.

5.10. Example: Sum of First N Numbers Using Recursion


#include <stdio.h>
int sum(int n) {
if (n == 0) // Base case
return 0;
else
return n + sum(n - 1); // Recursive call
}
int main() {
int n = 5;
printf("Sum of 1 to %d = %d\n", n, sum(n));
return 0;
}
Output:
Sum of 1 to 5 = 15

6. Scope and Lifetime of Variables in C:


6.1. Introduction
 In C, variables have scope and lifetime, which define where a variable can be accessed
and how long it exists in memory.
 Understanding these concepts is crucial for memory management, modular programming,
and avoiding errors.

6.2. Scope of Variables


Scope: The region of the program where a variable can be accessed or used.

6.2.1 Types of Scope


Scope Type Description Example
Variable declared inside a function or block. Accessible only int x; inside
Local Scope
within that block. main()
Global Scope Variable declared outside all functions. Accessible from any int x; before
Scope Type Description Example
function after declaration. main()
Variable declared inside a block {} like loops or if statements. for(int i=0; i<5; i+
Block Scope
Accessible only within that block. +)
Function label: inside a
Labels used in goto statements.
Scope function

6.2.2 Example: Scope


#include <stdio.h>
int globalVar = 100; // Global scope
void demo() {
int localVar = 50; // Local scope
printf("Inside demo: globalVar=%d, localVar=%d\n", globalVar, localVar);
}
int main() {
demo();
printf("In main: globalVar=%d\n", globalVar);
// printf("%d", localVar); // Error! localVar not accessible here
return 0;
}
Output:
Inside demo: globalVar=100, localVar=50
In main: globalVar=100

6.3. Lifetime of Variables


Lifetime: The duration for which a variable exists in memory during program execution.

6.3.1 Types of Lifetime


Lifetime Type Storage Class Description Example
Variable exists only during
auto (default for
Automatic function/block execution. Memory is int x; inside a function
local variables)
released after exit.
Variable exists throughout program
Static static execution but scope may be local. static int count = 0;
Retains value between calls.
Stored in CPU registers (if possible).
Register register Lifetime is automatic, fast access, cannot register int i;
use &.
Exists until explicitly freed. Lifetime int *ptr =
Dynamic (Heap) malloc/free
controlled by programmer. malloc(sizeof(int));
Lifetime Type Storage Class Description Example
Variable exists throughout program
Global/External extern int x; extern int x;
execution, accessible globally.

6.3.2 Example: Lifetime


#include <stdio.h>
void counter() {
static int count = 0; // retains value
int temp = 0; // automatic variable
count++;
temp++;
printf("count=%d, temp=%d\n", count, temp);
}
int main() {
counter();
counter();
counter();
return 0;
}
Output:
count=1, temp=1
count=2, temp=1
count=3, temp=1
Explanation:
 count retains its value between calls (static).
 temp is reinitialized every time (automatic).

6.4. Storage Classes


 Storage class determines scope, lifetime, and default initial value of a variable.
Storage Class Scope Lifetime Default Value
auto Local Function/block execution Garbage
register Local Function/block execution Garbage
static Local or Global Entire program 0
extern Global Entire program Depends on definition

6.5. Key Points


1. Scope → Where variable is accessible.
2. Lifetime → How long variable exists in memory.
3. Local variables → Limited scope, short lifetime.
4. Global/static variables → Wider scope (global) or persistent value (static), long lifetime.
5. Proper use avoids memory leaks and unexpected behavior.

6.6. Summary Table


Variable Type Scope Lifetime Example
Local Inside function/block Function/block execution int a; inside main
Global Entire program Entire program int g; outside all functions
Static Local/static Entire program static int x=0;
Register Local Function/block execution register int i;

7. Header Files in C
A header file in C is a file with extension .h that contains declarations (not definitions). It tells the
compiler what functions, macros, constants, or data types exist, so they can be used in multiple .c
files.
Think of a header file as a “menu card”:
 The menu card (header file) lists the available dishes (functions).
 The kitchen (source file) actually makes the dish (function implementation).

7.1. Purpose of Header Files


 Function declarations (prototypes)
 Macro definitions
 Constant definitions
 Structure/Union declarations
 Extern variable declarations
They act as an interface between source files.

7. 2. Types of Header Files


(A) Standard Library Header Files
These are provided by C’s standard library.

Header File Contains


<stdio.h> Input/output functions (printf, scanf, fopen)
<stdlib.h> Utility functions (malloc, exit, rand)
<string.h> String handling (strlen, strcpy, strcmp)
<math.h> Mathematical functions (sqrt, pow, sin)
<ctype.h> Character handling (isdigit, isalpha, toupper)
<time.h> Time/date functions (time, clock, difftime)
<stdbool.h> Boolean type support (true, false)
<limits.h> Defines integer limits (INT_MAX, CHAR_BIT)
Header File Contains
<float.h> Defines floating-point limits (FLT_MAX)
Example:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

(B) User-Defined Header Files


Created by programmers for modularity.
Example:
myheader.h
// myheader.h
void greet();
myheader.c
#include <stdio.h>
#include "myheader.h"
void greet() {
printf("Hello from my header!\n");
}
main.c
#include "myheader.h"

int main() {
greet();
return 0;
}
Compile:
gcc main.c myheader.c -o program
7. 3. Syntax of Including Header Files
Two ways to include:
1. Angle brackets (<>) → Search in standard library path.
2. #include <stdio.h>
Used for system/standard headers.
3. Double quotes ("") → Search in current directory first, then system paths.
4. #include "myheader.h"
Used for user-defined headers.

7.4. Contents of a Header File


A header file may contain:
 Function prototypes
 int add(int a, int b);
 Macro definitions
 #define PI 3.14159
 Constant declarations
 const int MAX = 100;
 Structure/typedef declarations
 typedef struct {
 int id;
 char name[20];
 } Student;
 Extern variable declarations
 extern int count;

7.5. Advantages of Header Files


✔ Code Reusability – Write once, use in multiple files.
✔ Easier Maintenance – Modify in one place, applies everywhere.
✔ Modularity – Separates declaration from implementation.
✔ Faster Development – Large projects can be divided among teams.
✔ Readability – Functions and constants are grouped logically.

7.6. Best Practices for Using Header Files


 Always use include guards or #pragma once to avoid multiple inclusion.
 Keep only declarations in .h files (no function definitions).
 Group related declarations into one header.
 Use <> for system headers and "" for user-defined headers.

7.7. Preventing Multiple Inclusion


If a header file is included in multiple .c files, it may cause multiple definition errors.
To prevent this → use include guards:
#ifndef MYHEADER_H
#define MYHEADER_H
void greet();
#endif
Or use:
#pragma once

7.8.Summary
 Header files = Declaration files (.h)
 Source files = Definition files (.c)
 Together → they support modular programming and code reuse.

8. Modular Programming in C
Modular programming is a software design technique where a program is divided into smaller,
independent, and reusable parts called modules.
Each module performs a specific task and can be developed, tested, and maintained independently.
In C, a module is usually built using:
 Header files (.h) → declarations (what is available)
 Source files (.c) → definitions (how it works)

8.1. Characteristics of Modular Programming


1. Decomposition → Large programs are broken into smaller modules.
2. Encapsulation → Each module hides its implementation and exposes only its interface (via
header).
3. Reusability → Modules can be reused in other projects.
4. Maintainability → Easy to debug or update without affecting the whole program.
5. Abstraction → The user of a module does not need to know its internal logic.

8.2. Structure of Modular Programming in C


Typical modular program structure:
main.c → contains main() function
module1.h → function prototypes, macros
module1.c → function definitions
module2.h
module2.c
During compilation:
main.c + module1.c + module2.c → compiled together

8.3. Example: Modular Program for Area Calculation


We’ll calculate the area of Circle and Rectangle using modular programming.
circle.h
// circle.h
#define PI 3.14159
double area_circle(double radius);
circle.c
#include "circle.h"

double area_circle(double radius) {


return PI * radius * radius;
}
rectangle.h
// rectangle.h
double area_rectangle(double length, double width);
rectangle.c
#include "rectangle.h"

double area_rectangle(double length, double width) {


return length * width;
}
main.c
#include <stdio.h>
#include "circle.h"
#include "rectangle.h"

int main() {
double r = 5.0, l = 4.0, w = 3.0;

printf("Area of Circle: %.2f\n", area_circle(r));


printf("Area of Rectangle: %.2f\n", area_rectangle(l, w));

return 0;
}
Compile:
gcc main.c circle.c rectangle.c -o area
./area

8.4. Advantages of Modular Programming


 Simplicity → Focus on one module at a time.
 Reusability → Same module can be reused in multiple programs.
 Teamwork → Different developers can work on different modules.
 Maintainability → Easy to fix bugs or upgrade a single module.
 Testing → Modules can be tested individually.

8.5. Best Practices for Modular Programming in C


1. Use header files to declare functions, macros, and structures.
2. Use source files (.c) for function definitions.
3. Keep modules independent (minimal dependency between them).
4. Use include guards in headers to avoid duplication.
5. Group related functionality into a single module (e.g., math operations, file handling).

8.6. Real-Life Analogy


Think of a car manufacturing plant:
 Engine department (module) → builds engines.
 Body department (module) → builds car body.
 Assembly department (main program) → combines them.
Each module can work independently, but together they form the complete product.

8.7. Summary
 Modular Programming = breaking a big program into smaller modules.
 Achieved in C using header files + source files.
 Provides abstraction, reusability, and maintainability.
STRINGS & POINTERS
1. Strings in C.
1.1. Introduction to Strings
 A string in C is a sequence of characters stored in a character array, terminated by a null
character '\0'.
 Unlike some languages, C does not have a built-in string type. Instead, strings are handled
as arrays of char.
Example:
char name[6] = "Hello";
Here memory layout:
'H' 'e' 'l' 'l' 'o' '\0'

1.2. Declaring Strings


There are two ways to declare a string:
(a) Character array with characters
char str[6] = {'H','e','l','l','o','\0'};
(b) String literal (easy way)
char str[] = "Hello";
Both are equivalent. But in method (b), the compiler automatically adds the null terminator.

1.3. Input and Output of Strings


Using printf and scanf
#include <stdio.h>
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name); // reads until space
printf("Hello %s\n", name);
return 0;
}
⚠️Limitation: scanf("%s", name); stops reading at space, tab, or newline.

Using gets and puts (old way, unsafe)


char str[50];
gets(str); // reads entire line
puts(str);
⚠️gets() is dangerous (buffer overflow), so it’s avoided.

Using fgets (safe way)


char str[50];
fgets(str, sizeof(str), stdin);
puts(str);

1.4. String Library Functions (<string.h>)


The string.h library provides useful functions:
Function Description Example
strlen(str) Returns length (not counting '\0'). strlen("Hello") → 5
strcpy(dest, src) Copies one string into another. strcpy(b, a);
strncpy(dest, src, n) Copies first n characters. strncpy(b, a, 3);
strcat(str1, str2) Concatenates (joins) two strings. "Hello" + "World"
strncat(str1, str2, n) Concatenates n characters.
strcmp(s1, s2) Compares strings. Returns 0 if equal.
strncmp(s1, s2, n) Compares first n chars.
strchr(str, ch) Finds first occurrence of a character.
strstr(str, sub) Finds substring.

Example: String Functions


#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char str3[40];

// Copy
strcpy(str3, str1);
printf("strcpy: %s\n", str3);

// Concatenate
strcat(str1, str2);
printf("strcat: %s\n", str1);

// Length
printf("strlen: %lu\n", strlen(str1));

// Compare
printf("strcmp: %d\n", strcmp("abc", "abd"));

return 0;
}
Possible Output:
strcpy: Hello
strcat: HelloWorld
strlen: 10
strcmp: -1

1.5. Strings vs Character Arrays


 Character Array: Just a collection of characters. May or may not end with '\0'.
 String: Must end with null character'\0'.
Example:
char arr[5] = {'H','e','l','l','o'}; // Not a string (no '\0')
char str[6] = {'H','e','l','l','o','\0'}; // String

1.6. Memory Representation


String "CSE" is stored as:
'C' 'S' 'E' '\0'
ASCII values: 67 83 69 0

1.7. Applications of Strings


 Storing and displaying text.
 Handling user input (names, addresses).
 File names and paths.
 Parsing text (search, replace, compare).
 Communication in networks (protocol messages).

1.8.Summary:
 Strings are char arrays ending with '\0'.
 Use <string.h> functions for operations.
 Input using scanf, fgets.
 Key operations: copy, concatenate, compare, search.

2. One-dimensional and Multi-dimensional Arrays in C.


2.1. Introduction to Arrays
 An array in C is a collection of elements of the same data type, stored in contiguous
memory locations.
 Each element is accessed using an index (starting from 0).
 Arrays allow storing multiple values under a single variable name.
2.2. One-Dimensional (1D) Arrays
Definition
 A 1D array is like a list of elements stored in a single row.
 Syntax:
data_type array_name[size];

Example
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 88, 92}; // 1D array

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


printf("marks[%d] = %d\n", i, marks[i]);
}
return 0;
}

Output:
marks[0] = 85
marks[1] = 90
marks[2] = 78
marks[3] = 88
marks[4] = 92

Key Points
 Elements accessed as array[index].
 Size must be a constant integer.
 Uninitialized elements get garbage values (unless global/static → default = 0).

2.3. Multi-Dimensional Arrays


Definition
 A multi-dimensional array is an array of arrays.
 Most common: two-dimensional (2D) arrays (tables/matrices).
 Syntax:
data_type array_name[rows][columns];

2.3.1 Two-Dimensional Arrays


 Like a table with rows and columns.
Example
#include <stdio.h>

int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

Output:
123
456

2.3.2 Three-Dimensional Arrays


 Used for representing 3D data (cubes, 3D matrices, images).
 Syntax:
int cube[3][3][3];
Example:
int cube[2][2][2] = {
{{1,2},{3,4}},
{{5,6},{7,8}}
};

2.4. Memory Representation


 1D Array: Elements stored sequentially.
Example: int arr[5] = {10,20,30,40,50};
Stored in memory as: [10][20][30][40][50]
 2D Array: Stored in row-major order (C default).
Example:
 int arr[2][3] = { {1,2,3}, {4,5,6} };
Stored in memory as: [1][2][3][4][5][6]

2.5. Differences Between 1D and Multi-Dimensional Arrays


Feature One-Dimensional Array Multi-Dimensional Array
Structure Linear (single row) Tabular/Matrix (rows, columns)
Syntax int arr[5]; int arr[3][4];
Use case Storing lists (marks, prices, IDs) Storing tables (matrices, 2D data)
Access arr[i] arr[i][j] or higher dimensions
Memory Continuous linear blocks Row-major order blocks
2.6. Applications
1D Arrays
 Store student marks, temperatures, salaries, scores.
2D Arrays
 Matrices (math operations), images (pixels), chessboard representation, tabular data.
3D Arrays
 3D graphics, medical imaging (CT scans), volumetric data.

3. Array Operations and Traversals in C.


3.1. Introduction
An array is a collection of elements of the same data type stored in contiguous memory
locations.
When we work with arrays, we often need to perform operations such as:
 Traversal
 Insertion
 Deletion
 Searching
 Sorting
 Updating

3.2. Traversal of an Array


Traversal means visiting each element of the array one by one.
Example: Traversing 1D Array
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};

printf("Array elements:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // accessing each element
}
return 0;
}

Output:
10 20 30 40 50

Traversal in 2D Array
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };

printf("Matrix elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

Output:
123
456

3.3. Array Operations


(a) Insertion
Adding a new element into the array.
 If array is unsorted: Insert at the end or at any index by shifting elements.
 If array is sorted: Maintain order while inserting.
#include <stdio.h>

int main() {
int arr[10] = {10, 20, 30, 40, 50};
int n = 5; // current size
int pos = 2, val = 25; // insert at index 2

for (int i = n; i > pos; i--) {


arr[i] = arr[i-1]; // shift right
}
arr[pos] = val;
n++;

printf("Array after insertion: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
10 20 25 30 40 50
(b) Deletion
Removing an element from the array.
#include <stdio.h>
int main() {
int arr[10] = {10, 20, 30, 40, 50};
int n = 5;
int pos = 2; // delete index 2 (30)

for (int i = pos; i < n-1; i++) {


arr[i] = arr[i+1]; // shift left
}
n--;
printf("Array after deletion: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
10 20 40 50

(c) Searching
 Linear Search: Check each element one by one.
 Binary Search: Faster, but works only on sorted arrays.
// Linear Search Example
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int key = 30, found = 0;

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


if (arr[i] == key) {
printf("Element found at index %d\n", i);
found = 1;
break;
}
}
if (!found) {
printf("Element not found\n");
}
return 0;
}

(d) Sorting
Arranging elements in order (ascending/descending).
 Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, Merge Sort etc.
Bubble Sort Example
#include <stdio.h>
int main() {
int arr[5] = {64, 25, 12, 22, 11};
int n = 5, temp;

for (int i = 0; i < n-1; i++) {


for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

printf("Sorted array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
11 12 22 25 64

(e) Updating
Changing the value of an existing element.
arr[2] = 100; // updates 3rd element
3.4. Summary Table
Operation Description Example
Traversal Visit all elements Printing array
Insertion Add element at position Insert 25 at index 2
Deletion Remove element Delete arr[3]
Searching Find an element Linear / Binary search
Sorting Arrange order Bubble Sort, Quick Sort
Operation Description Example
Updating Modify element arr[1] = 99;

 So Array Traversal = accessing elements one by one.


 Operations = Insertion, Deletion, Searching, Sorting, Updating.

4. String Handling in C: String Declaration.


4.1. What is a String in C?
 A string in C is an array of characters that ends with a special character called the null
terminator '\0'.
 Unlike some languages, C does not have a built-in string data type. Instead, strings are
managed as character arrays.
👉 Example:
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Here:
 Each character is stored in an array element.
 The last element '\0' tells the compiler where the string ends.

4.2. String Declaration Methods


(a) Character Array with Null Terminator
char str1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 Explicitly specifying each character including '\0'.
 Size is 6 (5 letters + null).

(b) String Literal Initialization


char str2[] = "Hello";
 Automatically adds the '\0' at the end.
 Size = 6 internally ('H' 'e' 'l' 'l' 'o' '\0').
 More convenient and commonly used.

(c) Fixed Size Declaration


char str3[10] = "Hello";
 Reserves space for 10 characters.
 "Hello" occupies 6 spaces (including '\0').
 Remaining 4 spaces contain garbage values or '\0'.

(d) Empty String Declaration


char str4[20]; // uninitialized (contains garbage)
char str5[20] = ""; // initialized as empty string (only '\0')
4.3. Example Program
#include <stdio.h>
int main() {
char str1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char str2[] = "Hello";
char str3[10] = "Hello";

printf("String 1: %s\n", str1);


printf("String 2: %s\n", str2);
printf("String 3: %s\n", str3);

return 0;
}

Output:
String 1: Hello
String 2: Hello
String 3: Hello

4.4. Key Rules for String Declaration


 Always reserve one extra space for '\0'.
 Strings must end with '\0', otherwise functions like printf("%s") won’t know where the string
ends.
 Strings can be declared with or without explicitly specifying size.
 Direct assignment to arrays after declaration is not allowed:
 char str[10];
 str = "Hello"; // ❌ Invalid
Must use strcpy() instead.

4.5. Memory Representation


For char str[] = "Hi";
Index Value
0 'H'
1 'i'
2 '\0'

 In short: A string in C = character array + null terminator.


5. String Input/Output
5.1. String Input in C
Since strings are character arrays, we can take input using different methods:

(a) Using scanf()


#include <stdio.h>

int main() {
char str[20];
printf("Enter a string: ");
scanf("%s", str); // input stops at space
printf("You entered: %s\n", str);
return 0;
}

Input:
Hello World
Output:
You entered: Hello
 Limitation: scanf("%s") reads only one word (stops at space, tab, or newline).

(b) Using gets() (❌ Not Recommended – unsafe)


char str[50];
gets(str);
 Reads entire line including spaces.
 But unsafe (may cause buffer overflow).

(c) Using fgets() (✔ Recommended)


#include <stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // safe, reads spaces too
printf("You entered: %s", str);
return 0;
}
 Reads spaces as well.
 Stops when buffer is full or newline (\n) is found.

(d) Character by Character using getchar()


#include <stdio.h>
int main() {
char c, str[20];
int i = 0;

printf("Enter a string (end with .): ");


while ((c = getchar()) != '.' && i < 19) {
str[i++] = c;
}
str[i] = '\0'; // terminate string

printf("You entered: %s\n", str);


return 0;
}

5.2. String Output in C


(a) Using printf()
printf("%s", str);
(b) Using puts()
puts(str);
 Automatically moves to next line after printing.
(c) Character by Character using putchar()
for (int i = 0; str[i] != '\0'; i++) {
putchar(str[i]);
}

5.3. Example: String Input and Output


#include <stdio.h>
int main() {
char name[30];

printf("Enter your name: ");


fgets(name, sizeof(name), stdin); // input
printf("Hello, ");
puts(name); // output

return 0;
}

Input:
Balaji AN

Output:
Hello, Balaji AN

5.4. Summary Table


Function Type Can Read Spaces? Safe? Notes
scanf("%s") Input ❌ No ⚠️Risky Stops at space
gets() Input ✅ Yes ❌ Unsafe Deprecated
fgets() Input ✅ Yes ✅ Safe Preferred
printf("%s") Output ✅ Yes ✅ Safe Most common
puts() Output ✅ Yes ✅ Safe Adds newline
putchar() Output N/A ✅ Safe Prints one char

 In short: Use fgets() for input and puts() or printf() for output.

6. C String Library Functions.


These functions are defined in the header file:
#include <string.h>

1. strlen() – String Length


 Returns the number of characters in a string (excluding '\0').
#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello World";
printf("Length: %lu\n", strlen(str));
return 0;
}
Output:
Length: 11

2. strcpy() – Copy String


 Copies one string into another.
char str1[20] = "Hello";
char str2[20];
strcpy(str2, str1); // str2 = "Hello"
 Make sure destination has enough space.

3. strncpy() – Copy (with Limit)


 Copies n characters from one string to another.
char str1[] = "Programming";
char str2[20];
strncpy(str2, str1, 5);
str2[5] = '\0'; // add null manually
printf("%s", str2); // Output: Progr

4. strcat() – Concatenate Strings


 Joins two strings (appends at the end).
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
printf("%s", str1); // Output: Hello World

5. strncat() – Concatenate with Limit


 Joins only n characters.
char str1[20] = "Hello ";
char str2[] = "Everyone";
strncat(str1, str2, 5);
printf("%s", str1); // Output: Hello Every

6. strcmp() – Compare Strings


 Compares two strings lexicographically.
 Returns:
o 0 → if equal
o <0 → if str1 < str2
o >0 → if str1 > str2
char s1[] = "Apple";
char s2[] = "Banana";
int result = strcmp(s1, s2);
printf("%d", result); // Negative (because Apple < Banana)

7. strncmp() – Compare with Limit


 Compares first n characters.
char s1[] = "Hello";
char s2[] = "Helium";
printf("%d", strncmp(s1, s2, 3)); // Output: 0 (first 3 same)

8. strchr() – Find First Occurrence of Character


 Returns pointer to first occurrence.
char str[] = "Programming";
char *p = strchr(str, 'g');
printf("%s", p); // Output: gramming
9. strrchr() – Find Last Occurrence of Character
char str[] = "Programming";
char *p = strrchr(str, 'g');
printf("%s", p); // Output: g

10. strstr() – Find Substring


char str[] = "Hello World";
char *p = strstr(str, "World");
printf("%s", p); // Output: World

11. strtok() – Tokenize String


 Splits a string into tokens based on delimiters.
#include <stdio.h>
#include <string.h>

int main() {
char str[] = "C,Java,Python";
char *token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}

Output:
C
Java
Python

12. memset() – Fill Memory with Character


char str[20];
memset(str, '*', 5);
str[5] = '\0';
printf("%s", str); // Output: *****

13. memcpy() – Copy Memory Block


char src[] = "Hello";
char dest[20];
memcpy(dest, src, strlen(src)+1);
printf("%s", dest); // Output: Hello

 Summary Table of Common String Functions


Function Purpose
strlen() Get length of string
strcpy() Copy string
strncpy() Copy with limit
strcat() Concatenate
strncat() Concatenate with limit
strcmp() Compare strings
strncmp() Compare with limit
strchr() Find first char
strrchr() Find last char
strstr() Find substring
strtok() Split string
memset() Fill memory
memcpy() Copy memory

7. Pointer Arithmetic.
What is Pointer Arithmetic?
A pointer is a variable that stores the memory address of another variable.
In C, we can perform arithmetic operations on pointers, but they behave differently from normal
integers.
 The allowed pointer arithmetic operations are:
1. Increment (++) and Decrement (--)
2. Addition (+) and Subtraction (-) with integers
3. Subtraction of two pointers
4. Comparison of two pointers

7.1. Increment and Decrement


When a pointer is incremented (ptr++), it moves to the next memory location of its data type.
Example:
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *p = arr;

printf("Address: %p, Value: %d\n", p, *p); // arr[0]


p++; // moves to next int (4 bytes ahead)
printf("Address: %p, Value: %d\n", p, *p); // arr[1]
return 0;
}
 If p is an int*, then p++ increases the address by 4 bytes (on 32-bit/64-bit systems).
If p is a char*, then p++ increases by 1 byte.

7.2. Pointer + Integer (Addition and Subtraction)


You can add or subtract an integer n to a pointer → it moves n elements forward/backward.
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;

printf("%d\n", *(p + 2)); // 30


printf("%d\n", *(p + 4)); // 50
printf("%d\n", *(p + 1)); // 20
Here p + 2 means "move 2 integers ahead from the base address".

7.3. Subtracting Two Pointers


Subtracting two pointers gives the number of elements between them, not the byte difference.
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[1]; // points to 20
int *q = &arr[4]; // points to 50
printf("Difference = %ld\n", q - p); // 3 elements apart

7.4. Pointer Comparisons


You can compare two pointers that point to elements of the same array.
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[0];
int *q = &arr[3];

if (p < q)
printf("p comes before q\n");
7.5. Example: Traversing Array with Pointer Arithmetic
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;

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


printf("Element %d = %d\n", i, *(p + i));
}
return 0;
}
Output:
Element 0 = 10
Element 1 = 20
Element 2 = 30
Element 3 = 40
Element 4 = 50

✅ Key Rules of Pointer Arithmetic


1. p++ → moves pointer to next element.
2. p-- → moves pointer to previous element.
3. p + n → moves pointer forward by n elements.
4. p - n → moves pointer backward by n elements.
5. q - p → gives number of elements between q and p.
6. Comparisons (<, >, ==) are valid only within the same array.

You might also like