0

Can someone tell me what is wrong with my code and why it is producing this output.

Code:

int main(){
  unsigned num;
  char response;

do{
 printf("Please enter a positive integer greater than 1 and less than 2000: ");
 scanf("%d", &num);
 if (num > 1 && num < 2000){
    printf("All the prime factors of %d are given below: \n", num);
    printPrimeFactors(num);
    printf("\n\nThe distinct prime factors of %d are given below: \n", num);
    printDistinctPrimeFactors(num);
 }
 else{
    printf("\nSorry that number does not fall between 1 and 2000.\n");
 }
 printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
 getchar();
 response = getchar();
}
while(response == 'Y' || response == 'y'); // if response is Y or y then program runs again
printf("Thank you for using my program. Good Bye!\n\n"); //if not Y or y, program terminates
return 0;
}

Output:

Please enter a positive integer greater than 1 and less than 2000: 1600
All the prime factors of 1600 are given below: 
2 2 2 2 2 2 5 5 

The distinct prime factors of 1600 are given below: 
2 5 

Do you want to try another number? Say Y(es) or N(o): yes
Please enter a positive integer greater than 1 and less than 2000: All the prime factors of 1600 are given below: 
2 2 2 2 2 2 5 5 

The distinct prime factors of 1600 are given below: 
2 5 

Do you want to try another number? Say Y(es) or N(o): Thank you for using my program. Good     Bye!
7
  • There seems to be nothing wrong with it! The prime factors of 1600 are 2, 2, 2, 2, 2, 2, 5, and 5 Commented Feb 1, 2013 at 21:39
  • yeah...if you see when i type "yes" is where it goes strange Commented Feb 1, 2013 at 21:40
  • 1
    not the actual code for the prime factors...but what the output produces from the user input Commented Feb 1, 2013 at 21:40
  • 2
    Did you try stepping through the code in a debugger to see what's going on? Hint - getchar() only reads a single character. What does that leave on the input stream when you call scanf() again? Hint 2 - check out fgets(3). Commented Feb 1, 2013 at 21:41
  • @CarlNorum My professor (yes this is "homework") wanted us to use getchar() for this assignment. Using scanf would resolve this issue, right? However, I have to use getchar()... Commented Feb 1, 2013 at 21:44

1 Answer 1

1

When you ask whether you want to repeat, you only read the y, leaving the es queued up in stdin. When you go to read the next number, scanf tries to parse that as a number, fails, and returns without altering num. When you prompt the user, you need to burn that whole line.

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.