I have a program that outputs the first 30 numbers of the fibonacci sequence. My declaration to hold the integers works and the loop to calculate them works but I am trying to output them 5 elements per line with a field width of 10. I have the field width but I can't get it to put only 5 elements per line. I could use some advice! Thanks.

Recommended Answers

All 4 Replies

#include <stdio.h>

int main ( void )
{
   int array[] =
   {
      1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
      16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
   };
   size_t i;
   for (i = 0; i < sizeof array / sizeof *array; ++i )
   {
      printf("%10d%c", array[i], i % 5 == 4 ? '\n' : ' ');
   }
   return 0;
}

/* my output
         1          2          3          4          5
         6          7          8          9         10
        11         12         13         14         15
        16         17         18         19         20
        21         22         23         24         25
        26         27         28         29         30
*/

i dont totally understand your code. Here is what I have for the output can you tell me what you think?

for(int i = 0; i < 30; i++)
{
    for(int count = 0; count < 5; count++)
    {
        cout << setw(10) << fib[i];
    }
    cout << endl;
}

Print an integer. If the counter divided by 5 has a remainder or 4, it's the last one: print a newline; otherwise use a space separator.

[edit]Its equivalent would be

printf ( "%10d", array [ i ] );
      if ( i % 5 == 4 )
      {
         putchar ( '\n' );
      }
      else
      {
         putchar ( ' ' );
      }

i dont totally understand your code.

That might be because your learning in C++ and dave is responding in C.

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.