why the result of " (num >> i)& 1 " is 1 for the second loop?
main() {
char num = 5 ;
int i , count = 0 ;
for(i=0;i<8;i++){
if ((num >> i)& 1 )
count++;
}
printf("%d", count);
}
For starters pay attention to that the variable num itself is not being changed within the for loop
for(i=0;i<8;i++){
if ((num >> i)& 1 )
count++;
}
Its binary representation is
00000101
(Note take into account that the declaration
char num = 5 ;
differs from the declaration
char num = '5' ;
end note.)
In the first iteration of the loop when i is equal to 0 the shift operator has no effect so the if statement evaluates to logical true and the variable count will be incremented.
The variable count also will be incremented when i is equal to 2.
So as a result you will get that count is equal to 2 because in the internal representation of the variable num only two bits are set..
To make it more clearer rewrite the program the following way
#include <stdio.h>
int main(void)
{
char num = 5 ;
int count = 0 ;
for ( int i = 0; i < 8; i++ )
{
int result = (num >> i)& 1;
printf( "i = %d, result = %d\n", i, result );
if ( result ) count++;
}
printf( "\ncount = %d\n", count );
}
The program output is
i = 0, result = 1
i = 1, result = 0
i = 2, result = 1
i = 3, result = 0
i = 4, result = 0
i = 5, result = 0
i = 6, result = 0
i = 7, result = 0
count = 2
In fact the output from top to bottom shows the internal representation of the variable num starting from its less significant bit to the most significant bit.
Related
So I want to start by saying that I already solved the problem, but there is something that is bugging me,
Here is the code first:
#include <stdio.h>
int flag = 1;
int controlNumber(int);
int main() {
int array[10] = { 233, 45, 777, 81, 999999, 36, 90, 88, 11, 61 };
int i;
int c;
for (i = 0; i < 10; i++) {
printf("%d >> ", array[i]);
c = controlNumber(array[i]);
if (c == 1) {
printf("all digits are equal\n");
} else {
printf("not all digits are equal\n");
}
}
return 0;
}
int controlNumber(int a) {
int q = a;
int r = a % 10;
int temp;
while (q != 0) {
temp = q % 10;
if (temp == r) {
q = q / 10;
} else {
flag = 0;
return flag;
}
}
return flag;
}
The code works only if the global variable flag is made local inside the scope of the function controlNumber with a value of 1, and I can't really figure out why that is the case since the logic should still be the same.
Also, I'm still a beginner to some extend so I apologize for any indentation errors.
For starters it is a very bad idea to define a function that depends on a global variable. In fact it is the reason of the bug of your program. You forgot to reset the global variable flag to 1 each time before calling the function.
The function can be defined the following way without any redundant global variable
int controlNumber( int n )
{
const int Base = 10;
int digit = n % Base;
while ( ( n /= Base ) && ( n % Base == digit ) );
return n == 0;
}
Here is a demonstrative program.
#include <stdio.h>
int controlNumber( int n )
{
const int Base = 10;
int digit = n % Base;
while ( ( n /= Base ) && ( n % Base == digit ) );
return n == 0;
}
int main(void)
{
int array[] = { 233, 45, 777, 81, 999999, 36, 90, 88, 11, 61 };
const size_t N = sizeof( array ) / sizeof( *array );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d >> ", array[i] );
if ( controlNumber( array[i] ) )
{
printf( "all digits are equal\n");
}
else
{
printf( "not all digits are equal\n" );
}
}
return 0;
}
The program output is
233 >> not all digits are equal
45 >> not all digits are equal
777 >> all digits are equal
81 >> not all digits are equal
999999 >> all digits are equal
36 >> not all digits are equal
90 >> not all digits are equal
88 >> all digits are equal
11 >> all digits are equal
61 >> not all digits are equal
If for example you will change the constant Base in the function and make it equal to 8
int controlNumber( int n )
{
const int Base = 8; //10;
int digit = n % Base;
while ( ( n /= Base ) && ( n % Base == digit ) );
return n == 0;
}
then you will get the following result.
233 >> not all digits are equal
45 >> all digits are equal
777 >> not all digits are equal
81 >> not all digits are equal
999999 >> not all digits are equal
36 >> all digits are equal
90 >> not all digits are equal
88 >> not all digits are equal
11 >> not all digits are equal
61 >> not all digits are equal
In this case for example the number 45 has the same digits in the octal representation because in the octal representation the number is written like 055.
Global variables retain their value. In your case, if flag is global, once set to 0 (within controlNumber) it will keep that value. There is no other place in the code to make it 1 again.
Making it a local variable to the function will cause it to initialize to 1 every time the function is called.
Edit: if you want to have it as global, you could set it to 1 every time controlNumber returns 0, i.e., before or after printf("not all digits are equal\n");.
I am new to the C programming. I came across the for loop example.
I don't understand some part of the loop. Output is 8. I don't get how b is incremented till 4.
Here is my code:
int a = 4;
int b = 2;
int result = 0;
for(int count = 0; count != b; count++) {
result = result + a;
}
printf("a times b is %i\n", result);
return 0;
Sometimes, the easiest thing to do is to get the program to explain itself:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int a = 4;
int b = 2;
int result = 0;
for(int count = 0; count != b; count++) {
printf("a = %3d, b = %3d, count = %3d, result = %3d\n", a, b, count, result);
result = result + a;
printf("a = %3d, b = %3d, count = %3d, result = %3d\n", a, b, count, result);
}
printf("a = %3d, b = %3d\n", a, b);
printf("a times b is %i\n", result);
return 0;
}
Output
a = 4, b = 2, count = 0, result = 0
a = 4, b = 2, count = 0, result = 4
a = 4, b = 2, count = 1, result = 4
a = 4, b = 2, count = 1, result = 8
a = 4, b = 2
a times b is 8
As you can see, b does not change. count changes and the loop is exited when count is equal to b.
The variable b is not incremented, the variable count starts from 0 and incremented in the for loop. When the count variable becomes 2 the loop ends. So, the loop runs twice (count 0 and count 1) and the result is 4 + 4 = 8.
At first, count = 0 which is not the same with b = 2 and so the loop starts. By doing so, the first iteration of loop gives a result,
result = 0 + 4
Since the loop ends and count variable should proceed count++ which means count = count + 1. Thus, count = 0 + 1 = 1 where it is not the same valeu with b = 2 again.
Proceed the loop again,
result = 4 + 4 # where the first number came from the result of first loop
Now count++ makes count = 2 which is now same value with b = 2. Then, the condition of the loop is not matched, count != 2, no further loop and print the value result = 8.
it will be executed 2 times
count= 0 ==> result=0+4
and count =1 ==> result=4+4 ==> result=8
when it will reach count= 2 the 2!=2 part will be false and we will exit the for loop
The loop runs only two times we can dry run the loop like that:
Initial values for variables: -> a = 4, b = 2, count = 0 and result = 0
loop first run ->
count = 0
count != 2 -> that is -> 0 != 2 => true
result = result + a -> 0 + 4 = 4
second run ->
count = 1
count != b -> that is -> 1 != 2 => true
result = result + a -> 4 + 4 = 8
third run ->
count = 2
count != b -> that is -> 2 != 2 => false
stop loop.
And the final resultent values are as follow: a= 4, b= 2 , count = 2 and result = 8
Goal is to have user enter numbers and print highest and lowest entered value. My problem is that the result always evaluates to 0.
I've tried declaring variables inside and outside of the main function. I'd rather keep them in the main function however.
I've also tried to have them undeclared and equal 0 but this just ends up giving me the same result.
float accumulate = 0;
int inpt;
//While loop that lasts until while loop breaks. Printf outside of while loop because it's annoying.
printf("Enter some numbers. Enter -1 to stop.\n");
while (inpt > -1) {
scanf_s("%i", &inpt);
if(inpt < lowest & inpt > 0) {
lowest = inpt;
total++;
accumulate += inpt;
printf("%i\n", lowest);
If I enter 5, 6, 7, I expect the lowest integer to be 5 but it prints out 0
Well there is no clear understanding in what are you trying there to archive.
As long as you have no min and max values to which you can compare it, you can try something like the following approach:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int input = 0;
int min = 0;
int max = 0;
int flag = 0;
int i = 0;
while ( i < 10 ) // stop after 9 Inputs
{
printf( "INPUT = " );
if ( scanf( "%d", &input ) != 1 )
{
printf( "Error,scanf()\n" );
exit( EXIT_FAILURE );
}
if ( flag == 0 )
{
min = input;
flag = 1;
}
if ( input > max )
{
max = input;
}else if ( input < min )
{
min = input;
}
if ( min != max ) // Do not print if input is always the same.
{
printf( "\t\tlow = %d | High = %d\n", min, max );
}
i++;
}
}
Output:
INPUT = 5
INPUT = 6
low = 5 | High = 6
INPUT = 7
low = 5 | High = 7
INPUT = 4
low = 4 | High = 7
INPUT = 5
low = 4 | High = 7
INPUT = 1
low = 1 | High = 7
INPUT = 2
low = 1 | High = 7
INPUT = 8
low = 1 | High = 8
INPUT = 7
low = 1 | High = 8
INPUT = 3
low = 1 | High = 8
Your program needs to know which number is lower and which number is higher if you have no numbers then you have to set them yourself.
I don't really understand what a few of you guys are saying and that code I posted wasn't complete but if anyone is trying to have user input a bunch of numbers and have it return the lowest number,
I got around it by changing
if(inpt < lowest && inpt > 0) {
lowest = inpt;
total++;
accumulate += inpt;
to
if(inpt < lowest && inpt > 0 || lowest == 0) {
lowest = inpt;
total++;
accumulate += inpt;
This puts an OR operator that checks if lowest is set to 0 and will replace it with the first actual number entered
Is it possible in C to have a fast for/while loop that loops through the odd numbers and 2? Without using arrays.
So I'd like it to loop through {1, 2, 3, 5, 7, 9, ..}
Of course. Here is a pretty straight forward way.
for(int i=1; i<N; i++) {
if(i>3) i++;
// Code
}
A bit more hackish variant:
for(int i=1; i<N; i+=1+(i>2)) {
// Code
}
But I think in this case that the most readable variant would be something like:
// Code for 1 and 2
// Then code for 3,5,7 ...
for(int i=3; i<N; i+=2) {
// Code
}
Another option
for(int i=1;;++i) // you didn't specify a limit
{
switch(i)
{
default:
if(!(i&1))continue;
case 1:
case 2:
DoSomething(i):
}
}
Another alternative which does use an array but only a small one that is a constant size of two elements no matter how many numbers in the sequence would be:
{
int i;
int iray[] = {1, 2};
int n = 15;
for (i = 1; i < n; i += iray[i > 2]) {
printf (" i = %d \n", i);
// code
}
}
which produces:
i = 1
i = 2
i = 3
i = 5
i = 7
i = 9
i = 11
i = 13
Extending this alternative to other sequences
And this alternative can be extended to other sequences where there is a change of a similar nature. For instance if the desired sequence was
1, 2, 3, 5, 8, 11, ..
Which involves several changes in the sequence. Beginning at 1 an increment of 1 is used followed by a first increment change beginning at 3 where an increment of 2 is used followed by a second change in the sequence beginning at 5 where an increment of 3 is used, you can make the following modification.
{
int i;
int iray[] = {1, 2, 3}; // increment changes
int n = 15;
// calculate the increment based on the current value of i
for (i = 1; i < n; i += iray[(i > 2) + (i > 3)]) {
printf (" i = %d \n", i);
// code
}
return 0;
}
which would produce:
i = 1
i = 2
i = 3
i = 5
i = 8
i = 11
i = 14
#include <stdio.h>
int main()
{
for(unsigned x = 0; x < 10; x++)
printf("%u%s element - %u\n",x + 1, !x ? "st" : x == 1 ? "nd" : x == 2 ? "rd" : "th", !x + x * 2 - (x >= 2));
return 0;
}
no jumps calculating in the !x + x * 2 - (x >= 2) so no pipeline flushes.
I need to write a function that accepts the length of series(0 and 1) and the user writes the series. The function tells the place of the longest same sun-series.
Example:
The function gets length = 12, and the user writes: 1 0 0 1 1 1 1 0 0 0 1 1
The answer for this one is 4 because the longest combination (four consecutive 1's) starts at 4th place.
Another example:
The length is: 12 and the user inputs : 1 0 0 0 1 1 0 1 1 1 0 0
The answer for this one is 2 (three consecutive 0's starting at position 2—if there are multiple sub-series with same length it returns the first one).
This is what I tried to do:
int sameNumbers(int seriaLength)
{
int i;
int place=0;
int num1, num2;
int sameCount;
int maxSameCount = 0;
printf("Please enter the seria: \n");
scanf("%d",&num1);
for(i = 1; i < seriaLength; i++)
{
scanf("%d",&num2);
while(num1 == num2)
{
sameCount++;
}
if(sameCount > maxSameCount)
{
maxSameCount = sameCount;
place = i;
}
scanf("%d",&num1);
}
return place;
}
Edit:
I need to do this without arrays.
Thanks!!
This seems to do what you want. To understand the logic, see the comments in the code.
#include <stdio.h>
int sameNumbers(int seriaLength)
{
int i, num, previousNum, length = 0, maxLength = 0, start = 0, startOfLongest = 0;
printf( "Please enter the series: " );
for( i = 0; i < seriaLength; i++ )
{
scanf( "%d", &num );
if( i > 0 && num == previousNum ) length++;
else { length = 1; start = i; } // if the number is not the same as the previous number, record the start of a new sequence here
if( length > maxLength ) { maxLength = length; startOfLongest = start; } // if we've broken (not equalled) the previous record for longest sequence, record where it happened
previousNum = num;
}
return startOfLongest + 1; // add 1 because the OP seems to want the resulting index to be 1-based
}
int main( int argc, const char * argv[] )
{
printf( "%d\n", sameNumbers( 12 ) );
return 0;
}