Finding Max Number in an Array C Programming - c

I am trying to find the max number in an array. I have created a function and I am using the following code:
int maxValue( int myArray [], int size)
{
int i, maxValue;
maxValue=myArray[0];
//find the largest no
for (i=0;i)
{
if (myArray[i]>maxValue)
maxValue=myArray[i];
}
return maxValue;
}
However I get a syntax error before ) token. What am I doing wrong and am I even doing this right? Any help would be greatly appreciated.

You must pass a valid array with at least one member to this function:
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int
maxValue(int myArray[], size_t size) {
/* enforce the contract */
assert(myArray && size);
size_t i;
int maxValue = myArray[0];
for (i = 1; i < size; ++i) {
if ( myArray[i] > maxValue ) {
maxValue = myArray[i];
}
}
return maxValue;
}
int
main(void) {
int i;
int x[] = {1, 2, 3, 4, 5};
int *y = malloc(10 * sizeof(*y));
srand(time(NULL));
for (i = 0; i < 10; ++i) {
y[i] = rand();
}
printf("Max of x is %d\n", maxValue(x, sizeof(x)/sizeof(x[0])));
printf("Max of y is %d\n", maxValue(y, 10));
return 0;
}
By definition, the size of an array cannot be negative. The appropriate variable for array sizes in C is size_t, use it.
Your for loop can start with the second element of the array, because you have already initialized maxValue with the first element.

A for loop has three parts:
for (initializer; should-continue; next-step)
A for loop is equivalent to:
initializer;
while (should-continue)
{
/* body of the for */
next-step;
}
So the correct code is:
for (i = 0; i < size; ++i)

the paren after the for seems to be missing some contents.
normally it should be something like
for (i=0; i<size; i++)

include:
void main()
{
int a[50], size, v, bigv;
printf("\nEnter %d elements in to the array: ");
for (v=0; v<10; v++)
scanf("%d", &a[v]);
bigv = a[0];
for (v=1; v<10; v++)
{
if(bigv < a[v])
bigv = a[v];
}
printf("\nBiggest: %d", bigv);
getch();
}

Related

C : Trying to split an integer into an array returns array of length 2, no matter the size of the integer

