By the way, happy 3.14 day.
Is there a program that can calculate pi to xx number of digits? Haven't heard of one yet...
Recently I came across some old newbie-code I had done to determine min and max between two inputted numbers. It wasn't very fancy, and I was initially stumped as to why it kept assigning the wrong numbers to min and max, only to realize it was me who was labeling the maximum/minimum wrong in the strings. go figure.
Thankfully, it's easier to find the max and min of any number within a given array (suppose the size = N). The logic flows like this: going through each number in the array, check the number (using if) to confirm if it is greater than the starting number, array[0], if so then the max number is the number at position array[a]. Next check the same number (using if) to confirm if it is less than min (which is also assigned array[0]), if so the min number is the position at array[a]. If neither condition passes, the loop moves on to the next number in the array.
For instance if the array was: int array[N] = {5, 9, 2, 6, 10, 1} and N = 5;
int max = array[0];
int min = array[0];
The loop would assign max and min as follows:
iteration 0
5 (array[0]) larger than max (array[0])? 5 !> 5, so max = array[0].
5 (array[0]) smaller than min (array[0])? 5 !< 5, so min = array[0].
iteration 1
9 (array[1]) larger than max (array[0])? 9 > 5, so max is now assigned array[1].
9 (array[1]) smaller than min (array[0])? 9 !< 5, so min remains as array[0].
iteration 2
2 !> 9, max = array[1].
2 < 5, min is now assigned array[2].
iteration 3
6 !> 9, max = array[1].
6 !< 2, min = array[2].
iteration 4
10 > 9, max is now assigned array[4].
10 !< 2, min = array[2].
iteration 5
1 !> 10, max = array[4].
1 < 10, min is now assigned array[5].
So the maximum integer is 10, and minimum integer is now 1.
Note that max and min are passed by reference & so the function can directly modify their contents using the loop. This is a kinda roundabout way to return two different variables from a function without using return, if the two variables are introduced in the main program before calling the function, as return can only return one variable per function.
No comments:
Post a Comment