0% found this document useful (0 votes)
7 views70 pages

C Program Structure and Loop Concepts

The document outlines the structure and components of a C program, including sections such as documentation, link, definition, global declaration, main function, and user-defined functions. It provides examples of C programs for finding the largest of three numbers, checking if a number is even or odd, and explains decision-making in algorithms with flowcharts. Additionally, it covers loop design principles, comparisons of loop types, and demonstrates array manipulation through function arguments.

Uploaded by

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

C Program Structure and Loop Concepts

The document outlines the structure and components of a C program, including sections such as documentation, link, definition, global declaration, main function, and user-defined functions. It provides examples of C programs for finding the largest of three numbers, checking if a number is even or odd, and explains decision-making in algorithms with flowcharts. Additionally, it covers loop design principles, comparisons of loop types, and demonstrates array manipulation through function arguments.

Uploaded by

katam.john1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT -1

1. Explain the general form of a C program with a neat diagram.

A C program follows a fixed and logical structure. Each part has a specific role, and
programs usually execute from top to bottom.

General Structure of a C Program

+----------------------------------+

| Documentation Section |

| (Comments about program) |

+----------------------------------+

| Link Section |

| (#include header files) |

+----------------------------------+

| Definition Section |

| (#define constants, macros) |

+----------------------------------+

| Global Declaration Section |

| (Global variables & functions) |

+----------------------------------+

| main() Function |

| +----------------------------+ |

| | Declaration Part ||

| | Executable Statements ||

| +----------------------------+ |

+----------------------------------+

| User Defined Functions |

| (Optional functions) |
+----------------------------------+

Explanation of Each Section

1. Documentation Section

• Contains comments describing the program.

• Helps others understand the purpose of the program.

/* Program to add two numbers */

2. Link Section

• Includes header files needed for the program.

• Example:

#include <stdio.h>

3. Definition Section

• Used to define constants or macros.

#define PI 3.14

4. Global Declaration Section

• Declares global variables and function prototypes.

• These can be used anywhere in the program.

int x, y;

5. main() Function

• Heart of the C program

• Program execution starts from main().

Inside main():

a) Declaration Part

• Variables used inside main() are declared here.


int a, b, sum;

b) Executable Statements

• Logic of the program (calculations, input/output).

sum = a + b;

printf("%d", sum);

6. User Defined Functions

• Functions written by the programmer.

• Called from main() if needed.

void display() {

printf("Hello");

Simple Example Program

#include <stdio.h>

int main()

int a = 5, b = 3, sum;

sum = a + b;

printf("Sum = %d", sum);

return 0;

Key Points to Remember

• Execution always starts from main()

• Each statement ends with ;

• { } define the block of code


• Header files are mandatory for input/output functions

[Link] a C program to find the largest of three numbers using if statements.


#include <stdio.h>

int main()

int a, b, c;

// Input three numbers

printf("Enter three numbers: ");

scanf("%d %d %d", &a, &b, &c);

// Checking the largest number using if statements

if (a > b && a > c)

printf("Largest number is %d", a);

else if (b > a && b > c)

printf("Largest number is %d", b);

else

printf("Largest number is %d", c);

return 0;
}

Explanation

1. #include <stdio.h>
→ Includes input/output functions.

2. int a, b, c;
→ Declares three integer variables.

3. scanf("%d %d %d", &a, &b, &c);


→ Takes three numbers from the user.

4. if (a > b && a > c)


→ Checks if a is greater than both b and c.

5. else if (b > a && b > c)


→ Checks if b is the largest.

6. else
→ If both conditions fail, c is the largest.

7. return 0;
→ Ends the program successfully.

3. Explain if statements with compound statements using an example.


What is an if Statement?

An if statement is a decision-making statement in C.


It executes a block of code only when a condition is true.

What is a Compound Statement?

A compound statement is a group of multiple statements enclosed within braces {


}.
It is also called a block of statements.

When we want to execute more than one statement under an if, we must use a
compound statement.

Syntax of if with Compound Statement

if (condition)

