-2

Here is my code. My question is, why does it keep printing only 5 numbers? Why won't it print 10 like it's supposed to?

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

   int main(){

   int r, col;

   srand((unsigned)time(NULL));

   for (col=1; col<=10; col++){

   r = rand() % 11;
   printf("%d\n", r);
   col++;

   }
  return 0;
  }
Lundin
  • 195,001
  • 40
  • 254
  • 396
CrushClaw
  • 1
  • 2

3 Answers3

3

Because, you are doing col++ twice, once in the loop body, and once in the post-loop statement.

for (col=1; col<=10; col++)   //...................(i)
                    ^^^^^^^

and

r = rand() % 11;
printf("%d\n", r);
col++;                       //.....................(ii)
^^^^^

So, for a single iteration, col gets incremented twice, iteration count gets halved.

Remove either of the statements.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You have made a mistake - you don't need to write the col++ twice!!

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

int main(){

    int r, col;

    srand((unsigned)time(NULL));

    for (col=1; col<=10; col++){

        r = rand() % 11;
        printf("%d\n", r);
    }

    return 0;
}
mohamede1945
  • 7,092
  • 6
  • 47
  • 61
STF
  • 1,485
  • 3
  • 19
  • 36
0

Double col++. "for" loop statement include three expressions. First is called once at beginning. Usually used for counter initialization. Second is loop continue condition check. Called before every iteration. If result of expression false loop will be stopped. Third part called after every iteration. Usually used for counter increment.

If you used col++ in the "for" and want "col" to be incremented by 1 every iteration you don't execute col++ in the loop body.

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

   int main(){

   int r, col;

   srand((unsigned)time(NULL));

   for (col=1; col<=10; col++){

   r = rand() % 11;
   printf("%d\n", r);
   //col++;

   }
  return 0;
  }
Beka
  • 97
  • 5