Issue finding the largest float in array - c

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;
}

Related

Array to int and Sum of them in C

im learning C and i am a bit confused with array handling.
I have a task that asks me to sum up 2 arrays of non negative integers.
example array 1 = {1,2,3} , array 2 = {4,5,6} -> 123+456 = 579
I searched a bit for a solution on how to convert those arrays of integers to an integer, but didnt really get helpful information.
I ended up with a code:
#include <stdio.h>
int sum(int A[],int B[], int n){
int i,j,t,k;
for(i=0;i<n;i++){
t= t+A[i];
}
for(j=0;j<n;j++){
k= k+B[j];
}
return t+k;
}
int main()
{
int n = 3;
int a[n] = {1,2,3};
int b[n] = {4,5,6};
printf("%d",sum(a,b,n));
return 0;
}
But my result is 1225283 which of course is wrong.
I found a solution where people write something like "t= 10* t+A[i]" , i dont get where that "10* " comes from, but i tested it and then "t" gets "123" but if i try the same for "k" it doesnt work, returning "k" doesnt give me "456". I am a bit confused, whats the proper way of handling this problem?
Thanks for any help.
You're basically adding digits 1+2+3 instead of creating the number 123. Your code also has various other flaws, like uninitialized variables. Here is a working example:
int array2int(int A[], int n) {
int ret = 0;
for(int i=0, k=1; i<n; i++){
ret = ret + k * A[i];
k *= 10;
}
return ret;
}
int sum(int A[],int B[], int n){
return array2int(A, n) + array2int(B, n);
}
First of all, in sum function, you haven't initialized neighter t nor k but you keep summing them and use later, so every time your code is executed, you chould get different result.
On the other hand, in something like "t= 10 t+A[i]", 10 comes from basic math, where a number could be resolved as a10^0 + b10^1 +c*10^2 + .... + m * 10^n. As a result, starting from least significant digit, everytime you try to add new digit (from least to most significant), you need your multipliciant to be 10 times greater.
int sum(int A[],int B[], int n){
int i,j,t=0,k=0,ten=1;
for(i=n-1;i>=0;i--){
t += ten*A[i];
ten *= 10;
}
ten = 1; /* initialize again*/
for(j=n-1;j>=0;j--){
k += ten*B[j];
ten *= 10;
}
return t+k;
}
Something like that should work.

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 complete function to use pointer arithmetic instead of array subscripting in C?

I am struggling with specific parts in my code that I seem to have formatted wrong. This code was taken from my programming book and the parts that were blank have a '$' around them. However, there are two blanks I can't seem to figure out. My current code is:
int sum_two_dimensional(const int a[][LEN], int n)
{
int i,j, sum = 0;
for(i=0, i<n; i++)
for(j = 0; j< LEN; j++)
sum+=a[i][j];
return sum;
}
int sum_two_dimensional_array(const in a[][LEN], int n)
{
int *p, sum = 0;
for(p= a[0]; p < a[0] ______; p++)
sum += ________; //my guess is a[p][sum];
return sum;
}
I tried several things in these blanks an it seems that I keep getting errors. I do not fully understand the array/pointer situation. The blanks that I filled in, (encased in $$$), I feel are right but feel free to double check me. I appreciate any help.
This exploits the fact that an array a[N][M] uses the same memory as a single dimension array a[N*M]
So you can "safely" iterate a[0] "out of bound" without triggering memory exception up to the index a[0][N*M-1]
int sum_two_dimensional_array( int a[][LEN], int n)
{
int *p, sum = 0;
for(p= a[0]; p < a[0]+n*LEN; p++)
sum += *p;
return sum;
}

passing array to function in c

