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

Programming in C Unit III

The document provides an overview of key concepts in C programming, focusing on arrays, functions, and pointers. It explains array declaration, initialization, and types, as well as the structure and usage of functions including their types and parameter passing methods. Additionally, it covers pointers, their syntax, and how they are utilized in C programming for memory management.

Uploaded by

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

Programming in C Unit III

The document provides an overview of key concepts in C programming, focusing on arrays, functions, and pointers. It explains array declaration, initialization, and types, as well as the structure and usage of functions including their types and parameter passing methods. Additionally, it covers pointers, their syntax, and how they are utilized in C programming for memory management.

Uploaded by

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

B.

Sc: Information Technology- First Year Semester-I


B.Sc: Computer Science- First Year Semester-I

Introduction to C Programming

Unit-III Notes
3.1 Arrays:-
• An array in C is a fixed-size collection of similar data items stored in contiguous memory locations.
• It can be used to store the collection of primitive data types such as int, char, float, etc., and also derived
and user-defined data types such as pointers, structures, etc.
• Array in C is one of the most used data structures in C programming.
• It is a simple and fast way of storing multiple values under a single name.

3.1.1 C Array Declaration:-


• In C, we have to declare the array like any other variable before using it.
• We can declare an array by specifying its name, the type of its elements, and the size of its
dimensions.
• When we declare an array in C, the compiler allocates the memory block of the specified size to the
array name.
Syntax of Array Declaration
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
where N is the number of dimensions.

The C arrays are static in nature, i.e., they are allocated memory at the compile time.

3.1.2 C Array Initialization:-


• Initialization in C is the process to assign some initial value to the variable.
• When the array is declared or allocated memory, the elements of the array contain some garbage
value. So, we need to initialize the array to some meaningful value.
There are multiple ways in which we can initialize an array in C.:
1. Array Initialization with Declaration:
• In this method, we initialize the array along with its declaration.
• We use an initializer list to initialize multiple elements of the array.
• An initializer list is the list of values enclosed within braces { } separated b a comma.
Syntax:-
data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size:


• If we initialize an array using an initializer list, we can skip declaring the size of the array as the
compiler can automatically deduce the size of the array in these cases.
• The size of the array in these cases is equal to the number of elements present in the initializer list as
the compiler can automatically deduce the size of the array.
Ex:-
data_type array_name[] = {1,2,3,4,5};
The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops):


• We initialize the array after the declaration by assigning the initial value to each element
individually.
• We can use for loop, while loop, or do-while loop to assign the value to each element of the array.
Ex:-
for (int i = 0; i < N; i++)
{
array_name[i] = valuei;
}

3.1.3 Access Array Elements:-


• We can access any element of an array in C using the array subscript operator [ ] and the index
value i of the element.
array_name [index];
• One thing to note is that the indexing in the array always starts with 0, i.e., the first element is at
index 0 and the last element is at N – 1 where N is the number of elements in the array.

3.1.4 Update Array Element:-


• We can update the value of an element at the given index i in a similar way to accessing an element
by using the array subscript operator [ ] and assignment operator =.
array_name[i] = new_value;

3.15 Types of Arrays:-


There are two types of arrays based on the number of dimensions it has. They are as follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays

1. One Dimensional Array in C:-


• The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.
Syntax of 1D Array in C:-
array_name [size];
2. Multidimensional Array in C:-
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the popular
multidimensional arrays are 2D arrays and 3D arrays.
A. Two-Dimensional Array in C:
• A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions.
• They can be visualized in the form of rows and columns organized in a two-dimensional plane.
Syntax of 2D Array in C:
array_name[size1] [size2];
Here,
• size1: Size of the first dimension.
• size2: Size of the second dimension.

B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array.
A 3D array has exactly three dimensions.
It can be visualized as a collection of 2D arrays stacked on top of each other to create the third dimension.
Syntax of 3D Array in C:
array_name [size1] [size2] [size3];
3.2 Functions:-
• A function in C is a set of statements that when called perform some specific tasks.
• It is the basic building block of a C program that provides modularity and code reusability.
• The programming statements of a function are enclosed within { } braces, having certain meanings
and performing certain operations.
• Functions are also called subroutines or procedures in other languages.

3.2.1 Syntax of Functions in C:


The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls

1. Function Declarations
• In a function declaration, we must provide the function name, its return type, and the number and
type of its parameters.
• A function declaration tells the compiler that there is a function with the given name defined
somewhere else in the program.
Syntax:
return_type name_of_the_function (parameter_1, parameter_2);

• The parameter name is not mandatory while declaring functions. We can also declare the function
without using the name of the data variables.
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names

Function Declaration

Note: A function in C must always be declared globally before calling it.

2. Function Definition
• The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function).
• A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly.

The below example serves as both a function definition and a declaration.


return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}

Function Definition in C

3. Function Call
• A function call is a statement that instructs the compiler to execute the function.
• We use the function name and parameters in the function call.

In the below example, the first sum function is called and 10,30 are passed to the sum function.
After the function call sum of a and b is returned and control is also returned back to the main
function of the program.