So I want to split each digit of a decimal number into an array. I have the following code:
#include <stdio.h>
int * splitNumberIntoArr(int num) {
int i = num;
int modulus,newNum;
static int arr[5];
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j++;
i = newNum;
};
return arr;
};
int main() {
int num;
printf("Provide a number:\t");
scanf("%d", &num);
int *arr;
arr = splitNumberIntoArr(num);
int k;
for(k = 0; k <= sizeof(arr) / sizeof(arr[0]); k++) {
printf("%d\n",arr[k]);
return 0;
};
When num is an integer consising of 3 digits, the code works how it is supposed to.
However, when the input consists of more than 3 digits, the array that is returned by the splitNumberIntoArr()
function only returns an array of length 2.
for example,
Since I am new to C, I struggle to understand why this problem even exists, taking into consideration the fact that the declared array is of length 5: static int arr[5];
Your help would be greatly appreciated.
Try something like this:
#include <stdio.h>
#include <string.h> // for memset
void splitNumberIntoArr(int num, int *arr) {
int i = num;
int modulus, newNum;
int j = 0;
while (i > 0) {
modulus = i % 10;
newNum = i / 10;
arr[j] = modulus;
j++;
i = newNum;
};
}
int main() {
int num;
scanf("%d", &num);
int arr[32];
memset(arr, -1, sizeof(arr));
splitNumberIntoArr(num, arr);
for (int k = 0; k < sizeof(arr) / sizeof(arr[0]) && arr[k] != -1; k++) {
printf("%d\n",arr[k]);
}
}
In main(), the sizeof(arr) is known, because it lies on the stack.

C code function calling not working

Ok I need to write two functions iterative and recursive to count negative elements in an array and then I need to build main. I was only able to write the recursive function but I cannot call it from main, it is an error somewhere. Can someone help me out solve it and help me with the iterative method?
#include <stdio.h>
main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(array, size)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
A working piece of code is this.You really need to take a look at pointers and the way they work.
Here you can see that I have a pointer ->pointing-< at the start of the array , so by passing the starting address of the array , and the length of the array , your functions knows what it is needed to be done.
#include <stdio.h>
int numero(int* array, int size);
int* recursive_count(int* array, int size , int* counter );
int main()
{
int vektor[100];
int* vekt_ptr = &vektor[0];
int i, madhesia;
int counter;
counter=0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
//int ret = numero(vekt_ptr, madhesia);
recursive_count(vekt_ptr, madhesia , &counter );
int ret = counter;
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array, int size)
{
int count = 0;
int j;
for (j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
int* recursive_count(int* array, int size , int* counter )
{
size--;
if(array[size] < 0 )
{
(*counter)++;
}
if(size==0)
{
return NULL;
}
return recursive_count(array++, size , counter );
}
Let's assume that you want to create dynamically an array of X length.
The compiler is going to have some memory for your array , depending on the length.
You initialize your array , lets say [2][45][1][-5][99]
When you call the function you have to pass where this is stored in memory.
int* vekt_ptr = &vektor[0]; -s going to give as something like 0x56c2e0.
This number is the address of your array , which is the address of the starting point of the array.This is equal with the address of first byte.
So when your function starts , it knows where your array starts and how long it is.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
Any function used in a program shall be declared before its usage.
This function declaration of the function definition
int numero(array, size)
{
// ...
}
is invalid because the types of the parameters array and size are undefined.
For the size of an array and for the count of elements it is better to use an unsigned integer type like for example size_t or at least unsigned int.
The program can look the following way
#include <stdio.h>
#define N 100
size_t iterative_numero( const int array[], size_t size );
size_t recursive_numero( const int array[], size_t size );
int main( void )
{
int vektor[N];
size_t madhesia = 0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%zu", &madhesia);
if ( N < madhesia ) madhesia = N;
/* Input array elements */
printf("Elementet: ");
for ( size_t i = 0; i < madhesia; i++ )
{
scanf( "%d", &vektor[i] );
}
size_t ret = iterative_numero(vektor, madhesia );
printf("\nTotal negative elements in array = %zu\n", ret);
ret = recursive_numero(vektor, madhesia );
printf("Total negative elements in array = %zu\n", ret);
return 0;
}
size_t iterative_numero( const int array[], size_t size )
{
size_t count = 0;
for ( size_t i = 0; i < size; i++)
{
if ( array[i] < 0 )
{
count++;
}
}
return count;
}
size_t recursive_numero( const int array[], size_t size )
{
return size == 0 ? 0 : ( array[0] < 0 ) + recursive_numero( array + 1, size - 1 );
}
the program output might look like
Madhesia e vektorit: 10
Elementet: 0 -1 2 -3 4 -5 6 -7 8 -9
Total negative elements in array = 5
Total negative elements in array = 5
First of all what you did is the iterative method, not recursive. Here I have called a recursive function from the main function.
#include <stdio.h>
int main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("\nElementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
printf("\nno of elements:%d",madhesia);
printf("\n");
for (i = 0; i < madhesia; i++)
{
printf("%d", vektor[i]);
}
printf("\n");
i=0;
int ret = numero(vektor,madhesia,0,i);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int array[],int size,int count,int j)
{
if (j<=size-1)
{
if(array[j]<0)
{
count++;
j++;
numero(array,size,count,j);
}
else
{
j++;
numero(array,size,count,j);
}
}
return count;
}
Put function prototype of numero() before main() to be able to call it. Declare function parameters with type:
int numero(int array[], int size);
int main() {
...
#include<stdio.h>
int numero(int *, int); //Function Prototype (1)
int main() //Return Type (2)
{
int vektor[100];
int i, madhesia;
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array,int size) //Parameters Data Type (3)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
Errors:
You have declared the function after "main()" so the program doesn't know that there is a function, so you have to give the function prototype before "main()" so that the program knows there is function ahead.
You missed writing the return type of "main()" which is integer.
In the function declaration you forgot to write the data type of the parameters.
NOTE: The array is always passed by reference so it has to taken in an integer pointer instead of a normal integer.
Some possible implementations:
int iterativeCountNegativeIntegers (int *array, int size)
{
int result = 0;
for (int i = 0; i < size; ++ i)
if (array[i] < 0)
result += 1;
return result;
}
int recursiveCountNegativeIntegers (int *array, int size)
{
if (size == 0)
return 0;
int partial = *array < 0;
return partial + recursiveCountNegativeIntegers(array+1, size-1);
}
The same, condensed:
int iterativeCountNegativeIntegers_1 (int *array, int size)
{
int result = 0;
while (--size >= 0)
result += *array++ < 0;
return result;
}
int recursiveCountNegativeIntegers_1 (int *array, int size)
{
return (size == 0) ? 0
: (*array < 0) + recursiveCountNegativeIntegers_1(array+1, size-1);
}

Function to return a pointer to the largest number in an array

as you can tell by the title I need to write a function that returns a pointer to the largest number in an array, the functions gets a pointer to a double array and it's size. In addition I need to write a main function that will use this function.
Here is the code that I wrote:
#include <stdio.h>
#include <stdlib.h>
void BigEl(double* arr, double arrSize);
void BigEl(double* arr, double arrSize)
{
int i;
double maximum, *x;
maximum = arr[0];
for (i = 1; i < arrSize; i++)
{
if (arr[i]>maximum)
{
maximum = arr[i];
}
}
*x = maximum;
}
void main()
{
double myarr[10];
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%d", &myarr[i]);
}
BigEl(myarr, 10);
}
I get this error:
Error 1 error C4700: uninitialized local variable 'x' used
I don't understand what I did wrong because I did initialized x.
Any kind of help is appreciated, in addition, tell me if the idea of my code was right because Im not sure if I understood the question correctly.
You did not initialize the variable x. You merely wrote to the the location pointed to by x, here:
*x = maximum;
when x was uninitialized, which is what the compiler is complaining about.
You want something like:
double *
BigEl(double* arr, size_t arrSize)
{
size_t i;
double *max = arr;
for (i = 1; i < arrSize; i++)
if (arr[i] > *max)
max = &arr[i];
return max;
}
Things I've changed:
Use size_t for the array size and the counter, not a double and an int.
Retain a pointer to the maximum element, not the maximum element's value.
Return the pointer to the maximum element.
Remove superflous braces.
You're not returning anything. Also, it might be good to take into consideration the case when the array size is 0. Moreover, the size should be passed as a constant. No other answer has mentioned this.
double* BigEl(double* arr, const size_t iSize)
{
if(iSize == 0)
return 0;
double max = arr[0], *x = &arr[0];
for(unsigned int i=1;i<iSize;++i){
if(arr[i] > max){
max = arr[i];
x = &arr[i];
}
}
return x;
}
Your assignment to *x is incorrect - you are saying "assign to the location pointed to by x, without first saying where that is. Aside from that, there are a couple of other issues:
#include <stdio.h>
#include <stdlib.h>
// return pointer to location from function
double * BigEl(double* arr, double arrSize)
{
int i;
// initialise both variables
double maximum = arr[0], *max_pos = arr;
for (i = 1; i < arrSize; i++)
{
if (arr[i]>maximum)
{
maximum = arr[i];
// assign address here
max_pos = &arr[i];
}
}
// return address
return max_pos;
}
int main()
{
double myarr[10];
double * max_pos;
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%lf", &myarr[i]);
}
// use return value here
max_pos = BigEl(myarr, 10);
return 0;
}
//function that returns a pointer to the largest number
double *BigEl(double* arr, int arrSize)
{
int i;
double *maximum;
maximum = &arr[0];
for (i = 1; i < arrSize; i++)
{
if (arr[i] > *maximum)
{
maximum = &arr[i];
}
}
return maximum;
}
int main(void)
{
double myarr[10];
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%lf", &myarr[i]);
}
printf("%f\n", *BigEl(myarr, 10));
return 0;
}
I need to write a function that returns a pointer to the largest
number in an array
I think you need the follwoing
#include <stdio.h>
double * largest_element( const double *a, int n )
{
const double *largest = a;
int i;
for ( i = 1; i < n; i++ )
{
if ( *largest < a[i] ) largest = a + i;
}
return ( double *)largest;
}
#define N 10
int main(void)
{
double a[N];
int i;
printf("Please insert %d numbers to the array: ", N );
for ( i = 0; i < N; i++ )
{
scanf( "%lf", &a[i] );
}
printf( "\nThe largest element of the array is %lf\n", *largest_element( a, N ) );
return 0;
}
If to enter for example
2.2 1.5 5.2 1.8 3.9 5.9 7.7 6.8 2.9 0.8
then the program output will be
The largest element of the array is 7.700000

Why does this program crashes on execution?

I am trying to run this code on Dev C++ but it keeps on crashing after the user inputs the two numbers. The program takes input m and n from user two numbers and then returns the output as the solution of the function A which is:
A(m,n) = A(m,n-1)+ A(m-1, n) , if m,n >0
A(m,n) = m-n if m or n <0
Can anybody please tell me why is it happening?
#include<stdio.h>
#include<stdlib.h>
int main() {
int num1=0;
int num2=0;
int rows=0;
int columns=0;
int i,j,**array;
printf("Enter two non-negative integer numbers \n");
scanf("%d %d",&num1,&num2);
//create 2d-Array
rows=num1+1;
columns=num2+1;
array=malloc(rows * sizeof(int *));
for(i=0;i<rows;i++)
{
array[i]=malloc(columns*sizeof(int));
}
//Fill data in array
computeArray(array,rows,columns);
// Display contents of array
for (i = 0; i < rows; i++ )
{
for(j= 0; j < columns; j++ )
{
printf("array[%d][%d] = %d\n", i,j, array[i][j] );
}
}
getch();
return 0;
}
int computeArray (int **array, int rows, int columns) {
int i,j;
for(i=0; i<rows;i++)
{
for(j=0;j<columns;j++)
{
array[i][j]=computeFunction(array,i,j);
}
}
return **array;
}
int computeFunction(int **array, int i, int j) {
int value=0;
if((i<0)||(j <0))
{
value = i-j;
printf("%d",value);
return value;
}
else
{
value = (array[i][j-1] + array[i-1][j]);
printf("%d",value);
return value;
}
return value;
}
When program's behavior is undefined, anything could happen. You should declare a prototype for the function computeArray and computeFunction before main:
int computeArray (int **array, int rows, int columns);
int computeFunction(int **array, int i, int j);
and change
if((i<0)||(j <0)) {...}
in computeFunction to
if((i<=0) || (j <= 0)){...}
&& instead of || may help.
The code fails at the
value = (array[i][j-1] + array[i-1][j]);
line, when j==0.
Debuggers tend to be very useful for spotting simple mistakes. Use them.

Loop through an array with pointers?

I am trying to learn pointers which is a real PITA when you don't quite fully understand it.
I am trying to print all the elements in the array but only the first element is printed.
#include <stdio.h>
int count(const int* numbers, int size)
{
for(; numbers < size; numbers++)
{
printf("%d", *numbers);
}
}
int main(void)
{
int numbers[] = {3, 4, 6, 3, 46};
int result = count(numbers, 5);
printf("%d\n", result);
return 0;
}
The loop in the count function does not seem to work properly since it is only looping through one time but I can't understand why.
The comparison numbers < size is wrong.
You have 3 options:
Have a separate index variable:
int count;
for(count = 0; count < size; count++)
{
printf("%d", numbers[count]);
}
Have a separate "cursor" pointer:
const int * const end = numbers + size;
for(; numbers < end; numbers++)
{
printf("%d", *numbers);
}
Decrement size:
for(; size != 0; size--, numbers++)
{
printf("%d", *numbers);
}
the count() function should be
int count(const int* numbers, int size)
{
for(; size > 0; numbers++, size--)
{
printf("%d", *numbers);
}
}
Because numbers is a pointer, it contains an address. size is an int and equals 5. The address is not 5, nor is it even near 5.
You might save the start address and calculate the offset:
int count(const int* numbers, int size)
{
const int* start = numbers;
for(; (int)(numbers - start) < size; numbers++)
{
printf("%d\n", *numbers);
}
}

Resources