Jump to content

Two problems

- - - - -

  • Please log in to reply
1 reply to this topic

#1
mircea2011

mircea2011

    Newbie

  • Members
  • Pip
  • 8 posts
Hy.

1). Determine the maximum number of integer using recursive function.
I do this program in two ways : one returns the maximum figure number through value, and another through adress.
But the second way, when I compile sometimes the result is good, sometimes is wrong. Why ?

#include<stdio.h>


int max(int n)

{

    int m;

    if (n<=9) return n;

    else

     {

         (m = max (n/10));

         if (m>n%10)  return m;

    else  return n%10;

     }

}


int max_2(int n, int *p)

{

    int m;

    if (n<=9) return n;

    else

     {

         (m = max (n/10));

         if (m>n%10)  return m;

    else  return *p = max_2(n%10, p);

     }

}


void main()

{

    int a, x, y;

    printf("\n Give a = "); scanf("%d", &a);

    printf("\n The maximum figure number %d is %d.\n", a, max(a));

    printf("\n Dati x = "); scanf("%d", &x);

    max_2(x, &y);

    printf("\n The maximum figure number %d is %d.\n", x, y);

}

 

2). Determine the largest number that can be formed with all the figures given number.
In my opinion you take the number, it becomes a vector of numbers, sort the array and turn back vector of digits in number.
I think that is a way. OK, but how to do this (it becomes a vector of numbers) ?
PS : problem must be solveb with basic instructions.

#include<stdio.h>

int main()

{

    int m, n, q, p, i, nr, tab[100];

    printf("\n Dati n = ");

    scanf("%d", &n);

    m=n; nr=0; p=0;

    while(m)

    {

        p=m%10;

        nr++;

        for(i=0; i<nr; i++)

           {

             tab[i]=p;

             printf("\n tab[%d] = %d\n", i+1, tab[i]);

           }

           m/=10;

    }

}

Edited by Alyn, 26 October 2011 - 07:03 AM.
added code tag


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
1) your second way is not recursive, it calls the first recursive function. Also, you don't always set *p to the output. Look at this line:
if (m>n%10) return m;

When that happens, *p doesn't point at the right value.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users