|
-
Nov 14th, 2009, 06:42 PM
#1
Thread Starter
Frenzied Member
[RESOLVED] Loop in C
Hi there.
I'm in the process of learning C.
I found a good tutorial (though I'm beginning to doubt that now...).
So now there's a problem I'm having trouble with solving.
The following is a sample of a loop with the condition before the code block.
Code:
#include <stdio.h>
int main()
{
const int MAGIC_NUMBER = 6;
int guessed_number;
printf("Try to guess what number I'm thinking of\n");
printf("HINT: It's a number between 1 and 10\n\n");
printf("debug: guessed number = %d", guessed_number);
printf("Enter your guess: ");
scanf("%d", &guessed_number);
while (guessed_number != MAGIC_NUMBER);
{
printf("Enter your guess: ");
scanf("%d", &guessed_number);
}
printf("\n\nYou win!\n");
return 0;
}
Now, say I input '4'.
It should enter the loop if I'm not mistaken.
But apparently I am mistaken, because when I compile it and I enter '4' it doesn't do anything.
It doesn't even print the debug line.
So what's the catch?
Is my compiler nuts or is there something wrong in the code?
Thanks.
Delete it. They just clutter threads anyway.
-
Nov 15th, 2009, 06:50 PM
#2
New Member
Re: Loop in C
A few comments about your code:
1) You print out guessed_number before you've input it, or even assigned it a dummy value when you first declared it. Perhaps move the debug line down three lines to a point after which you have read in guessed_number.
2) A while loop doesn't need a semicolon after the condition:
Code:
while (guessed_number != MAGIC_NUMBER);
The semicolon should be removed.
3) A suggestion: why not initialize guessed_number to a value not equal to MAGIC_NUMBER, and then just have the input and output lines within the while loop. Then you could get rid of a couple lines outside the loop.
For example:
Code:
#include <stdio.h>
int main()
{
const int MAGIC_NUMBER = 6;
int guessed_number = 3;
printf("Try to guess what number I'm thinking of\n");
printf("HINT: It's a number between 1 and 10\n\n");
while (guessed_number != MAGIC_NUMBER)
{
printf("Enter your guess: ");
scanf("%d", &guessed_number);
printf("debug: guessed number = %d", guessed_number);
}
printf("\n\nYou win!\n");
return 0;
}
-
Nov 15th, 2009, 07:11 PM
#3
Thread Starter
Frenzied Member
Re: Loop in C
Maybe I should start looking for a better tutorial. 
Turns out the only problem was that semicolon 
Don't you just love typo's?
Thanks man.
Delete it. They just clutter threads anyway.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|