please anyone explain me the logic behind this piece of looping.
public static void main(String[] args) {
int number = 0;
while (true) {
number = number + 1;
if (number >= 5) {
break;
}
if (number < 5) {
continue;
}
System.out.print(number + " ");
}
System.out.print(number + " ");
}
while(true) means an infinite loop and it will only break; the loop if(number >= 5) is true.
continue; means to ignore the succeeding commands and proceed to the next loop, therefore print function at the bottom of the loop will only execute if(number<5) is false (but will never happen because of the break; command above)
when the loop exits, the number's last value will be printed.
Related
I am trying to check whether a given number is prime but I've run into an issue. This is the code:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
bool isPrime(int input)
{
for (int i = sqrt(input); i >= 2; i--)
{
if (input % i == 0)
{
return false;
}
return true;
}
}
int main()
{
int input;
scanf("%d", &input);
if (isPrime(input))
{
printf("Is prime number");
} else
{
printf("Is not prime number");
}
return 0;
}
In the code block of my isPrime function, if I put return true; in the for loop like above, this will be wrong in some cases (for example, when input is 10, it will declare that 10 is a prime number). But if I put return true; outside the for loop, it works fine. So what is the difference?
Let's walk through your loop:
for (int i = sqrt(input); i >= 2; i--)
{
If the input is 10, then i starts out as 3 (remember that when assigning a floating-point value to an int, the fractional portion is discarded). 3 is greater than or equal to 2, so the loop body executes.
if (input % i == 0)
{
The remainder of 10 divided by 3 is not zero, so we do not enter the body of the if statement.
return false;
}
return true;
}
And then we immediately return true.
Because of this, no matter what input you provide, your loop will only iterate 1 time. If input is evenly divisible by the integer value of its square root (such as 9, 16, or 25), then the body of the if statement is executed and it returns false, otherwise it unconditionally returns true.
For your function to work properly, you must move the return true; statement outside the body of the loop - you should only return true when you've exhausted all values of i between sqrt(input) and 2.
The function returns true if the first divisor in the for loop does not divide the target number.
because this return statement
return true;
is inside the for loop.
bool isPrime(int input)
{
for (int i = sqrt(input); i >= 2; i--)
{
if (input % i == 0)
{
return false;
}
return true;
}
}
Moreover the function has undefined behavior if it is called for example for prime numbers 2 or 3 or if a non-positive number is passed to the function.
Placing the return statement
return true;
outside the loop does not make your function correct.
Pay attention to that there is no sense to check even numbers except the number 2 whether they are prime or not prime.
The function can be written the following way
bool isPrime( unsigned long long n )
{
bool prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned long long int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
The function can be called like
unsigned int input;
scanf("%u", &input);
if (isPrime(input))
{
printf("Is prime number");
} else
{
printf("Is not prime number");
}
When you put return true; inside of the loop, that statement will be executed whenever the preceding if condition is false. You only want to return true once you've completed your for loop and have found no divisors. That's why the return statement needs to be outside the loop.
This happens because your for loop isn't over with the complete traverse of i, but the return true statement tells the code to execute it the very first time your if condition goes false, and then exit the loop. So, imagine I give you 10 chocolate bars and tell you to take a bite from each, and only collect the dark ones. You take a bite on the first, it's sweet, you put it away. You take a bite on the second and it's dark. You collect it and you tell me you are done, although you actually aren't (You didn't check the rest of the chocolate bars to see if there are more dark ones there or not). That's what you are doing in your code. Hope the example is clear and helpful :)
The rule of the game Simon Says compares the individual character of the user input character sequence with each corresponding character sequence in Simon says. (assuming both sequences have the same length). Whenever the user has the same character at the same position as "Simon Says", the user increments their score by one.
I have set up the for and while loop that compares both sequences of character individually from i=0, however, I have some issue in killing the loop.
Any comments are appreciated. Thank you.
Here's what I have:
public class SimonSays {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String simonPattern;
String userPattern;
int userScore;
int i;
userScore = 0;
simonPattern = scnr.next();
userPattern = scnr.next();
for (i=0; i<=simonPattern.length();i++) {
while(userPattern.charAt(i) == simonPattern.charAt(i)){
userScore += userScore;
continue;
}
while(userPattern.charAt(i)!=simonPattern.charAt(i)){
break;
}
}
System.out.println("userScore: " + userScore);
return;
}
}
When using continue and break in loop scope its refer to the nearest loop (as you can see here) - so when you use them in the while loop they refer to it.
This what cause the infinity loop:
while(userPattern.charAt(i) == simonPattern.charAt(i)){
userScore += userScore;
continue; // this cause your infinity loop
}
The continue is execute on the while loop and the condition neer changes therefor - infinity loop.
In order to fix your issue, consider using the following code:
int userScore = 0;
for (; userScore < simonPattern.length(); userScore++) {
if (userPattern.charAt(userScore) != simonPattern.charAt(userScore))
break;
}
//Value of userScore here is the number of times the if statement return false -> which mean mumber of same chars
As the userScore is the number of char we already check in the pattern.
Hope that helps!
In an attempt to familiarize myself with fundamentals, I've been trying to write a simple program for choosing a password. The password is suppose to conform to the 5 listed conditions. The code is designed to loop through the password to determine if the conditions are satisfied and prompt users of any issues.
If the conditions are satisfied its coinciding variable is set to 1. Any variable left 0 is intended to prompt an invalid password. Unfortunately, it would appear that only the first character is being identified. All other conditions, aside from the first character, will fail regardless of the string.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int main(void) {
char password[21];
int loop;
int dollar = 0;
int digit = 0;
int upperCase = 0;
int lowerCase = 0;
printf("Requirements for a valid password:\n\n");
printf("1. Contain at least one $ sign.\n");
printf("2. Contain at least one number.\n");
printf("3. Contain at least one uppercase letter.\n");
printf("4. Contain at least one lowercase letter.\n");
printf("5. Contain no more than 20 characters.\n\n");
printf("Enter password: ");
scanf(" %s", &password);
printf("\n");
for (loop = 0; loop < 21; loop++) {
if (password[loop] == '$') {
dollar = 1;
break;
}
else {
printf("Invalid password, recheck for condition 1.\n\n");
break;
}
}
for (loop = 0; loop < 21; loop++) {
if (isdigit(password[loop])) {
digit = 1;
break;
}
else {
printf("Invalid password, recheck for condition 2.\n\n");
break;
}
}
for (loop = 0; loop < 21; loop++) {
if (isupper(password[loop])) {
upperCase = 1;
break;
}
else {
printf("Invalid password, recheck for condition 3.\n\n");
break;
}
}
for (loop = 0; loop < 21; loop++) {
if (islower(password[loop])) {
lowerCase = 1;
break;
}
else {
printf("Invalid password, recheck for condition 4.\n\n");
break;
}
}
if ((dollar * digit * upperCase * lowerCase) != 0) {
printf("Password saved!");
}
system("pause");
return(0);
}
So, let's do a simple dry run here. Let's take your code for the first condition (and as remaining all same in logic, so that should do).
for (loop = 0; loop < 21; loop++) {
if (password[loop] == '$') {
dollar = 1;
break;
}
else {
printf("Invalid password, recheck for condition 1.\n\n");
break;
}
}
Let's begin with loop value equals zero. Now the following conditions exist:
The first character is a $. In this case the if condition is satisfies, and we exit out after setting the dollar flag.
The first character is not a $ (this is where we primarily go wrong). The if condition fails, as expected - and so we move to the else straightaway. Here we go on to print the error message and break out of the loop, without checking the remaining characters! Logically, we should wait to print the error till we have processed ALL the characters and not found the condition to be satisfied.
So, now we understand the problem - we are printing the error and breaking out after just checking for the first character. But, how can we fix this?
Well, for starters we should wait till we search through all the characters. So the else part must move out of the loop. Also, we know that if we do indeed have the condition satisfied, we will set the dollar variable, and exit the loop. What if we don't find the condition satisfied? Well, in that case dollar will remain zero - and that's how we detect the error!
So, we could possibly do something like:
// Loop through the characters, and as soon as we find $ we set the dollar variable and break
for (loop = 0; loop < 21; loop++) {
if (password[loop] == '$') {
dollar = 1;
break;
}
}
// If dollar is still zero, we didn't encounter the $ character
if (dollar == 0) {
printf("Invalid password, recheck for condition 1.\n\n");
}
There are a couple of other simple mistakes in the code you posted, but primarily the logical flaw is the above. Look out for the comments to understand the other possible loopholes. Cheers!
i am trying to convert a string containing a 16-bit number in binary to a integer value.
It is a homework assignment and i have to use scanf("%1d.... ).
The problem i am having is that the loop wont end, i have no clue how to fix it.
for example:
input: 0000000000001111
output: 15
int read_binary_value()
{
int value = 0;
while( scanf("%1d", &value) == 1)
{
printf("%d ", value);
if (value == 1)
{
value += 1;
value << 1;
}
}
printf("yoyoyoyoyoyoyo");
printf("%d",value);
return value;
}
I modified your code and it works
int read_binary_value()
{
int total=0;
int value;
while( scanf("%1d", &value) == 1)
{
printf("%d", value);
if(!(value==0||value==1))
{
//Generate Error Message and Exit program
}
total = total << 1;
if (value == 1)
{
total += 1;
}
}
printf("yoyoyoyoyoyoyo\n");
printf("%d",total);
return total;
}
Your loop stop when get end of file.
Press CTRL+Z for windows and Ctrl+D for linux. Those are End of File character.
If you want to get 16 inputs you can use
for(i=0;i<16;i++) instead of the while to just run the loop 16 times and end. Or else within the while loop you can give
if(i==16)
break; incrementing i at the end of the loop. If you need to manually stop the loop, EOF char is the option.
Hey guys so this is the ques which i have coded but its not working properly..i cant seem to understand where am i going wrong..
Write a program that determines if a number that the user has entered is a prime
number. The program will continue to ask for numbers until the user enters a
value less than 2.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int num;
int count = 1;
bool check = true;
do{
printf("Enter a number: ");
scanf("%d", &num);
count = num - 1;
bool check = false;
while (count > 1 || num % count == 0){
check = true;
count--;
}
if (check == true){
printf("%d is a prime number\n", num);
}
else
printf("%d is not a prime number\n", num);
}
while (num > 2);
}
while (count > 1 || num % count == 0){
check = true; // <-
count--;
}
On the indicated line you set check to true - this means that if the body of the loop executes even once, check will be true after the loop and the program will indicate that the number is prime. What you should do instead is show the number as prime iff the entire loop runs to completion.
The loop condition is also wrong; num % count == 0 indicates that the number is not prime, so you can stop checking if that is true. (Hint: you can terminate the loop from within using break)
Also if the user enters 2 or less, the checks will still run before the outer loop terminates.
You'll want your while loop to look like this:
bool prime = true;
while (count > 1 && prime) {
prime = ((num % count) != 0);
count--;
}
The way you wrote it will assign check to true on the first iteration, regardless of num's primality.
Say
int num = 3;
or whatever number you want bigger than 2
instead of
int num;
This is to make use you enter the loop.