This is a simple program to find the smallest element of an array. But the previous versions of the following program gave an error where the smallest and largest numbers were displayed as 0. In the following version of the program, the compiler is giving me a segmentation error.
#include <stdio.h>
void minimum();
void maximum();
int n;
int main()
{
int array[n];
printf("Enter the size of your array:\n");
scanf("%d", &n);
printf("Enter the elements of your array:\n");
for (int i = 0; i < n; i++)
{
printf("Enter element %d:\n", i + 1);
scanf("%d", array);
}
minimum(array[n]);
maximum(array[n]);
return 0;
}
void minimum(int arr[n])
{
int* min;
min = &arr[0]; // Initialize min to the value of the first element of the array
for (int i = 1; i < n; i++)
{
if (*(arr+i)<*min)
{
*min = *(arr+i);
}
}
printf("The smallest element in the array is: %d\n", *min);
}
void maximum(int arr[n])
{
int* max;
max = &arr[0]; // Initialize min to the value of the first element of the array
for (int i = 1; i < n; i++)
{
if (*(arr+i)>*max)
{
*max = *(arr+i);
}
}
printf("The greatest element in the array is: %d\n", *max);
}
In the previous versions of this program I tried to pass two parameters to the function declaration first with only one int* and second with one int* and an int, both of which resulted in the smallest and biggest number being 0 although it should have been some other numbers. I also tried to pas the min and max to the functions along with the array pointer like void min(int*, int*);
which also gave an output where nim and max both equal to 0.
#include <stdio.h>
void minimum(int *, int);
void maximum(int *, int);
int main()
{
int n;
int array[100];
printf("Enter the size of your array:\n");
scanf("%d", &n);
printf("Enter the elements of your array:\n");
for (int i = 0; i < n; i++)
{
printf("Enter element %d:\n", i + 1);
scanf("%d", array);
}
minimum(array, n);
maximum(array, n);
return 0;
}
void minimum(int *arr, int n)
{
int *min = &arr[0]; // Initialize min to the value of the first element of the array
for (int i = 1; i < n; i++)
{
if (*(arr+i)<*min)
{
*min = *(arr+i);
}
}
printf("The smallest element in the array is: %d\n", *min);
}
void maximum(int *arr, int n)
{
int *max = &arr[0]; // Initialize min to the value of the first element of the array
for (int i = 1; i < n; i++)
{
if (*(arr+i)>*max)
{
*max = *(arr+i);
}
}
printf("The greatest element in the array is: %d\n", *max);
}
int array[n];check what isnwhen this line is executedint array[n];whennis not initialized properlynis a global variable, so it is initialized (to zero).