I have written a program to input 3 integers and find the mean, largest and smallest value:
#include <stdio.h>
int main(void) {
int array[2]; /* declares array */
int min = 99;
int max = -99;
float mean;
int i;
printf( "Please enter three numbers seperated by spaces: " );
scanf( "%d %d %d", &array[0], &array[1], &array[2] );
mean = ( array[0] + array[1] + array[2] ) / 3; /* calculates mean */
for( i = 0; i < 3; i++ ) {
/* displays array elements at the start of each loop */
printf ( " i = %d begin \t %d %d %d \n", i, array[0], array[1], array[2]);
/* finding the maximim */
if ( array[i] > max ) {
max = array[i];
}
/* displays array elements in the middle of each loop */
printf ( " i = %d mid \t %d %d %d \n", i, array[0], array[1], array[2]);
/* finding the minimum */
if ( array[i] < min ) {
min = array[i];
}
/* displays array elements at the end of each loop */
printf ( " i = %d end \t %d %d %d \n", i, array[0], array[1], array[2]);
}
printf( " final = %d %d %d \n", array[0], array[1], array[2] );
printf(" min = %d \t max = %d \t mean = %.1f \n", min, max, mean );
return 0;
}
I have written it so that the array elements are displayed at beginning and end of each iteration of the loop.
This is the output I get:
Please enter three numbers seperated by spaces: 5 6 7
i = 0 begin 5 6 7
i = 0 mid 5 6 7
i = 0 end 5 6 5
i = 1 begin 5 6 5
i = 1 mid 5 6 5
i = 1 end 5 6 5
i = 2 begin 5 6 5
i = 2 mid 5 6 5
i = 2 end 5 6 5
final = 5 6 5
min = 5 max = 6 mean = 6.0
Notice that the last element of the array changes when
/* finding the minimum */
if ( array[i] < min ) {
min = array[i];
}
is executed. This therefore affects the smallest value and largest value output. Any idea why this happens?
You declare your array to hold only 2 elements:
int array[2]; /* declares array */
The array needs to be able to hold 3 elements
int array[3]; /* declares array */
Trying to write past the end of the array results in undefined behavior.
Array indices can be a little confusing at first.
int array[2];
means two elements, and since indices start at [0]
, valid indices you can access are [0]
and [1]