In C How to use leftmost digit from an integer - c

I was wondering how to reverse my output to match entered number.
Example if user entered 543210, I want the output to be: Five Four Three Two One Zero. But instead it's reversed and I can't figure out how to reverse it.
I can't use loops or anything else.
Code:
int main(void){
int value;
int digit;
printf("enter:");
scanf("%i", &value);
while(value)
{
digit = value % 10;
value = value / 10;
if(digit != 0)
{
switch(digit)
{
case 0:
printf("zero ");
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
}
}
}
return 0;
}
Exmaple: If user entered 1234
Output would be: four three two one.
How would I fix it to be: One Two Three Four.

Since you've said that you aren't allowed to use loops, then recursion really is the thing that you are probably being expected to use. I personally am not sure if it would be right to not consider a recursion as a loop, but whatever.
You are using a while there, which also is a loop. If you are allowed to use loops, then you could just do the following, easy-to-understand modification in your code, and get the output you desire:
...
int input; // <-- added this
int value;
int digit;
printf( "enter:" );
scanf( "%i", &input ); // <-- notice the change in variable usage
value = 0;
while ( input ) {
value = 10 * value + input % 10; // adds the last digit of input to value from right
input /= 10;
}
while ( value ) { ... }
...
If you aren't allowed to use loops, then you probably are expected to use a special function, a function which outputs a specific value for a single case, and returns back to itself in any other case. You need a recursive function. Examine this simple example:
// This is in maths, not C
f(x) = 2x + 1 for all integer x >= 0
Out of many ways, this one way to describe the function which maps 0 to 1, then 1 to 3, then n to 2n + 1. If we wanted to define the exact same function recursively:
// In maths
f(x = 0) = 1 for x = 0
f(x > 0) = f(x-1) + 2 for integer x > 0
You see what's going on in there? It's saying that each subsequent f(x) is 2 greater than the previous one f(x-1). But more importantly, the function is calling itself! If you look closer, the called function f(x-1) will also call itself:
f(x) = f(x-1) + 2
f(x) = f(x-2) + 2 + 2
f(x) = f(x-3) + 2 + 2 + 2
...
// all these are the same
All this calling deeper and deeper has to end somewhere, and that somewhere is when f(x-...) is f(0), which has been explicitly defined to be 1.
This is what recursion is all about. Let me write out the examples I gave above in C:
// non-recursive version
int fnonrec( int x ){
return 2 * x + 1;
}
// recursive version
int frec( int x ){
if ( x == 0 )
return 1; // explicit return value for f(0)
else // redundant else, hehe
return frec( x - 1 ) + 2;
}
Definitions of the functions really look similar to how they were defined in maths, don't they? Yeah, well, I don't think giving you the answer for your question would be nice of me. All I can say is that you can print things in reverse really nicely with recursive functions.

//store user input to int variable "value"
char str[15];
sprintf(str, "%d", value);
You can then use the strrev function to reverse the string array. Manipulate it from there.

#include <stdio.h>
void print(int v){
static char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine"
};
int digit = v % 10;
int value = v / 10;
if(value){
print(value);
printf(" %s", numbers[digit]);
} else
printf("%s", numbers[digit]);
}
int main(void){
int value;
printf("enter:");
scanf("%i", &value);
print(value);
return 0;
}

Example using recursive function and numbers from the parameters :
#include <stdio.h>
void display(char c)
{
char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine "
};
printf("%s ", numbers[c]);
}
int aff_num(char *c)
{
if (*c == '\0')
return (0);
display(*c-48);
aff_num(++c);
return (1);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Need numbers\n");
return (-1);
}
aff_num(argv[1]);
return (0);
}

I'm a python hacker and I almost never program in C. that being said:
#include <stdlib.h>
#include <stdio.h>
int highest_power_of_ten(int value){
int exponent = 0;
int tens = 1;
while(value > tens){
tens *= 10;
exponent += 1;
}
return exponent-1;
}
int pow(int base, int exponent){
if (exponent == 0)
return 1;
int temp = base;
while(exponent > 1){
base *= temp;
exponent -= 1;
}
return base;
}
int main(int argc, char** argv){
char* digits[] =
{"zero","one","two","three","four","five","six","seven","eight","nine"};
int value, n, exp, x;
scanf("%i", &value);
while(highest_power_of_ten(value)>0){
exp = highest_power_of_ten(value);
x = pow(10, exp);
n = value/x;
printf("%s ",digits[n]);
value -= n*x;
}
printf("%s\n", digits[value]);
//system("PAUSE"); for windows i guess
return 0;
}

