Analyze of programs (recursive) [closed] - c

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

Related

C Function: Count the occurrences of a digit in an integer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm receiving Output: 1. I should count the number of times a digit appear in an integer, for example, for number 1222345 and n = 2 Should appear 3 times.
int countOccurrences(int n, int num)
{
int i,k;
i=0;
while(num!=0)
{
k=num%10;
num=num/10;
if(k==n)
{
i++;
}
}
}
// Main
void main()
{
int num= 1222345;
int n = 2;
printf("Occurance of a number: %d", countOccurrences(n,num));
}
You have undefined behavior in the code. The function is supposed to return an int and it didn't.
Solution is to add return i in the end of other function. This will give you correct result. In the countOccurrences() function
...
if(k==n)
{
i++;
}
}
return i;
}
I was skipping the discussion of error check and all that. As chux mentioned for n<=0 case you might want to add a different way of handling it but you didn't add it. Atleast consider those case and put an error message on whatever input you need.
Some corner cases are
n=0,m=0.
Negative value of n or m.
Put a return on your countOccurrences function please
int countOccurrences (int n, int num) {
int i, k;
i = 0;
while (num! = 0)
{
k = num% 10;
num = num / 10;
if (k == n)
{
i ++;
}
}
return i; }
As other have pointed out, there are important issues with your code.
Here is a recursive solution that you may find interesting:
int countOccurrences(int n, int num)
{
int count = ((num % 10) == n);
return (num < 10) ? count : count + countOccurrences(n, num / 10);
}
Few general remarks about your code:
When using printf(), you should #include <stdio.h>.
main() should return int.
Place spaces around operators and format your code consistently. This k = num % 10; is more readable than k=num%10;. (There's more to code formatting than a matter of taste; without spaces you create areas full of characters which are more difficult to parse for our visual system.)

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.

Sorting array of integers C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i'm a beginner c programmer studying computer science and i'm trying to create a sorting program to sort an array of integers although i keep getting wrong results, this is what i got so far:
#include <stdio.h>
#include <string.h>
#define TAM 9
int sort_array(int num1[],int num2[]);
int main(){
int i=0;
int num1[TAM] = {5,6,2,4,7,1,3,0};
int num2[TAM] = {0};
int * ptr_num2 = num2;
sort_array(num1,num2);
while(*ptr_num2 != '\0'){
printf("%c",*ptr_num2+48);
ptr_num2++;
}
putchar('\n');
return 0;
}
int sort_array(int num1[],int num2[]){
int min=256,max=0,i,j;
int * ptr_num1 = num1;
int * ptr_max = num1;
int * ptr_num2 = num2;
/* check for max */
while(*ptr_max != '\0'){
if(*ptr_max > max) max = *ptr_max;
ptr_max++;
}
for(i=0;i<TAM-1;i++){
/* check for min */
for(j=0;j<TAM-1;j++){
if(*ptr_num1 < min) min = *ptr_num1;
ptr_num1++;
num1[i] = max;
}
*ptr_num2 = min;
ptr_num2++;
}
return 0;
}
I've been banging my head for several hours on this already.
EDIT: Forgot to mention that some of these things might not make sense since i'm just experimenting with a few things.
I understand you do not know about the typical array sorts... Well, let me to introduce you to one of the more simple ones. Allthough it's usually not the most efficient one, it's the easiest one to understand, and considering the fact you are messing with little arrays and not databases, it will be just fine.
I am talking about good old Chum, our Bubble sort.
Bubble sort is a well known simple array sorting algorithm -
The logic is simple. You go over the whole array on pairs of two - I.e, Array[0] with Array[1], Array[1] with Array[2], etc...
Whenever you find that things are not the way they are supposed to be - in your case, The larger index number is bigger than the lower index number - you swap between them, until you reach an iteration where you passed through the whole array and didnt swap at all.
In case you didn't understand well, here's Pseudo code from wikipedia (OMG who the heck uses wikipedia i'm such a n00b):
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
And here's some C code:
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Here again, btw, the credit is not for me:
http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort
Hope this helped you, and good luck :)

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)

Resources