Good afternoon.
I need to enter an integer and determine whether there are two identical numbers which are located fairly close to each others( standing side by side). For instance, my input is "1224" and the output is "YES". Or my input is "1256" and the output is "NO".
I tried to do it like that:
{int a,b,c,d,i;
scanf("%d",&i);
while (i!=0)
{
a=i/1000;
b=(i/100)%10;
c=(i%100)/10;
d=i%10;
}
if (a==b || b==c || c==d)
{printf("YES");}
else
{printf("NO");}
return 0;
}
However, it failed. My classmates said me that "i" does not changes and, as a result, my code does not work. Unfortunately, i did not understand what they meant. So, could you tell me what's wrong in this code?
You don't need a while loop.
For your implementation, you can extract digits like this:
a = (i / 1000) % 10;
b = (i / 100) % 10;
c = (i / 10) % 10;
d = i % 10;
Your implementation works only with a 4 digit number.
A general implementation should look like this:
int main() {
int number;
scanf("%d", &number);
while (number >= 10) {
if (number % 10 == (number / 10) % 10) {
printf("YES");
return 0;
}
number /= 10;
}
printf("NO");
}
I think you want the scanf() inside the while
{int a, b, c, d, i = -1;
while (i != 0)
{
scanf("%d", &i);
b = (i/100) % 10;
c = (i%100) / 10;
d = i % 10;
if (a==b || b==c || c==d)
{printf("YES");}
else
{printf("NO");}
}
return 0;
}
Note: I've tried to keep your strange indentation style, but not whitespace usage.
Your friends are right that i is not changing in the while loop so it is resulting in an infinite while loop. I will provide a solution for not just 4 digit numbers for any digit numbers.
#include <stdio.h>
#include<string.h>
int main() {
int i;
int m = 0;
int n = 0;
char strin[] = "NO ";
scanf("%d", &i);
while (i != 0) {
m = i % 10;
i = i/10;
n = i % 10;
if(m == n){
strcpy(strin, "YES");
break;
}
}
printf("%s", strin);
return 0;
}
The approach for this question is to separate the last two digits of a number and compare them, if they are the same break from the loop, if they are not, then check it for the remaining number.
EDIT- This could be done with lesser variables, but I suppose you are a beginner and it will help you understand better.
i Will do it in java cause my c is a little rusty. However, you just need to travel through the array of numbers checking if the A[i]=A[i-1] value. (current value is equal to previous one)
public String checkNumber(int[] array){
for( int i=1; i<array.length-1; i++){
if(A[i]==A[i-1]){
return "yes";
{
{
return "no";
}
Here you have a link which shows how to pass an integer to an array of ints:
Convert an integer to an array of digits
If you input even numbers, only the odd numbers will be printed until it reaches 0. (0 will not be printed). For example, if you input 10, the output would be 9, 7, 5, 3, 1.
This is what I came up with. I'm wondering what should I decrement x by to get the desired output.
int x;
scanf("%d", &x);
while (x >= 0) {
printf("%d", x);
x = x - 2;
}
I'm wondering what should I decrement x by to get the desired output.
Subtracting 2 is fine, as long as you always start from an odd number. So you could change the loop into something like this:
for ( int i = x % 2 ? x : x - 1; // Is x odd? good.
// Otherwise, start from the previous one.
i > 0;
i -= 2 ) {
printf("%d\n", i);
}
int x, n;
printf("Give N: ");
scanf("%d", &n);
printf("odd numbers from 1 to %d are: \n", n);
x=n;
while(x<=n && x>0)
{
if(x%2!=0)
{
printf("%d\n", x);
}
x--;
}
return 0;
}
Your code was almost correct (indeed, it is a pity that you have selected as the correct question such a bad response) I will show you where is your error:
int x;
scanf("%d", &x);
if (x % 2 == 0) /* if the number is even */
x = x - 1; /* decrement it to convert it in an odd number */
while (x >= 0) {
printf("%d", x);
x = x - 2;
}
The thing is that you start your question with exactly that assert (if you input even numbers...)
Another problem is that you don't say what should happen when you introduce an odd number. Anyway, the code printed it, and all the odd numbers until we reach 0.
Why your code is better than the selected one? because your code only wastes time in the loop with the valid results, and doesn't get into the loop to decide that it has nothing to do. This saves a lot of loop executions (almost half of them) which, if your number is very large, can do your program a lot more efficient.
I need to write a C program which will read a number (in base 10) from user input and output it in any base which is a power of 2. The calculations have to be performed in one function, to_base_n, which takes the parameters num and base and prints the number in the respective base. As a validation check, the program also checks if the base is a power of two with the isPowerofTwo function.
The way the conversion is carried out is by means of long division which carries out the logic in the pseudocode below:
void to_base_n(int x, int n){
int r, i = 0
int digits[16]
while (x ≠ 0){
r = x mod n
x = x / n
digits[i] = r
i++
}
for (i = 0, i < 15, i++)
print digits[i]
}
Which I believe is arithmetically sound. But when I try to, for example, convert 82000 to base 4, I get the following output:
The large digits appearing are even bigger than num itself, so I figured the modulus cannot be entering the array properly (because ∀{x,n}; x mod n < x). I can't seem to find what's wrong with it. The full code is listed below.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isPowerofTwo(int);
void to_base_n(int, int);
int main(){
//Variables
int num, base;
//Prompt
printf("Please enter a number in base 10: ");
scanf("%d", &num);
printf("Please enter a base (2^n) to convert it to: ");
scanf("%d", &base);
//Precaution
while(!isPowerofTwo(base)){
printf("That number is not a power of 2. Please try again: ");;
scanf("%d", &base);
}
if(isPowerofTwo(base)){
//Output
printf("The number %d (base 10) is equivalent to ", num);
to_base_n(num, base);
printf(" (base %d).", base);
}
//Return Statement
return 0;
}
//Checks if Base is a Power of Two
bool isPowerofTwo(int base){
while((base % 2 == 0) && base > 1){
base = base / 2;
if(base == 1){
return true;
break;
}
}
return false;
}
//to_base_n
void to_base_n(int x, int n){
int r, i = 0;
int digits[16];
while(x != 0){
r = x % n;
x = x / n;
digits[i] = r;
i++;
}
for(i = 0; i < 15; i++)
printf("%d|",digits[i]);
}
Can anyone help explain what's wrong with it?
The number 82000 in base 4 would be:
110001100
Which is exacly what you get. Your mistake is that:
They are printed backwards.
You are printing more digits than you should, so you print garbage.
You ignore the number of digits extracted with your pseudo code, so you print uninitialised elements of the array.
for (i = 0, i < 15, i++)
print digits[i]
And they are printed in reverse order. I suggest changing it to this
for (i = i - 1, i >= 0, i--)
print digits[i]
and as C code in your function
for(i = i - 1; i >= 0; i--)
printf("%d|",digits[i]);
I want to reiterate the fact that I am not asking for direct code to my problem rather than wanting information on how to reach that solution.
I asked a problem earlier about counting specific integers in binary code. Now I would like to ask how one comes about counting the maximum block length within binary code.
I honestly just want to know where to get started and what exactly the question means by writing code to figure out the "Maximum block length" of an inputted integers binary representation.
Ex: Input 456 Output: 111001000
Number of 1's: 4
Maximum Block Length: ?
Here is my code so far for reference if you need to see where I'm coming from.
#include <stdio.h>
int main(void)
{
int integer; // number to be entered by user
int i, b, n;
unsigned int ones;
printf("Please type in a decimal integer\n"); // prompt
fflush(stdout);
scanf("%d", &integer); // read an integer
if(integer < 0)
{
printf("Input value is negative!"); // if integer is less than
fflush(stdout);
return; // zero, print statement
}
else{
printf("Binary Representation:\n", integer);
fflush(stdout);} //if integer is greater than zero, print statement
for(i = 31; i >= 0; --i) //code to convert inputted integer to binary form
{
b = integer >> i;
if(b&1){
printf("1");
fflush(stdout);
}
else{
printf("0");
fflush(stdout);
}
}
printf("\n");
fflush(stdout);
ones = 0; //empty value to store how many 1's are in binary code
while(integer) //while loop to count number of 1's within binary code
{
++ones;
integer &= integer - 1;
}
printf("Number of 1's in Binary Representation: %d\n", ones); // prints number
fflush(stdout); //of ones in binary code
printf("Maximum Block Length: \n");
fflush(stdout);
printf("\n");
fflush(stdout);
return 0;
}//end function main
Assuming you are looking for the longest run of 1's.
Heres how you do it for 32bits. You should be able to extend this idea to arbitrarily long bitstreams.
int maxRunLen(uint32_t num) {
int count = 0;
int maxCount = 0;
while(num) {
if(num & 1) count++;
else {
if( count > maxCount) maxCount = count;
count = 0;
}
num >>=1;
}
if( count > maxCount) maxCount = count;
return maxCount;
}
The idea is to test each bit in order to determine if it is a 1 or not. If it is 1, increment the count. Otherwise it is the end of a run and in this case check if the previous run is longer than any previous maximum run and reset the count.
The way to test a bit is using masking. In the above example the lowest order bit tested by
num & 1
To test the next bit in the number you move all the bits 1 bit to the right which is called a shift. More explicitly in this a case a logical right shift (>>). Example bit pattern 0110 becomes 0011. This is done in the above example:
num >>= 1;
Which is equivalent to:
num = num >> 1;
Try this:
int max_run_of_ones (unsigned x)
{
int max_run = 0;
int cur_run;
while (x != 0) {
// skip right-most zeros
while ((x & 1) == 0) {
x >>= 1;
}
// skip and measure right-most run of ones
cur_run = 0;
while ((x & 1) == 1) {
cur_run++;
x >>= 1;
}
if (cur_run > max_run) max_run = cur_run;
}
return max_run;
}
From looking at your code, it looks like you want to know the count of the bits set.
This is a guess...
Credit goes to Ratko Tomic for this. The guy is brilliant at bit operations.
int countBits( int value )
{
int n = 0;
if( value )
{
do
{
n++;
} while( 0 != (value = value & (value - 1) ) );
}
return( n );
}
This should solve it in python, using string operations...
The main point of this is to help others with understanding what you're trying to accomplish.
import re
number = 500
binary_repr = bin(number)[2:] # '111110100'
blocks = re.split(r'0+', binary_repr) # ['11111', '1', '']
block_lengths = [len(x) for x in blocks] # [5, 1, 0]
maximum_block_length = max(block_lengths) # 5
As a homework problem, I'm working on reading a decimal int from stdin, converting it to a different base (also provided from stdin) and printing it to the screen.
Here's what I've got so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, base, remainder, quotient;
printf("please enter a positive number to convert: ");
scanf("%d", &num);
printf("please enter the base to convert to: ");
scanf("%d", &base);
remainder = quotient = 1;
// validate input
if (num < 0 || base < 0) {
printf("Error - all numbers must be positive integers!\n");
return 1;
}
// keep dividing to find remainders
while (quotient > 0) {
remainder = num % base;
quotient = num / base;
num = quotient;
if (remainder >= 10) {
printf("%c", remainder + 55);
} else {
printf("%d", remainder);
}
}
printf("\n");
return 0;
}
This works great, only that the algorithm this uses calculates the converted numbers from least significant to most significant digit, thus printing it in reverse. So, for example, converting 1020 to hexadecimal ( 0x3FC ) will print CF3.
Is there a trick I could use to reverse these numbers to print in the correct order. I can only use if-else, while, simple math operators and printf()/getchar()/scanf() - no functions, arrays or pointers. thanks.
(removed original part of the post here, since it is not the solution)
Then the only solution I can see is to perform the loop that you have now the number of times that you have digits.
So, first you calculate all digits till you get to the last, and then print it.
Then you take the original value + base and start dividing again till you come to the second "highest value" digit, then print it.
It is a double loop and you calculate everything twice, but you don't use extra storage.
It's a good try, and well phrased question. If only we had more people asking questions in such a clear manner!
The restrictions seem artificial. I guess you haven't learned about functions, arrays, pointers etc., in your class yet, but I think this problem is not meant to be solved elegantly without functions and/or arrays.
Anyway, you can do something like this:
curr := base
pow := 1
while num / curr >= 1 do:
curr := curr * base
pow := pow + 1
while pow >= 1:
pow := pow - 1
print floor(num / base ** pow)
num := mod(num, base ** pow)
Basically, you are calculating how many digits you will need in the first loop, and then printing the digits in the correct order later.
Some specific issues with your code. I understand it's the beginning of a C class, but still, it's better to know of such issues now than to never realize them:
printf("please enter a positive number to convert: ");
You should add an fflush(stdout) after this to make sure the output appears before scanf() is called. By default, stdout is line buffered on many systems, so the prompt may not appear before your program waits for input.
printf("please enter the base to convert to: ");
Same as above.
if (remainder >= 10) {
printf("%c", remainder + 55);
} else {
printf("%d", remainder);
}
You're assuming ASCII character set. This need not be true. But without arrays or pointers, there's no easy way to print the alphabets corresponding to 10.... Also, your code may print weird characters for base > 36.
You should also be aware that it's very hard to use scanf() safely. Hopefully you will learn better ways of getting input later.
In one loop you can calculate the number of digits and the big_base.
In a second loop you can output the digits starting from the most significant, like this:
n = 1020, 3 hex digits, big_base = 16*16
1st step
1020 / (16*16) = 3
2nd step
n = 1020- 3*(16*16) = 252
252 / (16) = 15, F
3rd step
n = 252 - 15*16 = 12, C
Hey ! I recognize a famous homework I had in first year of my school too (#Epitech students : don't copy/paste the following code, try to come up with your own solution, it's for your own good ^^)
The solution to your problem is to perform the problem in a recursive way :
void my_putnbr_base(int num, int base)
{
int start;
int remainder;
remainder = num % base;
start = (num - remainder) / base;
if (start != 0)
my_putnbr_base(start, base);
if (remainder >= 10)
printf("%c", remainder + 55);
else
printf("%d", remainder);
}
Does your homework specifies that it should only work with positives numbers ? If not, it's easy to include the negative numbers handling :
void my_putnbr_base(int num, int base)
{
int start;
int remainder;
if (num < 0)
{
putchar('-');
my_putnbr_base(-num, base);
}
else
{
remainder = num % base;
start = (num - remainder) / base;
if (start != 0)
my_putnbr_base(start, base);
if (remainder >= 10)
printf("%c", remainder + 55);
else
printf("%d", remainder);
}
}
#arno : that's true, because the exemple code is using ASCII table. If we want something trully flexible we need the base in parameter. For example :
>> my_putnbr_base(4242, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
39U
>> my_putnbr_base(42, "0123456789ABCDEF")
2A
this implements the example :
void my_putnbr_base(int num, char *base)
{
int start;
int remainder;
int len;
len = strlen(base);
if (num < 0)
{
putchar('-');
my_putnbr_base(-num, base);
}
else
{
remainder = num % len;
start = (num - remainder) / len;
if (start != 0)
my_putnbr_base(start, base);
printf("%c", base[remainder]);
}
}
I hope it solves your problem !
edit: I didn't read correctly ^^ You are not allowed to use functions, so recursion is out of the question... Here is an interative way, you can put this in a main(). You can improve this code by adding the negative numbers handling and flexible bases, as I showed you :)
int my_putnbr_base_it(int num, int base)
{
unsigned int quotient = 1;
unsigned int remainder;
while ((num / quotient) >= base)
quotient *= base;
while (quotient)
{
if ((remainder = (num / quotient) % base) < 10)
printf("%d", remainder);
else
printf("%c", 55 + remainder);
quotient /= base;
}
return (0);
}
Hope it solves everything now !
You could rewrite the piece of code calculating each number to behave as a state machine. It will start in the initial state and compute the number of digits, then change the state to "print the Nth digit" to print the most significant digit, then change the state to proceed to the less significant digits, etc until it eneters the final state. Running this inside a loop you will output all digits in proper order.
You could use two loops. The first keeps generating powers of the base until it finds a power greater than the input number. The second starts from here (or rather, one power before) and works back to base^0 (i.e. 1) to compute the output digits most significant first.
Untested pseudo-code:
// Determine highest power, don't actually need "power" it's just there for illustration
power = 0;
baseraisedtopower = 1;
while (baseraisedtopower <= input)
{
baseraisedtopower *= base;
power++;
}
// Go back one step, could have saved previous result
baseraisedtopower /= base;
power--;
// Output
while (input > 0)
{
// Integer division, truncate
quotient = input / baseraisedtopower;
printf("%c", quotient + 55);
input -= quotient * baseraisedtopower;
baseraisedtopower /= base;
power--;
}
You can give a try at this approach.
It's more a proof of concept, you'll still need to handle some special case, but, hey, that's your homework :)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, base, remainder, quotient;
int divider;
printf("please enter a positive number to convert: ");
scanf("%d", &num);
printf("please enter the base to convert to: ");
scanf("%d", &base);
remainder = quotient = 1;
// validate input
if (num < 0 || base < 0) {
printf("Error - all numbers must be positive integers!\n");
return 1;
}
// First get the highest divider
divider = base;
while ( num / divider > base ) {
divider *= base;
}
do {
// Get the highest digit
remainder = num / divider;
// And update num accordingly
num -= remainder * divider;
divider /= base;
if (remainder >= 10) {
printf("%c", remainder + 55);
} else {
printf("%d", remainder);
}
} while ( divider );
printf("\n");
return 0;
}
Interesting task, you've got as a homework.
I am a beginner programmer to, and I've tried to resolve this task.
The following code is working (I haven't tested a lot, apparently is working). I am sure it's not the optimal&best solution, but was the only thing I've could come up with. It should work with any base. Unfortunately it won't convert 10->A, 11->B, etc.:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int nr,base,res,tp,tpb,tpbt,r,rnr,lp,lpt,i;
float baset,rt;
/** Read number */
printf("nr=");
scanf("%d",&nr);
/** Read base */
printf("base=");
scanf("%d",&base);
/** Returning result */
res=0;
/** Test if number is positive
and base is bigger than 2 */
if(nr<0||base<2){
/** Error */
res=1;
}
else{
/** Determine how many
digits are necessary */
lp=0;
baset=base;
while(baset>1){
lp++;
baset/=10;
}
/** Determine full power
of 10 when r has length of lp */
tpb=1;
while((lp--)>0){
tpb*=10;
}
/** Power of ten that will be
incremented */
tp=0;
/** Converted number (will be printed
as the result) */
rnr=0;
/** Algorithm */
while(nr>0){
r=nr%base;
nr/=base;
rt=r;
/** Temporary lp for
r */
lpt=0;
while(rt>1){
lpt++;
rt/=10;
}
/** Temporary tpb for
lpt */
tpbt=tpb;
for(i=0;i<lpt;i++){
tpbt/=10;
}
/** Build number */
rnr+=r*pow((double)(tpbt),(double)(tp++));
}
}
/** Show number */
printf("number is: %d \n",rnr);
return (res);
}
Based on what was suggested, the way to tackle this was to keep print the last number and repeat the loop for every digit. I kept track of the print condition by saving the previous quotient and printing when I got to it every time (then reseting the number and starting over), then reset it to the one before. Sounds complicated, but the change to the code was simple. My stop condition for the loop was when I had 2 consecutive prints, since most of the time it would just calculate quotient/remainder and print nothing, and when 2 digits print in a row, it's the last two. Anyway, here's the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, saved, base, remainder;
int quotient, prev_q, stop_q, just_printed;
printf("please enter a positive number to convert: ");
scanf("%d", &num);
printf("please enter the base to convert to: ");
scanf("%d", &base);
saved = num;
remainder = quotient = prev_q = just_printed = 1;
stop_q = 0;
// validate input
if (num <= 0 || base <= 0) {
printf("Error - all numbers must be positive integers!\n");
return 1;
}
// divide
while (1) {
remainder = num % base;
quotient = num / base;
num = quotient;
// print if it's the last number and reset num to the next
if (quotient == stop_q) {
if (remainder >= 10) { printf("%c", remainder + 55); }
else { printf("%d", remainder); }
// if 2 consecutive printing occur, this means it's time to end this
if (just_printed) { break; }
// next time print when hitting the previous quotient
stop_q = prev_q;
// reset the number to the original value
num = saved;
just_printed = 1;
} else {
just_printed = 0;
}
prev_q = quotient;
}
printf("\n");
return 0;
}
Thanks to everyone who pitched in!
We could use a recursive function to reverse the order of the digits of a number :
We'll need some mathematical functions from these libraries - stdlib.h and math.h
int reverse(int x)
{
if(abs(x)<=9)
{
return x;
}
else
{
return reverse(x/10) + ((x%10)*(pow(10, (floor(log10(abs(x)))))));
}
}
'If statement' is the base case for the recursive function.
'Else statement' may look intimidating at first but it's actually just simple arithmetic. floor(log10(abs(x))) gives us the number of digits of x, so ((x%10)*(pow(10, (floor(log10(abs(x))))))) is just putting the 'ones' place digit of the number to its correct place in accordance with the desired reversed number.
For better comprehension let's take an example, Let 123 be the number we need to reverse. The first thing that the function reverse will do is ask itself the reverse of 12 (reverse(x/10)) and when the function is called for the second time with argument 12 it'll ask itself the reverse of 1, Now this will be the base case for our function. It'll return 1 as abs(1)<=9, Now 2 will be prepended using ((x%10)*(pow(10, (floor(log10(abs(x)))))) it then will return 21 and 3 will be prepended by the same.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int reverse(int x);
int main()
{
int x, revInt;
scanf("%d", &x); // input : 123
revInt = reverse(x);
printf("%d", revInt); // output : 321
return 0;
}