Another method to get the digits in the right order:
E.g. To get the digit at 1st position in 123 divide 123 by 100, to get 2nd - 123 / 10, to get 3rd 123 / 1. That equals: value / 10^(index of desired digit)
So what we have to do is
Get the length of the (remaining) number by calculating log10(value).
Then get the (remaining) first (most significant) digit by dividing value by 10^length (length of 1.)
calculate value := value - 10^length and start from 1, unless the result is 0 (mind handeling numbers that end on 0).
while (value)
{
len = log10(value);
digit = (int) value / pow(10, len);
value -= pow(10, len);
}
And your code does never enter case 0. To fix that just leave the if(digit != 0) - that's what I meant when I wrote "mind the 0").
if(digit != 0) // enters if digit is not 0
{
switch(digit)
{
case 0: // enters if digit is 0
...
}
}

Related

Counting the number of zero in an integer

The program would ask the user an integer input.
and it counts how many zero the int has.
constraints: use while loop
ex:
input: 2400
count: 2
now I have no problem in that part, only when the user would input a zero.
supposed it counts 1.
ex:
input 0
count: 1
but then the program returns count 0.
here's the code:
int main(){
int n, counter = 0;
printf("Enter the number: ");
scanf("%d", &n);
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
printf("%d", counter);
return 0;
}
Use functions.
int countZeroes(int x)
{
int result = !x; // if x == 0 then result = 1
while(x)
{
result += !(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
printf("%d\n", countZeroes(0));
printf("%d\n", countZeroes(1000));
printf("%d\n", countZeroes(-202020));
}
https://godbolt.org/z/91hKr46eo
You have while(n != 0) this does so when you enter just 0 it doesn't run. So the counter that you have set to 0 at the beginning is still 0
Here is what I would have done :
int main()
{
int num, count = 0;
scanf("%d",&num);
if (num == 0) {
printf("1");
return 0;
}
while(num != 0) //do till num greater than 0
{
int mod = num % 10; //split last digit from number
num = num / 10; //divide num by 10. num /= 10 also a valid one
if(mod == 0) count ++;
}
printf("%d\n",count);
return 0;
}
Just don't forget to consider everything that can happen with a condition that you set
**Fixed it
A different version that prints the integer as a string, and looks for '0' characters in it. Tested.
#include <stdio.h>
#include <string.h>
int main(void)
{
int input = 0;
int zeroes = 0;
char *foundpos, teststring[100];
scanf("%d", &input);
sprintf(teststring, "%d", input);
foundpos = strchr(teststring, '0');
while (foundpos != NULL) {
++zeroes;
foundpos = strchr(foundpos + 1, '0');
}
printf("%d contains %d zeroes", input, zeroes);
}
Just count the zero digits you get between \n chars.
#include <stdio.h>
int main()
{
int ndigs = 0, c;
while ((c = getchar()) != EOF) {
switch (c) {
case '0': ndigs++;
break;
case '\n': printf(" => %d zero digs", ndigs);
ndigs = 0;
break;
}
putchar(c);
}
}
sample output:
$ ./a.out
123001202010
123001202010 => 5 zero digs
^D
$ _
No need to convert digits to a number, to convert it back to decimal digits. You can improve the program counting digits until a nondigit is detected, then output. But there's no need to convert a decimal representation of a number (in base 10) to internal representation to then get the digits you have destroyed (in the conversion) back again to count them.
As earlier mentioned, the problem is with the loop:
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
It doesnt do anything in case n == 0. But replacing it with n > 0 is not a good solution because ints can be negative too.
You should use do{}while() construction instead, it will always do one iteration of loop no matter what condition you put there. Notice that no matter what you get as a number, it is still a number so you can do one iteration of loop either way.
Just do as follows:
do{
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
} while( n != 0 );
This should work(if i didnt mess up the braces/semicolumns).

Evaluate a simple mathematical expression with limited tools, no arrays, and no library functions

Here's a question from the last year's first "Intro to programming" exam at my uni:
Using the getchar() function read an input sequence consisting of
numbers, + and - signs. The output should be the result of those
arithmetical operations.
For example, if the input is 10+13-12+25-5+100, the output should be 131.
Now, given that I have a little bit of C experience before attending uni, this problem seems easy to solve using pointers, arrays, etc.
But here's the catch: on the exam you can only use things that the students were taught so far. And given that this exam is only like a month after the start of the school year, your options are fairly limited.
You can only use variables, basic input/output stuff, operators (logical and bitwise), conditional statements and loops, functions.
That means no: arrays, strings, pointers, recursion, structures, or basically any other stuff that makes this easy.
How in the hell do I do this? Today is the second time I've spent 3 hours trying to solve this. I have solved it successfully, but only after "cheating" and using arrays, string functions (strtol), and pointers. It's important for me to know how to solve it by the rules, as I'll have similar stuff on the upcoming exam.
Edit: my attempts so far have amounted to using the while loop combined with getchar() for input, after which I just get stuck. I don't have the slightest idea of what I should do without using more "tools".
The solution is quite simple, but it might not be obvious for a beginner. I will not provide a complete program, but rather outline the steps needed to implement this with only a few variables.
First of all, it's important to notice two things:
Your input can only contain one of -, + or any digit (0123456789).
The getchar() function will read one character of input at a time, and will return EOF when the end of the input is reached or an error occurs.
Now, onto the solution:
Start by reading one character at a time, in a loop. You will only stop if you reach end of input or if an error occurs:
int c;
while ((c = getchar()) != EOF) {
// logic here
}
Start with an accumulator set to 0, and "add" digits to it every time you encounter a digit.
// outside the loop
int acc = 0;
// inside the loop
if (/* c is a digit */)
acc = acc * 10 + (c = '0');
Hint: that /* c is a digit */ condition might not be simple, you can put this in the else of the check for - and +.
Every time you encounter either - or +, remember the operation, and each time you encounter an operator, first perform the previous operation and reset the accumulator.
// outside the loop
int op = 0;
int result = 0;
// inside the loop
if (c == '+' || c == '-') {
if (op) {
// there already is a previous operation to complete, do it
if (op == '+')
result += acc;
else
result -= acc;
} else {
// first operation encountered, don't do anything yet
result = acc;
}
acc = 0; // reset
op = c; // remember the current operation for the future
}
When you reach the end of the input (i.e. you exit the loop), perform the last operation (same logic inside the if from point 3).
Output the result:
You would normally write something like:
printf("%d\n", result);
However, if you cannot use string literals ("%d\n") or the printf() function, you will have to do so manually using putchar(). This is basically the opposite of what we did before to scan numbers into an accumulator.
Print the sign first if needed, and make the value positive:
if (result < 0) {
putchar('-');
result = -result;
}
Find the maximum power of 10 that is lower than your number:
int div = 1;
while (result / div / 10)
div *= 10;
Use the power to extract and print each digit by division and modulo by 10:
while (div) {
putchar('0' + ((result / div) % 10));
div /= 10;
}
Note: the '0' + at the beginning is used to convert digits (from 0 to 10) to the relative ASCII character.
End with a newline:
putchar('\n');
When writing a parser, I typically find myself that I "buffer" the next operation that "will be done". When the input changes state - you are reading digits, but then you read an operation - then you execute the "buffered" action and buffer the next operation that will be done in the future.
Example:
10+13-12
^^ - we read 10
^ - result=10 - we buffer that we *will* have to do + in the future
^^ - reading 13
^ - och we stopped reading numbers!
we execute _buffered_ operation `+` , so we do result += 13
and buffer `-` to be done in the future
^^ - we read 12
^ - och, EOF! we execute buffered operation `-` , so we do result -= 12
- etc.
The code:
#include <stdio.h>
int main() {
int result = 0; // represents current result
int temp = 0; // the temporary number that we read into
int op = 0; // represents the _next_ operation that _will_ be done
while (1) {
int c = getchar();
switch (c) {
// we read an operation, so we should calculate _the previous_ operation
// or this is end of our string
case '+': case '-': case EOF:
if (op == 0) {
// we have nothing so far, so start with first number
result = temp;
} else if (op == '+') {
result += temp;
} else if (op == '-') {
result -= temp;
}
// the next operation we will do in future is stored in op
op = c;
// current number starts from 0
temp = 0;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
// read a digit - increment temporary number
temp *= 10;
temp += c - '0';
break;
}
// we quit here, the result for last operation is calculated above
if (c == EOF) {
break;
}
}
printf("%d\n", result);
// As I see it was mentioned that "%d\n" is a string,
// here's the simplest algorithm for printing digits in a number.
// Extract one digit from the greatest position and continue up
// to the last digit in a number.
// Take negative numbers and throw them out the window.
if (result < 0) {
putchar('-');
result = -result;
}
// Our program currently supports printing numbers up to 10000.
int divisor = 10000;
// 000100 should print as 100 - we need to remember we printed non-zero
int was_not_zero = 0;
while (divisor != 0) {
// extract one digit at position from divisor
int digit = result / divisor % 10;
// if the digit is not zero, or
// we already printed anything
if (digit != 0 || was_not_zero) {
// print the digit
putchar(digit + '0');
was_not_zero = 1;
}
// the next digit will be to the right
divisor /= 10;
}
putchar('\n');
}
#include <string.h>
#include <stdio.h>
void operate(int * sum, int * n, char todo) {
if (todo == 1) *sum += *n;
else if (todo == -1) *sum -= *n;
printf("%s %d\n", todo == 1 ? "ADD :" : "SUB :", *n);
*n = 0;
}
int main()
{
char * problem = "10+13-12+25-5+100";
int len = strlen(problem);
int i=0;
char c;
int n = 0;
int sum = 0;
char todo = 1;
while(i < len)
{
c = problem[i++];
if (c < 48 || c >= 58)
{
// Adds or subtracts previous and prepare next
operate(&sum, &n, todo);
if (c == '+') todo = 1;
else if (c == '-') todo = -1;
}
else
{
// Collects an integer
if (n) n *= 10;
n += c - 48;
}
}
operate(&sum, &n, todo); // Last pass
printf("SUM => %d\n", sum); // => 131
return 0;
}
#include <stdio.h>
void do_operation(char next_operation, int * result, int * number){
if (next_operation == '+'){
*result += *number;
*number = 0;
} else if (next_operation == '-'){
*result -= *number;
*number = 0;
} else {
printf("Unknown operation error.");
}
}
int main(int argc, char *argv[]){
char c;
int number = 0;
int result = 0;
char next_operation = '+';
do {
c = getchar();
if( c >= '0' && c <= '9' ){
number = number * 10 + c - 48;
} else if (c == '+'){
do_operation(next_operation, &result, &number);
next_operation = '+';
} else if (c == '-'){
do_operation(next_operation, &result, &number);
next_operation = '-';
} else {
do_operation(next_operation, &result, &number);
}
} while (c != '\n');
printf("%d", result);
}

How to split an arbitrary long input integer into pair of digits?

Expected Input:
123456
Expected output:
12
34
56
I have tried in this way
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, count = 0;
int value = 10000;
/*This for input validation. User can give exactly 6 digit as an input If
user breaks this condition then It
will redirect back to take input again */
while (1)
{
int countUpdate = 0;
int quotientUpdate = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
while (quotientUpdate != 0)
{
quotientUpdate = numberUpdate / 10;
numberUpdate = quotientUpdate;
countUpdate++;
}
if (countUpdate > 6 || countUpdate < 6)
{
printf("It allows exactly 6 digits\n");
}
else
{
break;
}
}
//This for finding the pair of two consecutive digits.
while (quotient != 0)
{
count++;
if (count == 4)
{
break;
}
quotient = number / value;
remainder = number % value;
if (count != 2)
printf("%d\n", quotient);
if (count == 1)
{
number = remainder;
}
else
{
number = quotient;
}
if (count == 1)
{
value = value / 1000;
}
if (count == 3)
{
remainder = remainder * 10 + 6;
printf("%d\n", remainder);
}
}
return 0;
}
My problem is: I have made this for the exact input 6 digits. From my code, I did not get the expected output. Output comes from my code like:
If a user gives an input 987654
Output shows:
98
76
56
But my expectation is:
98
76
54
Here is another problem: this code does not work for less than 6 or greater than 6 digits. But I want to solve this problem for any number of digit.
Can you help me identifying and solving my problem?
Your solution is a bit overcomplicated.
If you want to use integers, you could do it like this (untested).
Depending on range for your number, you might change to long long.
#include <stdio.h>
int main(void)
{
int number;
int digits = 1;
while (digits & 1)
{ // loop until we get an even number
printf("Enter a number: ");
int ret = scanf("%d", &number);
if (ret != 1)
continue;
// count number of digits
digits = 0;
while (number != 0)
{
number /= 10;
digits++;
}
if (digits & 1)
printf("Please enter even number of digits.\n");
}
// If we are here, we have 2, 4, 6, ... digits
// Calculate divider to chop first 2 digits
int divider = 1;
while (digits > 2)
{
divider *= 100;
digits -= 2;
}
// chop remaining digits and print 2 of them
while (divider)
{
pair = (number / divider) % 100;
printf("%d\n", pair);
divider /= 100;
}
return 0;
}
Another option would be to use strings instead of numbers and then simply print 2 characters per line.
I've updated your code a bit, it should be working and handle the "0" digit within the code. For the "0" digit at the beginning of the code, you should input a string and not a number.
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, count = 0;
int countUpdate = 0;
int value = 10000;
/*This for input validation. User can give exactly 6 digit as an input If
user breaks this condition then It
will redirect back to take input again */
while (1)
{
int quotientUpdate = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
while (quotientUpdate != 0)
{
quotientUpdate = numberUpdate / 10;
numberUpdate = quotientUpdate;
countUpdate++;
}
if (countUpdate < 2 || countUpdate % 2 != 0)
{
printf("Even number of digits only\n");
}
else
{
break;
}
}
count = countUpdate / 2;
numberUpdate = number;
int d[count];
for (int i = 0; i < count; i++)
{
d[i] = numberUpdate % 100;
numberUpdate /= 100;
}
for (int i = count - 1; i >= 0; i--)
{
if (d[i] < 10) printf("0");
printf("%d\n", d[i]);
}
return 0;
}
Before proposing my solution, I'll try to explain what's wrong in your code.
Analysis of the original code
First of all, since you have currently the fixed length limitation, your loop that checks if the number has exactly 6 digits can be omitted; the same check can be performed just checking the range:
if (number < 1000000 || number > 999999)
{
printf("It allows exactly 6 digits\n");
}
else
{
break;
}
The core of your logic is in the loop while (quotient != 0). It contains a lot of strange attempts you perform in order to compensate the previous mistake. It leads to the final reminder with a single digit instead of two, so you try to compensate it with this line
remainder = remainder * 10 + 6;
this obviously works only if the last digit is 6.
The root of the problem is in this row:
if (count == 1)
{
value = value / 1000;
}
But why 1000? value represents the divider in the next loop, so you want it to obtain a reminder with two digit less (instead of 3), so the correct division is value = value / 100;.
All the subsequent correction come after this one. The other answers widely cover the correct solution storing the input within an integer.
A solution involving strings
Since you need a solution with any number of digits, you must be aware that using an int you'll be able to manage at most 10 digits (because the maximum value of an integer is INT_MAX (2147483647).
Using an integer you'll only be limited by the size of the string buffer you choose.
That's the code. Our only limitation is forcing the user to insert only an even number of digits:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
// Put variables for further proceed
char number[101] = { 0 };
int isValid = 0, count = 0;
/*Input validation */
while(!isValid)
{
count = 0;
isValid = 1;
char *p = number;
printf("Enter a number: ");
scanf("%100s", number);
/* Check the validity of the string */
while(*p != '\0')
{
count++;
if(!isdigit(*p))
{
isValid = 0;
break;
}
p++;
}
if( !(isValid = isValid && ( count % 2 == 0 ) ) )
printf("Please insert an even number of digits (numbers only)\n");
}
/* Print the digits*/
for(int i=0; i<count; i+=2)
printf("%c%c\n", number[i], number[i+1] );
return 0;
}
I defined an array of 101 characters (100 + one for the string terminator) and I say scanf to store up to 100 characters (%100s)
I complicated a bit the input validator just to avoid to loop twice through the string (the first using strlen(), needed to check the even digits requirement,and the second to check the digits-only requirement)
In the end I just print two characters at a time using %c format specifier reading them from the string number
The output:
Enter a number: 1234567 // Test the check on an input with an odd number of digits
Please insert an even number of digits (numbers only)
Enter a number: 1234567A // Test the check on an input containing a non-digit char
Please insert an even number of digits (numbers only)
Enter a number: 1234567890123456 // Well formed input
12
34
56
78
90
12
34
56
Here is my solution to this problem. Hope it satisfy your requirement.
#include <stdio.h>
int main()
{
// Put variables for further proceed
int number, remainder, quotient = 1, numberUpdate, temp,count = 0;
int value = 1;
printf("Enter a number: ");
scanf("%d", &number);
numberUpdate = number;
temp = number;
if(number < 100) {
printf("%d",number);
} else {
while(numberUpdate > 100) {
value = value*100;
numberUpdate = numberUpdate/100;
}
while (temp > 0)
{
temp = number/value;
number = number%value;
value = value/100;
printf("%d\n",temp);
}
}
return 0;
}