Working of function in C

Note: Function call is neccessary to bring the program control to the function definition. If not
called, the function statements will not be executed.

3.2.2 Function Return Type:


• Function return type tells what type of value is returned after all function is executed.
• When we don’t want to return a value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the function.
Note: Only one value can be returned from a C function. To return multiple values, we have to use pointers
or structures.
3.2.3 Function Arguments
• Function Arguments (also known as Function Parameters) are the data that is passed to a function.
Example:
int function_name(int var1, int var2);

3.2.4 C Function Prototype:-


The C function prototype is a statement that tells the compiler about the function’s name, its return type,
numbers and data types of its parameters. By using this information, the compiler cross-checks function
parameters and their data type with function definition and function call.
Function prototype works like a function declaration where it is necessary where the function reference or
call is present before the function definition but optional if the function definition is present before the
function call in the program.
Syntax:
return_type function_name(parameter_list);
where,
• return_type: It is the data type of the value that the function returns. It can be any data type int,
float, void, etc. If the function does not return anything, void is used as the return type.
• function_name: It is the identifier of the function. Use appropriate names for the functions that
specify the purpose of the function.
• parameter_list: It is the list of parameters that a function expects in parentheses. A parameter
consists of its data type and name. If we don’t want to pass any parameter, we can leave the
parentheses empty.
3.2.5 How Does C Function Work?:-
Working of the C function can be broken into the following steps as mentioned below:
1. Declaring a function: Declaring a function is a step where we declare a function. Here we specify
the return types and parameters of the function.
2. Defining a function: This is where the function’s body is provided. Here, we specify what the
function does, including the operations to be performed when the function is called.
3. Calling the function: Calling the function is a step where we call the function by passing the
arguments in the function.
4. Executing the function: Executing the function is a step where we can run all the statements inside
the function to get the final result.
5. Returning a value: Returning a value is the step where the calculated value after the execution of
the function is returned. Exiting the function is the final step where all the allocated memory to the
variables, functions, etc is destroyed before giving full control back to the caller.

3.2.6 Types of Functions:


There are two types of functions in C:
1. Library Functions
2. User Defined Functions

Types of Functions in C

1. Library Function
• A library function is also referred to as a “built-in function”.
• A compiler package already exists that contains these functions, each of which has a specific
meaning and is included in the package.
• Built-in functions have the advantage of being directly usable without being defined, whereas user-
defined functions must be declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
• C Library functions are easy to use and optimized for better performance.
• C library functions save a lot of time i.e, function development time.
• C library functions are convenient as they always work.
2. User Defined Function
• Functions that the programmer creates are known as User-Defined functions or “tailor-made
functions”.
• User-defined functions can be improved and modified according to the need of the programmer.
• Whenever we write a function that is case-specific and is not defined in any header file, we need to
declare and define our own functions according to the syntax.
Advantages of User-Defined Functions
• Changeable functions can be modified as per need.
• The Code of these functions is reusable in other programs.
• These functions are easy to understand, debug and maintain.

3.2.7 Call by Value & Call by Reference:-


i)Call By Value in C
In call by value method of parameter passing, the values of actual parameters are copied to the function’s
formal parameters.
• There are two copies of parameters stored in different memory locations.
• One is the original copy and the other is the function copy.
• Any changes made inside functions are not reflected in the actual parameters of the caller.

ii) Call by Reference in C:


In call by reference method of parameter passing, the address of the actual parameters is passed to the
function as the formal parameters. In C, we use pointers to achieve call-by-reference.
• Both the actual and formal parameters refer to the same locations.
• Any changes made inside the function are actually reflected in the actual parameters of the caller.

3.2.8 Difference Between Call by Value and Call by Reference in C:

Call By Value Call By Reference

While calling a function, instead of passing the values


While calling a function, we pass the values of
of variables, we pass the address of variables(location
variables to it. Such functions are known as
of variables) to the function known as “Call By
“Call By Values”.
References.
Call By Value Call By Reference

In this method, the value of each variable in the In this method, the address of actual variables in the
calling function is copied into corresponding calling function is copied into the dummy variables of
dummy variables of the called function. the called function.

With this method, the changes made to the


With this method, using addresses we would have
dummy variables in the called function have no
access to the actual variables and hence we would be
effect on the values of actual variables in the
able to manipulate them.
calling function.

In call-by-values, we cannot alter the values of In call by reference, we can alter the values of
actual variables through function calls. variables through function calls.

Values of variables are passed by the Simple Pointer variables are necessary to define to store the
technique. address values of variables.

This method is preferred when we have to pass This method is preferred when we have to pass a large
some small values that should not change. amount of data to the function.

Call by value is considered safer as original Call by reference is risky as it allows direct
data is preserved modification in original data

3.2.9 What is Recursion in C?


• Recursion is the process of a function calling itself repeatedly till the given condition is satisfied.
• A function that calls itself directly or indirectly is called a recursive function and such kind of
function calls are called recursive calls.
• In C, recursion is used to solve complex problems by breaking them down into simpler sub-
problems.
• We can solve large numbers of problems using recursion in C. For example, factorial of a number,
generating Fibonacci series, generating subsets, etc.

