Hello i am trying to find the maximum and minimum in a given interval using dynamic arrays. It works to find the maximum and minimum, but not in the given number interval. Where am i going wrong ? Please help.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int main(){
int i, n;
int *bliznak;
int max = 0, min = 0;
int a = 0;
int b = 0;
int p = 0;
printf("Give upper and lower limit");
scanf("%d %d", &a, &b);
printf("enter elements");
scanf("%d", &n);
bliznak = (int*)calloc(n, sizeof(int));
if (bliznak==NULL)
{printf("ERROR"); exit(0);}
for (i = 0; i < n; i++)
{
printf("enter number %d ", i + 1);
scanf("%d", bliznak + i);
}
for (i > a; i < b; i++){
max = *(bliznak + i);
min = *(bliznak + i);
for (i = 1; i < n; i++)
{
{
if (*(bliznak + i)> max)
max = *(bliznak + i);
if (*(bliznak + i) < min)
min = *(bliznak);
}
}
}
printf("\n MAX Numb %d\n", max);
printf("\n Min Numb %d\n", min);
system("pause");
return 0;
}
This is a fixed version of your code
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int main(){
int i, n;
int *bliznak;
int max = 0, min = 0;
int a = 0;
int b = 0;
int p = 0;
printf("Give lower and upper limit");
scanf("%d%d", &a, &b);
printf("enter elements");
scanf("%d", &n);
bliznak = (int*)calloc(n, sizeof(int));
for (i = 0; i < n; i++)
{
printf("enter number %d ", i + 1);
scanf("%d", bliznak + i);
}
for (i = 0; i < n; i++) // changed loop condition
{
if( ( *(bliznak + i) ) >= a && ( *(bliznak + i) ) <= b )
{
max = *(bliznak);
min = *(bliznak);
break;
}
}
for (i = 0; i < n; i++)
{
if( ( *(bliznak + i) ) >= a && ( *(bliznak + i) ) <= b ) // this checks the interval
{
if (*(bliznak + i)> max)
max = *(bliznak + i);
if (*(bliznak + i) < min)
min = *(bliznak + i); // you forgot + i
}
}
printf("\n MAX Numb %d\n", max);
printf("\n Min Numb %d\n", min);
system("pause");
return 0;
}
Now lets loop at the problems
for (i > a; i < b; i++){
That loop is wrong. You are checking the indices, not the values. You should change it to
for (i = 0; i < n; i++) // changed loop condition
{
if( ( *(bliznak + i) ) >= a && ( *(bliznak + i) ) <= b )
{
max = *(bliznak);
min = *(bliznak);
break;
}
}
Then, in
if (*(bliznak + i) < min)
min = *(bliznak);
You forgot the + i
. It should be
min = *( bliznak + i );
To check for the intervals, use this
if( ( *(bliznak + i) ) >= a && ( *(bliznak + i) ) <= b )
as indicated in the code above.