Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Following code has no output when it executes. Can anyone explain the following code?
int main() {
int i, j;
for (i = 0; i < 10; i++) {
if (i % 2)
printf("%d\t", i);
else
break;
}
}
0 % 2 gives false so the loop terminates at the first iteration without calling the printf.
Your code has two issues:
1.
if (i % 2)
The condition of (i % 2) evaluates to false because the calculation - 0 divided by 2 - result in 0 -> 0 / 2 = 0. The remainder is also 0.
2.
else break;
That provides the result if (i % 2) is not true (which is the case with 0 at the first iteration) you immediately will break out of the for loop. Omit the break; statement in general, if you want to proof if all values from 0 to 9 have an remainder when divided by 2 or not.
Note that to pack break; in an separate else statement is nonetheless redundant.
Side note:
j has no use in your code.
I guess what you want is something like that:
#include <stdio.h>
int main (void) {
int i, j;
for ( i = 0; i < 10; i++ ) {
if ( ( j = i % 2 ) )
printf("(%d / 2) has a remainder of %d.\n", i, j);
else
printf("(%d / 2) has no remainder.\n", i);
}
}
Output:
(0 / 2) has no remainder.
(1 / 2) has a remainder of 1.
(2 / 2) has no remainder.
(3 / 2) has a remainder of 1.
(4 / 2) has no remainder.
(5 / 2) has a remainder of 1.
(6 / 2) has no remainder.
(7 / 2) has a remainder of 1.
(8 / 2) has no remainder.
(9 / 2) has a remainder of 1.
Try this code online.
Note that by the division 1 / 2, the result 0.5 is raised to the nearest upper integral value 1 because of the implicit double to int conversion.
i % 2 gives the remainder of the Euclidian division of i by 2. It does NOT mean "i is divisible by 2". If the latter is true, then i % 2 gives 0 which implicitely converts to false. If it is false, then i % 2 gives 1 which implicitely converts to true. Therefore, in the first iteration, the conditional ex^pression evaluates to false so you break out of the loop immediately.
If you want to check the divisibility of i by 2, you must use i % 2 == 0.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I need to make a program in C++ in which I insert a number 'n' that's with 4 digits and it's a simple number, in the console and the console is showing me the multiplication of the certain number with 4 digits which I first needed to write.
I tried to write (n/!2) in order to make the program execute only if the number can't divide by 2 and the console showed "main.cpp:22:36: warning: division by zero [-Wdiv-by-zero]".
I've tried removing
(n /! 2) and the code got executed without a problem. I will be glad if someone can tell me how can I fix it.
#include <bits/stdc++.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int getProduct(int n)
{
int product = 1;
while (n != 0) {
product = product * (n % 10);
n = n / 10;
}
return product;
}
int main()
{
int n;
cout << "insert n ";
cin >> n;
if (n >= 1000 && n <= 9999 && n /! 2) {
cout << (getProduct(n));
}
}
In the calculation n / !2 You effectively do n / 0.
! is short for not, not 2 is a boolean expression where 2 (anything but 0) is true.
not true is false.
false is promoted to an int in the calculation and false there becomes 0.
Solution: Use n % 2 != 0 or n & 1 to check for odd numbers.
You are looking for modulo operation. Modulo (the remainder from division) is equal to zero if number is divisible by the other one and non-zero otherwise.
if (n >=1000 && n <= 9999 && (n % 2) != 0)
tried to write (n/!2) in order to make the program execute only if the number can't divide by 2
n / !2
This evaluates to n / 0. which triggers your warning.
To check if n is odd, you should do this instead:
n % 2 != 0
! operator have higher precedence than / , So your expression becomes
=> n/(!2)
=> n/0
Instead you shoud use (n%2==0) to check for even number.
As I understand this code returns the number of digits entered in the function but I don't understand this operation:
(number /= 10) != 0 at all..I understand that this line
number /= 10
equal to number = number / 10 but why not but why in this function they don't write number / 10 != 0? and what are the differences?
std::size_t numDigits(int number) // function definition.
{ // (This function returns
std::size_t digitsSoFar = 1; // the number of digits
// in its parameter.)
while ((number /= 10) != 0) ++digitsSoFar;
return digitsSoFar;
}
(number /= 10) != 0
This actually has 3 steps. It...
Calculates number / 10
Assigns that value to number
Checks if that value is not equal to 0
So in answer to your question, "why in this function they don't write number / 10 != 0," let's walk through what that does:
Calculates number / 10
Checks if that value is not equal to 0
Can you see the difference between the two?
If you're still not sure why this matters, put an output statement in the while loop that'll show number and digitsSoFar and try to run that function both the way it's written and then with your proposed version.
The project I am working on needs to find some way of verifying that a variable after the modulus operation is either number != 0, number > 0, or number < (0 < x < 1). I have the first two understood, however employing the mod operator to accomplish the third is difficult.
Essentially what I am looking to do is to be able to catch a value similar to something like this:
a) 2 % 6
b) flag it and store the fact that .333 is less than 1 in a variable (bool)
c) perform a follow up action on the basis that the variable returned a value less than 1.
I have a feeling that the mod operator cannot perform this by itself. I'm looking for a way to utilize its ability to find remainders in order to produce a result.
edit: Here is some context. Obveously the below code will not give me what I want.
if (((inGameTotalCoins-1) % (maxPerTurn+1)) < 0){
computerTakenCoins = (inGameTotalCoins - 1);
inGameTotalCoins = 1;
The quotient is 0(2/6) with the fractional part discarded.The fractional part is .3333 ... So you are basically talking about the fractional part of the quotient , not the modulus value. Modulus can be calculated as follows :
(a / b) * b + (a % b) = a
(2 / 6) * 6 + (2 % 6) = 2
0 * 6 + (2 % 7) = 2
(2 % 6) = 2
*6 goes into 2 zero times with 2 left over.
How about this:-
int number1 = 2;
int number2 = 6;
float number3 = static_cast<float>(number1) / static_cast<float>(number2);
bool isfraction = number3 > 0 && number3 < 1;
if(isfraction){
std :: cout << "true\n" << number3;
}
else{
std :: cout << "false" << number3;
}
number != 0 includes number > 0 and number < (0 x < 1). And number > 0 includes number < (0 x < 1). Generally we do not classify so. For example, people classify number > 0, number == 0 and number < 0.
If you do the modulous operation, you get remainder. Remainder's definition is not one thing. You can see it at https://en.m.wikipedia.org/wiki/Remainder
I can't understand how to count number of 1's in binary representation.
I have my code, and I hope someone can explain it for me.
Code:
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
Why while ? For example if i have 1011, it wouldn't stop at 0?
Why nr += x%2 ?
Why x/=2 ?!
First:
nr += x % 2;
Imagine x in binary:
...1001101
The Modulo operator returns the remainder from a / b.
Now the last bit of x is either a 0, in which case 2 will always go into x with 0 remainder, or a 1, in which case it returns a 1.
As you can see x % 2 will return (if the last bit is a one) a one, thus incrementing nr by one, or not, in which case nr is unchanged.
x /= 2;
This divides x by two, and because it is a integer, drops the remainder. What this means is is the binary was
....10
It will find out how many times 2 would go into it, in this case 1. It effectively drops the last digit of the binary number because in base 2 (binary) the number of times 2 goes into a number is just the same as 'shifting' everything down a space (This is a poor explanation, please ask if you need elaboration). This effectively 'iterates' through the binary number, allowing the line about to check the next bit.
This will iterate until the binary is just 1 and then half that, drop the remainder and x will equal 0,
while (x != 0)
in which case exit the loop, you have checked every bit.
Also:
'count`is possibly not the most descriptive name for a function, consider naming it something more descriptive of its purpose.
nr will always be a integer greater or equal to zero, so you should probably have the return type unsigned int
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
This program basically gives the numbers of set bits in a given integer.
For instance, lets start with the example integer 11 ( binary representation - 1011).
First flow will enter the while loop and check for the number, if it is equal to zero.
while(11 != 0)
Since 11 is not equal to zero it enter the while loop and nr is assigned the value 1 (11%2 = 1).nr += 11%2;
Then it executes the second line inside the loop (x = x/2). This line of code assigns the value 5 (11/2 = 5 ) to x.
Once done with the body of the while loop, it then again checks if x ie 5 is equal to zero.
while( 5 != 0).
Since it is not the case,the flow goes inside the while loop for the second time and nr is assigned the value 2 ( 1+ 5%2).
After that the value of x is divided by 2 (x/2, 5/2 = 2 )and it assigns 2 to x.
Similarly in the next loop, while (2 != 0 ), nr adds (2 + 2%2), since 2%2 is 0, value of nr remains 2 and value of x is decreased to 1 (2/2) in the next line.
1 is not eqaul to 0 so it enters the while loop for the third time.
In the third execution of the while loop nr value is increased to 3 (2 + 1%2).
After that value of x is reduced to 0 ( x = 1/2 which is 0).
Since it fails the check (while x != 0), the flow comes out of the loop.
At the end the value of nr (Which is the number of bits set in a given integer) is returned to the calling function.
Best way to understand the flow of a program is executing the program through a debugger. I strongly suggest you to execute the program once through a debugger.It will help you to understand the flow completely.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How does the C process a conditional statement such as n >= 1 <= 10?
I initially thought that it would get evaluated as n >= 1 && 1 <= 10, as it would be evaluated in Python. Since 1 <= 10 is always true, the second porition of the and is redundant (the boolean value of X && True is equivalent to the boolean value of X).
However, when I run it with n=0, the conditional gets evaluated to true. In fact, the conditional always seems to evaluate to true.
This was the example I was looking at:
if (n >= 1 <= 10)
printf("n is between 1 and 10\n");
>= operator is evaluated from left to right, so it is equal to:
if( ( n >= 1 ) <= 10)
printf("n is between 1 and 10\n");
The first ( n >= 1 ) is evaluated either as true or false, which is equal to either 1 or 0. Then that result of 1 or 0 is compared to result <= 10 which will always evaluate to true.
Thus the statement printf("n is between 1 and 10\n"); will always be printed
It's evaluated left to right like this:
n = 5;
if (n >= 1 <= 10)
// then
if (1 <= 10)
// then
if (1)
It first checks if n >= 1. If it is, it evaluates to 1, otherwise 0. This leads to the next evaluation, 1 <= 10, which evaluates to 1 as well. Note that this also succedes:
n = 5;
if (n >= 3 == 1)
Because it's evaluated like this:
n = 5;
if (n >= 3 == 1) // but you should never write code like this
// then
if (1 == 1)
// then
if (1)
Also note why it works with n = 0
n = 0;
if (n >= 1 <= 10)
// then
if (0 <= 10) // 0 isn't greater or equal to 1, so 0 (false) is "returned"
// then
if (1) // but 0 is less than or equal to 10, so it evaluates as 1 (true)