return -1 in C? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I was given code and I don't understand why the function returns -1. I feel that it is a typo. The code is given below:
int equilibrium(int array[], int size)
{
int sum = 0;
int left_sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += array[i];
}
for (i = 0; i < size; i++) {
if (array[i] == sum - 2 * left_sum) {
return i;
}
left_sum += array[i];
}
return -1;
}

It looks like it uses -1 to mean "not found", it looks like a search function trying to find an index i where the condition in the innermost if is true.

equilibrium returns the equilibrium point of an array as an index in the array. When the array doesn't have an equilibrium point, the function returns -1 instead. It is used as followed:
int equilibrium_idx = equilibrium(somearrayvalue, somesize);
if( equilibrium_idx == -1 )
printf("It isn't balanced\n");
else
printf("The equilibrium index is %d\n", equilibrium_idx);

Related

Why a integer pointer automatically changed to 0x384 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Phenomenon: Since Fabi is passed through the pointer parameter, the address of Fabi enters the function normally for the first time. The second time Fabi becomes an inaccessible address 0x384(Watcher), but it has not been changed by itself and passed to the function as const.
The fibonacci_search function uses the global variable Fabi instead of the Fabi parameter, so there is no problem.
It is precisely because the inaccessible address is accessed, a Segmentation fault is reported, and the program terminates.
#include <stdio.h>
#include <stdlib.h>
int fibonacci_search( const int* const F,int* a,int n,int val){
int low = 0, high=n-1,maxn = n-1;
int mid;
int k = 0;
while(maxn>F[k]-1)
k++;
for(int i=maxn;i<F[k]-1;i++)
a[i]=a[maxn];
int i=1;
while(low <= high){
mid = low + F[k-1] - 1; //mid = low + F[k] - 1;
printf("The %dth search value is:%d\n",i++,a[mid]);
if( val < a[mid]){
high = mid-1;
k = k-1;
}else if( val > a[mid]){
low = mid + 1;
k = k-2;
}else{
if(mid<=n)
return mid;
else
return maxn;
}
}
return -1;
}
int main(void){
int biarr[] = {0,1,16,24,35,47,59,62,73,88,99,102,304,758,777,801,900};
int amount = 15;
int* Fabi= (int*) malloc(sizeof(int)*amount);
Fabi[0]=0;Fabi[1]=1;
for(int i=2;i<amount;i++){
Fabi[i]=Fabi[i-1]+Fabi[i-2];
}
for(int i =5;i<17;i++){
int result = fibonacci_search(Fabi,biarr,17,biarr[i]);
if(result == -1)
printf("Can not find the result.\n");
else
printf("Find the Value,the Index is:%d\n",result);
}
return 0;
}
The picture
You have a (possible) overflow here:
for(int i=maxn;i<F[k]-1;i++)
a[i]=a[maxn];
How could you be sure that F[k]-1 is a valid bound for your array a?
OMG.
when change
int biarr[] = {0,1,16,24,35,47,59,62,73,88,99,102,304,758,777,801,900};
to
int biarr[50] = {0,1,16,24,35,47,59,62,73,88,99,102,304,758,777,801,900};
Its right.
Thanks to: When you debug, have you made sure that there's no out-of-bounds writes to any of the arrays? Some programmer dude's remind.
Its really a peculiar phenomenon!!!

Sum of odd numbers using recursion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This might be simple but I'm new to recursion in c. I want to find the sum of odd integers based on user's input. For example if user inputs 3, function returns 9 (1 + 3 + 5 = 9)
int recursiveSumNOdd(int n)
{
int start = -2; //later start = start+2, so it starts at 0
int n1 = n*2; //total number of digits with rec
int num = 0;
int sum=0;
int count=0;
if(start>=n1)
{
return 0;
}
else
{
start = start+2;
count++;
sum = sum +recursiveSumNOdd(start);
}
return sum;
}
Explanations in comment:
int recursiveSumNOdd(int n) {
if (n == 1 || n == 0)// first "if" in a recursive is its stop condition
return n;
return 2 * n - 1 + recursiveSumNOdd(n-1); // formula for 2->3, 3->5 etc
}
int main(void) {
printf("%d\n", recursiveSumNOdd(3));
return 0;
}
NB: You may want to handle integer overflow
NB2: You can have a mathematics formula to return instantly the result, it is way better, but I guess it was to understand better recursion?
return n * n; // the sum of odd numbers is the square of user's input
You are over-complicating things.
You cannot have the sum of negative elements.
int sum_n_odd(unsigned n)
{
What is the sum of 0 (zero) elements?
if (n == 0) return 0;
If you knew the sum of n - 1 numbers, what is the sum of n numbers?
return sum_n_odd(n - 1) + something; // something is easy to figure out
}

