user681007
user681007

Reputation:

Undesired output c program

I have wrote a program that takes two integers(m and n) as input and then writes to a file all the prime numbers between them. I wanted the output to look neat so I print each number 7 spaces wide using the field-width modifier and only print 10 per line. The output is as expected apart from the first line, where only 9 numbers are printed.
Here is the code:

#include <stdio.h>
#include <math.h>

#define SIZE 100000000

char primes[SIZE];

void seive(void)
{
    int i, j;
    primes[1] = primes[0] = 1;
    for (i=3;i<=sqrt(SIZE);i+=2)           
        if (primes[i] == 1)
            continue;
        else 
            for (j=i*i;j<SIZE;j+=2*i)
                primes[j] = 1;
}

int main()
{
    int n, m, count;
    FILE *fp;
    fp = fopen("test.txt", "w");
    seive();
    scanf("%d %d", &m, &n);
    count = 0;
    if (m <= 2) {
       fprintf(fp, "%7d ", 2);
       count++;
       }
    if (!(m & 1))
       m++;
    for (m;m<=n;m+=2) {
        if (!primes[m]) {
           count++;
           if (count == 10) {
              fprintf(fp, "\n");
              count = 0;
           }
           fprintf(fp, "%7d ", m);
        }
    }
    return 0;
}

This is the output for the input 1 300:

      2       3       5       7      11      13      17      19      23 
     29      31      37      41      43      47      53      59      61      67 
     71      73      79      83      89      97     101     103     107     109 
    113     127     131     137     139     149     151     157     163     167 
    173     179     181     191     193     197     199     211     223     227 
    229     233     239     241     251     257     263     269     271     277 
    281     283     293   

As you can see only nine numbers are printed on the first line, but after it does as it should. I'm baffled. Thanks in advance.

Upvotes: 1

Views: 147

Answers (2)

I think it has something to do with the fact that you print your newline before you print your output in the loop.

change it to:

for (m;m<=n;m+=2) {
    if (!primes[m]) {
       count++;

       fprintf(fp, "%7d ", m);

       if (count == 10/*&& you're going to print more numbers*/) {
          fprintf(fp, "\n");
          count = 0;
       }
    }
}

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182769

count = 0;
if (m <= 2) {
   fprintf(fp, "%7d ", 2);
   count++;
   }

This starts a line, prints an entry, and increments count to 1.

    if (!primes[m]) {
       count++;
       if (count == 10) {
          fprintf(fp, "\n");
          count = 0;
       }
       fprintf(fp, "%7d ", m);

This starts a line, prints an entry, and sets count to zero.

Since the two code sections set count to different values (off by one), the produce different numbers of entries per line (off by one).

Upvotes: 1

Related Questions