You are on page 1of 8

Session 5 Modular Approach in C Programming and Introduction to Functions

1. Aim of the Session

In this session, concept of modular programming in the C programming language will be


explained along with an explanation of functions, their types, and how they are used in
modular programming.

2. Objectives

This Session is designed to:

• Define modular programming and its advantages.


• Understand the basic structure of a C program.
• Understand the different types of functions and their uses in modular programming.
• Create and call functions in C.
• Use function arguments and return values.
• Create modular programs using functions.

3. Learning Outcomes

At the end of this session, you should be able to:

• Explain the benefits of modular programming in C.


• Understand the basic structure of a C program and Identify the different parts of a C
program, including header files, functions, and the main function.
• Understand and differentiate between the different types of functions in C.
• Write and call functions in C programs.
• Use arguments and return values in functions.
• Create modular programs using functions in C.

4. Session Introduction

In this session we will discuss about

• The concept of modularization in C and the different types of functions used in


modular programming.
• Basic structure of a C program and identify the different parts of a C program,
including header files, functions, and the main function.
• How to create and call functions in C, and how to use function arguments and return
values.

5. Session Description

Modular Approach in C Programming

In C programming language, a modular approach refers to breaking down a program into


smaller, independent modules or functions that can be developed, tested, and maintained
separately.
The modular approach involves dividing a large program into smaller, more manageable
components, each of which performs a specific task. These modules can then be tested and
debugged independently, and once they are working correctly, they can be integrated to form
the complete program.

Advantages:

Code reusability: Modules can be reused in other programs, which can save time and effort
in development.

Improved readability: Breaking down a program into smaller modules makes it easier to read
and understand.

Simplified debugging: Modules can be debugged separately, which can simplify the debugging
process and reduce the time it takes to locate and fix errors.

Better maintenance: Modular programs are easier to maintain because changes can be made
to individual modules without affecting the entire program.

How to achieve modularity in c programming?

To achieve modularity in C programming, functions and header files are used. Functions
perform specific tasks within a program, and header files allow sharing of functions and data
structures across different parts of the program.

Basic Structure of C Program:

A C program is made up of various components, including variables, data types, operators,


control statements, functions, and libraries. These components are combined to create a
structured program that can perform a specific task or set of tasks.

The basic structure of a C program is as follows:

#include <stdio.h> // Include header file(s)

int main() // Declare main function

// Declarations and statements

return 0; // Return statement

C program consists of several components, including:

Preprocessor directives: These are commands that tell the compiler to perform
certain actions before compiling the code. They start with the '#' symbol, and
commonly include the inclusion of header files, such as "stdio.h" for input and output
operations.

Function declaration: This section specifies the names and arguments of any
functions that will be used in the program. It typically appears at the beginning of the
file, before the main() function.
main function: This is the starting point of the program. It contains the code that will
be executed when the program is run. The main function should always return an
integer value, typically 0, to indicate successful completion of the program.

Variables: These are used to store data, and must be declared before they can be
used. Variable declarations specify the data type, such as int or float, and a name for
the variable.

Statements: These are the individual instructions that make up the program. They can
include assignments, loops, conditionals, and function calls.

Example:

#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old.", age);
return 0;
}
The above program includes a preprocessor directive to include the standard input/output
library, declares the main function, declares an integer variable named "age," prompts the
user to enter their age, reads the input from the user, and prints a message to the screen with
the user's age. Finally, the main function returns 0 to indicate successful completion of the
program.

Functions in C

In C programming language, a function is a group of statements that performs a specific task.


Functions provide modularity to a program by breaking it down into smaller and more
manageable parts. They also improve code reusability, readability, and reduce the overall
complexity of the program.

There are two types of functions in C:

Library functions: These are pre-built functions that are available in standard C libraries.
Examples of library functions include printf(), scanf(), strlen(), etc. These functions are already
implemented, and we can use them by including the appropriate header file in our program.

User-defined functions: These are functions that are defined by the programmer to perform
a specific task. User-defined functions can take arguments and return values. They are
typically used to encapsulate a block of code that performs a specific task, making the code
easier to read, understand, and maintain.

Create and Call function.

1. Function declaration: When we want to use a function in our program, we first need to
tell the computer what the function is called, what kind of information it will return, and
what information it needs in order to work. This is called a function declaration, and it
goes at the top of our program. For example:

int sum(int a, int b); // function declaration


2. Function definition: Once we have declared the function, we need to actually write the
instructions for what the function should do. This is called a function definition, and it
comes after the declaration in our program. For example:

int sum(int a, int b) { // function definition


int result = a + b;
return result;
}
3. Calling a function: To use the function in our program, we "call" it by using its name and
passing in the information it needs to work. For example:

int x = 5, y = 7;
int z = sum(x, y); // call the sum() function
printf("The sum of %d and %d is %d", x, y, z);

This code calls the sum() function and passes it the values of x and y. The function
adds the two values together and returns the result, which is stored in the variable z.
The printf() function then displays the result to the screen.

Example:

#include <stdio.h>
// function declaration
int sum(int, int);
//main function
int main() {
int a = 5, b = 7;
int c = sum(a, b); // call the sum() function
printf("The sum of %d and %d is %d\n", a, b, c);
return 0;
}
// function definition
int sum(int x, int y) {
int result = x + y;
return result;
}
In this program, we first declare the sum() function at the top of the program. Then in the
main() function, we create two integer variables a and b, and we call the sum() function with
these two variables as arguments. The result of the function call is stored in the variable c,
and we use printf() to display the result to the screen.

Finally, we define the sum() function. This function takes two integer parameters x and y, adds
them together, and returns the result as an integer.

