Atually i have i understand the code but doesn't understand the logic of the code.I know what is going on but i doesn't know what is happening.The code is of even or odd.The code is.
#include<stdio.h>
int main() {
int i;
for(i=1; i<26; i++) {
if(i%2==1)
printf("%d\n",i);
}
return 0;
}
output:
1
3
5
7
9
11
13
15
17
19
21
23
25.
1st repitition:-
(i=1;i<26;i++)
if(i%2==1)
1%2==1
but the result of 1%2 is 0.
I am still getting 1 on my screen. I don't know how I get this '1' , even 1 is
not equal to 0.
2nd repitition:-
(i=1;i<26;i++)
if(i%2==1)
now, at 2nd repition i is 2. AND (2%2) is equal to 0 and 0 is not equal to 1 as follows (0==1) and i am getting 3 on my output screen as i mention above on my screen.
Either I didn't use if condition. how i get this 3 and so on.
The modulo operator gives your the remainder after integer division. Integer division is different to standard (floating point) division.
1/2 = 0.5 (floating point division)
1\2 = 0 (integer division)
Integer Division
Integer division tells you the total number of times the second number 'fits' inside the first number. It's more obvious with a bigger example:
10/3 = 3.333 etc.
10\3 = 3
You cannot fit another entire 3 into 10.
Modulo (the complement of Integer Division)
Modulo tells you how much space you have left (the remainder). After you put three 3s into 10, you have 1 space left.
10%3 = 1 (i.e. 10-3*3)
If you used 11 instead of 10, you would have 2 spaces left. If you used 12, you could fit another whole 3 in, leaving no space left.
10\3=3 (with 1 space remaining)
11\3=3 (with 2 spaces remaining)
12\3=4
13\3=4 (with 1 space remaining)
Modulo gives you the amount of space remaining:
10%3=1
11%3=2
12%3=0
13%3=1
etc.
Modulo by 2 (to assess even/odd)
In your example, you're doing modulo 2. You cannot fit any whole 2s into 1.
1\2=0 (quotient)
1%2=1 (remainder)
So... In your loop:
i=1 > 1%2=1 > 1==1 (true) > print 1
i=2 > 2%2=0 > 0==1 (false) > do nothing
i=3 > 3%2=1 > 1==1 (true) > print 3
i=4 > 4%2=0 > 0==1 (true) > do nothing
Modulus operator % in this case returns 0 if the number is even and 1 if the number is odd. So, your code:
for(i=1; i<26; i++) {
if(i%2==1)
printf("%d\n",i);
}
checks if the number is odd, and if it is, prints it out. That's the logic behind the modulus operator.
I would suggest in later use to modify this code into:
for(i=1; i<26; i++) {
if(i%2!=0)
printf("%d\n",i);
}
to avoid mistakes with negative numbers.
Read this!
I don't know which part of the comments you didn't understand, but the gist is:
1%2 is NOT 0, but 1.
Either you accept that, and then the program's behavior should be clear, or you don't accept it, and then you did not understand what the % operator does. Go and read up on it.
Related
I ran it through an IDE and the remainder values came out 3, 2, 0, 1.
I understand the first remainder, but not the rest.
Also, how come the loop terminates? Isn't x always going to be greater than 0, therefore continuing indefinitely? Thank you.
int x = 1023;
while (x > 0)
{
printf("%d", x% 10);
x = x /10;
}
Note that in C, when both operands of a division have integer type, the division also has an integer type, and the value is the result of division rounded toward zero.
So in the first iteration, the statement x = x /10; changes x from 1023 to 102 (not 102.3).
since you are dividing integers you are getting rounded results each time,
so each iteration of x becomes
102
10
1
Just print x each time and you will see.
So 102 modulo 10 is 2
10 modul0 10 is 0
1 modulo 10 is 1
I came across this program to convert decimals numbers into their binary equivalent in C. I do not understand how the printf statement works in this program.
int main()
{
int N;
scanf("%d", &N); // Enter decimal equivalent here
for( int j = floor(log2(N)); j >= 0; j-- ){
printf("%d", (N >> j) & 1);
}
}
Let's take an example to get through this problem. Suppose you enter N=65. Its binary representation is - 1000001. When your given code goes through it, j will start at floor(log2(65)), which is 6. So, the given loop will run 7 times, which means 7 numbers will be printed out (which fits the fact that 65's binary representation has 7 digits).
Inside the loop - The number is shifted by j bits each time to the right. When 1000001 is shifted to the right by 6 bits, it becomes 0000001. If shifted by 5, it is 0000010, and so on. It goes down to a shift by 0 bits which is the original number. When each of these shifted numbers are &ed with 1, only the least significant bit (the right most bit) remains. And this digit can either be a 0 or a 1.
If you would have noticed each right shift divides the number by 2. So when 1000001 is shifted by 1 to make 0100000, it is the binary representation of 32, which indeed is 65/2 in C. After all, this is the way someone manually calculates the binary representation of a number. Each division by 2 gives you a digit (starting from the end) of the representation, and that digit is either a 0 or a 1. The & helps in getting the 0 or 1.
In the end, 65 becomes 1000001.
What it is doing is:
Finding the largest number j such that 2^j <= N
Starting at the jth bit (counting from the right) and moving to the right ...
chopping off all of the bits to the right of the current chosen bit
chopping off all of the bits to the left of current chosen bit
printing the value of the single remaining bit
The code actually has undefined behavior because you did not include <stdio.h>, nor <math.h>. Without a proper declaration of floor() and log2(), the compiler infers the prototype from the calling context and gets int log2(int) and int floor(int), which is incompatible with the actual definition in the C library.
With the proper includes, log2(N) gives the logarithm of N in base 2. Its integral part is the power of 2 <= N, hence 1 less than the number of bits in N.
Note however that this method does not work for negative values of N and only works by coincidence for 0 as the conversion of NaN to int gives 0, hence a single binary digit.
I came across this problem while solving challenges on Hackerrank.
/*
Problem Statement
There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.
Input Format
The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.
Constraints
1≤N<100
N % 2=1 (N is an odd number)
0≤A[i]≤100,∀i∈[1,N]
Output Format
Output S, the number that occurs only once.
*/
The normal solution which I would write in this case turned out to be extremely complicated, with lots of nested if loops. On searching a bit, I found this solution which solves the problem by simply XOR-ing all the elements in the integer array with each other, and the result is the lonely integer.
Here's the related method (main() method which accepts input and parses it into integer array not shown as it's not relevant here) :
static int lonelyinteger(int[] a) {
int n = a.length;
int result = 0;
for( int i = 0; i < n; i++) {
result = result ^ a[i];
}
return result;
}
I am not sure how this XOR operation is able to return the "lonely integer" in the array. I'm aware of the two properties of XOR, as:
1. a^a=0
2. a^0=a
But other than this, I couldn't quite figure out how XOR worked here.
There is another question on SO with the same content, but that asks a different question, so I had to ask this (again).
I'd highly appreciate if anyone could provide a detailed explanation for this XOR operation.
Since a^a is equal to 0 for any a, all of the matching pairs of integers will cancel each other out, leaving 0. That is then XOR'ed with the final number. Since 0^a is equal to a for any a, the result will be that final number.
Simple demo:
$ ruby -e 'puts [1,1,2,2,3,3,4,5,5,6,6].reduce :^'
4
You can see why this works if you go through the individual pairs:
1 ^ 1 = 0
0 ^ 2 = 2
2 ^ 2 = 0
0 ^ 3 = 3
3 ^ 3 = 0
0 ^ 4 = 4
4 ^ 5 = 1
1 ^ 5 = 4
4 ^ 6 = 2
2 ^ 6 = 4
The result toggles between 0 and the latest number until you get to the loner; after that it toggles between that number and... whatever you get when you XOR it with the latest new number. The actual value there doesn't matter because it will be zapped when you XOR in the second copy of that number, and you're back to the copy of the singleton.
I sorted the numbers to make it easy to spot the singleton, but since XOR undoes itself, the order doesn't matter at all:
$ ruby -e 'puts [6,3,4,1,1,2,2,6,3,5,5].reduce :^'
4
6 ^ 3 is ... some number, and then that number ^ 4 is some other number, and then you XOR that with 1, and none of that matters because then you undo the 1, and then you throw in another intermediate result with the 2 and undo it right away, and then you undo the 6 and the 3, so you're back to just the 4. Which you XOR with 5 to get another ephemeral number that is then washed away by the final 5, leaving, once again, 4.
The output of below c program is,
output : 1,2,3,4 ........ 126,127,-128,-127 .... -2,-1 ?
#include <stdio.h>
#include <string.h>
int main()
{
char i=0;
for(i<=5 && i>=-1 ; ++i;i>0)
printf("%d\n",i);
printf("\n");
return 0;
}
please explain why is so ?
Here is a breakdown of your code, it's fairly sneaky:
for( i <= 5 && i >= -1 ; ++i; i > 0)
Typically a for-loop is, ( initial statement, expression, second statement ). Looking at your code before the first null statement: what you have done is an expression (in place of a statement), which does not matter at all however it's entirely useless. So removing that line (which has no effect on the result of this expression) gives us:
for( ; ++i; i > 0)
... now if you noticed you initialized i to be 0 before the for loop. What you are doing next is incrementing i and then returning its value (see here), and hence it will go from 1 ... -1 (overflowing at 127). This is because in C any non-zero value is true and 0 is false. Hence, once i becomes 0 it will stop running the loop. i can only become zero by overflowing.
Your third statement does not matter, it's irrelevant.
It is called overflow. Type "char" uses 1 byte of your RAM's capacity, so it can store only 256 values. These are [-128, 127]. When you try to get over 127, it will get back the the lowest value.
Other than that, your for loop is a little messed up. Try
for ( i = 0 ; i <= 5 ; ++i ) // This will print 0,1,2,3,4,5
printf( "%d\n" , i );
I'm guessing you're using the for loop incorrectly.
for(i<=5 && i>=-1 ; ++i;i>0)
The above code means:
Before anything, evaluate i<=5 && i>=-1 (which doesn't have any side effects so nothing happens)
On every iteration, increment i then check if it is zero. If it is non-zero, run another iteration.
At the end of every iteration, evaluate i>0 (which again, does nothing).
Therefore, your loop simplifies down to and is essentially
while (++i)
To explain your result, the system you're using is likely using implements a char as a signed two's complement integer which 'wraps' to a negative number when it is higher than 127 (since 128 in a 8 bit two's complement integer is a -128)
First of all, char occupies 1 byte and it is signed.
With the help of 8 bits (1 byte) the range of numbers that you can represent is
**-(2^(8-1)) to +((2^(8-1)) -1) [ie from -128 to +127].**
In your code you are incrementing i and also printing the same.
once i reaches 127 (in binary 0111 1111 = 127) and you again increment it becomes (1000 0000) which is -128.
And while printing you are using %d. so out will be in integer format.
That is why it is printing 1,2,3 ... -128, -127...
If you didn't understand how 1000 0000 is -128, read
What is 2's Complement Number?
Because this:
for(i<=5 && i>=-1 ; ++i;i>0)
works out as
1) Initialisation:
i<=5 && i>=-1
does nothing
2) Termination condition:
++i
increments i and will terminate when i gets to zero
3) statement executed each time round loop (normally an increment / decrement):
i > 0
does nothing.
So your code loops from i = 0 back till it's zero again
I am trying to understand how to repeat loops using the mod operator.
If you have two strings, "abc" and "defgh", how can % be used to loop through abc, repeating it until the end of defgh is reached? Namely, what is the mod relationship of the length of abc and defgh?
I don't really understand this concept.
Simple.
std::string abc("abc");
std::string defgh("defgh");
for (size_t i = 0; i < defgh.length(); ++i)
{
printf("%c", abc[i % abc.length()]);
}
Think about what the Modulus operator is doing, it discretely divides the left hand side by the right hand side, and spits back the integer remainder.
Example:
0 % 3 == 0
1 % 3 == 1
2 % 3 == 2
3 % 3 == 0
4 % 3 == 1
In our case, the left hand side represents the i'th position in "defgh", the right hand represents the length of "abc", and the result the looping index inside "abc".
The typical usage of mod is for generating values inside a fixed range. In this case, you want values that are between 0 and strlen("abc")-1 so that you don't access a position outside "abc".
The general concept you need to keep in mind is that x % N will always return a value between 0 and N-1. In this particular case, we also take advantage of the fact that if you increase x by 1 x % N also increases by 1. See it?
Another important property of modulus that we use here is the fact that it "rolls over". As you increase x by 1, x % N increases by 1. When it hits N-1, the next value will be 0, and so on.
Look at #Daniel's code. It's C++ but the concept is language-agnostic