I need to find the maximum and minimum element, swap the position of the maximum with the minimum, and calculate the sum and product of all the elements.
My attempt runs without errors, but the sum, product and change answers are not correct. Please if you could help me.
#include <stdio.h>
#include <conio.h>
int main()
{
int m[8];
printf("\nInput the elements of the array: ");
for (int i=0; i<8; i++) {
scanf("%d", &m[i]); }
int max=m[0], min=m[0];
for(int i=0; i<8; i++) {
if(max < m[i]) {
max=m[i]; }
if(min > m[i]) {
min=m[i]; } }
for(int i=0; i<8; i++) {
if(m[i] == min) {
m[i] = max; } }
for(int i=0; i<8; i++) {
if(m[i] == max) {
m[i] = min; } }
int sum=0, x=0;
for(int i=0; i<8; i++) {
sum += m[i];
x = m[i]*m[i]; }
printf("\n Maximum element: %d", max);
printf("\n Minimum element: %d", min);
printf("\n Sum of all elements: %d", sum);
printf("\n Product of all elements: %d", x);
printf("\n\n Array with the maximum and minimum elements changed:\n");
for(int i=0; i<8; i++) {
printf("%d", m[i]);
printf(" "); }
_getch();
}
The problem is in the pair of loops that exchange the minimum and maximum values.
The second for above, steps on what the first one established, since max is 2 times in the array at the beginning of the second for, so in the end the max value is lost and the min value is left 2 times in the final array.
Solution suggestion:
Then you just swap the values with the indices.
And it removes those loops that swap min and max values.
Finally, in the product I see an error, maybe you should do something like this, because what you now have in your code is a power and you will only get the value of the last element of the array.
You can try to declare a variable max and min, and compare them with each other with a for, in the end the value that these variables store will be the maximum or the minimum