[go: up one dir, main page]

0% found this document useful (0 votes)
4 views165 pages

Structure Programming

programación estructurada
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)
4 views165 pages

Structure Programming

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

Structure

Programming
COURSE CODE: CSE -0611-1103

Prepared By,
M d Zahid Akon
Lecturer
Department of CSE
CLO’S
Understand the Utilize Pointers and Manage
Fundamental Concepts of 01 04
Memory Dynamically
C Programming

Apply Control Structures in Implement Structures and


Program Development
02 05
Unions for Complex Data

Develop Modular Handle Files for Data


Programs Using 03 06
Functions and Array Storage and Retrieval
Summary of Course Content:
Sl Topics Hours CLOs
no

Introduction
3 CLO1
1 to C Programming: Syntax, Data Types, and Operators

Input/Output
3 CLO1
2 Operations, Basic Programs
im

Control
4 CLO1,
3 Flow: If-Else, Switch, Loops (For, While, Do-While) CLO2

Functions:
4 CLO2,
4 User-defined, Recursion, and Storage Classes CLO3

Arrays:
5 3 CLO3
Single-Dimensional and Multi-Dimensional
Summary of Course Content:
Sl Topics Hours CLOs
no

Strings
6 3 CLO3
and String Handling Functions

im
Pointers:
7 4 CLO4
Basics, Pointer Arithmetic, and Dynamic Memory Allocation

Structures,
8 4 CLO5
Enumerations, and Unions

File
9 4 CLO6
Handling: Read, Write, Append Modes

Debugging
10 3 CLO1-CLO6
and Error Handling
Recommended Books

PROGRAMMING IN ANSI C THE C PROGRAMMING LANGUAGE

1.E. Balagurusamy, Tata McGraw-Hill 1.B.W. Kernighan and D.M. Ritchie,


(ISBN: 9781259004612) 2nd Edition, Prentice Hall (ISBN:
9780131103627)
Lecture

INCLASS ASSESSMENT
Q&A

Assessment
Pattern

BRAIN STROMING PRACTICAL EXCERSISE

GROUP WORK
Course Plan
Week Topics Teaching Strategy(s) Assessment Alignment to
Strategy(s) CLO
1 Introduction to C Programming, Data Lecture, Q&A, In-class Participation, Quiz CLO1
Types, Operators Examples

2 Input/Output Operations, Basic Lecture ,Practical Exercises, Short Assignment, Quiz CLO1
Programs Group Discussions

3 Control Flow Statements: If-Else, Switch Lecture ,Live Coding, Quiz, Problem-solving CLO1, CLO2
Problem-Solving Tasks

4 Loops Lecture ,Live Coding, Quiz, Problem-solving CLO1, CLO2


Problem-Solving Tasks

5 Functions: User-defined, Recursion Interactive Lectures, Case Group Task, Quiz CLO2, CLO3
Studies

6 Arrays: Single-Dimensional, Multi- Lecture ,Exercises, Real- Quiz, Assignment CLO3


Dimensional world Examples
Course Plan
Week Topics Teaching Assessment Alignment to CLO
Strategy(s) Strategy(s)
7 Strings Lecture ,Code Assignment, Group CLO3
Demonstrations, Discussion
Hands-on Tasks

8 String Handling Functions Lecture ,Code Quiz, Assignment CLO3


Demonstrations,
Practical Labs

9 Pointers: Basics, Arithmetic, Lecture, Practical Lab Performance CLO4


Sessions Evaluation, Quiz
10 Dynamic Memory Allocation Lecture, Practical Lab Performance CLO4
Sessions Evaluation, Quiz
11 Structures, Enumerations, and Lecture, Group Group Task, CLO5
Unions Activities Assignment

12 File Handling: Read, Write, Append Lab Demonstrations, Lab Report, Quiz CLO6
Modes Code Reviews
Course Plan
Week Topics Teaching Strategy(s) Assessment Strategy(s) Alignment to CLO

13 Debugging and Error Handling Revision, Practical In-class Practice, Final CLO1-CLO6
Debugging Challenges Exam

14 Advanced Functions and Macros Lecture, Practical Quiz, Assignment CLO2, CLO3
Exercises

15 Advanced Pointer Techniques Lecture, Hands-on Quiz, Problem-Solving CLO4


Practice Task

16 Project Integration and Review Project-based Learning, Project Evaluation CLO1-CLO6


Group Work

17 Final Exam and Project Submission Written Exam, Project Final Exam, Project CLO1-CLO6
Presentation Grading
Week 1

Chapter 1
Introduction to C
Programming, Data
Types, Operators
Structured programming
Structured programming (sometimes known as modular programming) is a subset of procedural

programming that enforces a logical structure on the program being written to make it more

efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBASE

are designed with features that encourage or enforce a logical program structure.
Why is C called a structured
programming language?
C is called a structured programming
language because to solve a large problem,
C programming language divides the
problem into smaller modules called functions
or procedures each of which handles a
particular responsibility. The program which
solves the entire problem is a collection of
such functions.
My First Program
Data Types in C
A data type is an attribute associated with a
piece of data that tells a computer system how to
interpret its value. Understanding data types
ensures that data is collected in the preferred
format and that the value of each property is as
expected

• int: Stores integers (e.g., int age = 25;)

• float: Stores decimal numbers (e.g., float price = 12.99;)

• double: Stores large decimals (e.g., double pi =

3.141592;)

• char: Stores single characters (e.g., char grade = 'A';)


Format specifiers in C
Format specifiers are used in functions like printf and scanf to input or output values of different
data types.
Specifier Data Type Example
%d Integer printf("%d", 10);
(decimal)
%f Floating-point printf("%.2f",
3.14);
%c Character printf("%c", 'A');
%s String printf("%s",
"Hello");
%lf Double printf("%lf",
3.14159);
%x Hexadecimal printf("%x", 255);
integer
%o Octal integer printf("%o", 8);
Variables in C
•A variable is a named memory location used to store data.
•Its value can change during program execution.

