hello this program for calculate min and max in the array - c

I wrote the code with functions and it give me the address of the variable not the value in which the solution is in the same way of coding.
this is the output
and this is my code
#include <stdio.h>
int maxi(int feld[],int size);
int mini(int feld[],int size);
int main(void){
int feld[]={33,36,31,38,45,42,11,29,56,54};
int len;
int min,max;
len=sizeof(feld)/sizeof(int);
printf("Lange des Datenfeldes=%i\n",len);
max=maxi(feld,len);
min=mini(feld,len);
printf("Minimum = %i\tMaximum = %i\n",min,max);
return 0;
}
int maxi(int feld[],int len){
int i,max;
for(i=0;i<len;i++){
if(feld[i]<max){
feld[i]=max;
}
}
return max;
}
int mini(int feld[],int len){
int i,min;
for(i=0;i<len;i++){
if(feld[i]>min){
feld[i]=min;
}
}
return min;
}

You need to give a starting value to max and min in the functions.
A good choice would be max = INT_MIN; and min = INT_MAX;. Also, add #include <limits.h> in your includes since the INT_MAX and INT_MIN are defined in it.
int maxi(int feld[],int len){
int i;
int max = INT_MIN;
for(i=0;i<len;i++){
if(feld[i]<max){
max=feld[i];
}
}
return max;
}
EDIT: Your code also has the assignment of max and feld[i] reversed. I've fixed it in my function above.

You have to initislize max in maxi() and min in mini() first to some value in the array, say feld[0].
Don't use immediate value such as 0 to initialize because using such a value will cause trouble when all values in the array are greater or smaller rhan the value.
Including limits.h, using INT_MIN for max and INT_MAX for min is OK.
UPDATE:
You are trying to calculate minimum value in maxi() and maximum value in mini(). You have to reverse the direction of comparision operator of feld[i]<max and feld[i]>min.
Using INT_MIN and INT_MAX is good because it will also somewhat work when size <= 0.
UPDATE 2:
feld[i]=max; and feld[i]=min; are also wrong. They should be max=feld[i]; and min=feld[i];.

