DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   Creating a table in c (http://www.daniweb.com/forums/thread156159.html)

Ungodlyrich Nov 9th, 2008 12:37 am
Creating a table in c
 
I wanted to create a simple table by printing lines in between my values with a header at the top and my numbers left justified. However, when I get to a ten digit number or larger, my code seems to break and my count variable goes to zero as far as I can tell, causing a bunch of space to be printed where it doesn't need to be. I was wondering what I'm doing wrong. Thank you for any help you can offer!


#include <stdio.h>

int main ( int argc, char *argv[] ) {

  unsigned int y = 1;
  int x = 1;
  int limit = sizeof(int) * 8;
  int z, n, m, count;

  printf("|    x      |    y      | \n");

  for(z = 0; z < limit - 1; z++){

    x = x << 1;
    y = y << 1;
    m = x;
    count = 0;

    while(m > 0){
      m = m / 10;
      count++;
    }

    printf("|%d", x);

    for(n = 11; n >= count; n--)
      printf(" ");

    printf("|%u", y);

    for(n = 11; n >= count; n--)
      printf(" ");

    printf("|\n");

  return 0 ;
}

ddanbe Nov 9th, 2008 7:28 am
Re: Creating a table in c
 
You want to print a table with the powers of 2 and you want your integers to be signed and unsigned. You're making it to complicated I think, use \t to separate your output. Or use something like printf("|%d |%u |",x,y);

devnar Nov 9th, 2008 11:18 am
Re: Creating a table in c
 
The upper limit of an int is 2147483647(32-bit system). When x reaches the value 1073741824,
x<<1;
multiples that value by 2 which yields 2147483648 which is beyond the upper limit, hence the value goes in a circle and the number -2147483648 gets stored in x and consequently in m. since you've given
while(m>0)
count never gets incremented and stays at zero.

It would be better to stop your table when m becomes negative.


All times are GMT -4. The time now is 3:00 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC