Verify the existence of an element in a table [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 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)

Related

return -1 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 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);

Continue n iterations [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 6 years ago.
Improve this question
I'd like to use continue statement (parametrized) n times:
int n = 7;
while(running()) {
commandA;
if(something) continue; // <- not once, but n times
commandB;
...
}
I'd like to use something like for(int i=0; i<n; ++i) continue; but the continue should be applied to the outer (while) loop. I'd like to skip n passes of the while loop.
The purpose is to always execute commandA, but skip n times commandB if running() condition is satisfied.
Is it possible to code that in C?
You could use an extra variable, like this, if I understood correctly what you are trying to achieve:
#include <stdio.h>
int main(void) {
int max_skip = 7;
int i = 0;
int something;
while(i < 10) {
something = i % 2;
if(something && max_skip-- >= 0)
continue;
++i;
}
return 0;
}
You short circuiting will come into play (as I explained here), which will protect max_skip from decreasing.
One way would be:
int n = 7;
while(running()) {
commandA;
if (n) { --n; continue; }
commandB;
...
}
continue can only be used to jump to the next iteration of the loop it appears in. You can't parametrize it, and you can't make it apply to any other loop. You will have to rewrite your loop.

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.

Analyze of programs (recursive) [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 9 years ago.
Improve this question
I'm taking a C language course,and the lecturer loves to give a very complex recursive programs in the exam and ask what the call of the function does.
I would like to know some methods/tips for this kind of problems analyze.
Here is a question for example:
what does the following prog? (There are no computers on the exam)
#include <stdio.h>
#include <conio.h>
int* what(int *arr, int *maxLen, int *curLen)
{
int *res;
if (*arr == -1){
*maxLen = *curLen = 0;
return arr;
}
if (arr[1] == -1 ){
*maxLen = *curLen = 1;
return arr;
}
if (arr[2] == -1 ){
*maxLen = *curLen = 2;
return arr;
}
res = what(arr+1, maxLen, curLen);
if ((arr[1] - arr[2]) * (*arr - arr[1]) > 0 ){
*curLen = *curLen + 1;
if ( *curLen >= *maxLen){
*maxLen = *curLen;
res = arr;
}
}else
*curLen=2;
return res;
}
void main(){
int cur, max, i, j, *res, a[][20]= {{5,-1}, {5,6,-1},
{1,4,5,9,7,6,4,6,9,8,5,4,1,4,5,6,-1}};
for(i=0; i<3; i++){
res = what(a[i], &max, &cur);
printf("max=%d, ",max);
for ( j = 0 ; j < max ; j++)
printf("%d ", res[j]);
('\n');
}
}//end
If you have to analyze recursive code without any documentation (uncommon!), one approach is to treat it as you would a proof-by-induction:
1) Find the base case (the case where it returns without recursing). Understand what it does in that situation, for all the possible branches.
2) Then look at the recursive case. Understand what it's doing for the next-to-last case, using your understanding of the base case.
If necessary, repeat (2) until you understand the code.
As with other coding conventions, these become easier to "read" with practice
Note that this question isn't really specific to the C language; recursion is used in most languages, when appropriate. Some -- the "functional" languages -- use it particularly heavily.
Try the program on paper..execute line by line,keeping record in a stack diagram and striking out and adding elements as removed and added. Simple example is for finding factorial by recursion.
3!=3*(2!)->3*(2*(1!))->3*(2*(1)) returns 3*2->6
In exams use the working space and a pencil to try the execution

my C code is too awkward [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Assume the character a,b,c,d,e represent the number 1 to 9, and they cannot be equal to
each other.
Question:
How many equals that can meet (ab * cde = adb * ce).
Example:
36 * 495 = 396 * 45.
Here is my code,and the result is right.However,i think my code is too awkward,especially in (if(a!=b&&a!=c&&a!=d&&a!=e&&b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e&&c*d*e!=0))
I would appreciate it if someone could give me a better solution.
#include<stdio.h>
main(){
int a,b,c,d,e,m,n,i=0;
long f1,f2,f3,f4;
for(m=11;m<=99;m++){
a=m/10;
b=m%10;
if(a!=b&&a*b!=0)
{
for(n=101;n<=999;n++)
{
c=n/100;
d=n%100/10;
e=n%10;
if(a!=b&&a!=c&&a!=d&&a!=e&&b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e&&c*d*e!=0)
{
f1=a*10+b;
f2=c*100+d*10+e;
f3=a*100+d*10+b;
f4=c*10+e;
if(f1*f2==f3*f4) i++;
printf("\n%d%d*%d%d%d*=%d%d%d*%d%d\n",a,b,c,d,e,a,d,b,c,e);
}
}
}
}
printf("%d\n",i);
return 0;
}
If you can, instead of
int a,b,c,d,e;
Try to use
int numbers[5];
And then to check if your numbers are all different, you can use for loops
doubleOccurence = FALSE; /* where FALSE = 0 */
for (i=0; i < 4; i++) {
for (j=i+1; j < 5; j++) {
doubleOccurence = doubleOccurence || (numbers[i] == numbers[j]);
}
}
It looks a bit clearer to me.
Unfortunately you can't really iterate through a list of variables you are better off with an array of numbers like Julien mentions in his answer.
int nums[5];
replace a with nums[0], b with nums[1], etc....
But then I would go one step further to tidying up your code and call a function that takes in the array to check uniqueness:
if(listIsUnique(nums, 5)) // yes hardcoded the 5, but that can be sorted
{
...
}
And then:
bool listIsUnique(int* nums, int len)
{
for (int i = 0; i < len; i++)
for (int j = i + 1; j < len; j++)
if (nums[i] == nums[j])
return false; // return false as soon as you find a match - slightly faster :)
return true; // if we get here its a unique list :)
}
Note: code is untested, there may be mistakes :o

Resources