Parameter not being passed correctly. - c

I have a Piece of code here. The code Runs fine and there is no error shown by the system. Although I have a recursive function the recursion does not occurs.
Here is my code....
What exactly is the problem???
int no_of_moves(int n,int s[], int m)
{ int move=0,i;
if(n==1)
return 0;
for(i=m-1;(i>=0&&s[i]!=n&&n%s[i]==0); i--)
{
//printf("(%d %d)",n,s[i]);
move = max(move, 1+no_of_moves(s[i],s,m));
}
return move;
}

There is nothing easier than add debug output like this
int no_of_moves(int n,int s[], int m)
{ int move=0,i;
printf("Recursion test\n");
if(n==1)
return 0;
for(i=m-1;( i>=0 && s[i] != n && n%s[i] == 0); i--)
{
printf("(%d %d)",n,s[i]);
move = max(move, 1+no_of_moves(s[i],s,m));
}
return move;
}
Note
printf("Recursion test\n");
Output
Recursion test
(12 4)Recursion test
(12 3)Recursion test
(12 2)Recursion test
It means that your function is called recursively 3 times.
The problem why does the function give you wrong output is in passing parameters. But Q was
Program not entering into Recursion
but it does.

Related

Recursive print of binary number

I'm struggling to write a recursive way to print a binary number. Here is what I have so far:
int bin(unsigned char n)
{
if (n==0) {
return 0;
} else {
printf("%d", bin(n<<1));
}
}
bin(7)
What seems to be wrong with the logic above?
A few errors such as using << (shift up) instead of >> (shift down). Also not always returning something. I'm surprised the compiler didn't pull you up on that. You don't gain anything from a return value, So you may as well get rid of it.
A simple implementation could look like this. We need to have the wrapped function (bin_recur) to allow us to differentiate between 0 the input value and 0 which signifies its time to stop recursion.
#include <stdio.h>
void bin_recur(unsigned char n)
{
if (n > 0)
{
printf("%d", n & 1);
bin_recur(n >> 1);
}
}
void bin(unsigned char n)
{
if (n == 0)
{
printf("0\n");
} else
{
bin_recur(n);
printf("\n");
}
}
int main()
{
for(unsigned i = 0; i < 10; i++)
{
bin(i);
}
}
The fact that your bin function calls printf is not completely ideal. This is what's known as tight coupling and the function could be more reusable if it was not bound to how it is presented. Perhaps copying to a string is a good way or even using fprintf to print to a file.
Stopping when n is 0 is wrong.
This fails for the trivial case where n is 0 to start with.
What you really need to do is pass down a shift amount as a second argument and stop after 8 bits.
Using the return with value just gets in the way.
Here's some refactored code with a full diagnostic test:
#include <stdio.h>
void
bin2(unsigned char n,int shf)
{
if (shf <= 7) {
bin2(n,shf + 1);
printf("%d", (n >> shf) & 1);
}
}
void
bin(unsigned char n)
{
bin2(n,0);
}
int
main(void)
{
for (unsigned int chr = 0; chr <= 0xFF; ++chr) {
printf("%2.2X: ", chr);
bin((unsigned char) chr);
printf("\n");
}
return 0;
}
please add this lines to your code.
void binary(int n) {
if(n==0)
return;
binary(n/2);
printf("%d",n%2);
}
You need the print call to execute after the recursive function for this to work. Here's an example:
void bin(unsigned char n)
{
if (n > 1) bin(n>>1);
putchar(n&1 ? '1' : '0');
}
int main(void)
{
for (unsigned char i = 255; i; i--) {
printf("%d --> ", i), bin(i);
getchar(); // inspect element if you want
}
}
Link to running code here.

Bubble sort using recursive function in C

When I call my bubble sort recursive function, the array is not getting sorted.
#include"stdio.h"
void bubble(int *arr,int n,int vidx){
if(n==0)
return;
if(vidx == n)
bubble(arr,n-1,0);
return;
if(*(arr+vidx) > *(arr+vidx+1)){
int temp = *(arr+vidx);
*(arr+vidx) = *(arr+vidx+1);
*(arr+vidx+1) = temp;
bubble(arr,n,vidx+1);
return;
}
} int main(){
int a[] = {5,4,3,2,1};
bubble(&a,5,0);
for(int i = 0 ; i < 5 ; i++)
printf("%d,",a[i]);
return 0; }
Actual Output : 5,4,3,2,1,
Expected Output : 1,2,3,4,5,
if(vidx == n)
bubble(arr,n-1,0);
return;
This is why I advocate always using braces. As-is, that code is equivalent to:
if(vidx == n){ bubble(arr,n-1,0); }
return;
Most of the body of the bubble function is unreachable.
Edit: Incidentally, I notice two other bugs in what's left:
vidx can go up to the length of the array, so vidx+1 will index past the end, which could cause problems
When you hit two adjacent elements that are in the right order with respect to each other (i.e. *(arr+vidx) <= *(arr+vidx+1)), you make it to the end of the function without recursing further, stopping the sort prematurely.