How to show the digits which were repeated in c?

The question is that show the digits which were repeated in C.
So I wrote this:
#include<stdio.h>
#include<stdbool.h>
int main(void){
bool number[10] = { false };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == true)
{
printf("%d ", digit);
}
number[digit] = true;
n /= 10;
}
return 0;
}
But it will show the repeated digits again and again
(ex. input: 55544 output: 455)
I revised it:
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == 1)
{
printf("%d ", digit);
number[digit] = 2;
}
else if (number[digit] == 2)
break;
else number[digit] = 1;
n /= 10;
}
return 0;
}
It works!
However, I want to know how to do if I need to use boolean (true false), or some more efficient way?
To make your first version work, you'll need to keep track of two things:
Have you already seen this digit? (To detect duplicates)
Have you already printed it out? (To only output duplicates once)
So something like:
bool seen[10] = { false };
bool output[10] = { false };
// [...]
digit = ...;
if (seen[digit]) {
if (output[digit])) {
// duplicate, but we already printed it
} else {
// need to print it and set output to true
}
} else {
// set seen to true
}
(Once you've got that working, you can simplify the ifs. Only one is needed if you combine the two tests.)
Your second version is nearly there, but too complex. All you need to do is:
Add one to the counter for that digit every time you see it
Print the number only if the counter is exactly two.
digit = ...;
counter[digit]++;
if (counter[digit] == 2) {
// this is the second time we see this digit
// so print it out
}
n = ...;
Side benefit is that you get the count for each digit at the end.
Your second version code is not correct. You should yourself figured it out where are you wrong. You can try the below code to print the repeated elements.
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] > 0)
{
number[digit]++;;
}
else if (number[digit] ==0 )
number[digit] = 1;
n /= 10;
}
int i=0;
for(;i<10; i++){
if(number[i]>0)
printf("%d ", i);
}
return 0;
}
In case you want to print the repeated element using bool array (first version) then it will print the elements number of times elements occur-1 times and in reverse order because you are detaching the digits from the end of number , as you are seeing in your first version code output. In case you want to print only once then you have to use int array as in above code.
It is probably much easier to handle all the input as strings:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[256] = { 0 }; /* string to read */
char rep[256] = { 0 }; /* string to hold repeated digits */
int ri = 0; /* repeated digit index */
char *p = str; /* pointer to use with str */
printf ("\nEnter a number: ");
scanf ("%[^\n]s", str);
while (*p) /* for every character in string */
{
if (*(p + 1) && strchr (p + 1, *p)) /* test if remaining chars match */
if (!strchr(rep, *p)) /* test if already marked as dup */
rep[ri++] = *p; /* if not add it to string */
p++; /* increment pointer to next char */
}
printf ("\n Repeated digit(s): %s\n\n", rep);
return 0;
}
Note: you can also add a further test to limit to digits only with if (*p >= '0' && *p <= '9')
output:
$./bin/dupdigits
Enter a number: 1112223334566
Repeated digit(s): 1236
Error is here
if (number[digit] == true)
should be
if (number[digit] == false)
Eclipse + CDT plugin + stepping debug - help you next time
As everyone has given the solution: You can achieve this using the counting sort see here. Time complexity of solution will be O(n) and space complexity will be O(n+k) where k is the range in number.
However you can achieve the same by taking the XOR operation of each element with other and in case you got a XOR b as zero then its means the repeated number. But, the time complexity will be: O(n^2).
#include <stdio.h>
#define SIZE 10
main()
{
int num[SIZE] = {2,1,5,4,7,1,4,2,8,0};
int i=0, j=0;
for (i=0; i< SIZE; i++ ){
for (j=i+1; j< SIZE; j++){
if((num[i]^num[j]) == 0){
printf("Repeated element: %d\n", num[i]);
break;
}
}
}
}

