Handouts Module 4 Fns and Struct
Handouts Module 4 Fns and Struct
Structures: Basics of Structures, Structures and Functions, Arrays of Structures, Pointers to Structures.
Typedef, Unions, Bit-fields. Documentation of programs, Debugging programs, Program testing;
Learning Outcomes:
Apply top-down design principles to decompose complex problems into simpler, manageable functions.
Understand and apply scope rules, header files, and various utility functions from libraries like <ctype.h>,
<string.h>, <math.h>, and <stdlib.h>.
Utilize structures, typedefs, unions, and bit-fields in C programming, and practice program documentation,
debugging, and testing.
1
Top-down Design
the top-down approach goes from the general to the specific, and the bottom-up approach begins at the
specific and moves to the general.
Top-down design is a programming technique used in C to break down a large problem into smaller, more
manageable problems:
Start with a high-level design, then write the main function, and call sub-functions from the main function.
Each sub-function performs a specific task
• Benefits
• Make the new parts less complicated and easier to figure out
• The functions decrease the iteration of the same statements in a program. So, they decrease
the program’s size.
2
• The function improves code readability by offering modularity to the program.
• Functions can be called multiple times from different parts of a program, promoting code
reusability.
• They make programs easy to understand and manage by breaking a large program into smaller
pieces.
• Representation
A top-down design process can be represented by a structure chart, which is a modular design tool that uses
squares to represent modules and lines to connect them
Functions - Functions are "self contained" modules of code that accomplish a specific task. Functions
usually "take in" data, process it, and "return" a result. Once a function is written, it can be used over
and over and over again. Functions can be "called" from the inside of other functions.
Concept of modular programming, defining functions, formal parameters, actual parameters, pass by value,
recursion, arrays as function parameters.
Function declaration
Informs the compiler about the function's name, data type of parameters, number of parameters, and
return type
Library functions
Predefined functions in C, a type of function integral to efficient coding, come predefined in the system
library. Utilizing these functions, such as the printf() function from the <stdio.h> header file, is essential
for writing error-free code.
Built-in functions in the C programming system, such as main(), printf(), and scanf(). To use these
functions, you need to include the appropriate header files.
3
• textbackground() used to change text background
• Allows programmer to define their own function according to their requirement. Advantages of user defined
functions
• It helps to decompose the large program into small segments which makes programmer easy to understand,
maintain and debug.
• If repeated code occurs in a program. Function can be used to include those codes and execute when needed
by calling that function.
• Programmer working on large project can divide the workload by making different functions.
A function is a set of statements enclosed within curly brackets ({}) that take inputs, do the computation, and
provide the resultant output.
A function can be called multiple times, thereby allowing reusability and modularity in C programming.
A function declaration usually contains the function name, return type, and the parameter types. The following
is the syntax for defining a function in C:
return_type function_name(parameter_list);
Function definition:
statements;
return x;
NOTE:
A local variable in C is a variable that is declared within a function or block, and is only visible within that
function or block
Global variables in C are those that are declared outside of all functions. They are not confined to a specific
function, meaning they can be accessed and modified by any function within the program.
• Global variables can be accessed by all the functions present in the program.
4
• Only a one-time declaration is required.
• Global variables are very useful if all the functions are accessing the same data.
O/P
Functions in C can be categorized into four types based on the value returned and the arguments passed:
5
Formal parameters and Actual parameters
Formal Parameters:
Formal parameters are the variables listed in a function's parameter list within its definition.
They act as placeholders for the values that will be provided when the function is called.
Actual Parameters:
Actual parameters, also known as arguments, are the values or expressions passed to a function during a
function call.
These values are assigned to the corresponding formal parameters in the function definition.
Calling functions
A function in C can be called either with arguments or without arguments. These functions may or may
not return values to the calling functions. All C functions can be called either with arguments or without
arguments in a C program. Also, they may or may not return any values.
Call by value in C is where in the arguments we pass Call by reference is the method in C where we call
value and that value can be used in function for the function with the passing address as
performing the operation. Values passed in the arguments. We pass the address of the memory
function are stored in temporary memory so the blocks which can be further stored in a pointer
changes performed in the function don’t affect the variable that can be used in the function. Now,
actual value of the variable passed. changes performed in the values inside the function
can be directly reflected in the main memory.
6
Types of Function According to Arguments and Return Value
Functions can be differentiated into 4 types according to the arguments passed and value returns these are:
Function with arguments and return value Function with arguments but no return value
7
Example Example
8
Function with no argument and no return value Function with no arguments but returns a value
When a function has no arguments, it does not There could be occasions where we may need to
receive any data from the calling function. Similarly, design functions that may not take any
when it does not return a value, the calling function arguments but returns a value to the calling
does not receive any data from the called function. function. An example of this is getchar function
which has no parameters but it returns an
Syntax:
integer and integer-type data that represents a
Function declaration : void function(); character.
Function definition :
void function()
statements; }
Example Example:
Recursion
Factorial Formula
Factorial of 3 is: 3! = 3 × 2 × 1
Some formulae
9
Facorial Each number is equal to the sum of the preceding two numbers
Tribonacci T_n=T_(n-1)+T_(n-2)+T_(n-3)
P-Factorial by recursion
10
Tutorials
To print area of a square To print area of a triangle and square using
function
// Function without argument and with return value
To calculate the average of 5 numbers using void in a Calling function within a function
function
11
Note on header files from C library
Ex:
#include <stdio.h>
int main()
12
Register variables tell the compiler to store the variable in CPU register instead of memory. Frequently used
variables are kept in registers and they have faster accessibility. We can never get the addresses of these
variables. “register” keyword is used to declare the register variables. They are local to the function.
Ex:
The block structure of a C program is a sequence of declarations, definitions, and statements enclosed within
curly braces ({ }). Blocks are fundamental to structured programming, and are used to form control structures.
Initialization refers to defining a constant or variable values that are used in the code for executing a computer
program. Initialization plays a key role in programming as the variables that are used for writing the code
occupy a certain amount of memory in the CPU.
Structures: Basics of Structures, Structures and Functions, Arrays of Structures, Pointers to Structures.
Typedef, Unions, Bit-fields. Documentation of programs, Debugging programs, Program testing.
STRUCTURES
Arrays can be used for the same data types. If different data types, we can not use arrays. Structures can be
used for different data types.
• Structures allow you to group together variables of different types under a single name.
Declaring Structure
• struct StructureName {
• // members
• data_type1 member1;
• data_type2 member2;
• // ...
• };
• Declaration
• Initialization
13
Accessing members of the structure
There are two ways to access structure members:
A structure pointer is defined as the pointer which points to the address of the memory block that
stores a structure known as the structure pointer. Complex data structures like Linked lists, trees,
graphs, etc. are created with the help of structure pointers. The structure pointer tells the address of
a structure in memory by pointing the variable to the structure variable.
To declare a structure pointer struct keyword is used followed by the structure name and pointer name
with an asterisk * symbol. Members of a structure can be accessed from pointers using two ways that
are. Using dot and asterisk operator on a pointer. The -> (arrow) operator is used to access class,
structure or union members using a pointer.
Example:
The statement *ptr = &s1; assigns the address of variable s1 to the pointer ptr:
• &: The address-of operator, which is used to get the address of data stored in a variable , ptr: A pointer
variable that stores the address of the variable s1
SYNTAX:
member definition;
member definition;
...
member definition;
Examples of strings
strcopy(str1,str2);
strcpy(str1, “ Kerala”);
14
1-P-Structure variable type 1 2-P- WAP to print details of the person (name,
age, Height) using Structures Type 2
15
Print the record of the book, as shown using By Assigning values
structure
16
UNIONS
In C programming, a union is a user-defined data type that allows different data types to be stored in the same
memory location. All the members of a union share the same memory location. Therefore, if we need to use
the same memory location for two or more members, then union is the best data type for that.
Example:
Memory efficiency
Unions are an efficient way to reuse memory because only one member can be accessed at a time.
Declaration
Members
A union can have multiple members, but only one member can contain a value at a given time.
Use
Unions are similar to structures, but all of a union's members start at the same location in memory. Unions
can be useful when communicating with peripherals through memory mapped registers.
17
Bit Fields in C
In C language, we have union and struct data types where we can declare user-defined data types. The size of
the struct depends on data members. But sometimes, we do not need such a huge size of the data type,
because it occupies memory, and it creates a waste of memory.
Documentation of programs
When documenting your C code, it is important that you provide a clear and concise description of what your
program and/or function(s) accomplish. Furthermore, your code needs to be commented in a meaningful way.
Variables
Structures
18
C Compiler
A compiler is a software that converts the source code to the object code. In other words, we can say that it
converts the high-level language to machine/binary language. Moreover, it is necessary to perform this step
to make the program executable. This is because the computer understands only binary language.
Linker in C
A linker is an important utility program that takes the object files, produced by the assembler and compiler,
and other code to join them into a single executable file. A loader is a vital component of an operating system
that is accountable for loading programs and libraries.
• Program Testing
The process of verifying that a software system is functional, reliable, and performs as expected. Testing can
be manual or automated, and it doesn't require knowledge of the source code. Testers perform testing.
• Debugging
The process of identifying, analyzing, and fixing errors found during testing. Debugging is a complex process
that requires a proper understanding of the source code. Programmers or developers perform debugging
Types of errors
Syntax errors
These errors are caused by incorrect grammar in the code and are usually the easiest to fix. Examples include
missing semicolons.
Run-time errors
These errors occur during the execution of a program and can cause it to crash or produce incorrect output.
Examples include division by zero or null pointer dereference.
Linker errors
These errors occur when functions cannot be found and are usually caused by misspelling or missing header
files.
Logical errors
19
These errors occur when the program runs without any syntax or run-time errors but produces incorrect or
unexpected results. Examples include incorrect sequence or wrong Boolean expression.
Semantic errors
These errors are logical errors or incorrect program logic. They can cause the program to compile successfully,
but to not function as intended. Examples include incorrect use of variables, functions, or data types
Debugging Programs
Debugging in C is the process of locating and fixing mistakes, bugs, and other problems in a C program. It
involves detecting and correcting logical, syntactic, and runtime issues to guarantee the program works
correctly.
3. Fix it.
The following are a number of approaches popularly adopted by programmers for debugging.
• Brute Force Method. This is the foremost common technique of debugging however is that the least
economical method. ...
• Program Slicing.
Some of the top 5 Debugging tools which are used by the software developers are- Visual Studio Code,
Android Studio, IntelliJ IDEA, ReSharper, PyCharm Debugger, Chrome DevTools and X code
Case study:
A bookshop uses a PC to maintain an inventory of books. The list includes details such as: Author, Title,
price, stock position. To see the availability of the book, owner enters the title and system replies whether
the book is available or not, and display the details of Author, Title, price, stock position.
20