{
statement1;

statement2;

statement3;

• { } combine multiple statements into one logical unit

• All statements inside { } execute only if the condition is true

Example Program

Program to check whether a number is positive

#include <stdio.h>

int main()

int num;

printf("Enter a number: ");

scanf("%d", &num);

if (num > 0)

printf("The number is positive\n");

printf("You entered %d", num);

return 0;

Explanation (Line by Line)


1. int num;
→ Declares an integer variable.

2. scanf("%d", &num);
→ Takes input from the user.

3. if (num > 0)
→ Checks whether the number is greater than zero.

4. { ... }
→ Compound statement (block).

5. printf("The number is positive");


→ First statement executed if condition is true.

6. printf("You entered %d", num);


→ Second statement executed under the same if.

4. Describe decision steps in algorithms with a flowchart.


What is a Decision Step in an Algorithm?

A decision step is a point in an algorithm where a condition is tested, and based on


the result (true/false or yes/no), the flow of execution follows different paths.

Decision steps are used to make choices in algorithms.

Decision Symbol in Flowchart

• Decision steps are represented by a Diamond (◇) shape in a flowchart.

• It has:

o One input

o Two or more outputs (Yes/No, True/False)

Example Problem

Check whether a number is even or odd

Algorithm (Decision Steps Included)

1. Start

2. Read number n
3. Check condition n % 2 == 0

4. If true, print "Even"

5. Else, print "Odd"

6. Stop

Flowchart for Decision Step

┌──────────┐

│ Start │

└────┬─────┘

┌────▼─────┐

│ Read n │

└────┬─────┘

┌────▼─────┐

│ n % 2=0? │ ◇ Decision

└───┬───┬─┘

Yes No

│ │

┌──────▼┐ ┌──▼────┐

│ Print │ │ Print │

│ Even │ │ Odd │

└───────┘ └───────┘

│ │

└──┬──┘

┌─────▼─────┐

│ Stop │
└───────────┘

Explanation of Decision Step

• The diamond checks a condition

• If the condition is true, flow goes to the Yes branch

• If the condition is false, flow goes to the No branch

• Only one path executes at a time

Where Decision Steps are Used

• if statement

• if-else statement

• switch statement

• Loop conditions (while, for)

Key Exam Points

• Decision steps control the logic flow

• Represented using diamond symbol

• Outcome decides next step of execution

5. Write a program to check whether a given number is even or odd.


#include <stdio.h>

int main()
{
int num;

// Input from user


printf("Enter a number: ");
scanf("%d", &num);

// Checking even or odd


if (num % 2 == 0)
{
printf("The number is Even");
}
else
{
printf("The number is Odd");
}

return 0;
}

UNIT -II
1. Explain loop design principles with examples.

Loops are used to repeat a set of statements until a specified condition is satisfied.
Good loop design makes programs correct, readable, and efficient.

1. Initialization Principle

• Initialize the loop control variable before the loop starts.

• It decides the starting point of the loop.

Example

int i = 1; // initialization

2. Condition (Termination) Principle

• The loop must have a clear terminating condition.

• Prevents infinite loops.

Example

while (i <= 5) // condition

3. Update (Progress) Principle

• The loop variable must change in every iteration.

• Ensures the loop moves towards termination.

Example
i++; // update

4. Correct Choice of Loop

Choose the loop based on the problem:

Loop Used When

for Number of iterations is known

while Condition checked before execution

do-while Loop must execute at least once

5. Avoid Infinite Loops

• Always ensure the condition becomes false at some point.

Wrong Example (Infinite Loop)

int i = 1;

while (i <= 5)

printf("%d", i);

// missing i++

Example: Printing Numbers from 1 to 5

#include <stdio.h>

int main()

int i;

for (i = 1; i <= 5; i++)

{
printf("%d ", i);

return 0;

Explanation

• Initialization → i = 1

• Condition → i <= 5

• Update → i++

• Loop executes 5 times

Example Using do-while Loop

int i = 1;

do

printf("%d ", i);

i++;

} while (i <= 5);

• Executes at least once, even if condition is false initiallY

2. Write a C program to compute the sum of first n natural numbers using a loop.
#include <stdio.h>

int main()

int n, i;

int sum = 0;

// Input from user


printf("Enter the value of n: ");

scanf("%d", &n);

// Loop to calculate sum

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

sum = sum + i;

// Output

printf("Sum of first %d natural numbers = %d", n, sum);

return 0;

3. Compare while, for, and do–while loops.


Comparison of while, for, and do–while Loops in C

Loops are used to execute a block of statements repeatedly based on a


condition.
The three main loops in C are while, for, and do–while.

Tabular Comparison (Exam-Oriented)

do–while
Feature while loop for loop
loop

Before Before loop After loop


Condition check
loop body body body

At least 1
Minimum executions 0 times 0 times
time
do–while
Feature while loop for loop
loop

Number of Number of Loop must


Best used when iterations iterations execute
not known known once

Done
Done Inside loop
Initialization before
before loop header
loop

Inside loop Inside loop Inside


Increment/Decrement
body header loop body

Compact & Slightly


Syntax simplicity Simple
structured longer

Not Not Required


Ending semicolon
required required after while

Syntax Comparison

1. while Loop

initialization;

while (condition)

statements;

update;

2. for Loop

for (initialization; condition; update)

statements;

}
3. do–while Loop

initialization;

do

statements;

update;

} while (condition);

Execution Example

Condition is false initially (i = 6)

int i = 6;

Loop Output

while (i <= 5) No output

for (; i <= 5; ) No output

do–while (i <= 5) Prints once

Key Differences in Words (Very Important for Exam)

• for loop
→ Best when the number of repetitions is known in advance.

• while loop
→ Used when repetitions depend on a condition.

• do–while loop
→ Used when loop body must execute at least once.

Conclusion

• Use for for counting loops

• Use while for condition-based loops

• Use do–while when minimum one execution is required


4. Write a program to print a multiplication table using nested loops.
#include <stdio.h>

int main()

int i, j;

// Outer loop for rows (1 to 10)

for (i = 1; i <= 10; i++)

// Inner loop for columns (1 to 10)

for (j = 1; j <= 10; j++)

printf("%4d", i * j);

// New line after each row

printf("\n");

return 0;

5. Write a program to read and print elements of an array using a for loop.
#include <stdio.h>

int main()

int arr[50];
int n, i;

// Read number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Reading array elements

printf("Enter %d elements:\n", n);

for (i = 0; i < n; i++)

scanf("%d", &arr[i]);

// Printing array elements

printf("Array elements are:\n");

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

return 0;

6. Explain passing arrays as arguments to functions

Passing Arrays as Arguments to Functions in C

In C, arrays can be passed to functions so that the function can access and
modify the array elements.
When an array is passed, the base address of the array is actually passed to the
function.
Why Pass Arrays to Functions?

• To avoid repeating code

• To perform operations like sum, search, sort

• To handle large data efficiently

How Arrays are Passed in C

• Array name represents the address of first element

• Changes made inside the function affect the original array

Syntax

return_type function_name(data_type array_name[], int size)

or

return_type function_name(data_type *array_name, int size)