Decimal to Binary conversion using recursion with while loop

my binary conversion doesn't work after it recurs a second time, it seems to work only during the first time through. The purpose of the is have a user input a number to convert to Hex, Octal, and brinary from a integer and keep on asking and converting until the user inputs 0. Please help!
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
long toBinary(int);
int main(void) {
int number = 0;
long bnum;
int zero = 0;
while(number != zero) {
puts("\nPlease enter a number you would like to convert to");
puts("\nHexadecimal, octal, and binary: ");
scanf("%d", &number);
if(number != zero) {
printf("\nThe Hexadecimal format is: %x", number);
printf("\nThe Octal format is: %o", number);
bnum = toBinary(number);
printf("\nThe binary format is: %ld\n", bnum);
}
else {
puts("\nI'm sorry you have to enter a number greater than 0.\n");
puts("\nOr have enter an invalid entry.");
}
}
return 0;
}
long toBinary(int number) {
static long bnum, remainder, factor = 1;
int long two = 2;
int ten = 10;
if(number != 0) {
remainder = number % two;
bnum = bnum + remainder * factor;
factor = factor * ten;
toBinary(number / 2);
}
return bnum;
}
You just need a function to convert an integer to its binary representation.
Assuming the int is 32 bits then this should work:
#include <stdio.h>
int main()
{
char str[33];
str[32] = 0;
int x = 13, loop;
for (loop = 31; loop >= 0; --loop) {
str[loop] = (x & 1) ? '1' : '0';
x = x >> 1;
}
printf("As %s\n", str);
return 0;
}
You can make this into a function, read x etc...
EDIT
For octal/hex - printf will do this for you
EDIT
Here goes recursively
#include <stdio.h>
void PrintBinary(int n, int x) {
if (n > 0) {
PrintBinary(n - 1, x >> 1);
}
printf("%c",(x & 1) ? '1' : '0');
}
int main()
{
PrintBinary(32,12);
return 0;
}
First of all I am surprised it even works once. Firstly, your while condition is while number does not equal zero. But right off the bat, number equals 0 and zero equals 0. Therefore the while should never run. If you want to keep this condition for the main loop, change it to a do-while loop: do { //code } while (number != zero);. This will run the code at least once, then check if the inputted number doesn't equal zero. That brings me to the next issue; your scanf for number is scanning for a double and placing it in a regular integer memory spot. Quick fix: scanf("%i",&number);. Also I am finding some functions called puts.. I find it best to keep with one printing function, printf. Now, I am finding afew errors in your toBinary function, but if it works than I guess it works. These are all the errors i could find, I hope this helped. But for future reference there is no need to declare a variable for a const number like 2 or 10 at this level.
#include <stdint.h>
char* toBinary(int32_t number, int index){
static char bin[32+1] = {0}, *ret;
if(index == 32){
memset(bin, '0', 32);
return toBinary(number, 31);
} else if(number & (1<<index))
bin[31-index] = '1';
if(index)
(void)toBinary(number, index-1);
else
for(ret = bin; *ret == '0';++ret);
return ret;
}
...
int number = -1;
...
printf("\nThe binary format is: %s\n", toBinary(number, 32));

Resources