How to make a Worst case in mergesort in c? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
DataCount is how many times at sorting numbers.
int* MakeMWData(int DataCount)
{
// make array
int* Data = (int*)malloc(DataCount*sizeof(int));
int number = 2;
int count = 0;
Data[0] = 1;
// input data
int i,j;
for( i = DataCount;; i/=2)
{
count++;
for( j = 1; j<DataCount;j++)
{
//merge sort worst
i think this isn't correct.
if(j%i == 0 && j %(i * 2) != 0)
{
Data[j] = number;
number++;
}
}
if(i==1)
break;
}
for( i = 0; i<DataCount ; i++)
{
if(Data[i] ==0)
Data[i] = number;
number++;
}
return Data;
}
Making worst Data in main function.
int* MergeData = MakeMWData(DataCount[i]);
The way mergesort works is dividing the array in two arrays, recursively (logn times), untill being able to compare pairs of elements. Then it merges the recursively created arrays also sorting them at the same time.
For some sorting algorithms (e.g. quicksort), the initial order of the elements can affect the number of operations to be done. However it doesn't make any change for mergesort as it will have to do exactly the same number of operations anyway: recursively divide into small arrays and then merge them back, in total Θ(nlogn) time.

Verify the existence of an element in a table [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to C Algorithm and come to ask for some help.
I hope to check whether or not an element exists in a table, can anyone give me some good algorithm? What I do is a cycle and a flag, then quit the cycle and verify the flag. But it looks like stupid, so I guess there would be more efficient algorithm. My code is following:
int j=0;
u8_t next_header[]={0x11, 0x22};
for(i = 0; i < sizeof(next_header); ++i)
{
if (buf[6] != next_header[i])
continue;
else
++j;
}
if(j == 0)
{
// execution
}
else
{
// execution
}
pack it in a function, so you can jump out of the loop using return as soon as the element is found:
int search_for_elements(int element)
{
int i;
u8_t next_header[]={0x11, 0x22};
for(i = 0; i < sizeof(next_header); ++i)
{
if (element == next_header[i])
return 1; // found the element;
}
return 0; // :( no element found
}
Yes, if your table is a simple array looping is the way to go. That said, the usual pattern is to use a break statement instead of a continue.
int found = 0;
for(i=0=; i<the_array_length; i++){
if(array[i] == the_element_i_am_searching){
found = 1;
break;
}
}
Also, its more idiamatic to test booleans with if(i) instead of if(i != 0). (That said, if your variable is a number that is not always 0 or 1, like your j , I would keep the explicit comparison for clarity)

Distinguishing between two array indices? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with arrays. I copied this code from a book:
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
int p, i, primes[50], primeIndex = 2;
bool isPrime;
primes[0] = 2;
primes[1] = 3;
for (p = 5; p <= 50; p = p + 2) {
isPrime = true;
for (i = 1; isPrime && p / primes[i] >= primes[i]; ++i)
if (p % primes[i] == 0)
isPrime = false;
if (isPrime == true) {
primes[primeIndex] = p;
++primeIndex;
}
}
for (i = 0; i < primeIndex; ++i)
printf ("%i ", primes[i]);
printf ("\n");
return 0;
}
In particular, I'm having trouble understanding the difference between the primeIndex and the i variables. The primeIndex refers to the array number and i refers to the number placed into the array. Right?
primeIndex is the place where the next found prime is written in the prime array, and also the number of primes known so far. i is the index of the prime used for trial division. For each candidate, i loops from 1 (we don't need to try out primes[0] = 2 because only odd numbers are checked) to the index of the first prime larger than the square root of the candidate.

Resources