while( num != 101 && num != 102 && num != 103 ){
printf( "Enter number: " );
scanf( "%d", &num );
}
I'm making a C program using Loops that accepts numbers from the user until the user inputs the numbers 101, 102, and 103. The above three conditions in while loop is working as an OR operator. If one of the three conditions is met, the while loop stops. What I need is that while loop should be stopped when the three conditions are met. I already tried to use || instead of && but the program just keeps looping. Thank you in advance!!
CodePudding user response:
while( num == 101 && num == 102 && num == 103 ){
printf( "Enter number: " );
scanf( "%d", &num );
}
This is an infintive loop, because that is what you want. It "should be stopped when the three conditions are met". Num could only justify one condidition. Num couln't be all three values (101 AND 102 AND 103) at the same time. Except you have a quantum computer.
CodePudding user response:
The actual purpose of your program is unclear.
It appears that all three numbers (101, 102 and 103) must be entered by the user before the program will continue.
Typically you would use three separate variables. Are you attempting to simulate a combination lock? If that is the case then the following code seems to work. (Interestingly it is, indeed, a combination lock since the numbers can be entered in any order.)
/* enter the numbers 101, 102 and 103 to exit the while loop
*/
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
printf("\n");
bool flag101 = false;
bool flag102 = false;
bool flag103 = false;
do {
printf("enter number: ");
int num;
scanf("%d", &num);
if (num == 101) {
printf("101 entered\n");
flag101 = true;
}
if (num == 102) {
printf("102 entered\n");
flag102 = true;
}
if (num == 103) {
printf("103 entered\n");
flag103 = true;
}
} while (! (flag101 && flag102 && flag103));
printf("\n");
printf("all three numbers have been entered\n");
return 0;
}