help

This is a discussion on help within the C Programming forums, part of the General Programming Boards category; This program suppose to change a number to binary format. but somehow it's printing infite 0s. /* Program that utilizes ...

  1. #1
    j
    Guest

    Question help

    This program suppose to change a number to binary format.
    but somehow it's printing infite 0s.

    /* Program that utilizes simple functions to convert decimal numbers */
    /* to binary and produces formatted output */

    #include <stdlib.h>
    #include <stdio.h>

    int main(void)
    {

    /* Declaration */
    int m;
    int binarynum = 0;
    int binarynum2;

    /* Ask User to Input numbers */
    printf("Enter a number that you want to change in binary format ");
    scanf("%d", &m);

    /* Print Output for Binaryrep Function */
    printf("\n");
    printf("The binary format for interger %d is ", m);

    /* Call Binaryrep Function */
    while (binarynum != EOF)
    {
    binarynum2 = binaryrep(m);

    /* Print result of Binaryrep Function */
    printf("%d", binarynum2);
    }

    return 0;
    }

    /* Function Power */
    int power(int j, int k)
    {
    /* Declaration */
    int num2;
    int result = 1;

    num2 = k;

    if(num2 == 0)
    {
    result=1;
    return result;
    }
    else
    {
    for (num2 = 1; num2 <= k; ++num2)
    {
    result = result * j;

    }
    return result;
    }
    }

    /* Function Binaryrep */
    int binaryrep(int i)
    {
    int FirstPower = 15;
    int num6;

    /* Convert interger to binary format */
    while (FirstPower >= 0)
    {
    num6 = power ( 2, FirstPower);

    if (num6 <= i)
    {
    return 1;
    i = i - num6;
    }
    else
    {
    return 0;
    }
    FirstPower = FirstPower -1;
    }
    }

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    The reason why it goes wrong is this loop:

    /* Call Binaryrep Function */
    while (binarynum != EOF)
    {
    binarynum2 = binaryrep(m);

    /* Print result of Binaryrep Function */
    printf("%d", binarynum2);
    }

    The variable binarynum is set to a value which is not equal to EOF. So (binarynum != EOF) == TRUE. The loop ends when (binarynum == EOF) == TRUE. In your loop, the value of binarynum is never changed. So binarynum will never be equal to EOF and the loop will never end.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21