data_type variable_name = value; // defining single variable


or
data_type variable_name1, variable_name2; // defining multiple
variable
• data_type: Type of data that a variable can store.
• variable_name: Name of the variable given by the user.
• value: value assigned to the variable by the user.
Identifiers In C
• An identifier can include letters (a-z or A-Z), and digits (0-
9).
• An identifier cannot include special characters except the
‘_’ underscore.
• Spaces are not allowed while naming an identifier.
• An identifier can only begin with an underscore or letters.
• We cannot name identifiers the same as keywords
because they are reserved words to perform a specific
task. For example, printf, scanf, int, char, struct, etc. If we
use a keyword’s name as an identifier the compiler will
throw an error.
• The identifier must be unique in its namespace.
• C language is case-sensitive so, ‘name’ and ‘NAME’ are
different identifiers.
Operators
Week 2

Input/Output
Operations,
Basic Programs
Basic Input and Output in C
C language has standard libraries that allow input and output in a program. The stdio.h or standard
input output library in C that has methods for input and output

scanf() printf()

The scanf() method, in C, reads the value The printf() method, in C, prints the value
from the console as per the type specified passed as the parameter to it, on the
and store it in the given address. console screen.

Syntax: Syntax:

scanf("%X", &variableOfXType); printf("%X", variableOfXType);


Simple C program to display "Hello
World"
Explanation:

•#include <stdio.h> – This line includes the standard


input-output library in the program.

•int main() – The main function where the execution


of the program begins.

•printf(“Hello, World!\n”); – This function call prints


“Hello, World!” followed by a new line.

•return 0; -This statement indicates that the program


ended successfully.
Print an Integer Value in C
#include <stdio.h>

// Driver code
int main()
{
// Declaring integer
int x = 5;

// Printing values
printf("Printing Integer value %d", x);
return 0;
}
C program to add two numbers
#include <stdio.h>

int main() {
int a, b, sum = 0;

// Read two numbers from the user


printf("Enter two integers: ");
scanf("%d %d", &a, &b);

// Calculate the addition of a and b


// using '+' operator
sum = a + b;

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

return 0;
}
C Program to Swap Two Numbers
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;

// Swapping values of a and b


temp = a;
a = b;
b = temp;

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


return 0;
}
C Program to
Swap Two
Numbers WithOut
using Third
Variables.
Week 3

Chapter 3
Conditional S tatements in C
Unlock the Power of Decision-Making in Your C Programs
Introduction to Conditional Statements
Controlling Program Flow

Conditional statements dictate which code block executes based


on specific conditions

Decision-Making Power

Allow your programs to react to different inputs, scenarios, and


events
The If S tatement: S yntax and Examples

Bas ic Syntax Example

if (condition) { #include
// Code to execute if condition is true int main() {
} int num = 10;
if (num > 5) {
printf("Number is greater than 5\n");
}
return 0;
}
The Else If Statement: Nested Conditional Logic
Adding Another Condition Example

if (condition1) { #include
// Code to execute if condition1 is true int main() {
} else if (condition2) { int num = 7;
// Code to execute if condition2 is true if (num > 10) {
} printf("Number is greater than 10\n");
} else if (num > 5) {
printf("Number is greater than 5\n");
}
return 0;
}
The Els e If L adder: Chaining Multiple Conditions
Chain of Checks Example

if (condition1) { #include
// Code to execute if condition1 is true int main() {
} else if (condition2) { int grade = 85;
// Code to execute if condition2 is true if (grade >= 90) {
} else if (condition3) { printf("A\n");
// Code to execute if condition3 is true } else if (grade >= 80) {
} ... printf("B\n");
} else if (grade >= 70) {
printf("C\n");
} else {
printf("D\n");
}
return 0;
}
The Switch Statement: Handling Multiple Cases
Multiple Case Choices Example

switch (expression) { #include


case value1: int main() {
// Code to execute for value1 char grade = 'B';
break; switch (grade) {
case value2: case 'A':
// Code to execute for value2 printf("Excellent!\n");
break; break;
default: case 'B':
// Code to execute if no case matches printf("Good!\n");
} break;
case 'C':
printf("Fair!\n");
break;
default:
printf("Invalid grade!\n");
}
return 0;
}
Graphical Repres entation of Conditional
S tatements

1 Decis ion Points

2 Branching Paths

3 Code Execution
Conditional Statement Examples with Code and Output
Example 1 Example 2

if (age >= 18) { switch (day) {


printf("You are eligible to vote\n"); case 1:
} else { printf("Monday\n");
printf("You are not eligible to vote\n"); break;
} case 2:
printf("Tuesday\n");
break;
Output: You are eligible to vote default:
printf("Invalid day\n");
}

Output: Monday
Choos ing the Appropriate Conditional
S tatement
1 If/E lse If L adder
For a sequence of related
conditions

2 Switch Statement
For handling specific cases of
a single variable

3 Nested If/E lse If


For complex conditions with multiple levels of logic
B es t Practices and Tips for Conditional
S tatements

Clear L ogic Proper Indentation Use Comments

Make your conditions easy to understand Improves readability and maintains code Explain the purpose and functionality of
and follow structure your code
Week 4
Chapter 4
Loop

Dive into the world of loops in C programming, exploring their syntax, structure,
and applications.
Introduction to Loops in C

Repetitive Tas ks
Loops automate the execution of a
block of code multiple times, simplifying
repetitive tasks.

Iteration Control
They allow you to control the number of
iterations, ensuring precise execution
based on conditions.
The for Loop: Syntax and Structure

for (initialization; condition; increment) {


// Code to be executed
}
The while Loop: Conditional
Execution

while (condition) {
// Code to be executed
}
The do-while Loop: Pos t-
Condition Checking
do {
// Code to be executed
} while (condition);
Nested Loops: Combining Loops

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


for (int j = 0; j < 3; j++) {
// Code to be executed
}
}
Loop Control S tatements:
break and continue
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop
} else if (i % 2 == 0) {
continue; // Skip to the next iteration
}
// Code to be executed
}
Graphical Representation of
Loop Execution

Visualize loop execution through animations and diagrams,

understanding how loops work and the flow of control.


Example Code: Printing a
S tar Pattern
#include

int main() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Output Demonstration:
Visualizing the Loop

See the output in action, demonstrating the pattern created by the loop and how
it iterates to produce the desired result.
F unctions: User-defined,
R ecursion
This presentation dives into the world of functions in C programming, exploring
user-defined functions and the powerful concept of recursion.
What are Functions?

Modular Code

Break down a program into smaller, reusable units

Code Organization
Improve readability and maintainability
Syntax and Structure of User-
defined Functions

return_type function_name(parameter_list) {
// Function body
// Statements to perform
return value;
}
Defining and Calling F unctions

int add(int a, int b) {


return a + b;
}

int main() {
int sum = add(5, 3);
printf("Sum: %d\n", sum);
return 0;
}

1 1 . Definition 2 2. Call
Specifies code and return type Executes the function's code
Defining and Calling Functions

int add(int a, int b) {


return a + b;
}

int main() {
int sum = add(5, 3);
printf("Sum: %d\n", sum);
return 0;
}

1 1. Definition 2 2. Call
Specifies code and return type Executes the function's code
F unction Parameters and Arguments
int multiply(int a, int b) {
return a * b;
}

int main() {
int product = multiply(5, 3);
printf("Product: %d\n", product);
return 0;
}

Parameters Arguments

Variables in function definition Values passed during function call


Function R eturn Types
int sum(int a, int b) {
return a + b;
}

float average(int a, int b) {


return (float) (a + b) / 2;
}

void printMessage() {
printf("Hello from function!\n");
}

int float
Returns an integer Returns a floating-point number

void
Doesn't return a value
Returning Values from
Functions
int add(int a, int b) {
return a + b;
}
Passing Arrays to F unctions

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
printArray(numbers, size);
return 0;
}

Array Pointer
Pass ed by reference Access array elements
Recursion: Functions Calling Themselves

int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int result = factorial(5);
printf("Factorial of 5: %d\n", result);
return 0;
}

1 Base Case
Stops the recursion

2 Recursive Case
Calls itself with a smaller input
F unction Pointers
void (*funcPtr)(int);

void greet(int num) {


printf("Greetings %d times!\n", num);
}

int main() {
funcPtr = greet;
(*funcPtr)(3);
return 0;
}

1 F unction Pointer

2 Stores F unction Address

3 Dynamic F unction Call


Storage Classes in Functions
int add(int a, int b);

int main() {
int sum = add(5, 3);
return 0;
}

int add(int a, int b) {


return a + b;
}

auto
1
Local scope

static
2
Retains value across calls

extern
3
Declares variables outside of functions

register
4
Stores in registers
Practical Examples and
Graphical R epresentations

1 2
Sorting Searching
Bubble sort, insertion sort Linear search, binary search

3
Data Structures
Linked lists, stacks, queues
Recursive Functions: Definition and Concept

Self-Calling Base Case

Functions that call themselves within their own definition A condition to stop the recursion
Implementing R ecursion with
Examples

int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
Advantages and
Disadvantages of Recursion

Elegance Stack Overflow


Provides concise and elegant Deep recursion can exhaust the
solutions stack memory
Week 6

Chapter 6

Arrays in C: A Deep Dive


Explore the world of single-dimensional and multi-dimensional arrays
in C programming, uncovering their structure, manipulation, and
diverse applications.
Introduction to Arrays
Organized Data Memory Efficiency

Efficiently store collections of related data of the same Contiguous blocks of memory for compact storage and
data type. fast access.
Declaring and Initializing
Single-Dimensional Arrays
Declaration Initialization
data_type array_name[size]; int numbers[5] = {1 0, 20, 30,
40, 50};

Example
float temperatures[7] = {25.5, 27.2, 28.0, 26.8, 29.1 , 27.5, 28.3};
Accessing and Manipulating
E lements

1 Access
array_name[index]

Modification
2
array_name[index] =
new_value;
Example
3
numbers[2] = 60; // Change element at index 2 to 60
Graphical R epresentation of
Single-Dimensional Arrays

Memory Location Element Index

Contiguous memory blocks for E ach element has a unique index


efficient data storage and access. for easy retrieval and modification.

Data Values

E lements hold data of the same


data type, allowing for uniform
operations.
Declaring and Initializing Multi-Dimensional Arrays

Declaration Initialization Example


data_type int matrix[3][2] = {{1, 2}, {3, 4}, {5, char board[8][8]; // Representing
array_name[row_size][column_siz 6}}; a chessboard
e];
Accessing and Manipulating
Elements

1 Access 2 Modification
array_name[row_index][c array_name[row_index][c
olumn_index] olumn_index] =
new_value;

3 Example
matrix[1 ][0] = 1 0; // Change element at row 1 , column 0 to 1 0
Graphical Representation of
Multi-Dimensional Arrays

1 Rows represent the first dimension

2 Columns represent the second dimension

3 Each element occupies a unique position in the 2D grid


Array Operations: Traversal,
Searching, Sorting
Traversal
Visiting each element systematically

Searching
Finding a specific element within the array

Sorting
Arranging elements in ascending or descending order
Code E xamples and Outputs

1 Code

2 Input

3 Output
Strings in C

Explore the world of strings in C programming with a visual guide that


