Search code examples
cfunctionreturn-valuereturn-type

How can I return multiple values without using arrays or pointers or structures?


We were given a source code to convert decimal to binary and octal.This is the source code that I am going to use the function Dec2BinOct() to return the values of the converted decimal.

#include<stdio.h>
int main()
{
    unsigned long n, place=1, bin=0, r, o=0, place2=place;  
    printf("Conversion: Decimal to binary and octal.\n");
    printf("Enter number: ");
    scanf("%lu", &n);
    printf("%lu is ", n);
           
    for(unsigned long g = n; g != 0; place = place * 10)  {  
        r = g % 2;    
        bin = bin + (r * place);
        g = g / 2;  
    }  
    
    printf("%lu in Binary Form. \n", bin);
                
    printf("%lu is ", n);
    while (n != 0) {
        o = o + (n % 8) * place2;
        n =   n / 8;
        place2 = place2 * 10;
    }
    printf("%lu in Octal Form.\n\n", o);
    return 0;
}

We were tasked to apply functions for our assignment and were required to use the function Dec2BinOct() as stated earlier, but our teacher told us that it is the minimum required function. I don't seem to get the right program after so many tries. I just needed some help and this is due tomorrow. I appreciate all of your help


Solution

  • If you want multiple values but not at once, you can just generalize both operations and provide base to which a number should be converted:

    unsigned long Dec2AnotherBase(unsigned long n, int base){
        unsigned long place=1, result=0;
        for(; n; place*=10, n/=base) 
            result += n % base * place;
        return result;
    }
    

    In your main function you replace your loops with those:

    bin=Dec2AnotherBase(n, 2);
    o=Dec2AnotherBase(n, 8);
    

    I also simplified your code a little. Here's what I did:

    • Replaced bin=bin+(r*place) and place=place*10 with shorter bin+=r*place and place*=10.
    • Eliminated r variable because it's only used once (also no brackets around % are needed as % operator is the same precedence as * and evaluated left-to-right).
    • Moved g=g/2 inside increment statement using , operator.
    • Removed curly brackets which were no longer required in a loop reduced to a single statement.
    • Removed g since it is created unnecessarily (you can operate directly on n as it is already a copy of a variable passed to the function).
    • Contentious: Replaced n!=0 in condition with n as every non-zero value is implicitly converted to logical true.