Understanding the Problem: Finding Minimum and Maximum in an Array
Before diving into pointers, the basic approach to finding the minimum and maximum values in an array is:
- Initialize two variables,
minandmax, with the first element of the array. - Iterate over the array starting from the second element.
- For each element:
- If it is less than
min, updatemin. - If it is greater than
max, updatemax.
- If it is less than
Example with array [23, 45, 6, 98]:
- Start: min = 23, max = 23
- Compare 45: max = 45 (since 45 > 23)
- Compare 6: min = 6 (since 6 < 23)
- Compare 98: max = 98 (since 98 > 45)
Final output: min = 6, max = 98
Why Use Pointers?
In C, when passing variables to functions, the default is call by value, meaning changes inside the function do not affect the original variables. To update original variables min and max from inside a function:
- Pass their addresses (pointers) to the function.
- Dereference pointers inside the function to update actual variables.
This method allows the function to indirectly "return" multiple values since C functions cannot return two variables simultaneously.
For a deeper understanding, you can refer to Understanding Variable Data Types and Operators in C++ which explains how variables and pointers operate in memory.
Pointer-Based Implementation Breakdown
Main Function Setup
- Define an array of integers.
- Calculate the array's length using
sizeof(array) / sizeof(array[0]). - Declare
minandmaxvariables. - Call a function
minmaxpassing:- The array,
- Its length,
- Addresses of
minandmax(&min,&max).
To understand array handling and memory representation, see Understanding Arrays in Programming: Declaration, Initialization, and Memory Representation.
minmax Function Logic
- Receive array pointer, length, and pointers to
minandmax. - Initialize
*minand*maxwith the first element of the array (using pointer dereferencing). - Loop through the array from the second element to the end:
- Compare each element with
*minand update if smaller. - Compare each element with
*maxand update if larger.
- Compare each element with
Important Notes
- Always dereference pointers (
*min,*max) to access or modify the actual variable values. - Passing addresses ensures that changes inside
minmaxaffect theminandmaxdeclared inmain.
For more on data structures and pointers, consider reading Understanding Data Structures Through C Language: A Comprehensive Guide.
Example Output
Given the array: [10, 3, 67, 98, 45]
The program prints:
- Minimum value in the array is 3
- Maximum value in the array is 98
Summary
Using pointers to pass variables by reference allows functions in C to modify multiple values outside their scope. This approach is essential for tasks like finding minimum and maximum elements in arrays where both values must be returned.
By understanding pointer dereferencing and address passing, you can write more efficient and flexible programs in C.
We've understood the basics of pointers. But it is equally important for us to
understand the application of pointers. In this presentation we will try to
understand one of the application of pointers
that is finding the largest and smallest
element in an array using pointers. So, let's get started. Before moving onto the actual program,
let's try to understand the basic idea behind finding
the largest and the smallest element in an array. Suppose, we have this array which
consist of four elements: 23, 45, six and 98. And apart from this we have these
two variables min and max.
As the name suggests, min contains
minimum value of this array and max will contain the
maximum value of this array. Initially, I'm initializing these two variables with
the first element of the array that is 23
and here is the pictorial representation of these two
variables min and max which contain value 23, okay. Now for the purpose of finding the
minimum and maximum value of this array we need one for loop which goes from one to three.
I want my for loop to learn from one index
to three index that is the last index of this array. Why am I starting from this index? Because I've already initialized the min and max
variables with the first element of the array.
I want to compare the rest of the elements
of this array with the first element, initially. That is why I'm starting from this element
instead of starting from this element. Because there is no point of
comparing 23 with 23, right!
Also, it is important to note
that, this is not the actual program. I'm writing this program in a casual way. That's why instead of writing the for loop in the
actual c syntax, I'm just writing this in a casual way.
This for loop simply runs from one to three. We just want to understand the basic idea. So, at this point we should
not focus on this syntax, okay.
In this for loop, we basically
have these two steps: in the first step we'll find out the minimum value and
in the second step we'll find out the maximum value. Here, we're trying to compare this
element with the minimum element.
If you find out that this element is
less than the minimum element then definitely this element is
the minimum possible element. Therefore the new minimum
element will be this element.
Otherwise if this element is greater
than the maximum element then definitely this element
is the maximum element. Therefore we'll put this element
in the max variable, okay.
We can see here that 45 is greater than 23, right.
Therefore the new maximum element is 45. So, we can replace this 23
by 45 in this max variable. Now, let's compare this element with the
new minimum and new maximum element.
As six is less than 23; therefore, the new
minimum element will be six not 23. Hence, we can replace this 23 by six, right. Now, in the third iteration of the for loop, we'll simply compare
98 with the new minimum and the new maximum element.
98 is not less than six but
98 is greater than 45, right! Therefore, we can say that the
new maximum element is 98. Hence, we can replace this 45 by 98.
At the end of this for loop, we have obtained
our new minimum and new maximum element that is six and 98, respectively. So, this is the basic idea of finding the
minimum and maximum element of an array.
But here as we can observe that I have not used any pointers
at all. In the actual program I'm going to use the pointers. Let's see how we can find the minimum
and maximum element using pointers. Let's dive into the code.
Inside this main function we can see that we have
an array which consists of these many values and we have these two variables min and max which will take
care of the minimum and the maximum element of the array and with the help of this len variable we're
basically trying to calculate the length of this array.
By using this idea of size of the whole array divided
by the size of the first element of the array. And we're calling this min max function
also in which we are passing the whole array, the length of the array and the
addresses of the min variable and the max variable
And here in this min max function, we are receiving
the whole array, the length of the array and we're receiving the addresses of the min
variable and max variable in these pointers. With the help of this min max function, we're trying to calculate
the minimum and the maximum element of the array.
And the logic that we've understood to calculate the minimum
and maximum element of the array is given over here. Here instead of dealing with the actual variables, we're
dealing with the pointers. But, why are we doing this? We can see here the actual declaration of these
variables min max is inside this main function, right.
And we're trying to make changes to these min and max
variables outside of this main function in this function. So, if we simply pass the copies of these variables to
this function and make changes in this function then it will not get reflected
in these variables, right.
Because we're passing the copies
that what is called call by value. But we want the changes that we make to these
variables outside of this function to get reflected back to this function again. That is why we're passing
the addresses of these variables instead of values.
Here there is a need of dealing with pointers if want to
make the changes reflected back to these variables in this function. Here, we should understand this fact that we cannot
return two variables from this function at a time. It is not possible to return two or more variables from
this function. That is why we're taking the help of pointers.
Right. We cannot return min and max
variables at a time from this function. That is why with the help of these pointers we're making changes
to the actual variables outside of this function, right. There is one important point for us to
understand. Here we're dealing with pointers;
therefore, we cannot simply write min
equals to max equals to arr zero. We first have to dereference the pointers,
so that we can go to the actual locations and then make changes to them, okay. Here also
we have to dereference the pointers first
and then compare them with the actual values. Now in simple words, basically in this function we
are making changes to these original variables only. Because here we are passing the addresses
of these variables to this function
and making changes in those addresses. Therefore it will automatically get
reflected back to these variables and then we can print them on the screen.
Now let me execute this program, okay. The minimum value in the array is three
and maximum value is nine eight seven. We can see here in this array that minimum value is
three and maximum value is nine eight seven.
Therefore this program is working fine. Okay friends, this is it for now.
Thank you for watching this presentation.
You can calculate the length using sizeof operator: divide the total size of the array by the size of one element, like this: int len = sizeof(array) / sizeof(array[0]);. This correctly determines the number of elements to iterate over in the minmax function.
Pointer dereferencing means accessing or modifying the value stored at the memory address the pointer holds. In the minmax function, *min and *max refer to the actual min and max variables in main, so when we assign *min = array[0];, we update the original min variable outside the function.
Pointers allow a function to modify variables defined outside its scope by passing their memory addresses. In the minmax function, passing addresses of min and max lets the function update their values directly, enabling it to return both the minimum and maximum from a single function call.
First, declare your array and calculate its length. Initialize min and max variables in main. Then, call the minmax function passing the array, its length, and pointers to min and max (using &min, &max). Inside minmax, dereference these pointers to set initial values and iterate through the array to update min and max accordingly.
C functions can return only one value. To effectively 'return' multiple values like min and max, we pass pointers (addresses) to variables from the calling function. By dereferencing these pointers inside the called function, multiple values can be modified and accessed after the function completes.
A common mistake is forgetting to pass variable addresses (using &) to the function, or not dereferencing pointers inside the function before using them. Both errors can prevent the original min and max variables from updating correctly. Also, ensure the array length is correct to avoid out-of-bounds access.
By using pointers, functions can modify multiple variables without relying on global variables or complex return types. This makes the code modular, reusable, and allows efficient memory management, which is crucial for low-level programming in C.
Heads up!
This summary and transcript were automatically generated using AI with the Free YouTube Transcript Summary Tool by LunaNotes.
Generate a summary for freeRelated Summaries
Understanding Float, Double, and Long Double Data Types in C
This guide explains the fundamental floating-point data types: float, double, and long double, their memory sizes, precision differences, and underlying representations like fixed and floating point. Learn through real coding examples why these types matter and how to use them effectively for precise numerical calculations.
Understanding Arrays in Programming: Declaration, Initialization, and Memory Representation
This video provides a comprehensive overview of arrays in programming, covering their declaration, initialization, and how they are represented in memory. It explains the need for arrays, the types of arrays, and the importance of data types in array declarations.
Comprehensive Guide to Integer Data Types and Modifiers in C Programming
This article explores integer data type modifiers in C, including short, long, signed, and unsigned. Learn about memory size differences, value ranges, and how to use symbolic constants and printf specifiers to work effectively with these data types.
Understanding Variables in C Programming: Declaration, Initialization, and Usage
This lesson introduces the concept of variables in C programming, explaining their declaration, definition, initialization, and how to use them effectively. Learn how variables act as memory storage with simple examples and best practices to manage variable values within your programs.
Understanding Float, Double, and Long Double Data Types in C Programming
This guide explains the differences between float, double, and long double data types in C, focusing on their sizes, precision, and usage for representing fractional numbers. It covers fixed versus floating-point representations, illustrates precision limits with coding examples, and clarifies common pitfalls in numerical operations.
Most Viewed Summaries
Kolonyalismo at Imperyalismo: Ang Kasaysayan ng Pagsakop sa Pilipinas
Tuklasin ang kasaysayan ng kolonyalismo at imperyalismo sa Pilipinas sa pamamagitan ni Ferdinand Magellan.
A Comprehensive Guide to Using Stable Diffusion Forge UI
Explore the Stable Diffusion Forge UI, customizable settings, models, and more to enhance your image generation experience.
Pamamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakaran ng mga Espanyol sa Pilipinas, at ang epekto nito sa mga Pilipino.
Mastering Inpainting with Stable Diffusion: Fix Mistakes and Enhance Your Images
Learn to fix mistakes and enhance images with Stable Diffusion's inpainting features effectively.
Pamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakarang kolonyal ng mga Espanyol sa Pilipinas at ang mga epekto nito sa mga Pilipino.