3.2.10 Recursive Functions in C:-


In C, a function that calls itself is called Recursive Function.
The recursive functions contain a call to themselves somewhere in the function body. Moreover, such
functions can contain multiple recursive calls.
Basic Structure of Recursive Functions:
The basic syntax structure of the recursive functions is:
type function_name (args)
{
// function statements
// base condition
// recursion case (recursive call)
}

Basic Structure of Recursive Function in C

3.3 Pointers:-
• A pointer is defined as a derived data type that can store the address of other C variables or a
memory location.
• We can access and manipulate the data stored in that memory location using pointers.
• Pointers are one of the core components of the C programming language.
• A pointer can be used to store the memory address of other variables, functions, or even other
pointers.
• The use of pointers allows low-level memory access, dynamic memory allocation, and many other
functionality in C.

3.3.1 Syntax of C Pointers


The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing
operator in the pointer declaration.
datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to functions,
structures, etc.
3.3.2 How to Use Pointers?:
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing

1. Pointer Declaration
• In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use
the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is not initialized. Such
pointers are called wild pointers.

2. Pointer Initialization
• Pointer initialization is the process where we assign some initial value to the pointer variable.
• We generally use the ( &: ampersand ) addressof operator to get the memory address of a variable
and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
• We can also declare and initialize the pointer in a single step. This method is called pointer
definition as the pointer is declared and initialized at the same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to some value before starting
using it. Otherwise, it may lead to number of errors.

3. Pointer Dereferencing
• Dereferencing a pointer is the process of accessing the value stored in the memory address specified
in the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration.
Dereferencing a Pointer in C

3.4 Structures:-
• The structure in C is a user-defined data type that can be used to group items of possibly different
types into a single type.
• The struct keyword is used to define the structure in the C programming language.
• The items in the structure are called its member and they can be of any valid data type.
• Additionally, the values of a structure are stored in contiguous memory locations.

3.4.1 C Structure Declaration:


• We have to declare structure in C before using it in our program.
• In structure declaration, we specify its member variables along with their datatype.
We can use the struct keyword to declare the structure in C using the following syntax:
Syntax:
struct structure_name
{
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory is allocated to the
structure in the declaration.
3.4.2 C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating variables of the
structure type. We can define structure variables using two methods:
1. Structure Variable Declaration with Structure Template:
struct structure_name
{
data_type member_name1;
data_type member_name1;
....
....
}
variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template:


// structure declared beforehand
struct structure_name variable1, variable2, …....;

3.4.3 Access Structure Members


We can access structure members by using the ( . ) dot operator.
Syntax:
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to access the
members.

3.4.5 Initialize Structure Members:


Structure members cannot be initialized with the declaration. For example, the following C program fails in
the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

The reason for the above error is simple. When a datatype is declared, no memory is allocated for it.
Memory is allocated only when variables are created.
Default Initialization
• By default, structure members are not automatically initialized to 0 or NULL.
• Uninitialized structure members will contain garbage values. However, when a structure variable is
declared with an initializer, all members not explicitly initialized are zero-initialized.
struct Point
{
int x;
int y;
};

struct Point p = {0}; // Both x and y are initialized to 0


We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.

1. Initialization using Assignment Operator


struct structure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.

2. Initialization using Initializer List


struct structure_name str = { value1, value2, value3 };
In this type of initialization, the values are assigned in sequential order as they are declared in the structure
template.

3. Initialization using Designated Initializer List


Designated Initialization allows structure members to be initialized in any order. This feature has been added
in the C99 standard.
struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };
The Designated Initialization is only supported in C but not in C++.
3.4.6 Nested Structures:-
• C language allows us to insert one structure into another as a member.This process is called nesting
and such structures are called nested structures.
There are two ways in which we can nest one structure into another:
1. Embedded Structure Nesting
In this method, the structure being nested is also declared inside the parent structure.
Example:
struct parent {
int member1;
struct member_str member2 {
int member_str1;
char member_str2;
...
}
...
}

2. Separate Structure Nesting


In this method, two structures are declared separately and then the member structure is nested inside the
parent structure.
Example:
struct member_str {
int member_str1;
char member_str2;
...
}

struct parent {
int member1;
struct member_str member2;
...
}
One thing to note here is that the declaration of the structure should always be present before its definition as
a structure member. For example, the declaration below is invalid as the struct mem is not defined when it
is declared inside the parent structure.
struct parent {
struct mem a;
};

struct mem {
int var;
};
Accessing Nested Members:
We can access nested Members by using the same ( . ) dot operator two times as shown:
str_parent.str_child.member;
Assignment-III
Q1.Write Short Notes On:-
(a) C Array Initialization
(b) Types of Arrays
(c) Syntax of Functions in C
(d) C Function Prototype
(e) Types of Functions
(f) Call by Value & Call by Reference
(g) Recursive Functions in C
(h) Nested Structures

Q2. Differentiate Between Call by Value & Call by Reference.

Q3. How we can use Pointers in C?

You might also like