0% found this document useful (0 votes)
48 views19 pages

LDP Unit-3

The document discusses arrays and strings in C programming. It explains key concepts of arrays like declaration, initialization, accessing and iterating elements. It also covers one dimensional and two dimensional arrays, and compares their characteristics. The document further discusses declaration and initialization of array of strings and invalid operations on them. It finally covers concepts of built-in functions and user defined functions in C.

Uploaded by

binatripathi95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views19 pages

LDP Unit-3

The document discusses arrays and strings in C programming. It explains key concepts of arrays like declaration, initialization, accessing and iterating elements. It also covers one dimensional and two dimensional arrays, and compares their characteristics. The document further discusses declaration and initialization of array of strings and invalid operations on them. It finally covers concepts of built-in functions and user defined functions in C.

Uploaded by

binatripathi95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT-3

Array, String, Functions and Recursion


What is an Array?
An array is a collection of items of same data type stored at contiguous memory locations.

Concepts of array
In C programming, an array is a collection of elements, all of the same data type, stored at
contiguous memory locations. Each element in an array is identified by an index or a key
value, which represents its position in the array. Arrays are widely used for storing and
manipulating collections of data in computer programs. Here are the key concepts related to
arrays in C programming:

1. Declaration:
Arrays are declared by specifying the data type of the elements they will hold, followed by
the array name and the size of the array in square brackets. For example:
int numbers[5]; // declares an integer array of size 5

2. Initialization:
Arrays can be initialized at the time of declaration:
int numbers[5] = {1, 2, 3, 4, 5};

Alternatively, you can initialize individual elements later in the program.

3. Accessing Elements:
Array elements are accessed using their index, starting from 0. For example:
int x = numbers[2]; // accesses the third element of the array (index 2)

4. Array Indexing:

Arrays in C use zero-based indexing. This means the first element of the array is accessed
using index 0, the second element with index 1, and so on.

5. Array Size:
The size of an array is fixed upon declaration and cannot be changed during runtime. It is
specified in square brackets. For example, int numbers[5] creates an array that can hold 5
integers.
6. Iterating Through Arrays:
Arrays can be traversed using loops. For example, a for loop can be used to iterate through
all elements of an array:
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

} 7. Multidimensional Arrays:
C supports multidimensional arrays. They are essentially arrays of arrays. For example, a 2D
array can be declared as follows:
int matrix[3][3]; // declares a 3x3 matrix

8. Passing Arrays to Functions:


Arrays can be passed to functions in C. When you pass an array to a function, you are
actually passing the reference to its first element. For example:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}

9. Strings as Arrays:
In C, strings are essentially arrays of characters. Strings are terminated by a null character
('\0'), which indicates the end of the string.

10. Array Arithmetic:


Pointer arithmetic can be performed on arrays in C. For instance, if arr is an array, arr + 1
will point to the next element of the array.

1-Dimentional & 2-Dimentional arrays


Array is a data structure that is used to store variables that are of similar data types
at contiguous locations. The main advantage of the array is random access and cache
friendliness. There are mainly three types of the array:
 One Dimensional (1D) Array
 Two Dimension (2D) Array
 Multidimensional Array
One Dimensional Array:
 It is a list of the variable of similar data types.
 It allows random access and all the elements can be accessed with the help of their
index.
 The size of the array is fixed.
 For a dynamically sized array, vector can be used in C++.
 Representation of 1D array:

Two Dimensional Array:


 It is a list of lists of the variable of the same data type.
 It also allows random access and all the elements can be accessed with the help of
their index.
 It can also be seen as a collection of 1D arrays. It is also known as the Matrix.
 Its dimension can be increased from 2 to 3 and 4 so on.
 They all are referred to as a multi-dimension array.
 The most common multidimensional array is a 2D array.
 Representation of 2 D array:

Difference Table:
Basis One Dimension Array Two Dimension Array

Store a single list of the


Store a ‘list of lists’ of the element of a
Definition element of a similar data
similar data type.
type.

Represent multiple data Represent multiple data items as a table


Representation
items as a list. consisting of rows and columns.
The declaration varies for
different programming The declaration varies for different
language: programming language:
1. For C++, 1. For C++,
Declaration datatype datatype
variable_name[row] variable_name[row][column]
2. For Java, 2. For Java,
datatype [] datatype [][] variable_name= new
variable_name= new datatype[row][column]
datatype[row]

Dimension One Two

size of(datatype of the size of(datatype of the variable of the


Size(bytes) variable of the array) * array)* the number of rows* the
size of the array number of columns.

Address of a[i][j] can be calculated in


two ways row-major and column-major
1. Column Major: Base Address +
Size of each element (number of
Address of a[index] is rows(j-lower bound of the
Address equal to (base Address+ column)+(i-lower bound of the
calculation. Size of each element of rows))
array * index). 2. Row Major: Base Address + Size
of each element (number of
columns(i-lower bound of the
row)+(j-lower bound of the
column))

int arr[5]; //an array with int arr[2][5]; //an array with two rows
one row and five columns and five columns will be created.
Example will be created. a b c d e
{a , b , c , d , e} f g h i j

Declaration and initialization of arrays and string


In C programming String is a 1-D array of characters and is defined
as an array of characters. But an array of strings in C is a two-
dimensional array of character types. Each String is terminated with
a null character (\0). It is an application of a 2d array.
Syntax:
char variable_name[r] = {list of string};

Here,
 var_name is the name of the variable in C.
 r is the maximum number of string values that can be stored in a
string array.
 c is the maximum number of character values that can be stored
in each string array.
Example:
// C Program to print Array
// of strings
#include <stdio.h>
// Driver code
int main()
{
char arr[3][10] = {"Geek", "Geeks", "Geekfor"};
printf("String array Elements are:\n");

for (int i = 0; i < 3; i++)


{
printf("%s\n", arr[i]);
}
return 0; }

We have 3 rows and 10 columns specified in our Array of String but


because of prespecifying, the size of the array of strings the space
consumption is high. So, to avoid high space consumption in our
program we can use an Array of Pointers in C.

Invalid Operations in Arrays of Strings

We can’t directly change or assign the values to an array of strings


in C.
Example:
char arr[3][10] = {"Geek", "Geeks", "Geekfor"};
Here, arr[0] = “GFG”; // This will give an Error that says assignment
to expression with an array type.
To change values we can use strcpy() function in C
strcpy(arr[0],"GFG"); // This will copy the value to the arr[0].

Functions and Recursion


Concepts of Built-in functions & user defined functions
In C programming, functions are blocks of code that perform a specific task. Functions
provide modularity and code reusability in a program. There are two types of functions in C:
built-in functions (standard library functions) and user-defined functions.

1. Built-in Functions (Standard Library Functions):


C programming language provides several built-in functions through standard libraries. These
functions are already defined and can be used directly in your program after including the
appropriate header files. Some commonly used standard library functions include:
 Input/Output Functions:
 printf(): Used for output/printing.
 scanf(): Used for input/reading.
 getchar(): Reads a character from the standard input.
 puts(): Outputs a string followed by a newline character.
 gets(): Reads a line from the standard input.
 Mathematical Functions:
 sqrt(): Calculates the square root of a number.
 pow(): Calculates the power of a number.
 fabs(): Returns the absolute value of a floating-point number.
 rand(): Generates a random number.
 String Functions:
 strlen(): Calculates the length of a string.
 strcpy(): Copies one string to another.
 strcat(): Concatenates two strings.
 strcmp(): Compares two strings.

To use these functions, you need to include the appropriate header file. For example, to use
printf(), you include <stdio.h>.

2. User-Defined Functions:
User-defined functions are created by the programmer to perform specific tasks within a C
program. These functions enhance the modularity of the program and make the code easier to
understand and maintain. User-defined functions consist of a function declaration, function
definition, and a function call.
 Function Declaration:
 Syntax: return_type function_name(parameters);