Example Program

Program to Print Array Elements Using a Function

#include <stdio.h>

// Function declaration

void display(int arr[], int n);

int main()

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

// Passing array to function

display(a, 5);
return 0;

// Function definition

void display(int arr[], int n)

int i;

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

Explanation (Step-by-Step)

1. void display(int arr[], int n)


→ Function accepts an array and its size

2. display(a, 5);
→ Array name a passes base address

3. arr[i]
→ Accesses elements of original array

4. Any change in arr[] affects a[] in main()

Example Showing Modification

void update(int arr[])

arr[0] = 100;

int a[3] = {1, 2, 3};


update(a);

// a[0] becomes 100

Important Points (Exam Ready)

• Array name = base address

• Arrays are passed by reference

• Size must be passed separately

• Function parameters cannot store array size automatically

7. Write a program to find the largest element in an array.

#include <stdio.h>

int main()

int arr[100];

int n, i, j, temp;

// Read number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Read array elements

printf("Enter %d elements:\n", n);

for (i = 0; i < n; i++)

scanf("%d", &arr[i]);

}
// Bubble sort (ascending order)

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

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

if (arr[j] > arr[j + 1])

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

// Largest element will be at last position

printf("Largest element in the array = %d", arr[n - 1]);

return 0;

8. Explain enumerated data types with examples.


What is an Enumerated Data Type?

An enumerated data type (keyword: enum) is a user-defined data type in C


that consists of a set of named integer constants.

It is used when a variable can take only one value from a fixed set of
options.

Why Use enum?

• Improves code readability


• Makes programs easy to understand

• Reduces use of magic numbers

• Useful for menu-driven programs, days, directions, states

Syntax of enum

enum enum_name

constant1,

constant2,

constant3,

...

};

• By default:

o constant1 = 0

o constant2 = 1

o constant3 = 2

o and so on…

Example 1: Simple enum

#include <stdio.h>

enum day { MON, TUE, WED, THU, FRI, SAT, SUN };

int main()

enum day today;

today = WED;
printf("Value of WED = %d", today);

return 0;

Output

Value of WED = 2

Example 2: Assigning Custom Values

#include <stdio.h>

enum status { OFF = 0, ON = 1 };

int main()

enum status s;

s = ON;

if (s == ON)

printf("Device is ON");

else

printf("Device is OFF");

return 0;

Example 3: enum Used in a Switch Case

#include <stdio.h>
enum color { RED, GREEN, BLUE };

int main()

enum color c = GREEN;

switch (c)

case RED:

printf("Color is Red");

break;

case GREEN:

printf("Color is Green");

break;

case BLUE:

printf("Color is Blue");

break;

return 0;

Important Points (Exam Ready)

• enum constants are integers

• Values start from 0 by default

• You can assign custom values

• enum improves program clarity

• enum variables take only predefined values


Advantages

✔ Easy to read
✔ Less error-prone
✔ Better code maintenance

Limitations

✘ No string values
✘ Values are internally integers

UNIT - III
1. Explain top-down design with structure charts.

What is Top-Down Design?

Top-down design is a program design approach in which a complex problem is broken


down into smaller, manageable modules.
The design starts from the main problem and gradually moves downward into sub-
problems until each module is simple enough to be coded easily.

Also called stepwise refinement.

Key Idea

• Start with the overall system

• Divide it into sub-modules

• Each sub-module performs one specific task

• Continue dividing until no further breakdown is needed

What is a Structure Chart?

A structure chart is a graphical representation of top-down design.


It shows:

• The hierarchical relationship between modules

• How modules call each other


It does not show program logic, only module structure.

Symbols Used in Structure Charts

• Rectangle → Module / Function

• Lines → Calling relationship between modules

Example Problem

Design a program to calculate the total and average of student marks

Top-Down Decomposition

1. Main Program

2. Read Marks

3. Calculate Total

4. Calculate Average

5. Display Result

Structure Chart (Neat Diagram)

+------------------+

| MAIN PROGRAM |

+------------------+

/ | \

/ | \

+-------------+ +-----------+ +--------------+

| Read Marks | | Calculate | | Display |

| | | Total | | Result |

+-------------+ +-----------+ +--------------+

+-------------------+
| Calculate Average |

+-------------------+

Explanation of Structure Chart

• Main Program controls the entire execution

• Each rectangle is a separate module

• Lower-level modules perform specific tasks

• Easy to map each module to a function in C

Advantages of Top-Down Design

✔ Easy to understand
✔ Simplifies debugging and testing
✔ Encourages modular programming
✔ Easy maintenance and modification

Disadvantages

✘ Initial design takes more time


✘ Not suitable for very small programs

Key Exam Points

• Top-down design = divide and conquer

• Uses structure charts

• Structure charts show module hierarchy

• Helps in modular and structured programming

2. Write a C program using functions to find the factorial of a number.


#include <stdio.h>

// Function declaration

long int factorial(int n);


int main()

int num;

long int fact;

// Input from user

printf("Enter a number: ");

scanf("%d", &num);

// Function call

fact = factorial(num);

// Output

printf("Factorial of %d = %ld", num, fact);

return 0;

// Function definition

long int factorial(int n)

long int f = 1;

int i;

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

f = f * i;
}

return f;

3. Trace a recursive function to compute factorial.

Recursive Definition of Factorial

Factorial of a number n is defined as:

𝑛! = 𝑛 × (𝑛 − 1)!

with the base condition:

0! = 1

Recursive C Function for Factorial

#include <stdio.h>

int factorial(int n)

if (n == 0)

return 1;

else

