user292489
user292489

Reputation: 45

how to count multiples of numbers in an input file?

i was trying to count the number of multiples of 2, 3, and 6 respectielly from the users input file. but for some reason, my counter is not working. can any bosy hep me please. my code:

#include <stdio.h>
int main (void)
{
  int num[12];
  int i;
  int counttwo;
  int countthree;
  int countsix;
  int total=0;
  printf("enter 12 integer numbers:\n");
  for(i=0;i<12;i++){

 scanf("%d", &num[i]);
  }
  for(i=0;i<12;i++){
    counttwo=0;
      if(num[i]%2==0){
       counttwo++;
      }
      countthree=0;
       if(num[i]%3==0)
  {
      countthree++;
   }
       countsix=0;
      if(num[i]%6==0)
        {
          countsix++;
}
      printf("There are %d multiples of 2:\n", counttwo);
      printf("There are %d multiples of 3:\n", countthree);
      printf("There are %d multiples of 6:\n", countsix);
}
  return 0;

}

Upvotes: 0

Views: 1208

Answers (3)

Zai
Zai

Reputation: 1175

  • Reset counttwo, countthree, and countsix to 0 before for-loop
  • Remove redundant for-loop for scanf
  • Move 3 printf's out of the for-loop

This is the fixed code

#include <stdio.h>
int main (void)
{
  int num[12];
  int i;
  int counttwo = 0; //Reset counttwo, countthree, and countsix to 0
  int countthree = 0;
  int countsix = 0;
  int total=0;
  printf("enter 12 integer numbers:\n");

  for(i=0;i<12;i++){

      scanf("%d", &num[i]);

      if(num[i]%2==0){
       counttwo++;
      }

      if(num[i]%3==0){
       countthree++;
      }

      if(num[i]%6==0) {
        countsix++;
      }
  }

  printf("There are %d multiples of 2:\n", counttwo);
  printf("There are %d multiples of 3:\n", countthree);
  printf("There are %d multiples of 6:\n", countsix);

  return 0;

}

Upvotes: 0

Tyler McHenry
Tyler McHenry

Reputation: 76660

Think about what happens to the values of counttwo, countthree and countsix within the second loop. Pay particular attention to the lines counttwo = 0, countthree = 0, and countsix = 0.

Upvotes: 1

tur1ng
tur1ng

Reputation: 3309

Your reset the counter variables each iteration step. Put the

counttwo=0;
countthree=0;
countsix=0;

code before the for().

Upvotes: 1

Related Questions