can someone please help me figure out what i'm doing wrong here? i'm getting inaccurate results here. I seem to be getting the first value in the array each time and i cant seem to figure out what i'm doing incorrectly
#include <stdio.h>
int getbillsum ( int price[] );
int main( void )
{
int itemprice [10];
int total = 0;
for (int c=0;c <10;c++ ) //Looping to get item prices
{
printf ("\nEnter the price of the item: ");
scanf (" %d", &itemprice[c]);
}
total = getbillsum (itemprice);
printf ("%d", total);
return 0;
}
int getbillsum (int price []) //function to sum the values in array
{
int sum = 0;
for (int i=0; i<sizeof(price); i++)
{
sum+=price[i];
}
return sum;
}
You can't pass arrays to functions in C (well, not as an array anyway). Arrays decay into pointers, the sizeof which is always the same (4 for 32 bit systems, 8 for 64 bits).
For more information see paragraph 2.3 here.
The easiest, most common and most reliable way of solving your issue is to pass the length of the array as a second argument:
int getbillsum (int *price, size_t len)
{
int sum = 0;
for (int i=0; i<len; ++i)
sum += price[i];
return sum;
}
//usage
int main ( void )
{
int price[10];
for(int i=0;i<10;++i)
scanf(" %d", &price[i]);
printf("Sum: %d\n", getbillsum(price, sizeof(price)/sizeof(*price)));
return 0;
}
You also had a problem in your code: you added the return statement inside of your loop.
Just a quick-tip: The sum of an array of ints is not unlikely to be too much for a single int to hold, so I'd change the return-type of getbillsum to long, too
I've also edited your question, addressing quite a lot of issues considering how short your code was:
int getbillsum ( price );//missing type, changed to
int getbillsum ( int price[] );//better would be int getbillsum ( int *price ); but considering your question, left it as array
scanf ("%d", &itemprice[c]);//unsafe, changed it to
scanf (" %d", &itemprice[c]);//add space
total = getbillsum (itemprice,9);//why the second param?
total = getbillsum (itemprice);//to match function prototype
return sum;//moved OUTSIDE of the loop...
sizeof(price) does not give you the length of the array, but the size of the pointer (int price[]), which is probably 4. Also, you immediately return in the first for run. Put return outside the for loop.
You do fix it by supplying the array size, but you never use it. Update your getbillsum function:
int getbillsum (int price [], int length) //function to sum the values in array
{
int sum = 0;
for (int i=0; i<length; i++)
{
sum+=price[i];
}
return sum;
}
In addition to posted answers, you can consider a technique suggested in this answer.
Edit Quoted from comment
it's non-standard, dangerous (think of overflow, forgetting to
dereference at the correct offset and the like), and you should not
try this
In your case it will be something like that :
void *p = calloc(sizeof(itemprice) + sizeof(unsigned long int),1));
*((unsigned long int*)p) = 10;
quote from linked answer
n is now stored at ((unsigned long int)p)
Your getbillsum will look like that now (did not compile it, consider it as pseudocode)
int getbillsum (void* p)
{
int* price = p+sizeof(unsigned long int);
unsigned long int size = *p;
int sum = 0;
for (int i=0; i<size; i++)
{
sum+=price[i];
}
return sum;
}

How do I amend this function which converts a decimal int to a binary int, with each of its digits in a array?

Let's say I have a temperature in celsius, int tC, and I want to convert that to binary form, with each of the bits in a integer array, arr[5]. I tried to use the remainder by two method to check if the number has a remainder. I tried using this function, but it always seems to mess up, even though in theory it does work. Any help is appreciated. Also, I could use pointers, but am not too sure how to use them in this particular case.
int main(void)
{
int arr[5];
int tC = 39;
int i;
for(i=0; i<5; i++)
{
if(tC%2==0)
arr[i] = 0;
else
arr[i] = 1;
tC/=2;
}
printf("\n%d\n", arr[5]);
}
Just a little change required:
#include<stdio.h>
int main(void)
{
int arr[5];
int tC = 39;
int i;
for(i=4; i>=0; i--)
{
if(tC%2==0)
arr[i] = 0;
else
arr[i] = 1;
tC/=2;
}
for(i=0; i<5; i++)
printf("%d", arr[i]);
}
Since you are storing the binary values in an array and looping from 0-4 (<5) - the values are getting saved in reverse order. You just need to loop from 4-0 (0 included). Also, in printf you were printing the individual bit value stored in the arr[5] which is UB since the last index is 4 - also, you were not looping to print all bit values in your array.

Resources