I was given a problem to interchange the position of the max and min numbers in a given set of numbers and print out the old arrangement and new arrangement
The old one is like this : 5,5678,62,6000
and the new one is expected to be like this: 6000,5678,62,5
I've tried running different variations of the print code to print it all to no avail, as I've been able to interchange the max and min position of the numbers
int main () {
int m [4] = {5,5678,62,6000};
int i;
int max=m[0];
int min=m[0];
int pMin = 0;
int pMax = 0;
int temp = 0;
{
printf( "%d\n", m[i]) ;
}
for (i=0; i<4; i++){
{
printf( "%d\n", m[i]) ;
}
if ( m[i] > max )
{
max = m[i] ;
}
}
for (i=0; i<4; ++i){
if ( m[i] < min )
{
min = m[i] ;
}
}
temp = min;
min = max;
max = temp;
printf ("min = %d\n", min);
printf ("max = %d\n", max);
printf( "%d\n", m[i]) ;
getch();
}
If i'm able to do it right by only inputting this line of code
temp = min;
min = max;
max = temp;
I should be able to achieve the aim of switching the places of the maximum and minimum numbers, but i also want to print out the result such that the 2 numbers in the middle are unaltered just the first and last.
The old one is like this : 5,5678,62,6000
and the new one is expected to be like this: 6000,5678,62,5
You should get a warning from your compiler (if not, enable warning flags, like the -Wall
in GCC), about this printing statement, inside its own block:
{
printf( "%d\n", m[i]) ;
}
I think you meant to loop over the array and print its contents, which you do afterwards. But when you try to find the max
, you seem to have forget to loop over the array.
Your code invokes Undefined Behavior (UB) here:
printf("%d\n", m[i]) ;
since you go out of range, because i
has the last value after the previous for loop (to find the min
), which was 4 (size of the array). So you are indexing the array beyond its end, namely m[4]
, which explains the garbage value of the output.
Here is the plan, which you were getting close, but let's list it here:
Note: If there are more than one maximum elements, take into account the last one seen. Similarly for the minimum element.
Putting everything together, you get this:
#include <cstdio>
int main () {
int m [4] = {5,5678,62,6000};
int i;
int max=m[0], max_idx;
int min=m[0], min_idx;
int temp = 0;
for(int i = 0; i < 4; ++i)
{
printf( "%d\n", m[i]) ;
}
for (i=0; i<4; i++)
{
if ( m[i] > max )
{
max = m[i];
max_idx = i;
}
}
for (i=0; i<4; ++i)
{
if ( m[i] < min )
{
min = m[i];
min_idx = i;
}
}
temp = min;
m[min_idx] = max;
m[max_idx] = temp;
printf ("min = %d\n", min);
printf ("max = %d\n", max);
printf("The new array is:\n");
for(int i = 0; i < 4; i++)
printf("%d\n", m[i]);
}
Output:
5
5678
62
6000
min = 5
max = 6000
The new array is:
6000
5678
62
5