Home > database >  Why is the output of these 2 programs not same
Why is the output of these 2 programs not same

Time:09-17

I am trying to find the numbers that are not divisible by 3,5,7 and counting them And printing the ones that are divisible

The two approaches are

#include <stdio.h>
int main()
{
   int count=0;
   
   for(int i = 1; i<=500;i  )
   {
       if(i%3==0 && i%5==0 && i%7==0) {
            printf("%d \n", i);
       }
       else {
           count  ;
       }
   }
    printf(" the count is : %d \n", count);
}

/*
WAP to count the numbers from (1-500) which are not divisible by 3, 4 and  
*/
#include <stdio.h>
int main()
{
    int count=0;
    
    for(int i = 1; i<=500;i  )
    {
        if(i%3!=0 && i%5!=0 && i%7!=0) {
            count  ;
        }
        else {
            printf("%d \n", i);
        }
    }
     printf(" the count is %d \n", count);
}

The problem is that the output should be same but it is not

CodePudding user response:

Because these two if statements are not opposite from each other. The negation from

if(i%3==0 && i%5==0 && i%7==0)

would be

 if(!(i%3==0 && i%5==0 && i%7==0))

which changes equals to not equals, but also changes ANDs to ORs. So the second code should have something like this

if(i%3!=0 || i%5!=0 || i%7!=0)
  •  Tags:  
  • c
  • Related