Understanding returning values functions C

I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}

Subset using Backtracking

The following question I was asked to solve using backtracking:
It's supposed to return the length of the longest subset of differences that replaces a sign.
For example:
for this given series [11,6,7,8,9] it returns 3.
because it includes this subset [11,8,9] and [11,6,8] .
*In this series a:[11,8,9] a[1]-a[0]<0 and a[2]-a[1]>0 .In other words the sign of the difference between each neighbor changes. *
I pretty much finished the coding but have no idea how to return the max length using backtracking.
Any note/help will be highly appreciated.
/* this function checks if we can add another number to the sequence
and still the differences between the numbers replace a sign.It's enough
to check the last two*/
int check_rec(int series[],int arr[],int n)
{ int count=0,c=n;
int temp1=0,temp2=0;
while(c>=0 && count!=2)
{
if (arr[c]==1 && count==0)
{ temp1=series[c];
count++;
}
if (arr[c]==1 && count==1 )
{ temp1=series[c];
count++;
}
c--;
}
if(count<2) return 1;
if(temp1>temp2 && series[n+1] < temp1) return 1;
if(temp1<temp2 && series[n+1]> temp1) return 1;
return 0;
}
int count_ones(int arr[],int n)
{ int c;
for(int i=0;i<n;i++)
{
if(arr[i])
c++;
}
return c;
}
// 1 in the array helper indicates that the index has been chosen.
void max_crazy(int series[], int n,int helper[],int length,int max[])
{
if(n==0)
{
int x=count_ones(helper,n);
if(x>max[0])
max[0]=x;
}
for(int i=0;i<2;i++)
{
if(n!=length && i==1 && !check_rec(series,helper,length-n))
continue;
helper[0]=i;
max_crazy(series,n-1,helper+1,length,max);
}
}
you can send a pointer that saves the max in the recursive function , and every time you reach the if(n==0) you have to check if the count_ones bigger than max then max=count_ones

Search of an element on a unsorted array recursively

This is an exercise that I took from an exam. It asks to write a function that receives an unsorted array v[] and a number X and the function will return 1 if X is present in v[] or 0 if X is not present in v[]. The function must be recursive and must work in this manner:
1. Compares X with the element in the middle of v[];
2. The function calls itself (recursion!!) on upper half and on the lower half of v[];
So I've written this function:
int occ(int *p,int dim,int X){
int pivot,a,b;
pivot=(dim)/2;
if(dim==0) //end of array
return 0;
if(*(p+pivot)==X) //verify if the element in the middle is X
return 1;
a=occ(p,pivot,X); //call on lower half
b=occ(p+pivot,dim-pivot,X); //call on upper half
if(a+b>=1) //if X is found return 1 else 0
return 1;
else{
return 0;
}
}
I tried to simulated it on a sheet of paper and it seems to be correct (Even though I'm not sure) then I've written it on ideone and it can't run the program!
Here is the link: https://ideone.com/ZwwpAW
Is my code actually wrong (probably!) or is it a problem related to ideone. Can someone help me? Thank you in advance!!!
The problem is with b=occ(p+pivot,dim-pivot,X); when pivot is 0. i.e. when dim is 1.
the next function call becomes occ(p,1,X); This again leads to the call occ(p,1,X); in a continuous loop.
It can be fixed by adding a condition to the call, as shown in the code below.
int occ(int *p,int dim,int X){
int pivot,a=0,b=0;
pivot=(dim)/2;
if(dim==0){
return 0;
}
if(*(p+pivot)==X)
return 1;
if (pivot != 0)
{
a=occ(p,pivot,X);
b=occ(p+pivot,dim-pivot,X);
}
if(a+b>=1)
return 1;
else{
return 0;
}
}
The implemetation is causing a stack overflow, as the recursion does not terminate if the input contains only one element. This can be fixed as follows.
int occ(int *p, int dim, int X)
{
int pivot, a, b;
pivot = (dim) / 2;
if (dim == 0)
{
return 0;
}
if (*(p + pivot) == X)
{
return 1;
}
if (dim == 1)
{
if (*(p + pivot) == X)
{
return 1;
}
else
{
return 0;
}
}
a = occ(p, pivot, X);
b = occ(p + pivot, dim - pivot, X);
if (a + b >= 1)
{
return 1;
}
else
{
return 0;
}
}
It's enought to change only this one line in the source code to avoid the endless loop with occ(p,1,X):
//if(dim==0) //end of array
if (pivot == 0)
return 0;

Resources