Identifiers in C:

 An identifier is a name used to identify a variable, function, or any other user-defined item in
C.
 It can consist of letters (both uppercase and lowercase), digits, and underscores.
 The first character of an identifier must be a letter or an underscore. It cannot start with a
digit.
 Identifiers are case-sensitive, i.e., uppercase and lowercase letters are considered different.
 There is no limit on the length of an identifier, but it is recommended to keep them meaningful
and not too long for readability.
Examples:
Variables:
 Valid identifiers: count, total_sum, average_1
 Invalid identifiers: 1count (starts with a digit), total-sum (contains a hyphen), average#1
(contains special character)
Functions:
 Valid identifiers: calculateSum, printMessage, findMaxValue
 Invalid identifiers: 123function (starts with a digit), print-message (contains a hyphen),
findMaxValue! (contains special character)
Constants:
 Valid identifiers: PI, MAX_VALUE, TOTAL_COUNT
 Invalid identifiers: 1PI (starts with a digit), MAX-VALUE (contains a hyphen), TOTAL COUNT
(contains a space)
User-defined types:
 Valid identifiers: Student, Point2D, ComplexNumber
 Invalid identifiers: 1Student (starts with a digit), Point-2D (contains a hyphen),
Complex_Number (contains an underscore and uppercase letters)
Labels:
 Valid identifiers: start, loop1, exit_label
 Invalid identifiers: 1start (starts with a digit), loop-1 (contains a hyphen), exit-label (contains
a hyphen)

Comments in C Program

 In C programming, comments are non-executable lines that are used to provide explanations,
annotations, and documentation within the source code.
 Comments are ignored by the compiler and do not affect the program's functionality.
 They are essential for making code more understandable, especially for other programmers
who may need to read or modify the code later on.
 C supports two types of comments:
o Single-line Comments:

Single-line comments begin with two forward slashes (//) and continue until the end
of the line. Anything written after // on the same line is considered a comment.

Example:

// This is a single-line comment

int age = 30; // Variable to store age


o Multi-line Comments:
Multi-line comments (also known as block comments) allow you to comment on
multiple lines at once. They start with /* and end with */. Everything between these
delimiters is considered a comment.
Example:
/* This is a multi-line comment.
It can span across multiple lines.
Comments are not executed by the compiler. */
int x = 10; // Variable x

Usage and Best Practices:

 Comments should be used to explain the purpose and functionality of code sections,
especially complex or obscure parts.
 They are useful for temporarily disabling a part of the code during debugging without deleting
it entirely.
 Comments can be used to credit the author, provide version information, or document any
changes made to the code.
 Avoid writing comments that simply restate the code. Comments should add value and
provide insights that are not immediately evident from the code itself.
 Always use comments to explain the logic and algorithmic steps in intricate functions or
algorithms.

6. Activities related to the Session

Group discussion: The session will conclude with a group discussion on the benefits of
modular programming in C and the different types of functions in C. The students will also
be encouraged to share their experiences with modular programming in C and ask any
questions they may have.

7. Examples & Contemporary Extracts of Articles / Practices to convey the idea of the Session

Programming is the process of subdividing a computer program into separate sub-programs.


A module is a separate software component. It can often be used in a variety of applications
and functions with other components of the system. This article discusses advantages,
disadvantages of modular approach in programming.

Modular Approach in Programming - GeeksforGeeks

8. Table Numbering

---

9. Figures with caption

---

10. Self-Assessment Questions (SAQs)


1. What is the purpose of a function in C?
2. What is function declaration and function definition?
3. How do you call a function in C?
4. What is main function in C?
5. What is header file in C?
6. True or False: Identifiers in C are Case Sensitive. Explain your Answer.
7. Which syntax is used to write single-line comments in C?

a) /* comment */
b) { comment }
c) // comment
d) <!-- comment -->
8. How are multi-line comments represented in C?
a) // comment
b) <!-- comment -->
c) /* comment */
d) { comment }

11. Summary

In this session, we learned about modular programming in C and how to use functions to create
more manageable and maintainable programs.

12 Terminal Questions

1. What is the purpose of a "main" function in C programming, and how can you use it
to manage the execution of a modular program?
2. How can you use the "include" directive to include header files from other modules
in your C source code?
3. Explain the benefits of modular programming approach in c.
4. Write a C program to calculate the sum of two numbers, and add appropriate
comments to explain the variables and calculation steps.

13. Case Studies

• The Linux Kernel: The Linux operating system kernel is written in C and is a prime
example of modular programming. The kernel is divided into separate modules, each
responsible for a specific functionality such as device drivers, file systems, or network
protocols. The modules are loaded and unloaded dynamically at runtime, allowing for
easy customization and efficient use of system resources.
• Apache HTTP Server: The Apache HTTP Server is a widely used web server written in
C. It uses a modular programming approach to allow for easy customization and
extensibility. Modules can be added or removed at runtime, and the server can be
configured to include only the modules needed for a specific deployment. The code is
separated into modules for handling requests, processing responses, and managing
server resources.

14. References of Books / Websites / Link


 "The C Programming Language" by Brian Kernighan and Dennis Ritchie - This is the classic
book on C programming and is a great resource for learning about functions in C.
 "C Programming: A Modern Approach" by K. N. King - This book is another excellent
resource for learning C programming, including functions.
 "C Functions" by Michael J. Misamore - This book is focused specifically on functions in C
and can be a great resource for those who want to deepen their understanding of this
topic.

Sites and Web links:

 https://data-flair.training/blogs/basic-structure-of-c-program/ This weblink provides


basic structure of c program.

15. Keywords

• Modularity
• Header files
• Main function
• Include directive.
• Libraries

You might also like