return n * factorial(n - 1);

int main()

int num = 4;

int result;
result = factorial(num);

printf("Factorial = %d", result);

return 0;

Tracing the Function Call (Example: factorial(4))

Step-by-Step Function Calls

factorial(4)

= 4 * factorial(3)

= 4 * (3 * factorial(2))

= 4 * (3 * (2 * factorial(1)))

= 4 * (3 * (2 * (1 * factorial(0))))

= 4 * (3 * (2 * (1 * 1)))

= 4 * (3 * (2 * 1))

= 4 * (3 * 2)

=4*6

= 24

Call Stack Representation

Function Call Returned Value

factorial(0) 1

factorial(1) 1×1=1

factorial(2) 2×1=2

factorial(3) 3×2=6

factorial(4) 4 × 6 = 24
Flow of Execution

1. Function calls keep going deeper until base condition is met.

2. Once n == 0, function starts returning values.

3. Results are multiplied while unwinding the stack.

[Link] a recursive program to find Fibonacci series.


#include <stdio.h>

// Recursive function to find nth Fibonacci number

int fibonacci(int n)

if (n == 0)

return 0;

else if (n == 1)

return 1;

else

return fibonacci(n - 1) + fibonacci(n - 2);

int main()

int n, i;

// Input from user

printf("Enter number of terms: ");

scanf("%d", &n);

printf("Fibonacci series:\n");

for (i = 0; i < n; i++)


{

printf("%d ", fibonacci(i));

return 0;

[Link] different storage classes with examples.

Storage Classes in C (Explained with Examples)

Storage classes in C define scope, lifetime, visibility, and default value of variables.
There are four main storage classes:

1. auto

2. register

3. static

4. extern

1. auto Storage Class

Explanation

• Default storage class for local variables

• Scope: Within the block

• Lifetime: Till block execution

• Default value: Garbage

Example

#include <stdio.h>

int main()

auto int a = 10; // auto is optional

printf("a = %d", a);


return 0;

2. register Storage Class

Explanation

• Stores variable in CPU register (if possible)

• Faster access

• Address (&) cannot be used

Example

#include <stdio.h>

int main()

register int i;

for (i = 1; i <= 5; i++)

printf("%d ", i);

return 0;

3. static Storage Class

Explanation

• Retains value between function calls

• Default value: 0

• Scope depends on where declared

Example

#include <stdio.h>
void fun()

static int count = 0;

count++;

printf("count = %d\n", count);

int main()

fun();

fun();

fun();

return 0;

Output

count = 1

count = 2

count = 3

4. extern Storage Class

Explanation

• Used to access global variable defined in another file or same file

• Does not allocate memory again

Example

#include <stdio.h>

int x = 10; // global variable


int main()

extern int x;

printf("x = %d", x);

return 0;

Comparison Table (Exam-Friendly)

Storage Class Scope Lifetime Default Value

auto Block Block execution Garbage

register Block Block execution Garbage

static Block / Global Entire program 0

extern Global Entire program 0

Key Exam Points

• auto is default for local variables

• register improves speed

• static preserves value

• extern shares global variables

[Link] a program demonstrating call by value and call by reference.


CALL BY VALUE

#include <stdio.h>

// Function for call by value

void swapValue(int x, int y)

{
int temp;

temp = x;

x = y;

y = temp;

printf("Inside function (Call by Value): x = %d, y = %d\n", x, y);

int main()

int a = 10, b = 20;

printf("Before function call: a = %d, b = %d\n", a, b);

swapValue(a, b);

printf("After function call: a = %d, b = %d\n", a, b);

return 0;

CALL BY REFERENCE

#include <stdio.h>

// Function for call by reference

void swapReference(int *x, int *y)

int temp;

temp = *x;

*x = *y;

*y = temp;
printf("Inside function (Call by Reference): a = %d, b = %d\n", *x, *y);

int main()

int a = 10, b = 20;

printf("Before function call: a = %d, b = %d\n", a, b);

swapReference(&a, &b);

printf("After function call: a = %d, b = %d\n", a, b);

return 0;

7)Explain pointers to pointers with a suitable example.

A pointer to pointer is a variable that stores the address of another pointer.


It is also called a double pointer.

In simple words:

• Normal variable → stores a value

• Pointer → stores address of a variable

• Pointer to pointer → stores address of a pointer

Declaration

int **pp;

• pp → pointer to pointer to int

Memory Relationship

a → normal integer
p → pointer to a

pp → pointer to p

Example Program

#include <stdio.h>

int main()

int a = 10;

int *p;

int **pp;

p = &a; // p stores address of a

pp = &p; // pp stores address of p

printf("Value of a = %d\n", a);

printf("Using pointer p = %d\n", *p);

printf("Using pointer to pointer pp = %d\n", **pp);

return 0;

Output

Value of a = 10

Using pointer p = 10

Using pointer to pointer pp = 10

Explanation (Step by Step)


1. int a = 10;
→ Normal integer variable.

2. int *p;
→ Pointer that can store address of an integer.

3. int **pp;
→ Pointer that can store address of pointer p.

4. p = &a;
→ p points to a.

5. pp = &p;
→ pp points to p.

6. *p
→ Value of a.

7. **pp
→ Value of a through double pointer.

8. Write a program to dynamically allocate memory using malloc() and free().


#include <stdio.h>

#include <stdlib.h> // for malloc() and free()

int main()

int *ptr;

int n, i;

// Read number of elements

printf("Enter number of elements: ");

scanf("%d", &n);

// Dynamic memory allocation

ptr = (int *)malloc(n * sizeof(int));


// Check if memory allocation is successful

if (ptr == NULL)

printf("Memory allocation failed");

return 1;

// Read elements

printf("Enter %d elements:\n", n);

for (i = 0; i < n; i++)

scanf("%d", &ptr[i]);

// Display elements

printf("You entered:\n");

for (i = 0; i < n; i++)

printf("%d ", ptr[i]);

// Free dynamically allocated memory

free(ptr);

return 0;

9. Explain functions returning pointers with examples.


A function returning a pointer means the return value of the function is an address,
not a normal value.

The function returns the memory address of a variable, array, or dynamically


allocated memory.

Why Use Functions Returning Pointers?

• To return arrays or strings

• To return dynamic memory

• To improve efficiency

• To share memory between functions

General Syntax

data_type *function_name(parameters);

Example 1: Returning Pointer to the Largest Element

#include <stdio.h>

// Function returns pointer to largest element

int* findLargest(int arr[], int n)

int i;

int *max = &arr[0];

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

if (arr[i] > *max)

max = &arr[i];

}
return max;

