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 ;
}

Recommended Answers

All 3 Replies

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);

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.

Dude you ave count being assigned to 0 within ur first for loop, therefore the value count will be when it exits the for loop is only 1. thus at some point when compared to count it will continue to be read as one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.