int add(int a, int b); // Function declaration); // Function declaration
 Function Definition:
 Syntax:
return_type function_name(parameters) {
// Function body
// Code to perform the task
} a + b; // Function to add tw

o numbers }
 Function Call:
 Syntax: return_type variable = function_name(arguments);
int sum = add(3, 5); // Calling the add function and storing the result in the 'sum' variable //
Calling the add function and storing the result in the 'sum' variable
Prototypes
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.
For example,
int func(int, char, char *, float);

Difference between Function Declaration and Function Prototype

Function Declaration Function Prototype

Function Declaration is used to tell The function prototype tells the compiler about the
the existence of a function. existence and signature of the function.
Function Declaration Function Prototype

A function declaration is valid even


A function prototype is a function delcaration that
with only function name and return
provides the function’s name, return type, and
type.
parameter list without including the function body.

Typically used in header files to Used to declare functions before their actual
declare functions. definitions.

Syntax: Syntax:
return_type function_name(); return_type function_name(parameter_list);

Definition
In C programming, #define is a preprocessor directive that is used to define macros. The
macros are the identifiers defined by #define which are replaced by their value before
compilation. We can define constants and functions like macros using #define. The
generics in C are also implemented using the #define preprocessor directive along
with _Generic.
Syntax of C #define
The syntax of #define preprocessor directive in C is:
For Defining Constants
#define MACRO_NAME value
For Defining Expressions
#define MACRO_NAME (expression within brackets)
For Defining Expression with Parameters
Arguments passed in the macros can be used in the expression.
#define MACRO_NAME(ARG1, ARG2,..) (expression within brackets)

Declaration
In C programming, a declaration is a statement that specifies the type and name of a variable,
function, or an array, but does not initialize it. Declarations inform the compiler about the
existence of a variable or function before they are used in the program. This enables the
compiler to perform type checking and generate appropriate code when variables are used or
functions are called. Declarations are essential for ensuring that the program's syntax and data
types are correct.

Variable Declarations:

int age; // Declaration of an integer variable named 'age'


float pi; // Declaration of a floating-point variable named 'pi'
char grade; // Declaration of a character variable named 'grade' a character variable named
'grade'
Function Declarations:

int age; // Declaration of an integer variable named 'age'

float pi; // Declaration of a floating-point variable named 'pi'

char grade; // Declaration of a character variable named 'grade'

Array Declarations:

int numbers[10]; // Declaration of an integer array named 'numbers' with a size of 10

char name[50]; // Declaration of a character array (string) named 'name' with a size of
50

In the above examples, int, float, and char are data types. add and greet are function names.
numbers and name are variable names. The semicolon at the end of each declaration
statement is necessary to terminate the statement in C.

It's important to note that a declaration without an initialization means that the variable is
created, but it contains garbage values (for basic types like integers or floating-point
numbers) until you assign a valid value to it. Functions, on the other hand, need to be defined
after they are declared in C, as the declaration only informs the compiler about the function's
signature.

Recursion
Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to
experiment with it.

Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers together
by breaking it down into the simple task of adding two numbers:

Example
int sum(int k);

int main() {
int result = sum(10);
printf("%d", result);
return 0;
}

int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}

Parameters
In C programming, parameters (also known as arguments) are values that are passed into a
function when the function is called. Functions use parameters to accept data from the caller
and perform operations on that data. Parameters allow functions to be versatile and work with
different sets
of data each time they are called.
Here's the general syntax of a function in C with parameters
return_type function_name(parameter_type parameter1, parameter_type parameter2, ...,
parameter_type parameterN) {
// Function body
// Code that uses the parameters
// Optionally, return a value using 'return' statement if the function has a return type }
In this syntax:
return_type is the data type of the value that the function returns (or void if the function
doesn't return any value).
function_name is the name of the function.
parameter_type specifies the data type of each parameter.
parameter1, parameter2, ..., parameterN are the names of the parameters.
Here's an example of a function called add that takes two integers as parameters and returns
their sum:
int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
In this example, int num1 and int num2 are parameters of the function add.
When calling a function with parameters, you provide the actual values (arguments) for the
parameters. For example:
int result = add(3, 5); // Calls the 'add' function with arguments 3 and 5, and assigns the result
(8) to the 'result' variable.
In this call, 3 and 5 are the arguments passed to the add function. These values are assigned to
num1 and num2 parameters respectively in the function's definition. The function computes
the sum (8 in this case) and returns it to the caller.
Functions can have multiple parameters of different data types, allowing you to pass various
types of data to functions for processing. Parameters enable functions to be reusable and
flexible, making them a fundamental concept in C programming.

Parameter passing
parameters can be passed to functions in several ways: by value, by address (or reference),
and by pointer. Each method has its own use cases and implications, and understanding these
concepts is crucial for effective parameter passing in C.
1. Passing by Value:
When you pass a parameter by value, you are passing the actual value of the variable to the
function. Changes made to the parameter inside the function do not affect the original
variable outside the function.

#include <stdio.h>
void modifyValue(int x) {
x = x * 2;
printf("Inside function: %d\n", x);
}
int main() {
int num = 5;
modifyValue(num);
printf("Outside function: %d\n", num);
return 0;
}
2. Passing by Address (Reference):
When you pass a parameter by address, you are passing the memory address of the variable.
This allows you to modify the original variable's value using pointers inside the function.
#include <stdio.h>
void modifyValue(int *x) {
*x = *x * 2;
}
int main() {
int num = 5;
modifyValue(&num); // Pass the address of 'num'
printf("Modified value: %d\n", num); // Output: 10
return 0;
}
3. Passing by Pointer:
Passing by pointer is similar to passing by address. When you pass a pointer as a parameter,
you can directly modify the value that the pointer points to, allowing you to change the
original variable's value.
#include <stdio.h>
void modifyValue(int *x) {
*x = *x * 2;
}

int main() {
int num = 5;
int *ptr = &num;
modifyValue(ptr); // Pass the pointer 'ptr'
printf("Modified value: %d\n", num); // Output: 10
return 0;
}

Calling a Function
you call a function by using its name followed by parentheses (). If the function requires
parameters, you pass the values for those parameters within the parentheses. If the function
does not require any parameters, you still need to use empty parentheses. Here's the basic
syntax for calling a function in C:
function_name(parameters);
Example :
#include <stdio.h>
// Function declaration
int add(int num1, int num2);
int main() {
int result;
// Calling the 'add' function with arguments 3 and 5
result = add(3, 5);

// Printing the result


printf("Sum: %d\n", result); // Output: Sum: 8
return 0;
}
// Function definition
int add(int num1, int num2) {
return num1 + num2;
}

Types of Functions
functions can be categorized into several types based on their roles and
return types
1. Standard Library Functions:
These are built-in functions provided by the C standard library. They are predefined and can
be directly used in C programs after including the appropriate header file. Examples include
printf(), scanf(), strlen(), strcpy(), rand(), and sqrt(). Standard library functions are
standardized across all C compilers.
2. User-Defined Functions:
User-defined functions are functions created by the programmer. They provide modularity
and code reusability. You can define your own functions for specific tasks. User-defined
functions are declared, defined, and called by the programmer as needed.
Example:
int add(int a, int b) {
return a + b;
}
3. Recursive Functions:
Recursive functions are functions that call themselves either directly or indirectly. They are
useful for solving problems that can be broken down into smaller, similar subproblems.
Recursive functions have a base case to terminate the recursion.
Example (Factorial using recursion):
int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
4. Inline Functions:
Inline functions are a C language feature that allows the compiler to insert the code of a
function directly into the calling code rather than executing a function call. This can improve
performance for small, frequently used functions.
Example:
inline int square(int x) {
return x * x;
}
5. Function Pointers:
Function pointers are pointers that point to the address of functions. They allow functions to
be passed as arguments to other functions and provide a way to implement polymorphism and
callbacks in C.
Example (Function pointer as a parameter):
#include <stdio.h>
void greet() {
printf("Hello, World!\n");
}
void callFunction(void (*func)()) {
func();
}
int main() {
callFunction(greet); // Output: Hello, World!
return 0;
}

Recursive function
Macros
Macros can be used to replace simple expressions or values, providing clarity and ease of modification for constants or
frequently used code snippets.

#define MAX_SIZE 100


#define SQUARE(x) ((x) * (x))

int main() {
int arr[MAX_SIZE];
int area = SQUARE(5); // Replaced with ((5) * (5)) = 25
// ...
return 0; }
Macros for Function-like Behavior:
Macros can be used to create function-like behavior. However, be cautious when using
macros for complex operations, as they can lead to unexpected behavior due to multiple
evaluations.

#define MAX(a, b) ((a) > (b) ? (a) : (b))


int main() {
int x = 5;
int y = 10;
int max_value = MAX(x++, y++); // Replaced with ((x++) > (y++) ? (x++) :
(y++))
printf("Max value: %d\n", max_value); // Output: Max value: 11
printf("x: %d, y: %d\n", x, y); // Output: x: 7, y: 12
return 0;
}
Conditional Macros:
Macros can also be defined conditionally based on whether a certain macro is defined or not,
using #ifdef, #ifndef, #endif, and #else preprocessor directives.
#define DEBUG // Uncomment to enable debugging
int main() {
#ifdef DEBUG
printf("Debug mode is enabled.\n");
#else
printf("Debug mode is disabled.\n");
#endif
return 0;
}
Per-Processing Recursion
recursion refers to a function calling itself directly or indirectly. However, the C preprocessor
does not support recursion in the same way that the actual functions do. The C preprocessor,
which runs before the compilation starts, does not have the capability to perform recursive
operations. Preprocessor macros are expanded in a single pass, and there are no mechanisms
to handle recursive macro expansion.
For example, consider the following attempt at a recursive macro that calculates the factorial
of a number:
#define FACTORIAL(n) (n <= 1 ? 1 : n * FACTORIAL(n - 1))

This macro attempts to calculate the factorial of a number using recursion. However, if you
try to use this macro like this:

int result = FACTORIAL(5);

It will not work as expected because the C preprocessor does not support recursive macro
expansion. The preprocessor will expand FACTORIAL(5) once, and the result would look
something like this:
int result = (5 <= 1 ? 1 : 5 * (5 - 1));
This expression is not recursive; it only contains a single occurrence of the FACTORIAL
macro.
If you need recursion in C, you have to use recursive functions rather than recursive macros.
Functions can call themselves recursively, which allows you to perform recursive operations
in C programs. Here's how you can implement the factorial function using recursion in C:
#include <stdio.h>
int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int result = factorial(5);
printf("Factorial: %d\n", result); // Output: Factorial: 120
return 0;
}

Solving problems using Recursion like Ackerman’s Function


⎧n+1 if m=0

A(m−1,1) if m>0 and n=0


A(m−1,A(m,n−1)) if m>0 and n>0

#include <stdio.h>
int ackermann(int m, int n) {
if (m == 0) {
return n + 1;
} else if (m > 0 && n == 0) {
return ackermann(m - 1, 1);
} else {
return ackermann(m - 1, ackermann(m, n - 1));
}
}

int main() {
int m = 3;
int n = 2;
int result = ackermann(m, n);
printf("Ackermann(%d, %d) = %d\n", m, n, result);
return 0;
}
In this example, the ackermann function is implemented recursively based on the definition
of Ackermann's function. When you run the program with m = 3 and n = 2, the output will
be:
Ackermann(3, 2) = 29
Ackermann's function is interesting because it can produce extremely large values even for
relatively small inputs. It's used as a benchmark to test the efficiency of various programming
languages and systems due to its rapid growth. When working with Ackermann's function or
any recursive function, it's important to consider the computational complexity and ensure
that the function terminates properly for the given inputs.

You might also like