int main()

int a[5] = {10, 25, 5, 40, 15};

int *p;

p = findLargest(a, 5);

printf("Largest element = %d", *p);

return 0;

Example 2: Returning Pointer to Dynamically Allocated Memory

#include <stdio.h>

#include <stdlib.h>

int* createArray(int n)

int *ptr = (int *)malloc(n * sizeof(int));

return ptr;

int main()

int *arr, i;
arr = createArray(3);

if (arr == NULL)

printf("Memory allocation failed");

return 1;

for (i = 0; i < 3; i++)

arr[i] = (i + 1) * 10;

for (i = 0; i < 3; i++)

printf("%d ", arr[i]);

free(arr);

return 0;

Important Rule (Very Important for Exam )

Never return the address of a local variable

Wrong Example

int* fun()

int x = 10;

return &x; // Wrong

}
✔ Local variables are destroyed after function ends.

Valid Things a Function Can Return

✔ Pointer to array
✔ Pointer to dynamically allocated memory
✔ Pointer to global or static variable

10. Discuss the role of pointers in modular programming


What is Modular Programming?
Modular programming is a programming approach where a large program is
divided into small, independent, reusable modules (functions).
Each module performs one specific task.

Why Pointers are Important in Modular Programming?


Pointers allow efficient data sharing and communication between modules
without copying large amounts of data.

Roles of Pointers in Modular Programming

1. Passing Data Between Functions (Call by Reference)


• Pointers allow functions to modify actual variables of another module.
Example
void update(int *x)
{
*x = 50;
}
✔ Changes made in one module affect another.

2. Efficient Handling of Arrays and Structures


• Arrays and structures are passed using pointers, not copied.
void display(int *arr, int n);
✔ Saves memory and execution time.

3. Dynamic Memory Sharing


• Pointers help modules share dynamically allocated memory.
int* create()
{
return (int *)malloc(sizeof(int));
}
✔ Memory created in one module used in another.

4. Returning Multiple Values


• Using pointers, a function can return more than one value.
void calc(int a, int b, int *sum, int *diff)
{
*sum = a + b;
*diff = a - b;
}

5. Data Abstraction and Encapsulation


• Pointers allow controlled access to data across modules.
• Enhances security and maintainability.

6. Support for Complex Data Structures


• Linked lists, trees, stacks, queues use pointers.
• These are often implemented as separate modules.

7. Reduced Code Redundancy


• Pointer-based functions can work on different data sizes and types.

Advantages of Using Pointers in Modular Programming


✔ Memory efficient
✔ Faster execution
✔ Reusability of code
✔ Better inter-module communication

Precautions
⚠ Avoid dangling pointers
⚠ Always initialize pointers
⚠ Free dynamically allocated memory

Key Exam Points


• Pointers enable call by reference
• Improve performance
• Essential for dynamic memory
• Core part of modular design
UNIT – IV
[Link] string handling functions with examples.

In C, strings are handled using library functions provided in the header file
#include <string.h>
A string is a character array terminated by the null character '\0'.

Commonly Used String Handling Functions

1. strlen() – Find Length of String


Purpose
Returns the number of characters in a string (excluding '\0').
Syntax
int strlen(char str[]);
Example
#include <stdio.h>
#include <string.h>

int main()
{
char s[] = "Hello";
printf("Length = %d", strlen(s));
return 0;
}
Output
Length = 5

2. strcpy() – Copy One String to Another


Purpose
Copies one string into another.
Syntax
char* strcpy(char dest[], char src[]);
Example
#include <stdio.h>
#include <string.h>

int main()
{
char src[] = "C Language";
char dest[20];
strcpy(dest, src);
printf("Copied string: %s", dest);

return 0;
}

3. strcat() – Concatenate (Join) Strings


Purpose
Appends one string to the end of another.
Syntax
char* strcat(char dest[], char src[]);
Example
#include <stdio.h>
#include <string.h>

int main()
{
char s1[20] = "Hello ";
char s2[] = "World";

strcat(s1, s2);
printf("Result: %s", s1);

return 0;
}
Output
Result: Hello World

4. strcmp() – Compare Two Strings


Purpose
Compares two strings lexicographically.
Syntax
int strcmp(char s1[], char s2[]);
Return Values
• 0 → strings are equal
• < 0 → first string is smaller
• > 0 → first string is greater
Example
#include <stdio.h>
#include <string.h>
int main()
{
char a[] = "Apple";
char b[] = "Apple";

if (strcmp(a, b) == 0)
printf("Strings are equal");
else
printf("Strings are not equal");

return 0;
}

