0

I wrote a simple C program to print all the multiples of 3 but there is some error during runtime my code is:

#include <stdio.h>

void main(void) {
    int i, x;
    for(i = 1; i < 1000; i++) {
        x = i % 3;
        if(x == 0) {
            printf("%d\n", i);
        }
     }
}

the problem is that if I enter numbers greater than 891 till 1000 in the loop the output is starting from 6 instead of 3 and if i write the code as above than the output is starting from 114. for the values less than or equal to 891 it is showing the correct output.

7
  • 2
    This works for me. how are you viewing the output? Commented Feb 8, 2014 at 8:22
  • 3
    Cannot reproduce, what you posted behaves properly. Try redirecting the output to a file, might be whatever you're using to view the output that's truncating it. Commented Feb 8, 2014 at 8:22
  • I am using code::blocks its running it in command prompt....Yes I guess the output is truncated Commented Feb 8, 2014 at 8:24
  • For me too its working fine.But i dont know why are you using variable x.its not necessary.We can simply use. if((i%3)==0) { printf("%d\n",i);}.In this way you can avoid use of variable x. Commented Feb 8, 2014 at 8:32
  • @Rajdhar but you will need a variable for the if statement i guess, or u saying to directly put the expression i%3 inside if? Commented Feb 8, 2014 at 8:36

1 Answer 1

1

Make sure you can view all output:

reuts@reuts-K53SD:~/ccccc$ cat mmph.c && gcc mmph.c
#include<stdio.h>
main(){

    int i,x;
    for(i=1;i<1000;i++)
    {
        x=i%3;

        if(x==0){
            printf("%d\n",i);

        }
    }
}
reuts@reuts-K53SD:~/ccccc$ ./a.out | egrep "^3$|999"
3
999

As you can see, this works. Your output is probably truncated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.