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

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;
}

Related

How to make 123 become 122333

Please tell me how to print num in the same form as 122333 when num = 123 is entered in c.
I can make a repetition of a number separately, but I can't print it out by adding it to num.
you can get the number of digits first in your desired number, then you can get digit by digit from the left using the equation digit = num / (10^(numOfDigits)) % 10 where numOfDigits is just a variable used to indicate which digit to extract right now.
so when you get digit by digit you can use for-loop to loop digit times on that digit to be printed.
so you can do something like:
#include <stdio.h>
#include <math.h>
int main() {
int num = 123;
int numOfDigits = 0;
int dummy = num;
// finding number of digits
while (dummy != 0)
{
// increment number of digits
numOfDigits++;
// go to next digit
dummy /= 10;
}
printf("output = ");
while (numOfDigits != 0){
// get the current digit
int digit = (num / (int)pow(10,(numOfDigits-1))) % 10;
for (int i = 0; i < digit; ++i) {
// print the number
printf("%d", digit);
}
// go to next digit
numOfDigits--;
}
printf("\n");
return 0;
}
and this is the output:
output = 122333

Count How many zeroes in the inputed number?

Write a program that takes an integer and
prints the number of trailing zeroes.
Example:
Enter the number: 24100
Trailing zeroes: 2
I have no Idea what condition to create to determine the number of zeroes in a number.
You could use a modulus trick here:
int input = 24100;
int num_zeroes = 0;
while (input > 0) {
if (input % 10 == 0) {
num_zeroes = num_zeroes + 1;
input = input / 10;
}
else {
break;
}
}
printf("%d", num_zeroes); // 2
int cnt = 0; while( input && input % 10 == 0) cnt++, input /= 10;
But, if you think you'll have access to SO when you are sitting the proficiency tests when applying for jobs, you are sadly mistaken.

How can check if the digits of a number are prime and if so multiply them in C

The problem says that the user will input numbers till he inserts 0 (exit) then if there are any prime digits in that given number, the program shall multiply them.
For example:
input : 4657
output : 35 ( 5 * 7 )
Here is what I have tried so far but I cannot pull it off with the multiplication... my code might look a little bit clumsy, I am a beginner :)
int main() {
int number;
int digit, prime;
int i, aux;
int multiplier;
input:
printf("Give Number :");
scanf("%d", &number);
do {
multiplier = 1;
digit = number % 10;
number = number / 10;
printf("%d \n", digit);
prime = 1;
for (i = 2; i <= sqrt(digit); i++) {
if (digit % 1 == 0) {
prime = 0;
}
}
if (prime != 0) {
multiplier = multiplier * digit;
}
} while (number != 0);
printf("The result : %d\n", multiplier);
goto input;
return 0;
}
There are multiple problems in your code:
missing #include <stdio.h>
use of label and goto statement to be avoided at this stage.
testing for prime digits can be done explicitly instead of a broken loop.
digit % 1 == 0 is always true, you should write digit % i == 0 (maybe a typo from copying someone else's code?
i <= sqrt(digit) will not work unless you include <math.h> and still a bad idea. Use i * i < 10 instead.
0 and 1 should not be considered primes.
it is unclear what the output should be if none of the digits are prime, let's assume 1 is OK.
Here is a modified version:
#include <stdio.h>
int main() {
for (;;) {
int number, multiplier;
printf("Give Number :");
if (scanf("%d", &number) != 1 || number <= 0)
break;
multiplier = 1;
while (number != 0) {
int digit = number % 10;
number = number / 10;
if (digit == 2 || digit == 3 || digit == 5 || digit == 7)
multiplier *= digit;
}
printf("The result: %d\n", multiplier);
}
return 0;
}

Checking if each digit is divisible by 2

I am writing a C program to ask the user to enter in a pin code and checks if each digit in the number is divisible by 2. For instance, if they enter 123452 it tells the user that it is wrong because 1,2,3,5 isn't divisible by 2. If I enter 642642 it says it is fine but if I enter in 622248 it displays invalid number, which is wrong because every digit in 622248 is divisible by 2. How can I fix this error?
#include <stdio.h>
#define N 6
int main(void)
{
int num, digits[N], i, invalid, count = 1, sum = 0;
TOP:
printf("Enter pin code (attempt %d): ", count++);
scanf("%d", &num);
invalid = num;
// stores each digit of the number entered into the the array
for (i = 6; i >= 0; i--) {
digits[i] = num % 10;
num = num / 10;
}
// if the user enters more than 6 digits than it will give you an error.
if (digits[N] > 6) {
printf("Code %d is invalid!\n", invalid);
goto TOP;
}
// loops through the array elements and see if each digit is divisble by 2, if not then print an error.
for (i = 0; i < 6; i++) {
if (digits[i] % 2 != 0) {
printf("Code %d is invalid!\n", invalid);
goto TOP;
}
else {
printf("Congratulation, code %d is valid!\n", invalid);
break;
}
}
return 0;
}
If you are permitted to process the input as a string, rather than an integer, all that is needed is strspn to determine the validity of the digits in the pin and strlen to determine the validity of the length:
#include <string.h>
size_t len = strlen(str_pin);
if (len <= 6 && strspn(str_pin, "24680") == len)
{
puts("Valid pin");
}
else
{
puts("Invalid pin");
}
There's a problem with how you're storing the digits:
for (i = 6; i >= 0; i--) {
digits[i] = num % 10;
num = num / 10;
}
The length of the array digits is 6, meaning that valid indexes go from 0 to 5, but you start reading into index 6. This writes past the bounds of the array invoking undefined behavior.
Change the loop to start at 5.
for (i = 5; i >= 0; i--) {
digits[i] = num % 10;
num = num / 10;
}
This check is also invalid:
if (digits[N] > 6) {
Because it again reads past the end of the array. Even if it did not read past the end, you're checking if an element of the array is greater than 6, not if there are more than 6 digits.
You divide num by 10 in a loop to get the digits, so if this value is non zero then you know there are too many digits.
if (num > 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;
}
}
}
}

Resources