demystifies key concepts and empowers you to manipulate text with
ease.
What are Strings in C?
Arrays of Characters Null Termination

Strings are essentially arrays of characters in C. Each Strings are terminated by a null character ('\ 0'),
character in the string is stored in a contiguous memory signifying the end of the string. This allows for efficient
location. string manipulation and length calculation.
Declaring and Initializing
S trings

1 S tring Literals 2 Character Arrays


Use double quotes to Initialize character arrays
create string literals. For directly with characters.
example: char str[] = For example: char str[6] =
"Hello"; {'H', 'e', 'l', 'l', 'o', '\0'};
String Manipulation:
Concatenation
strcat Function
The strcat function appends a source string to the end
of a destination string.

Example
char str1[] = "Hello"; char str2[] = " World"; strcat(str1,
str2); // str1 now contains "Hello World"
S tring Manipulation:
Comparison

strcmp F unction Return Values

- 0: S trings are equal. -


The strcmp function Positive: First string is
compares two strings lexicographically greater. -
lexicographically. Negative: First string is
lexicographically smaller.
String Manipulation:
Extraction

strncpy Function Example


The strncpy function copies a char str1[] = "Hello World"; char
specified number of characters str2[6]; strncpy(str2, str1, 5); //
from a source string to a str2 now contains "Hello"
destination string.
S tring Manipulation: Modification
strchr F unction 1
The strchr function locates the first occurrence of a
specified character within a string and returns a
pointer to the character's location. 2 E xample
char str[] = "Hello World"; char *ptr = strchr(str, 'W'); //
ptr points to the first occurrence of 'W' in str
S tring Manipulation: S earching

strstr F unction
1

E xample
char str[] = "Hello World"; char *ptr = strstr(str, "World");
2
// ptr points to the first occurrence of "World" in str
Practical Coding Examples
and Outputs

1 2
Input Output
char str[] = "Hello, World!"; Hello, World!
Conclusion and Key Takeaways

1 Mastering S trings

E fficiency
2 Efficient string manipulation is crucial for text-based applications.

F lexibility
3 C provides a rich set of functions for manipulating
strings, offering great flexibility.
String Handling Functions
in C
This presentation explores essential string handling functions in C, illustrating
their usage and impact with code examples and visual representations.
Introduction to S tring Handling
In C, strings are treated as arrays of characters, each terminated String handling functions simplify manipulation of these arrays,
with a null character ('\0'). enabling operations like concatenation, copying, and comparison.
strlen(): Measuring String
Length
Code Output

#include Length of string: 13


#include