5. strrev() – Reverse a String


(Compiler dependent – works in Turbo C / some compilers)
Example
#include <stdio.h>
#include <string.h>

int main()
{
char s[] = "HELLO";
printf("Reverse = %s", strrev(s));
return 0;
}

6. strlwr() and strupr() – Change Case


(Also compiler dependent)
strlwr(s); // converts to lowercase
strupr(s); // converts to uppercase

Summary Table (Exam-Friendly)


Function Purpose

strlen() Find length of string

strcpy() Copy string

strcat() Join strings


Function Purpose

strcmp() Compare strings

strrev() Reverse string

strlwr() Lowercase

strupr() Uppercase

Key Exam Points


• All string functions are in string.h
• Strings end with '\0'
• Destination array must be large enough
• strcmp() compares ASCII values

[Link] a program to reverse a string.


#include <stdio.h>
#include <string.h>

int main()
{
char str[50], rev[50];
int i, j = 0, len;

printf("Enter a string: ");


gets(str);

len = strlen(str);

for (i = len - 1; i >= 0; i--)


{
rev[j++] = str[i];
}
rev[j] = '\0';

printf("Reversed string: %s", rev);

return 0;
}
[Link] a program to compare two strings.
#include <stdio.h>
#include <string.h>

int main()
{
char str1[50], str2[50];

// Input strings
printf("Enter first string: ");
gets(str1);

printf("Enter second string: ");


gets(str2);

// Compare strings
if (strcmp(str1, str2) == 0)
printf("Strings are equal");
else
printf("Strings are not equal");

return 0;
}
METHOD 2
#include <stdio.h>

int main()
{
char str1[50], str2[50];
int i = 0, flag = 0;

printf("Enter first string: ");


gets(str1);

printf("Enter second string: ");


gets(str2);

// Compare characters one by one


while (str1[i] != '\0' || str2[i] != '\0')
{
if (str1[i] != str2[i])
{
flag = 1;
break;
}
i++;
}

if (flag == 0)
printf("Strings are equal");
else
printf("Strings are not equal");

return 0;
}

[Link] whole-line input of strings in C.


Whole-line input means reading an entire line of text including spaces until a
newline (\n) is encountered.
Example input:
Hello World from C
Normal input functions like scanf("%s", str) cannot read spaces, so special
methods are used.

Why Whole-Line Input is Needed


• Reading sentences
• Reading addresses, names, messages
• User-friendly input

Methods for Whole-Line Input in C

1. gets() Function (Not Recommended )


Explanation
• Reads a full line including spaces
• Unsafe (buffer overflow risk)
• Removed from modern C standards
Example
char str[50];
gets(str);
⚠ Use only for exam understanding, not real programs.
2. fgets() Function (Recommended ✔)
Explanation
• Safest and standard method
• Reads up to n-1 characters
• Stops at newline or end of file
Syntax
fgets(str, size, stdin);
Example
#include <stdio.h>

int main()
{
char str[50];

printf("Enter a line: ");


fgets(str, 50, stdin);

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

return 0;
}

3. scanf() with Format Specifier


Explanation
• %[^\n] reads characters until newline
Example
#include <stdio.h>

int main()
{
char str[50];

printf("Enter a line: ");


scanf("%[^\n]", str);

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

return 0;
}
⚠ Does not consume newline; use carefully.
Comparison Table (Exam-Friendly)
Reads Recommended
Function Safety
Spaces

scanf("%s") No Safe

gets() ✔ Yes
Unsafe

fgets() ✔ Yes ✔ Safe ✔

scanf("%[^\n]") ✔ Yes Moderate ✔

Key Exam Points


• Whole-line input reads spaces
• fgets() is safest
• gets() is deprecated
• scanf("%s") stops at space

5, Write a program using structures to store student information

#include <stdio.h>

// Define structure
struct student
{
int roll_no;
char name[50];
float marks;
};

int main()
{
struct student s;

// Input student information


printf("Enter Roll Number: ");
scanf("%d", &s.roll_no);

printf("Enter Name: ");


scanf(" %[^\n]", [Link]); // reads whole line including spaces

printf("Enter Marks: ");


scanf("%f", &[Link]);

// Display student information


printf("\n--- Student Information ---\n");
printf("Roll Number : %d\n", s.roll_no);
printf("Name : %s\n", [Link]);
printf("Marks : %.2f\n", [Link]);

return 0;
}

[Link] passing structure variables to functions

In C, structure variables can be passed to functions just like normal variables.


There are two main methods:
1. Passing the entire structure (Call by Value)
2. Passing the address of the structure (Call by Reference)

1. Passing Entire Structure (Call by Value)


Explanation
• A copy of the structure is passed to the function.
• Changes made inside the function do not affect the original structure.
• Requires more memory.
Example
#include <stdio.h>

struct student
{
int roll;
float marks;
};

void display(struct student s)


{
printf("Roll = %d\n", [Link]);
printf("Marks = %.2f\n", [Link]);
}

int main()
{
struct student st = {101, 85.5};
display(st); // passing entire structure

return 0;
}

2. Passing Structure by Reference (Using Pointer)


Explanation
• Address of structure is passed.
• Changes inside the function affect the original structure.
• More efficient and commonly used.
Example
#include <stdio.h>

struct student
{
int roll;
float marks;
};

void update(struct student *s)


{
s->marks = 90.0; // arrow operator
}

int main()
{
struct student st = {101, 85.5};

update(&st); // passing address

printf("Updated Marks = %.2f", [Link]);

return 0;
}

Difference Between the Two Methods


