C - The loop doesn't continue
Why doesn't this loop continue after I enter the letter y
into the char
answer?
I thought getchar()
would help but it doesn't seem like its doing anything.
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
printf("Enter a number: n");
scanf("%d", &num);
while(answer != 'n')
{
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
c loops
add a comment |
Why doesn't this loop continue after I enter the letter y
into the char
answer?
I thought getchar()
would help but it doesn't seem like its doing anything.
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
printf("Enter a number: n");
scanf("%d", &num);
while(answer != 'n')
{
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
c loops
if you expect your loop to return to theprintf("Enter a number: n")
-part, please note that this part is outside of the loop. What do you actually observe and what do you expect?
– Stephan Lechner
Nov 21 '18 at 10:57
1
If you want to skip leading white-space before a character, use a format string with a space. As in" %c"
. Also note that with your loop condition, anything but a lower-case'n'
would continue the loop, not only'y'
.
– Some programmer dude
Nov 21 '18 at 10:57
2
And this is also a very good time to learn how to debug your programs. Step through the code line by line in a debugger, checking the values of all variables (and save the result fromgetchar
in a dummy variable so you can check that too).
– Some programmer dude
Nov 21 '18 at 11:00
I just tested your code and it has the expected behaviour if you like to stop when you write 'n' and continue when you write 'y' so I don't see your problem
– Welgriv
Nov 21 '18 at 11:04
add a comment |
Why doesn't this loop continue after I enter the letter y
into the char
answer?
I thought getchar()
would help but it doesn't seem like its doing anything.
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
printf("Enter a number: n");
scanf("%d", &num);
while(answer != 'n')
{
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
c loops
Why doesn't this loop continue after I enter the letter y
into the char
answer?
I thought getchar()
would help but it doesn't seem like its doing anything.
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
printf("Enter a number: n");
scanf("%d", &num);
while(answer != 'n')
{
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
c loops
c loops
edited Nov 21 '18 at 14:25
Francesco Boi
2,71522643
2,71522643
asked Nov 21 '18 at 10:55
Lidor CohenLidor Cohen
235
235
if you expect your loop to return to theprintf("Enter a number: n")
-part, please note that this part is outside of the loop. What do you actually observe and what do you expect?
– Stephan Lechner
Nov 21 '18 at 10:57
1
If you want to skip leading white-space before a character, use a format string with a space. As in" %c"
. Also note that with your loop condition, anything but a lower-case'n'
would continue the loop, not only'y'
.
– Some programmer dude
Nov 21 '18 at 10:57
2
And this is also a very good time to learn how to debug your programs. Step through the code line by line in a debugger, checking the values of all variables (and save the result fromgetchar
in a dummy variable so you can check that too).
– Some programmer dude
Nov 21 '18 at 11:00
I just tested your code and it has the expected behaviour if you like to stop when you write 'n' and continue when you write 'y' so I don't see your problem
– Welgriv
Nov 21 '18 at 11:04
add a comment |
if you expect your loop to return to theprintf("Enter a number: n")
-part, please note that this part is outside of the loop. What do you actually observe and what do you expect?
– Stephan Lechner
Nov 21 '18 at 10:57
1
If you want to skip leading white-space before a character, use a format string with a space. As in" %c"
. Also note that with your loop condition, anything but a lower-case'n'
would continue the loop, not only'y'
.
– Some programmer dude
Nov 21 '18 at 10:57
2
And this is also a very good time to learn how to debug your programs. Step through the code line by line in a debugger, checking the values of all variables (and save the result fromgetchar
in a dummy variable so you can check that too).
– Some programmer dude
Nov 21 '18 at 11:00
I just tested your code and it has the expected behaviour if you like to stop when you write 'n' and continue when you write 'y' so I don't see your problem
– Welgriv
Nov 21 '18 at 11:04
if you expect your loop to return to the
printf("Enter a number: n")
-part, please note that this part is outside of the loop. What do you actually observe and what do you expect?– Stephan Lechner
Nov 21 '18 at 10:57
if you expect your loop to return to the
printf("Enter a number: n")
-part, please note that this part is outside of the loop. What do you actually observe and what do you expect?– Stephan Lechner
Nov 21 '18 at 10:57
1
1
If you want to skip leading white-space before a character, use a format string with a space. As in
" %c"
. Also note that with your loop condition, anything but a lower-case 'n'
would continue the loop, not only 'y'
.– Some programmer dude
Nov 21 '18 at 10:57
If you want to skip leading white-space before a character, use a format string with a space. As in
" %c"
. Also note that with your loop condition, anything but a lower-case 'n'
would continue the loop, not only 'y'
.– Some programmer dude
Nov 21 '18 at 10:57
2
2
And this is also a very good time to learn how to debug your programs. Step through the code line by line in a debugger, checking the values of all variables (and save the result from
getchar
in a dummy variable so you can check that too).– Some programmer dude
Nov 21 '18 at 11:00
And this is also a very good time to learn how to debug your programs. Step through the code line by line in a debugger, checking the values of all variables (and save the result from
getchar
in a dummy variable so you can check that too).– Some programmer dude
Nov 21 '18 at 11:00
I just tested your code and it has the expected behaviour if you like to stop when you write 'n' and continue when you write 'y' so I don't see your problem
– Welgriv
Nov 21 '18 at 11:04
I just tested your code and it has the expected behaviour if you like to stop when you write 'n' and continue when you write 'y' so I don't see your problem
– Welgriv
Nov 21 '18 at 11:04
add a comment |
3 Answers
3
active
oldest
votes
I have made few corrections in your program.
- It was difficult to understand what your program does. I have made your program more readable and modular by defining a separate re-usable function for
factorial
. - It makes more sense to ask user again for the number if user has entered
'y'
. So, I have moved required code. - I don't recommend mix use of
scanf
andgetchar
in the program. So, we can just usescanf
for the program. Thescanf()
function removes whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don't remove whitespace.
Use " %c" with a leading blank
to skip optional white space. Do not use a trailing blank in a scanf() format string.
Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.
#include <stdio.h>
unsigned long factorial(unsigned long num)
{
unsigned long mult = 1;
unsigned long k = 1;
while (k <= num) {
mult *= k;
k++;
}
return mult;
}
int main(void)
{
char answer = 'y';
do {
int num = 0;
printf("Enter a number: n");
scanf(" %d", &num);
unsigned long mult = factorial(num);
printf("%d! = %lun", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
scanf(" %c", &answer);
} while (answer != 'n');
return 0;
}
add a comment |
getchar(); // takes the user input but assigns it nowhere
scanf("%c", &answer); // reads newline, aborts while loop
Use c = getchar();
and omit the scanf
.
Also note that a more idiomatic way of doing this would be with a do-while
loop instead.
1
In the first iteration that will read the newline left over from the first call toscanf
.
– Some programmer dude
Nov 21 '18 at 11:45
add a comment |
Your code works and the loop continues: it does not re-ask for the number because that part is outside the loop. Move it inside. Also notice that your code continues executing even when pressing any other key rather than n
.
This is a one way to do it starting from your code:
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
while(answer != 'n')
{
printf("Enter a number: n");
scanf("%d", &num);
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: any key for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410581%2fc-the-loop-doesnt-continue%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
I have made few corrections in your program.
- It was difficult to understand what your program does. I have made your program more readable and modular by defining a separate re-usable function for
factorial
. - It makes more sense to ask user again for the number if user has entered
'y'
. So, I have moved required code. - I don't recommend mix use of
scanf
andgetchar
in the program. So, we can just usescanf
for the program. Thescanf()
function removes whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don't remove whitespace.
Use " %c" with a leading blank
to skip optional white space. Do not use a trailing blank in a scanf() format string.
Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.
#include <stdio.h>
unsigned long factorial(unsigned long num)
{
unsigned long mult = 1;
unsigned long k = 1;
while (k <= num) {
mult *= k;
k++;
}
return mult;
}
int main(void)
{
char answer = 'y';
do {
int num = 0;
printf("Enter a number: n");
scanf(" %d", &num);
unsigned long mult = factorial(num);
printf("%d! = %lun", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
scanf(" %c", &answer);
} while (answer != 'n');
return 0;
}
add a comment |
I have made few corrections in your program.
- It was difficult to understand what your program does. I have made your program more readable and modular by defining a separate re-usable function for
factorial
. - It makes more sense to ask user again for the number if user has entered
'y'
. So, I have moved required code. - I don't recommend mix use of
scanf
andgetchar
in the program. So, we can just usescanf
for the program. Thescanf()
function removes whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don't remove whitespace.
Use " %c" with a leading blank
to skip optional white space. Do not use a trailing blank in a scanf() format string.
Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.
#include <stdio.h>
unsigned long factorial(unsigned long num)
{
unsigned long mult = 1;
unsigned long k = 1;
while (k <= num) {
mult *= k;
k++;
}
return mult;
}
int main(void)
{
char answer = 'y';
do {
int num = 0;
printf("Enter a number: n");
scanf(" %d", &num);
unsigned long mult = factorial(num);
printf("%d! = %lun", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
scanf(" %c", &answer);
} while (answer != 'n');
return 0;
}
add a comment |
I have made few corrections in your program.
- It was difficult to understand what your program does. I have made your program more readable and modular by defining a separate re-usable function for
factorial
. - It makes more sense to ask user again for the number if user has entered
'y'
. So, I have moved required code. - I don't recommend mix use of
scanf
andgetchar
in the program. So, we can just usescanf
for the program. Thescanf()
function removes whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don't remove whitespace.
Use " %c" with a leading blank
to skip optional white space. Do not use a trailing blank in a scanf() format string.
Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.
#include <stdio.h>
unsigned long factorial(unsigned long num)
{
unsigned long mult = 1;
unsigned long k = 1;
while (k <= num) {
mult *= k;
k++;
}
return mult;
}
int main(void)
{
char answer = 'y';
do {
int num = 0;
printf("Enter a number: n");
scanf(" %d", &num);
unsigned long mult = factorial(num);
printf("%d! = %lun", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
scanf(" %c", &answer);
} while (answer != 'n');
return 0;
}
I have made few corrections in your program.
- It was difficult to understand what your program does. I have made your program more readable and modular by defining a separate re-usable function for
factorial
. - It makes more sense to ask user again for the number if user has entered
'y'
. So, I have moved required code. - I don't recommend mix use of
scanf
andgetchar
in the program. So, we can just usescanf
for the program. Thescanf()
function removes whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don't remove whitespace.
Use " %c" with a leading blank
to skip optional white space. Do not use a trailing blank in a scanf() format string.
Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.
#include <stdio.h>
unsigned long factorial(unsigned long num)
{
unsigned long mult = 1;
unsigned long k = 1;
while (k <= num) {
mult *= k;
k++;
}
return mult;
}
int main(void)
{
char answer = 'y';
do {
int num = 0;
printf("Enter a number: n");
scanf(" %d", &num);
unsigned long mult = factorial(num);
printf("%d! = %lun", num, mult);
printf("Would you like to try another number? n");
printf("Enter: y for yes | n for non");
scanf(" %c", &answer);
} while (answer != 'n');
return 0;
}
edited Nov 21 '18 at 13:16
answered Nov 21 '18 at 12:47
abhiaroraabhiarora
2,29431532
2,29431532
add a comment |
add a comment |
getchar(); // takes the user input but assigns it nowhere
scanf("%c", &answer); // reads newline, aborts while loop
Use c = getchar();
and omit the scanf
.
Also note that a more idiomatic way of doing this would be with a do-while
loop instead.
1
In the first iteration that will read the newline left over from the first call toscanf
.
– Some programmer dude
Nov 21 '18 at 11:45
add a comment |
getchar(); // takes the user input but assigns it nowhere
scanf("%c", &answer); // reads newline, aborts while loop
Use c = getchar();
and omit the scanf
.
Also note that a more idiomatic way of doing this would be with a do-while
loop instead.
1
In the first iteration that will read the newline left over from the first call toscanf
.
– Some programmer dude
Nov 21 '18 at 11:45
add a comment |
getchar(); // takes the user input but assigns it nowhere
scanf("%c", &answer); // reads newline, aborts while loop
Use c = getchar();
and omit the scanf
.
Also note that a more idiomatic way of doing this would be with a do-while
loop instead.
getchar(); // takes the user input but assigns it nowhere
scanf("%c", &answer); // reads newline, aborts while loop
Use c = getchar();
and omit the scanf
.
Also note that a more idiomatic way of doing this would be with a do-while
loop instead.
answered Nov 21 '18 at 11:39
atsats
1094
1094
1
In the first iteration that will read the newline left over from the first call toscanf
.
– Some programmer dude
Nov 21 '18 at 11:45
add a comment |
1
In the first iteration that will read the newline left over from the first call toscanf
.
– Some programmer dude
Nov 21 '18 at 11:45
1
1
In the first iteration that will read the newline left over from the first call to
scanf
.– Some programmer dude
Nov 21 '18 at 11:45
In the first iteration that will read the newline left over from the first call to
scanf
.– Some programmer dude
Nov 21 '18 at 11:45
add a comment |
Your code works and the loop continues: it does not re-ask for the number because that part is outside the loop. Move it inside. Also notice that your code continues executing even when pressing any other key rather than n
.
This is a one way to do it starting from your code:
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
while(answer != 'n')
{
printf("Enter a number: n");
scanf("%d", &num);
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: any key for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
add a comment |
Your code works and the loop continues: it does not re-ask for the number because that part is outside the loop. Move it inside. Also notice that your code continues executing even when pressing any other key rather than n
.
This is a one way to do it starting from your code:
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
while(answer != 'n')
{
printf("Enter a number: n");
scanf("%d", &num);
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: any key for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
add a comment |
Your code works and the loop continues: it does not re-ask for the number because that part is outside the loop. Move it inside. Also notice that your code continues executing even when pressing any other key rather than n
.
This is a one way to do it starting from your code:
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
while(answer != 'n')
{
printf("Enter a number: n");
scanf("%d", &num);
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: any key for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
Your code works and the loop continues: it does not re-ask for the number because that part is outside the loop. Move it inside. Also notice that your code continues executing even when pressing any other key rather than n
.
This is a one way to do it starting from your code:
#include <stdio.h>
int main(void)
{
char answer = 'y';
int num = 0;
while(answer != 'n')
{
printf("Enter a number: n");
scanf("%d", &num);
int mult = 1;
int k = 1;
while (k <= num)
{
mult *= k;
k++;
}
printf("%d! = %dn", num, mult);
printf("Would you like to try another number? n");
printf("Enter: any key for yes | n for non");
getchar();
scanf("%c", &answer);
}
}
answered Nov 21 '18 at 13:56
Francesco BoiFrancesco Boi
2,71522643
2,71522643
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410581%2fc-the-loop-doesnt-continue%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
if you expect your loop to return to the
printf("Enter a number: n")
-part, please note that this part is outside of the loop. What do you actually observe and what do you expect?– Stephan Lechner
Nov 21 '18 at 10:57
1
If you want to skip leading white-space before a character, use a format string with a space. As in
" %c"
. Also note that with your loop condition, anything but a lower-case'n'
would continue the loop, not only'y'
.– Some programmer dude
Nov 21 '18 at 10:57
2
And this is also a very good time to learn how to debug your programs. Step through the code line by line in a debugger, checking the values of all variables (and save the result from
getchar
in a dummy variable so you can check that too).– Some programmer dude
Nov 21 '18 at 11:00
I just tested your code and it has the expected behaviour if you like to stop when you write 'n' and continue when you write 'y' so I don't see your problem
– Welgriv
Nov 21 '18 at 11:04