int main() {
char str[] = "Hello,
world!";
int len =
strlen(str);
printf("Length of
string: %d\n", len);
return 0;
}
s trcat(): Concatenating
S trings
Code Output

#include
Hello, world!
#include
int main() {
char str1[] = "Hello,
";
char str2[] =
"world!";
strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
strcpy(): Copying Strings
Code Output

#include Hello, world!


#include

int main() {
char str1[] = "Hello,
world!";
char str2[20];
strcpy(str2, str1);
printf("%s\n", str2);
return 0;
}
s trcmp(): Comparing S trings

Code

#include
#include

Output
int main() {
char str1[] = "Hello";
char str2[] = "World"; Comparison result: -15

int result = strcmp(str1, str2);


printf("Comparison result: %d\n", result);
return 0;
}
strrev(): Reversing Strings
Code Output

#include !dlrow ,olleH


#include

int main() {
char str[] = "Hello, world!";
strrev(str);
printf("%s\n", str);
return 0;
}
s trtok(): S ubs tring Extraction
Code
#include
#include
Output
int main() {
char str[] = "Hello, Hello
world!"; world!
char *token =
strtok(str, ", ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL,
", ");
}
return 0;
}
strupr(): Converting to
Uppercase
Code Output

#include HELLO, WORLD!


#include

int main() {
char str[] = "hello,
world!";
strupr(str);
printf("%s\n", str);
return 0;
}
s trlwr(): Converting to
L owercas e
Code Output

#include hello, world!


#include

int main() {
char str[] = "HELLO,
WORLD!";
strlwr(str);
printf("%s\n", str);
return 0;
}
Pointers: Basics and
Arithmetic in C
This presentation will explore the fundamental concepts of pointers in C
programming, along with essential arithmetic operations and visual
representations for better understanding.
Understanding P ointers in C
Memory Addresses Direct Access

Pointers in C store memory addresses, providing a way to directly Pointers enable efficient data manipulation by offering direct
access and manipulate data stored in specific memory locations. access to memory, eliminating the need for copying data, and
optimizing memory usage.
Declaring and Initializing
Pointers
1 Declaration 2 Initialization
Declare a pointer variable Initialize a pointer by assigning
using the asterisk (*) symbol it the address of a variable
before the variable name, using the ampersand (&)
followed by the data type it operator.
points to.
P ointer Arithmetic: Incrementing and Decrementing

Increment Decrement

Incrementing a pointer moves it to the next memory location, Decrementing a pointer moves it to the previous memory location,
typically the size of the data type it points to. also based on the data type size.

int *ptr = &num; char *chPtr = &letter;


ptr++; // Moves ptr to the next integer location chPtr--; // Moves chPtr to the previous character
location
Pointer Arithmetic: Addition and Subtraction

Addition Subtraction

Adding an integer value to a pointer moves it forward in memory Subtracting an integer value from a pointer moves it backward in
by a multiple of the data type size. memory by a multiple of the data type size.

int *ptr = &num; char *chPtr = &letter;


ptr += 2; // Moves ptr two integer locations chPtr -= 3; // Moves chPtr three character
ahead locations back
Graphical Representation of P ointer Arithmetic

Increment Decrement Addition Subtraction


Moving the pointer to the next Moving the pointer to the Moving the pointer forward by a Moving the pointer backward
address. previous address. specific number of units. by a specific number of units.
Pointer Dereferencing and
Accessing Values
Dereferencing Value Retrieval
The dereference operator (*) Dereferencing a pointer allows
accesses the value stored at the you to read and manipulate the
memory address pointed to by a data stored at the memory
pointer. location it points to.
P ointer Arithmetic with Arrays
Array Access
1
A pointer to an array represents the starting address of the array.

Element Access
2 Pointer arithmetic is used to access elements of the array by moving the pointer to the
desired element's address.

Efficiency

3 Pointer arithmetic with arrays provides a concise and efficient


way to access and manipulate array elements directly.
Pointers and Dynamic Memory Allocation
Dynamic Allocation
Dynamic memory allocation enables you to request memory from the heap during program execution.
1

Heap
2
The heap is a region of memory where dynamically allocated blocks reside.

Pointers
3 Pointers are used to store the addresses of dynamically allocated memory blocks.

Flexibility
4 Dynamic memory allocation provides flexibility for managing memory
usage based on program requirements.
Practical Applications of Pointers
in C

1 2
Data S tructures Memory Management
P ointers are essential for building dynamic P ointers play a crucial role in managing
data structures like linked lists, trees, and memory allocation and deallocation in C
graphs. programs.

3
F unction Parameters
P ointers can be passed as function
parameters to modify data directly within
the called function.
Dynamic Memory Allocation in
C
Dynamic memory allocation is a powerful technique in C that allows you to
manage memory during runtime, providing flexibility and efficiency for your
programs.
What is Dynamic Memory Allocation?
Static Memory Allocation Dynamic Memory Allocation

Memory is allocated at compile time, and the size of the variable Memory is allocated at runtime, allowing you to allocate memory
is fixed. This is suitable for variables whose size is known in as needed. This is useful for variables whose size is unknown
advance, such as arrays or structures. beforehand, or whose size changes frequently, like strings or lists.
The malloc() Function
Declaration Usage

It takes the size of memory needed in bytes as an argument. It


void *malloc(size_t size);
returns a pointer to the allocated memory block. If the allocation
fails, it returns NULL.

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


The calloc() Function
Declaration Usage

It allocates memory for an array of num elements, each of size


void *calloc(size_t num, size_t size);
bytes. It initializes the allocated memory to zero. It returns a
pointer to the allocated memory block. If the allocation fails, it
returns NULL.

int *ptr = (int *)calloc(5, sizeof(int));


The realloc() Function
Declaration Usage

It resizes a previously allocated memory block. It takes a pointer


void *realloc(void *ptr, size_t new_size);
to the existing memory block and the new size as arguments. It
returns a pointer to the resized memory block. If the allocation
fails, it returns NULL. The original memory block may be moved.

int *ptr = (int *)realloc(ptr, 10 * sizeof(int));


The free() Function
Declaration Usage

It deallocates a memory block previously allocated with malloc,


void free(void *ptr);
calloc, or realloc. It takes a pointer to the memory block as an
argument. It doesn't return anything.

free(ptr);
Example: Dynamically Allocating an Integer Array
Code Output

#include <stdio.h> Enter the size of the array: 5


#include <stdlib.h> Enter the elements of the array:
1 2 3 4 5
int main() { Elements of the array:
int n; 1 2 3 4 5
printf("Enter the size of the array: ");
scanf("%d", &n);

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

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

printf("Enter the elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Elements of the array:\n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

free(arr);
return 0;
}
Example: Dynamically Allocating a 2D Array
Code Output

#include <stdio.h> Enter the number of rows: 2


#include <stdlib.h> Enter the number of columns: 3
Enter the elements of the 2D array:
int main() { 1 2 3
int rows, cols; 4 5 6
printf("Enter the number of rows: "); Elements of the 2D array:
scanf("%d", &rows); 1 2 3
printf("Enter the number of columns: "); 4 5 6
scanf("%d", &cols);

int **arr = (int **)malloc(rows * sizeof(int *));

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

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


arr[i] = (int *)malloc(cols * sizeof(int));
if (arr[i] == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
}

printf("Enter the elements of the 2D array:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &arr[i][j]);
}
}

printf("Elements of the 2D array:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

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


Example: Reallocating Dynamic Memory
Code

#include <stdio.h>
for (int i = 5; i < 10; i++) {
#include <stdlib.h>
ptr[i] = i + 1;
int main() {
}
int *ptr = (int *)malloc(5 * sizeof(int));

printf("Reallocated array:\n");
if (ptr == NULL) {
for (int i = 0; i < 10; i++) {
printf("Memory allocation failed!\n");
printf("%d ", ptr[i]);
return 1;
}
}
printf("\n");
for (int i = 0; i < 5; i++) {
ptr[i] = i + 1;
free(ptr);
}
return 0;
}
printf("Original array:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
ptr = (int *)realloc(ptr, 10 * sizeof(int));
Output
if (ptr == NULL) {
printf("Memory reallocation failed!\n");
return 1;
Original array:
} 1 2 3 4 5
Reallocated array:
1 2 3 4 5 6 7 8 9 10
Conclusion: Benefits and
Considerations of Dynamic
Memory Allocation

Benefits Considerations
F lexibility: Allocate memory only Memory leaks: Unreleased
when needed. Efficiency: Avoid memory can lead to program
allocating unnecessary memory. instability. S ecurity vulnerabilities:
Adaptability: Easily adjust memory Incorrect memory management
usage based on program can create security risks.
requirements. Complexity: Requires careful
handling and understanding of
memory management techniques.
Structures, Enumerations,
and Unions in C

This presentation explores the fundamental data structures in C -


structures, enumerations, and unions. We'll delve into their
functionalities, provide illustrative examples, and shed light on their
distinctive features and practical applications.
S tructures in C
What are Structures? E xample

Structures are user-defined data types that allow you to


struct Student {
group variables of different data types under a single
char name[50];
name. Think of them as blueprints for creating custom data
int roll_no;
types to represent real-world entities like students,
float marks;
employees, or products.
};
Example: A Structure to Represent a Person
Code Output

#include <stdio.h> Name: John Doe


Age: 30
struct Person { Address: 123 Main Street
char name[50];
int age;
char address[100];
};

int main() {
struct Person person1;

strcpy(person1.name, "John Doe");


person1.age = 30;
strcpy(person1.address, "123 Main Street");

printf("Name: %s\n", person1.name);


printf("Age: %d\n", person1.age);
printf("Address: %s\n", person1.address);

return 0;
}
E numerations in C
What are E numerations? E xample

E numerations (enums) are user-defined data types that


enum Days {
consist of a set of named integer constants. They provide a
Monday, Tuesday, Wednesday,
way to represent a fixed set of values, making your code
Thursday, Friday, Saturday, Sunday
more readable and maintainable.
};
Example: An Enumeration for Days of the Week
Code Output

#include <stdio.h> Today is 2

enum Days {
Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday
};

int main() {
enum Days today = Wednesday;

printf("Today is %d\n", today);

return 0;
}
Unions in C
What are Unions? E xample

Unions are user-defined data types that allow you to store


union Shape {
different data types in the same memory location. They're
int square_side;
useful when you want to represent different data types
float circle_radius;
using the same variable, but only one value is needed at a
};
time.
Example: A Union to Represent a Shape
Code Output

#include <stdio.h> Area of square: 25


Area of circle: 19.634954
union Shape {
int square_side;
float circle_radius;
};

int main() {
union Shape shape;

shape.square_side = 5;
printf("Area of square: %d\n", shape.square_side *
shape.square_side);

shape.circle_radius = 2.5;
printf("Area of circle: %f\n", 3.14159 * shape.circle_radius *
shape.circle_radius);

return 0;
}
Differences between Structures,
Enumerations, and Unions

Structures Enumerations
Store multiple members of different Define a set of named integer
data types. Each member has its constants. Used to represent a
own memory space. Used to fixed set of values.
represent complex data structures.

Unions
Store different data types in the same memory location. Only one member
can be active at a time. Used when only one data type is needed at a time.
Graphical Representation of Structures,
Enumerations, and Unions

Structure Enumeration Union


Multiple members, each with its own Named integer constants, representing Different data types share the same
memory space. a fixed set of values. memory space, only one member active
at a time.
P ractical Applications of
S tructures, E numerations,
and Unions

1 Structures 2 E numerations
Representing employee Defining days of the week,
records, student data, and months of the year, and
product information. traffic light colors.

3 Unions
Creating a data type that can represent both an integer and a
floating-point number, depending on the context.
File Handling in C: Read,
Write, Append Modes

This presentation provides a comprehensive overview of file handling in


C, covering the fundamental concepts, functions, and best practices.
We will explore the various file opening modes, including read, write,
and append, and demonstrate their applications through practical
examples. Get ready to unlock the power of file manipulation in C!
Introduction to F ile Handling in C
File Handling in C Why File Handling is Important

File handling in C allows programs to interact with external File handling is essential for creating programs that can
data stored in files. This enables us to read data from files, store data persistently, share data with other programs, and
write new data to files, and modify existing files. manage data in various formats.
The fopen() Function: Opening a File
Syntax Explanation

The fopen() function opens a file and returns a file pointer


FILE *fp = fopen("filename", "mode");
(FILE *) to access the file. The filename argument specifies
the path to the file, and the mode argument indicates the
purpose of opening the file.
F ile Opening Modes: R ead, Write, Append

1 R ead Mode ("r") 2 Write Mode ("w") 3 Append Mode ("a")


Opens an existing file for Creates a new file for writing. If Opens an existing file for
reading. If the file doesn't exist, the file exists, it's overwritten. appending data. If the file
the function fails. doesn't exist, it's created.
Reading from a File: The fread() Function

Syntax Explanation

The fread() function reads data from a file into a memory


size_t fread(void *ptr, size_t size, size_t
buffer. It takes the following arguments: - ptr: Pointer to the
nmemb, FILE *fp);
memory buffer to store the data - size: Size of each data
element - nmemb: Number of data elements to read - fp:
File pointer to the opened file
Writing to a F ile: The fwrite() F unction
Syntax E xplanation

The fwrite() function writes data from a memory buffer to a


size_t fwrite(const void *ptr, size_t size,
file. It takes the following arguments: - ptr: Pointer to the
size_t nmemb, FILE *fp);
memory buffer containing the data - size: Size of each data
element - nmemb: Number of data elements to write - fp:
File pointer to the opened file
Appending to a File: The fprintf() Function

Syntax Explanation

The fprintf() function writes formatted data to a file. It takes


int fprintf(FILE *fp, const char *format, ...);
the following arguments: - fp: File pointer to the opened file
- format: Format string specifying how the data should be
formatted - ...: Additional arguments containing the data to
be written
Handling F ile E rrors and E xceptions
E rror Handling E xception Handling

It's crucial to check for file errors after opening, reading, Use the perror() function to display a user-friendly error
writing, or closing a file. The ferror() function can be used message based on the error code returned by the system.
to determine if an error has occurred.
Example: Reading from a File

Code Output
Content: This is the content of the file.
#include <stdio.h>

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

fp = fopen("data.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}

fgets(buffer, 100, fp);


printf("Content: %s", buffer);

fclose(fp);
return 0;
}
E xample: Writing to a File

Code Output
(The file output.txt now contains the following text):
#include <stdio.h> This is the data to write to the file.

int main() {
FILE *fp;
char data[] = "This is the data
to write to the file.";

fp = fopen("output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return 1;
}

fprintf(fp, "%s\n", data);

fclose(fp);
return 0;
}
Debugging and Error
Handling in C
This presentation will explore the essential concepts of debugging and error
handling in the C programming language. We'll delve into different types of
errors, debugging techniques, and best practices to enhance your code's
reliability and maintainability.
Importance of Debugging and Error Handling

Program Stability Error Prevention User Experience

Debugging ensures your program runs Error handling mechanisms catch Effective error handling provides clear
smoothly and predictably, preventing potential issues during runtime, mitigating and informative messages to users,
unexpected crashes and malfunctions. problems before they affect users. enhancing their overall experience.
Common Types of Errors in C
Syntax Errors Runtime Errors Logical Errors
Violations of the C language Issues that arise during program Incorrect program logic that leads to
grammar, such as missing execution, like memory access unexpected or unintended behavior,
semicolons or incorrect keywords. violations or division by zero. even though the code is syntactically
correct.
S yntax E rrors: E xample and
Output
int main() {
printf("Hello, world!\n
}

Output: error: expected ';' before '}' token


Runtime Errors: Example and
Output
#include <stdio.h>

int main() {
int x = 10;
int y = 0;
int z = x / y;
printf("Result: %d\n", z);
return 0;
}

Output: Floating point exception (core dumped)


Logical E rrors: E xample and
Output
#include <stdio.h>

int main() {
int num1 = 5;
int num2 = 10;
int sum = num1 - num2; // Should be addition
printf("Sum: %d\n", sum);
return 0;
}

Output: Sum: -5 (Expected: 1 5)


The `printf()` Debugging
Technique
#include <stdio.h>

int main() {
int num1 = 5;
int num2 = 10;
printf("num1: %d\n", num1);
printf("num2: %d\n", num2);
int sum = num1 + num2;
printf("Sum: %d\n", sum);
return 0;
}

Output: num1: 5 num2: 10 Sum: 15


Using `gdb` for Debugging: E xample and Output

int main() {
int x = 10;
int y = 0;
int z = x / y; // Potential error
printf("Result: %d\n", z);
return 0;
}

Output: (gdb) run S tarting program: ./program P rogram received signal S IGFPE , F loating point exception. [... stack trace ...] (gdb) print x $1 = 10 (gdb) print y
$2 = 0 (gdb) print z $3 = 0 (gdb)
Handling Errors with `errno`
and `perror()`
#include <stdio.h>
#include <errno.h>

int main() {
FILE *fp = fopen("myfile.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// ... file operations ...
fclose(fp);
return 0;
}

Output: Error opening file: No such file or directory


Best Practices for E ffective
Debugging and E rror Handling

Test Thoroughly Document Code


Run your code with various inputs to identify Add comments to explain the logic and
potential issues in different scenarios. purpose of your code, making it easier to
understand and debug.

Use Assertions Handle E rrors Gracefully


Assert conditions that should always be true Provide informative error messages to
during runtime to catch logical errors early users, and attempt to recover from errors
on. gracefully.
Advanced Functions and
Macros in C
This presentation will explore the powerful features of advanced functions and
macros in C, delving into their definitions, usage, and best practices. We'll
examine how functions enhance code organization and reusability, while
macros offer flexible code manipulation.
What are F unctions?
Functions are self-contained blocks of code designed to perform Functions improve code readability and maintainability by
specific tasks. They encapsulate logic, making code more breaking down complex tasks into smaller, reusable units. They
modular and easier to manage. promote code reuse, reducing redundancy and enhancing
efficiency.
Defining and Calling Functions
Defining a Function Calling a Function

int add(int a, int b) { int main() {


return a + b; int result = add(5, 3);
} printf("Result: %d\n", result);
return 0;
}
Output: Result: 8
F unctions with P arameters
F unction Definition F unction Call

int multiply(int x, int y) { int main() {


return x * y; int product = multiply(4, 7);
} printf("Product: %d\n", product);
return 0;
}
Output: Product: 28
Return Values from Functions
Function Definition Function Call

float calculateAverage(float num1, float num2) { int main() {


return (num1 + num2) / 2; float average = calculateAverage(10.5, 15.2);
} printf("Average: %.2f\n", average);
return 0;
}
Output: Average: 12.85
Recursion
F unction Definition F unction Call

int factorial(int n) { int main() {


if (n == 0) { int result = factorial(5);
return 1; printf("Factorial of 5: %d\n", result);
} else { return 0;
return n * factorial(n - 1); }
} Output: Factorial of 5: 120
}
Preprocessor Directives and
Macros
1 Preprocessor Directives 2 Macros
Code snippets replaced with
Instructions processed before equivalent text during
compilation, influencing how compilation, providing flexibility
the source code is treated. and optimization.
Macro S ubstitution
Macro Definition Macro Usage

#define PI 3.14159 int main() {


float circumference = 2 * PI * 5;
printf("Circumference: %.2f\n", circumference);
return 0;
}
Output: Circumference: 31.42
Macros with Arguments
Macro Definition Macro Usage

#define SQUARE(x) (x * x) int main() {


int number = 7;
int squared = SQUARE(number);
printf("Squared value: %d\n", squared);
return 0;
}
Output: Squared value: 49
P itfalls of Macros
1 Side E ffects 2 Type Safety 3 Debugging Challenges
Macros can lead to unexpected Macros lack type checking, making
results when applied to expressions them prone to errors when used with Macros are expanded during pre-
with side effects (e.g., function calls), different data types. processing, making it challenging to
potentially causing unexpected debug issues directly in the source
behavior. code.
Advanced Pointer Techniques
in C
This presentation will explore some advanced techniques for using pointers in C
programming, including pointers to pointers, pointers to arrays, dynamic
memory allocation, pointers and structures, and pointers as function arguments.
P ointers to P ointers
Concept E xample

A pointer to a pointer is a variable that stores the memory address


int x = 10;
of another pointer. It's like having a pointer that points to a pointer,
int *ptr1 = &x;
allowing you to indirectly access the data pointed to by the
int **ptr2 = &ptr1;
original pointer.

printf("%d\n", **ptr2); // Output: 10


Example: Swapping two integers using pointers to
pointers
Code Explanation

The `swap` function takes two pointers to pointers as arguments. By


void swap(int **ptr1, int **ptr2) {
dereferencing these pointers, it swaps the values pointed to by the
int *temp = *ptr1;
original pointers.
*ptr1 = *ptr2;
*ptr2 = temp;
}

int main() {
int a = 10, b = 20;
int *ptr1 = &a, *ptr2 = &b;
swap(&ptr1, &ptr2);
printf("a = %d, b = %d\n", a, b); // Output: a = 20,
b = 10
return 0;
}
P ointers to Arrays
Concept E xample

A pointer to an array is a variable that stores the memory address


int arr[] = {1, 2, 3, 4, 5};
of the first element of the array. It allows you to access and
int *ptr = arr;
manipulate array elements directly using pointer arithmetic.

printf("%d\n", *ptr); // Output: 1


printf("%d\n", *(ptr + 1)); // Output: 2
Example: Accessing array elements using pointers
to arrays
Code Explanation

The code iterates through the array using a `for` loop and
int main() {
accesses each element using the pointer `ptr`. The pointer
int arr[] = {10, 20, 30, 40, 50};
arithmetic `*(ptr + i)` accesses the element at the `i`-th index.
int *ptr = arr;

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


printf("%d ", *(ptr + i)); // Output: 10 20
30 40 50
}

return 0;
}
Dynamic Memory Allocation
Concept E xample

Dynamic memory allocation allows you to allocate memory during


int *ptr = (int *) malloc(sizeof(int));
program execution, unlike statically allocated memory, which is
if (ptr == NULL) {
fixed at compile time. Functions like `malloc()`, `calloc()`, and
// Handle memory allocation failure
`realloc()` provide this capability.
}

*ptr = 10;
printf("%d\n", *ptr); // Output: 10

free(ptr); // Release the allocated memory


Example: Dynamically allocating and initializing an array
Code Explanation

The code first prompts the user for the array size, dynamically allocates memory using `malloc`,
int main() {
and then initializes the elements of the allocated array.
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);

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


if (arr == NULL) {
// Handle memory allocation failure
}

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


arr[i] = i + 1; // Initialize the array elements
}

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


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

free(arr); // Release the allocated memory


return 0;
}
P ointers and S tructures
Concept E xample

You can use pointers to access and manipulate the members of a


struct Student {
structure. This allows for efficient data manipulation and passing
char name[50];
structures as arguments to functions.
int rollno;
};

int main() {
struct Student s1 = {"John Doe", 101};
struct Student *ptr = &s1;

printf("%s %d\n", ptr->name, ptr->rollno); //


Output: John Doe 101
return 0;
}
Example: Accessing structure members using pointers

Code Explanation

The `printBook` function takes a pointer to a `Book` structure. It accesses the members of
struct Book {
the structure using the arrow operator (`->`) to display the book details.
char title[100];
char author[50];
int pages;
};

void printBook(struct Book *book) {


printf("Title: %s\n", book->title);
printf("Author: %s\n", book->author);
printf("Pages: %d\n", book->pages);
}

int main() {
struct Book b1 = {"The Hitchhiker's Guide to the Galaxy",
"Douglas Adams", 42};
printBook(&b1);
return 0;
}
P ointers and F unction Arguments
Concept E xample

Passing pointers as arguments to functions allows you to modify


void increment(int *num) {
the original data directly within the function. This is more efficient
*num = *num + 1;
than passing copies of large data structures.
}

int main() {
int num = 10;
increment(&num);
printf("%d\n", num); // Output: 11
return 0;
}
Week 16

Chapter 16
Project Integration and Review
Beginner Projects
1.Basic Calculator
1. Features: Perform basic arithmetic operations (+, -, *, /).
2. Skills: Input handling, control structures, and functions.
2.Unit Conversion Tool
1. Features: Convert between units (e.g., length, weight,
temperature).
2. Skills: Switch-case, modular programming.
3.Student Record System
1. Features: Add, view, and delete student records.
2. Skills: Arrays, file handling, basic menu systems.
4.Number Guessing Game
1. Features: The program generates a random number, and the
user guesses it with hints provided.
2. Skills: Loops, random number generation, conditional
statements.
5.Simple Tic-Tac-Toe Game
1. Features: Two players can play a classic game of tic-tac-toe
on a 3x3 grid.
2. Skills: 2D arrays, nested loops, and conditional logic.
3. Inventory Management System
1. Library Management System Features:
Features: •Add, update, and remove products.
•Add, delete, and search for books. •Track inventory levels and notify when
•Issue and return books to/from students. stock is low.
•View issued books and calculate late return fines. •Generate purchase and sales reports.
•Skills Used: • Skills Used:
•File handling (to store book and student data). •Arrays or linked lists for inventory storage.
•Structures (to manage records). •File handling for saving and retrieving
data.
2. Hospital Management System •Functions for modularity.
Features:
•Add, search, and delete patient records. 4. Employee Management System
•Manage doctor schedules and appointments. Features:
•Generate bills for services provided. •Add, update, and delete employee
• Skills Used: details (e.g., name, position, salary).
•File handling (to save patient and doctor data). •Calculate salary, including bonuses and
•Structures and dynamic memory allocation. deductions.
•Input validation. •Search for employees by name or ID.
Skills Used:
•Structures for employee records.
•File handling for persistence.

You might also like