0% found this document useful (0 votes)
19 views

Handouts Module 4 Fns and Struct

Uploaded by

udayampta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Handouts Module 4 Fns and Struct

Uploaded by

udayampta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

HANDOUTS 4

Introduction to Problem Solving through Programs


Module 4 (Functions, Structures and pointers)
Top-down Design. Implementation of Algorithms using functions: Use of procedures to emphasize
modularity, Basics of Functions, Functions Returning Non-integers, Recursion, External Variables. Scope
Rules, Header Files – Character Class Tests: <ctype.h> , String Functions: <string.h>, Mathematical Functions:
<math.h>, Utility Functions: <stdlib.h>. Static Variables, Register Variables, Block Structure, Initialization

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:

After completion of this unit, the student will be able to

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

Top-down design can help to:

• Clarify what needs to be done

• Make the new parts less complicated and easier to figure out

• Allow more than one person to work on the solution

• Improve the modularity of a program, making it easier to debug

• 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.

The function is of two types user-defined function and library function. I

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.

Some of the math.h Library Functions

• sin() returns the sine of a radian angle.

• cos() returns the cosine of an angle in radians.

• tan() returns the tangent of a radian angle.

• floor() returns the largest integral value less than or equal to x.

• ceil() returns the smallest integer value greater than or equal to x.

• pow() returns base raised to the power of exponent(x y )

Some of the conio.h Library Functions

• clrscr() used to clear the output screen.

• getch() reads character from keyboard.

3
• textbackground() used to change text background

User defined function

• 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.

Functions in C are the basic building blocks of a C program.

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 declaration : int function ( int );

Function call : function( x );

Function definition:

int function( int x )

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.

Local Variable Global Variables

O/P

Printing local var inside main function 10

Printing local var inside function 100

Functions in C can be categorized into four types based on the value returned and the arguments passed:

• Functions that take arguments and return a value


• Functions that take arguments and return no value
• Functions that take no arguments and return a value
• Functions that neither take arguments nor return a value
// Example: int sum = add(5, 3);

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.

Formal parameters are declared in the function prototype and definition.

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.

Actual parameters can be constants, variables, or expressions.

Formal parameters Example

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 Call by Reference

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 and no return value

⚫ Function with no arguments and with return value

⚫ Function with no arguments and no return value

Function with arguments and return value Function with arguments but no return value

Syntax: When a function has arguments, it receives any


data from the calling function but it returns no
Function declaration : int function ( int );
values. These are void functions with no return
Function call : function( x ); values.

Function definition: Syntax:

int function( int x ) Function declaration : void function ( int );

{ Function call : function( x );

statements; Function definition:

return x; void function( int x ) {


} statements; }

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 call : function();

Function definition :

void function()

statements; }

Example Example:

Output : Sum of two given values = 16


Output: The total amount is :8811.708984

Recursion

Recursion in C programming refers to a function calling itself.

Factorial Formula

The formula to find the factorial of a number is

n! = n × (n-1) × (n-2) × (n-3) × ….× 3 × 2 × 1

Factorial of 3 is: 3! = 3 × 2 × 1

Some formulae

9
Facorial Each number is equal to the sum of the preceding two numbers

n! = n × (n-1) × (n-2) × (n-3) × ….× 3 × 2 × 1

Fibonacci Fn = Fn-1 + Fn-2

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

Some Data example calling library functions

11
Note on header files from C library

Static Variables, Register Variables, Block Structure, Initialization


A static variable is a variable in computer programming that is allocated during compilation and remains in
existence for the entire program run. Static variables are accessible throughout the application and are more
performant than application variables.

Ex:

#include <stdio.h>

int main()

{ static int x; int y;

printf("%d \n%d", x, y);}

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:

register char x = 'S'; register int a = 10;

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.

• Each variable within a structure is called a member.

• Structure information is accessed using dot operator (.).

Declaring Structure

• struct StructureName {

• // members

• data_type1 member1;

• data_type2 member2;

• // ...

• };

Structure Declaration and Initialization

• Declaration

struct StructureName variableName;

• Initialization

struct StructureName variableName = {value1, value2, ...};

13
Accessing members of the structure
There are two ways to access structure members:

1. By . (member or dot operator): variableName.member1;

2. By -> (structure pointer operator)

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:

struct [structure tag]{

member definition;

member definition;

...

member definition;

} [one or more structure variables];

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

Type 3 : Assigning values to the structure Car structure

15
Print the record of the book, as shown using By Assigning values
structure

Structure and Using function call

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

S1 is the union variable

Unions are an efficient way to reuse memory because only one member can be accessed at a time.

Declaration

Unions are created using the union keyword.

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

The five main types of errors in C programming are:

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.

Line 14, error expected , or ;….

Basic method of all debugging:

1. Know what your program is supposed to do.

2. Detect when it doesn't.

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. ...

• Backtracking. This is additionally a reasonably common approach. ...

• Cause Elimination 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

You might also like