Explain the result of the program? - c

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

Related

A code snippet to count the number of similar 1's in a bit-stream

I was trying to count the number of consecutive bits of a bit-stream and I have this code. I assume that, this has to to run until when the number becomes 0 and the count then should return the value. But why is there no conditional statement to equate the number to zero(otherwise i doubt this can be an infinite loop) so that the execution jumps out of the loop and returns the count value once it's over. Please don't duplicate it as I'm only a kid without adequate reputation to comment any doubt.
int count_consecutive_ones(int in) {
int count = 0;
while (in)
{
in = (in & (in << 1));
count++;
}
return count;
}
First of all: The code does not count the number of consecutive bits of a bitstream. All bits in a bitstream are consecutive. That's way it is called a bit stream. It counts the number of consecutive ones in a bitstream. No, not in a bitstream, but in an integer.
Let me explain that:
while(in)
{
…
}
… is a while loop that runs as long as its condition is true. In C for a long time there has been no boolean type at all. A condition is false if the expression of any type is not a representation of zero, otherwise true. For integers that means, that the value of 0 is false, each other value is true. You can read that as …
while( in != 0)
{
…
}
… with != in the meaning of unequal.
Inside the loop you have …:
in = (in & (in << 1));
This is a bit tricky: It moves the integer by one bit to the left (in << 1) and then computes the bit-and operation with the original value itself. This produces 1's on all places, where a 1 is aside a 1. Doing that over and over, it counts 1's being aside.
So you do not have to iterate over the bits to find a leading 1 and then the number of 1's following.

regard C programming code and logic building

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.

Understanding the exit condition of a 'for' loop

I had this question after reading the Stack Overflow quesion Print an int in binary representation using C.
In a user's comment, they posted this for loop, which assigns either a 1 or a 0 to the bit position in order to convert from an int decimal to char * binary.
for(; bits--; u >>= 1)
str[bits] = u & 1 ? '1' : '0';
I understand why there doesn't need to be an initialized value. This is the syntax for a for loop that I've always known:
for ( variable initialization; condition; variable update )
I don't understand how 'bit--' can be an exit condition. Please help me understand how this code works (I tested it, and it is valid).
In C, a value of zero evaluates to "false" in a Boolean context. So when bits-- evaluates to 0, in the context of the loop it evaluates to "false" and terminates the loop.
If you say, for example:
int x = 1;
if (--x)
{
printf("True!\n");
}
else
{
printf("False!\n");
}
It will output "False", because --x evaluates to 0, which is "false" in a Boolean context.
All conditions basically boil down to checking whether something is 0 or not. 0 means false, everything else means true. So that loop will break when bits is 0.
You will sometimes see while or if conditions written
if (variable) // or while(variable)
That is just shorthand for
if (variable != 0) // or while (variable != 0)
So
for (; bits--; u >>= 1)
is short for
for (; bits-- != 0; u >>= 1)
bits-- is an assignment expression of type int (since it will return the value of b, which is int). To match the for loop syntax, it gets converted to a Boolean expression, which means it is true if bits != 0.
In fact, the condition is identical to bits!=0, but by using bits--, it changes the value of bits at the same time, making the code more compact. That's all.
As others said, in C, you can use integers as a condition - 0 or false, and anything else for true. (Actually, you almost always do it - even an expression like a<b is an int.)
So, the loop will end when bits-- will be 0.
When the -- operator comes after the variable, it decreases the variable, and gets the previous value of it. For example, if you have int a=3,b; b=a--;, then b will be 3, and a will be 2.
So, the loop will exit after that bits will been decreased from 0 to -1.
That means that, if in the beginning, bits==8 (for example), the loop will iterate 8 times, when in the first, bits will be 7 (because the condition had checked), and in the last, bits will be 0. It is a nice way to loop through an array (Since in C, an array of bits variables is being indexed from 0 to bits-1).

What does the condition "if (n/10)" with integral n specify?

I am looking at the following piece of code:
void printd(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10)
printd(n / 10);
putchar(n % 10 + '0');
}
I understand the first if statement fine, but the second one has me confused on a couple of points.
By itself, since "n" is an integer, I understand that n/10 will shift the decimal point to the left once - effectively removing the last digit of the number; however, I am having a little trouble understanding how this can be a condition by itself without the result being equal to something. Why isn't the condition if ((n/10) >= 0) or something?
Also, why is the '0' passed into the putchar() call?
Can someone tell me how it would read if you were to read it aloud in English?
Thanks!
The n / 10 will evaluate to false if the result is 0, true otherwise. Essentially it's checking if n > 10 && n < -10 (the -10 doesn't come into play here due to the n = -n code)
The + '0' is for character offset, as characters '0'-'9' are not represented by numbers 0-9, but rather at an offset (48-57 with ascii).
Can someone tell me how it would read if you were to read it aloud in English?
If you're talking about the conditional, then I would say "if integer n divided by 10 is not zero"
n/10 will not shift the decimal number since n is an integer. The division will produce the result like this: if n = 25, then n/10 would be 2 (without any decimal points), similarly if n = 9, then n/10 would be 0 in which case if condition would not be satisfied.
Regarding the +'0', since n%10 produces an integer result and in putchar you are printing a char , you need to convert the integer to a char. This is done by adding the ascii value of 0 to the integer.
In C, there is no separate boolean type; an expression like a > b evaluates to zero if false, non-zero if true. Sometimes you can take advantage of this when testing for zero or non-zero in an int.
As for the '0', that just performs character arithmetic so that the right character is printed. The zero character has an ASCII encoding value which isn't zero, so the n value is used as an offset from that encoding to get the right numeric digit printed out.

why this for loop goes in infinite loop executation?

see i have one code like this
int main () {
uint32_t i ;
for(i=4;i>=0;i--)
printf("i is %d \n",i);
return 0;
}
it goes in infinite loop.
why i's value goes below 0 & still loop is going to executive?
uint32_t means unsigned integer and so its value is always >= 0 - thus your loop executes infinitely.
Note that many compilers will issue a warning indicating that i>=0 comparison is always true.
You see negatives values in your printf because you print it as %d, but in the condition, the uint32_t is always positive (you are doing an overflow).
You are using uint32_t means unsigned and then checking the condition in for loop that i >= 0 so when the loop executes for value i = 0 and then it makes the i = -1 but i is unsigned so it will make the value of i INT_MAX(what ever your system supports). so and still the value is greater than 0 so condition is true.
And the answer for how it prints the negative values for i is that, you are using the '%d' that is for signed.
If you want to see the result you can use the '%u' option so it will print the original unsigned value of i.
If you want the result that you want from the program then try to cast the uint to int at the time of condition checking.

Resources