LearnFrenzy
Sign in Take a free test

C Loops · Predict the Output · Question 9

Loop with a double counter stepping by 0.1 – output Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>

int main(void) {
    int steps = 0;
    for (double x = 0.0; x < 1.0; x += 0.1)
        steps++;
    printf("%d\n", steps);
    return 0;
}
  • A 10
  • B 11 Correct
  • C 9
  • D It never ends
Correct Answer: Option B

0.1 is slightly off in binary, and after ten additions x is 0.9999999999999999 – still less than 1.0 – so the loop runs an 11th time. Use an integer counter for an exact number of passes.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links