By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,512 Members | 1,830 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,512 IT Pros & Developers. It's quick & easy.

Trying to understand if and do/while

momotaro
100+
P: 357
I don't understand how this function works!!! and specialy the "if condition" and it's return!!!!
please help!!!!

Expand|Select|Wrap|Line Numbers
  1. Boolean UserSaysYes(void)
  2. {
  3.    int c;
  4.    printf("(y,n)?");
  5.    do{
  6.         while((c = getchar()) == '\n')
  7.             ;
  8.         if(c == 'y' || c == 'Y' || c == 'n' || c == 'N')
  9.              return(c == 'y' || c == 'Y');
  10.         printf("please respond by typing one of the letters y or n\n");
  11.       }while(1) // this one also !!!!!
  12.  
May 31 '07 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 102
I don't understand how this function works!!! and specialy the "if condition" and it's return!!!!
please help!!!!

Expand|Select|Wrap|Line Numbers
  1. Boolean UserSaysYes(void)
  2. {
  3.    int c;
  4.    printf("(y,n)?");
  5.    do{
  6.         while((c = getchar()) == '\n')
  7.             ;
  8.         if(c == 'y' || c == 'Y' || c == 'n' || c == 'N')
  9.              return(c == 'y' || c == 'Y');
  10.         printf("please respond by typing one of the letters y or n\n");
  11.       }while(1) // this one also !!!!!
  12.  
Hi momotaro,
The "if" condition checks whether the character entered is one among y,Y,n,N. If the character is one among the specified ones then the return statement is executed, otherwise the printf statement is executed.

Coming to the return statement: here the character entered is compared with y and Y. If it is one among the two then true(1) is returned, otherwise false(0) is returned to the calling function.
i.e., If the character entered is y or Y then it'll be "return 1", and if its n or N then it'll be "return 0".

I hope this helps you.

Regards,
Pradeep
May 31 '07 #2

AdrianH
Expert 100+
P: 1,251
I don't understand how this function works!!! and specialy the "if condition" and it's return!!!!
please help!!!!

Expand|Select|Wrap|Line Numbers
  1. Boolean UserSaysYes(void)
  2. {
  3.    int c;
  4.    printf("(y,n)?");
  5.    do{
  6.         while((c = getchar()) == '\n')
  7.             ;
  8.         if(c == 'y' || c == 'Y' || c == 'n' || c == 'N')
  9.              return(c == 'y' || c == 'Y');
  10.         printf("please respond by typing one of the letters y or n\n");
  11.       }while(1) // this one also !!!!!
  12.  
Any non-zero or non-NULL value is considered to be true when put in the context of being a Boolean. Given that, you should be able to figure out what the while does.


Adrian
May 31 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.