Structure Programming
Structure Programming
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
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
INCLASS ASSESSMENT
Q&A
Assessment
Pattern
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
5 Functions: User-defined, Recursion Interactive Lectures, Case Group Task, Quiz CLO2, CLO3
Studies
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
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
3.141592;)
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:
// 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;
return 0;
}
C Program to Swap Two Numbers
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;
Chapter 3
Conditional S tatements in C
Unlock the Power of Decision-Making in Your C Programs
Introduction to Conditional Statements
Controlling Program Flow
Decision-Making Power
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
2 Branching Paths
3 Code Execution
Conditional Statement Examples with Code and Output
Example 1 Example 2
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
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
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
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
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 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 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
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
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);
int main() {
funcPtr = greet;
(*funcPtr)(3);
return 0;
}
1 F unction Pointer
int main() {
int sum = add(5, 3);
return 0;
}
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
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
Chapter 6
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
Data Values
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
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
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
Example
char str1[] = "Hello"; char str2[] = " World"; strcat(str1,
str2); // str1 now contains "Hello World"
S tring Manipulation:
Comparison
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
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
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 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
int main() {
char str[] = "hello,
world!";
strupr(str);
printf("%s\n", str);
return 0;
}
s trlwr(): Converting to
L owercas e
Code Output
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.
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.
Element Access
2 Pointer arithmetic is used to access elements of the array by moving the pointer to the
desired element's address.
Efficiency
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
free(ptr);
Example: Dynamically Allocating an Integer Array
Code Output
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
free(arr);
return 0;
}
Example: Dynamically Allocating a 2D Array
Code Output
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
#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
int main() {
struct Person person1;
return 0;
}
E numerations in C
What are E numerations? E xample
enum Days {
Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday
};
int main() {
enum Days today = Wednesday;
return 0;
}
Unions in C
What are Unions? E xample
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
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
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
Syntax Explanation
Syntax Explanation
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;
}
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;
}
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
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
}
int main() {
int x = 10;
int y = 0;
int z = x / y;
printf("Result: %d\n", z);
return 0;
}
int main() {
int num1 = 5;
int num2 = 10;
int sum = num1 - num2; // Should be addition
printf("Sum: %d\n", sum);
return 0;
}
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;
}
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;
}
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
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;
return 0;
}
Dynamic Memory Allocation
Concept E xample
*ptr = 10;
printf("%d\n", *ptr); // Output: 10
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 main() {
struct Student s1 = {"John Doe", 101};
struct Student *ptr = &s1;
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;
};
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
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.