Feature Call by Value Call by Reference

What is passed Copy of structure Address of structure

Memory usage More Less


Feature Call by Value Call by Reference

Original data Not modified Modified

Efficiency Less More

Key Exam Points


• Structures can be passed like variables
• Use pointer (struct *) for efficiency
• Arrow operator (->) used with structure pointers
1. Write a
program
to
demonstr
ate arrays
of
structure
s
#include <stdio.h>

// Define structure
struct student
{
int roll_no;
char name[50];
float marks;
};

int main()
{
struct student s[3]; // array of structures
int i;

// Input details for 3 students


for (i = 0; i < 3; i++)
{
printf("\nEnter details of student %d\n", i + 1);

printf("Roll Number: ");


scanf("%d", &s[i].roll_no);
printf("Name: ");
scanf(" %[^\n]", s[i].name); // whole-line input

printf("Marks: ");
scanf("%f", &s[i].marks);
}

// Display student details


printf("\n--- Student Details ---\n");
for (i = 0; i < 3; i++)
{
printf("\nStudent %d\n", i + 1);
printf("Roll Number : %d\n", s[i].roll_no);
printf("Name : %s\n", s[i].name);
printf("Marks : %.2f\n", s[i].marks);
}

return 0;
}
2. Explain
unions
with
memory
allocatio
n
diagram
A union is a user-defined data type similar to a structure, but with one key
difference:
All members of a union share the same memory location.
This means only one member can store a value at a time.

Syntax of Union
union union_name
{
data_type member1;
data_type member2;
data_type member3;
};

Example of Union
#include <stdio.h>
union data
{
int i;
float f;
char c;
};

int main()
{
union data d;

d.i = 10;
printf("i = %d\n", d.i);

d.f = 3.14;
printf("f = %.2f\n", d.f);

d.c = 'A';
printf("c = %c\n", d.c);

return 0;
}
⚠ Only the last assigned member holds a valid value.

Memory Allocation in Union


• Union size = size of the largest member
• All members use the same memory block
Example:
union data
{
int i; // 4 bytes
float f; // 4 bytes
char c; // 1 byte
};
Largest member = int or float = 4 bytes
So, union size = 4 bytes

Memory Allocation Diagram


Union data (4 bytes total memory)
+--------------------+
| i |
| f | ← All share SAME memory
| c |
+--------------------+
or more clearly:
Memory Block (4 bytes)
┌──────────────────┐
│ Shared Memory │ ← used by i / f / c
└──────────────────┘
When:
• d.i = 10 → memory holds integer
• d.f = 3.14 → integer value is overwritten
• d.c = 'A' → float value is overwritten

Union vs Structure (Important for Exams)


Feature Structure Union

Memory Separate for each Shared among


allocation member members

Size of largest
Size Sum of all members member

Access All members at once One member at a time

Memory More
Less
efficiency

Advantages of Union
✔ Saves memory
✔ Useful when only one value is needed at a time
✔ Used in embedded systems, compilers

Limitations
✘ Only one member valid at a time
✘ Careful programming required

Key Exam Points


• Union shares memory
• Size = largest data member
• Only last assigned value is valid
• Declared using keyword union

UNIT – V
1. Explain file handling concepts with examples.
What is File Handling?
File handling in C allows a program to store data permanently in files and
retrieve it later.
Unlike variables, file data is not lost when the program ends.

Types of Files in C
1. Text Files – Data stored as characters
o Example: .txt
2. Binary Files – Data stored in binary form
o Example: .dat

Basic Steps in File Handling


1. Declare a file pointer
2. Open a file
3. Perform file operations (read/write)
4. Close the file

1. File Pointer
FILE *fp;
• FILE is a structure defined in <stdio.h>
• fp points to a file

2. Opening a File – fopen()


Syntax
fp = fopen("filename", "mode");
File Modes
Mode Meaning

r Read

w Write

a Append

r+ Read & write


Mode Meaning

w+ Read & write (overwrite)

a+ Read & append

Example: Opening a File


fp = fopen("[Link]", "w");

3. Writing to a File
Using fprintf()
fprintf(fp, "Hello C File");
Example
#include <stdio.h>

int main()
{
FILE *fp;

fp = fopen("[Link]", "w");

fprintf(fp, "Welcome to C file handling");

fclose(fp);

return 0;
}

4. Reading from a File


Using fscanf()
fscanf(fp, "%s", str);
Example
#include <stdio.h>

int main()
{
FILE *fp;
char str[50];

fp = fopen("[Link]", "r");
fscanf(fp, "%s", str);
printf("%s", str);

fclose(fp);

return 0;
}

5. Character-Based File Functions


Function Purpose

fgetc() Read one character

fputc() Write one character

Example
char ch = fgetc(fp);
fputc(ch, fp);

6. File Closing – fclose()


fclose(fp);
• Frees file resources
• Prevents data loss

7. Checking File Errors


if (fp == NULL)
{
printf("File cannot be opened");
}

Key Exam Points


• File pointer is mandatory
• fopen() opens a file
• Always close files
• Use correct file mode

2. Write a program to read and write data into a file.


#include <stdio.h>

int main()
{
FILE *fp;
char data[100];

// Writing data into file


fp = fopen("[Link]", "w");

if (fp == NULL)
{
printf("File cannot be opened for writing\n");
return 1;
}

printf("Enter data to write into file:\n");


fgets(data, sizeof(data), stdin);

fputs(data, fp);
fclose(fp);

// Reading data from file


fp = fopen("[Link]", "r");

if (fp == NULL)
{
printf("File cannot be opened for reading\n");
return 1;
}

printf("\nData read from file:\n");


fgets(data, sizeof(data), fp);
printf("%s", data);

fclose(fp);

return 0;
}