Code is backwards. int maxi(int feld[],int len){... if(feld[i]<max){ should be if(feld[i] > max){.
Assignment also in wrong order.
Initialize max. #munircontractor #MikeCAT
Similar problems with mini().
int maxi(int feld[], int len){
// int max;
int max = INT_MIN;
int i;
for(i=0;i<len;i++){
// if(feld[i]<max){
if(feld[i] > max){
// feld[i] = max;
max = feld[i];
}
}
return max;
}

Related

Selection Sort algorithm in C doesn't print the entire sorted array

#include <stdio.h>
#include <stdlib.h>
int smallest(int [],int);
int select_sort(int[],int);
int smallest(int arr[],int len){
int small_index=0;
int small=arr[0];
for(int i=0;i<len;i++){
if(arr[i]<small){small=arr[i];
small_index=i;
}
}
return small_index;
}
int select_sort(int arra[],int len){
int new_arra[100];
for(int i=0;i<len;i++){
int small=smallest(arra,len);
new_arra[i]=arra[small];
printf("%d",new_arra[i]);
}
return new_arra;
}
int main()
{
int arr[100]={6,1,0,-2,18};
select_sort(arr,5);
return 0;
}
I wrote this code for the selection sorting program and i know ideally i should be using the dynamic allocation for arrays in the select_sort function, but i was attempting it without it. It is supposed to print the array in an ascending order and I think I am messing up variable assignment somewhere, because when i run the program it only prints the smallest integer of the input array len number of times and not the rest of them.
If you don't mind messing up with your initial array, you can do:
int select_sort(int arra[],int len)
{
int maxValue = Integer.Max_Value;
int new_arra[100];
for(int i=0;i<len;i++){
int small=smallest(arra,len);
new_arra[i]=arra[small];
arra[small]= maxValue;
printf("%d",new_arra[i]);
}
return new_arra;
bear in mind that this is highly unefficient

After a pointer Returns from a function i cant print it

I am relatively new to C. My program is supposed to fill in the array with random numbers and i have to find the max and min using 1 function. The program works fine up until the point i have to return the values my 2 pointers get from the function. When i go to print them the porgram stop working and exits with the return value of 3221225477. I have been trying to fix this for 3 hours and i am going INSANE. Please help in any way you can i would really apreciate it.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void MaxMin(int size, int *B, int *Max, int *Min);
int main(int argc, char *argv[])
{
int N, i,*A,*MAX,*MIN;
srand(time(NULL));
/*Making sure the user enters a proper value for the array*/
do
{
printf("Give the number of spaces in the Array\n");
scanf("%d",&N);
}
while(N<1);
A = (int *) malloc(N*(sizeof(N)));
/*Giving random numbers to the array and printing them so i can make sure my code is finding the max min*/
for(i=0;i<N;i++)
{
A[i]=rand()%100;
printf("\n%d\n",A[i]);
}
/*Calling my void function so that the pointers MAX and MIN have a value assigned to them */
MaxMin(N, A, MAX, MIN);
/*Printing them*/
printf("\nMax = %d\nMin = %d",*MAX,*MIN);
free(A);
return 0;
}
/*The function*/
void MaxMin(int size, int *B, int *Max, int *Min)
{
/*using 2 temporary ints to get max min cause pointers and arrays confuse me*/
int max=B[0],min=B[0],i;
for(i=1;i<size;i++)
{
if(max<B[i])
{
max = B[i];
}
if(min>B[i])
{
min = B[i];
}
}
/*These have the proper value last i chekced */
Max = &max;
Min = &min;
}
(edit) SOLUTION Ty so much for the help !
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void MaxMin(int size, int *B, int *Max, int *Min);
int main(int argc, char *argv[])
{
int N, i,*A,MAX ,MIN ;
srand(time(NULL));
/*Making sure the user enters a proper value for the array*/
do
{
printf("Give the number of spaces in the Array\n");
scanf("%d",&N);
}
while(N<1);
A = (int *) malloc(N*(sizeof(int)));
/*Giving random numbers to the array and printing them so i can make sure my code is finding the max min*/
for(i=0;i<N;i++)
{
A[i]=rand()%100;
printf("\n%d\n",A[i]);
}
/*Calling my void function so that the pointers MAX and MIN have a value assigned to them */
MaxMin(N, A, &MAX, &MIN);
/*Printing them*/
printf("\nMax = %d\nMin = %d",MAX,MIN);
free(A);
return 0;
}
/*The function*/
void MaxMin(int size, int *B, int *Max, int *Min)
{
*Max=B[0];
*Min=B[0];
int i;
for(i=1;i<size;i++)
{
if(*Max<B[i])
{
*Max = B[i];
}
if(*Min>B[i])
{
*Min = B[i];
}
}
}
You passed to the function MaxMin pointers MAX and MIN by value. That is the function deals with copies of (indeterminate) values of the passed pointers. Changing the copies does not influence on the original arguments.
Within main you should declare MIN and MAX as objects of the type int.
int N, i,*A, MAX, MIN;
and call the function ,like
MaxMin(N, A, &MAX, &MIN);
Within the function you should write
*Max = &max;
*Min = &min;
And at last in main you should call printf like
printf("\nMax = %d\nMin = %d", MAX, MIN);
Pay attention to that the expression sizeof( N ) used in this statement
A = (int *) malloc(N*(sizeof(N)));
is error prone. The type of the variable N can be changed for example from the type int to the type size_t. In this case the size of the allocated memory will be incorrect, You should write for example
A = (int *) malloc(N*(sizeof( *A )));
You have three bugs:
In main, you don't assign MAX or MIN any values. So you pass garbage to MaxMin.
In MaxMin, Max and Min are about to go out of scope. Changing their values before they go out of scope has no effect on anything.
In main, you don't create any place to hold the maximum and minimum values. So where are you expecting them to be stored?

Changing the value of a variable with pointers not working

Basically I have a function called MinSubTab that is supposed to calculate the sum of the array passed and also to change the value passed in the first argument from inside the function without using return. This is done with pointers. Anyway, I think it'd be easier if I just showed you the code so here it is:
maintab.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "tab.h"
int main(){
int *reftab;
int min;
reftab = (int *)malloc(sizeof(int) * NMAX);
InitTab(reftab,NMAX);
printf("\n Total: %d et min: %d", MinSumTab(&min, reftab, NMAX), min);
free(reftab);
return 0;
}
tab.c
void InitTab(int *tab, int size){
srand(time(NULL));
for (int i=0; i<size; i++){
*(tab+i) = rand() % 10;
}
}
int MinSumTab(int *min, int *tab, int size){
int total=0;
int minimum = NMAX;
int temp = *min;
for (int i=0; i<size; i++){
total += *(tab+i);
}
for (int i=0; i<size; i++){
if(*(tab+i)<minimum){
minimum = *(tab+i);
}
}
*min = minimum;
return total;
}
So the expected result here is that the sum is printed (which it is) and the minimum value of the array is printed (which it is not). Every single time the min variable equals 8 and I've no idea how to actually change the value of min from within that function.
Please help as my brain has no more capacity for rational thought, it's been 1.5 hrs and no solution in sight. Thanks
Looks like a small mistake:
You initialize minimum with NMAX, which I assume is 8 (the size of the array). 99.9% of the random numbers will be bigger. So 8 is chosen as the minimum.
What you really want is to initialize it with RAND_MAX – the maximum value rand() can return.
In C order of evaluation and argument passing is undefined.
You can of course the order yourself but it only to feed your curiosity.
#include <stdio.h>
volatile char *message[] = {
"fisrt", "second", "third", "fourth"
};
int print(size_t x)
{
printf("%s\n", message[x]);
return x;
}
int main()
{
printf("%d %d %d %d\n", print(0), print(1), print(2), print(3));
return 0;
}
Note. There is one exception from this rule.
Logical operators are evaluated form the left to the right.
if( x != NULL && *x == 5)is safe because x will not be dereferenced if it is NULL

How to pass parameters by reference in recursive algorithms in c?

algorithm that given an array delivers the largest number by recursion, but passing the result by reference.
tam: size of array
first I realized it by value and it worked for me but I need to pass it by reference the result, I really do not know what the error could be, if you can guide me please, since when compiling it, I did not return anything
#include <stdio.h>
#include <stdlib.h>
void search(int a[], int tam, int max,int *result);
int main()
{
int max,tam=5, result;
int array[5]={3,1,5,8,6};
max=array[0];
search(array, tam, max, &result);
printf("the biggest number is: %d",result);
return 0;
}
void search(int a[], int tam, int max, int *result )
{
if(tam==1)
*result=max;
if(max<a[tam-1])
max=a[tam-1];
search(a,tam-1,max,result);
}
Blockquote
When compiling with 'clang -Wall', you get the following warning:
warning: all paths through this function will call itself [-Winfinite-recursion]
Indeed, in you don't have an effective base case and inductive step in your function.
I would suggest converting to the following:
#define MAX(x, y) ((x) > (y)) ? x : y
int search(int a[], int tam )
{
// base case if last element
if (tam == 1) return a[0];
// inductive case (max of this and following elements)
return MAX(a[0], search(a + 1, tam - 1));
}
Since the OP's code attempts to be tail recursive, and #Gill Bates 's answer is head recursive, I am showing a tail recursive solution.
int find_max_helper(const int *a, int n, int max)
{
if (n==0) return max;
else return find_max_helper(a+1, n-1, MAX(max, a[0]));
}
//returns the maximum value in the array of size n elements
//or 0 if the array is empty
int find_max(const int *a, int n)
{
return n > 0 ? find_max_helper(a+1, n-1, a[0]) : 0;
}

Issue finding the largest float in array

I'm having a problem in C when I'm trying to find the largest float of an array, but my largest int works just fine. I think I might be going past the array length but I don't see how it is possible.
int largestInt(int array[], int length){
int max = array[0];
int i;
for( i=1; i<length; i++){
if(array[i] > max){
max = array[i];
}
}
return max;
}
The above code works fine for ints, however if I change it to work with floats as follows,
float largestFloat(float array[], int length){
float max = array[0];
int i;
for( i=1; i<length; i++){
if(array[i] > max){
max = array[i];
}
}
return max;
}
Sometimes it will give me the right answer, and sometimes it will just give me a huge number not even in the original array. Which leads me to believe that I'm going past the length of the array.
float f[15] = {9.5, 45.64, 313.11, 113.89, 81.56, 250.00, 11.9, 469.98, 313.11, 4.68, 34.33, 8013.55, -10.15, 11.5, 88.0} <-- filled with 15 values
largestFloat(f,15);
This is what I would run.
Not seeing an entire example, I'd have to say that you are correct. The array size is probably wrong. First fix the return type:
float largestFloat(float array[], int length){
Next, you might want to add a guard against an empty array, since that will automatically overlflow fetching array[0]:
if (length < 1) return 0;
The rest of largestFloat() is good.
Then call with:
float f[15] = {2.3 ... 102} <-- filled with 15 values
size_t length = sizeof f / sizeof f[0];
float f_max = largestFloat(f, length);
printf("max=%g, length=%d\n", f_max, length);
That will compute (at compile time) the actual size of the array f. Look for cases where the length is not what you thought it should be. This can happen if you type a . instead of a , between values that don't already have a decimal point. That and miscounting are the only ways I know of to get 14 or fewer values from what appears to be 15.
The problem is that you find the largest float but then return the int value
int largestFloat(float array[], int length){ // return type is int
float max = array[0]; // max is float
int i;
for( i=1; i<length; i++){
if(array[i] > max){
max = array[i];
}
}
return max;
}

Resources