3. Write a program to append data to an existing file.


#include <stdio.h>

int main()
{
FILE *fp;
char data[100];

// Open file in append mode


fp = fopen("[Link]", "a");

if (fp == NULL)
{
printf("File cannot be opened\n");
return 1;
}

// Input data
printf("Enter data to append into file:\n");
fgets(data, sizeof(data), stdin);

// Append data to file


fputs(data, fp);

fclose(fp);

printf("Data appended successfully");

return 0;
}

4. Explain random access file operations with a program.


What is Random Access in Files?
Random access allows a program to move the file pointer to any desired
position in a file and read or write data without reading the file sequentially
from the beginning.
This is very useful when:
• Files are large
• Specific records need to be accessed or modified

Functions Used for Random Access


1. fseek()
Moves the file pointer to a specified location.
fseek(FILE *fp, long offset, int origin);
• offset → number of bytes to move
• origin → starting point
Origin Meaning

SEEK_SET Beginning of file

SEEK_CUR Current position

SEEK_END End of file

2. ftell()
Returns the current position of file pointer.
long pos = ftell(fp);

3. rewind()
Moves file pointer back to the beginning of the file.
rewind(fp);

Example Program: Random Access File Operation


Program to Write Integers and Read a Specific Position
#include <stdio.h>

int main()
{
FILE *fp;
int num;
long position;

// Open file in write mode


fp = fopen("[Link]", "w+");

if (fp == NULL)
{
printf("File cannot be opened");
return 1;
}

// Write numbers into file


for (num = 1; num <= 5; num++)
{
fprintf(fp, "%d ", num * 10);
}
// Move file pointer to beginning
rewind(fp);

// Move to 3rd number (random access)


fseek(fp, 6, SEEK_SET); // skips first two numbers and spaces

fscanf(fp, "%d", &num);

printf("Number read using random access = %d\n", num);

// Show current position


position = ftell(fp);
printf("Current file pointer position = %ld\n", position);

fclose(fp);

return 0;
}

Explanation of Program
1. fopen("[Link]", "w+")
→ Opens file for read and write.
2. fprintf()
→ Writes numbers into file.
3. rewind(fp)
→ Moves file pointer to beginning.
4. fseek(fp, 6, SEEK_SET)
→ Moves file pointer 6 bytes from start.
5. fscanf()
→ Reads data from that position.
6. ftell()
shows current pointer location

3. Compare
linear
search
and
binary
search.
1. Linear Search
Explanation
• Searches elements one by one from the beginning.
• Stops when the element is found or list ends.
• Does not require sorted data.
Example
Array: 10 25 30 45 50
Search 30 → check 10 → 25 → 30 (found)

2. Binary Search
Explanation
• Works by dividing the list into halves.
• Requires the list to be sorted.
• Much faster for large datasets.
Example
Sorted Array: 10 25 30 45 50
Search 30 → middle = 30 (found)

Comparison Table (Exam-Oriented)


Feature Linear Search Binary Search

Data requirement Can be unsorted Must be sorted

Divide and
Searching method Sequential conquer

Time complexity (Best) O(1) O(1)

Time complexity O(log n)


O(n)
(Average)
Time complexity (Worst) O(n) O(log n)

Implementation Simple Slightly complex

Efficiency Low for large data High for large data

Small or unsorted Large, sorted lists


Use case
lists

Advantages & Disadvantages


Linear Search
✔ Simple to implement
✔ Works on unsorted data
✘ Slow for large datasets
Binary Search
✔ Very fast
✔ Efficient for large data
✘ Requires sorted data

4. Compare
bubble
sort,
insertion
sort and
selection
sort.
Comparison of Bubble Sort, Insertion Sort, and Selection Sort

Sorting algorithms arrange data in ascending or descending order.


Bubble sort, insertion sort, and selection sort are simple sorting techniques,
commonly asked in exams.

1. Bubble Sort

Working

• Compares adjacent elements

• Swaps them if they are in the wrong order

• Largest element “bubbles” to the end in each pass

Time Complexity

• Best: O(n) (already sorted)

• Average: O(n²)

• Worst: O(n²)

2. Insertion Sort

Working

• Builds sorted list one element at a time

• Inserts each element into its correct position

Time Complexity
• Best: O(n) (already sorted)

• Average: O(n²)

• Worst: O(n²)

3. Selection Sort

Working

• Finds the smallest element

• Places it at the correct position

• Repeats for remaining elements

Time Complexity

• Best: O(n²)

• Average: O(n²)

• Worst: O(n²)

Comparison Table (Exam-Oriented)

Feature Bubble Sort Insertion Sort Selection Sort

Swap adjacent Insert element in sorted Select minimum and


Basic idea
elements part swap

Comparisons Many Less Fixed

Swaps More Less Minimum

Best case O(n) O(n) O(n²)

Average case O(n²) O(n²) O(n²)

Worst case O(n²) O(n²) O(n²)

Stable Yes Yes No

Adaptive Yes Yes No

Suitable for Very small data Nearly sorted data Small datasets
Advantages & Disadvantages

Bubble Sort

✔ Easy to understand
✘ Very slow

Insertion Sort

✔ Efficient for small & nearly sorted data


✘ Not suitable for large datasets

Selection Sort

✔ Minimum swaps
✘ Always slow

*****programs on linear search, binary search and its explanations or methods

*****programs on bubble sort, insertion sort, selection sort and its explanations or
methods

You might also like