How to show the digits which were repeated in c? - 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;
}
}
}
}

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).

Programming C - Debugging Numbers-Strings Conversion Problems

I'm working on an exercise problem for a programming class and I'm a bit out of my depth debugging it. My main problem is that I have had to convert strings into integers and vice-versa and I don't understand well how that works. I'll attach a copy of the exercise and another of my code. Any and all help is appreciated.
CODE:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
string Company_Check(long number);
bool Luhn (long number);
int main(void)
{
//Prompt for card Number
long card = get_long("Number:");
//Applying Luhn's Algorithm
bool validity = Luhn(card);
if (validity==true) //The card passed the test
{
//Finding and printing company name
printf("\nCompany: %s\n", Company_Check(card));
} else //The card didn't pass the test
{
printf("INVALID (Luhn’s Algorith)\n");
}
}
string Company_Check(long number)
{
//Declaring variables
char num[30];
char char_first_two[3]; //This is where I'll save the first two digits of the number
int int_first_two;
char char_first_one[3]; //This is where I'll save the first one digit of the number
int int_first_one;
//Creating the two 'First digits' var
int first_two = 10*(atoi(num[0]))+ atoi([num[1]);
int fist_one = atoi(num[0]);
//Analizing cases
if (first_two == 34 || first_two == 37)
{
printf("American Express\n");
} else if (first_two == 51 || first_two == 52 || first_two == 53 || first_two == 54 || first_two == 55)
{
printf("Mastercard\n");
} else{
//Could be (1) Visa or (2) INVALID
if (first_one == 4)
{
printf("Visa\n");
} else
{
printf("INVALID\n");
}
}
}
bool Luhn (long number) //Done
{
int i; //Used in the for loops
int sum1; //Used to tally the sums in Step 4
int sum2; //Used to tally the sums in Step 4
int total; //Used to tally the sums in Step 4
int cod; //Counter of Digits
int lastnumber; //Used in Steps 5 and 6
char num[30]; //Card number & total in String format
char fot[30]; //First Every-Other number list
char sot[30]; //Second Every-Other number list
//1. Converting the long NUMBER to a string NUM
sprintf(num, "%d", number);
//2. Calculating the number of digits of the number
cod = 0;
for(i=0; num[i+1]!= '\0' ; i++)
{
cod++;
}
//3. Creating two CHAR arrays of the first and second every-other number list
if (cod%2==0)//number of digits is even
{
for(i=0; num[i+1]!= '\0' ; i++)
{
if (i%2==0) //We're dealing with the FIRST set of every other numbers
{
fot[i/2]=num[i];
}
else //We're dealing with the SECOND set of every other numbers
{
sot[((int)(i/2))+1]=num[i];
}
}
fot[(cod/2)+1]= '\0';
sot[(cod/2)+1]= '\0';
} else //number of digits is odd
{
for(i=0; num[i+1]!= '\0' ; i++)
{
if (i%2==0) //We're dealing with the SECOND set of every other numbers
{
sot[i/2]=num[i];
}
else //We're dealing with the FIRST set of every other numbers
{
fot[((int)(i/2))+1]=num[i];
}
}
sot[(cod/2)+1]= '\0';
fot[(cod/2)+1]= '\0';
}
//4. Sum Algorithm
sum1=0;
sum2=0;
total=0;
for(i=0 ; fot[i+1]!= '\0' ; i++)
{
sum1 =+ atoi(fot[i]);
}
for(i=0 ; sot[i+1]!= '\0' ; i++)
{
sum2 =+ atoi(sot[i]);
}
total = sum1 + sum2;
//5. Isolating the last number
//converting the total into a string (using var NUM because its no longer needed)
sprintf(num, "%d", total);
//Calculating the number of digits
cod = 0;
for(i=0; num[i+1]!= '\0' ; i++)
{
cod++;
}
//putting the last number in a var
lastnumber = atoi(num[cod-1]);
//6. Studying cases
if (lastnumber==0)
{
return true;
}
else
{
return false;
}
}
Problem:
Problem

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

Comparing digits of two inputs to see if they are the same

I am currently trying to finish a code where a user inputs two 5 digit long numbers. The code then checks to see if there are any identical numbers in the same spot for the two numbers and displays how many identical numbers there are in the same spot of the two inputs. (ex. comparing 56789 and 94712 there would be one similar digit, the 7 in the 3rd digit place.) As of now I have been able to break down the inputs into the digits in each spot, I just need help comparing them. Originally I thought I could just create an int that would serve as a counter and use modulus or division to output a 1 whenever the digits were the same, but I have been unable to put together a formula that outputs a 1 or 0 depending on if the digits are alike or not.
suppose you know the length of strings n (as a condition you would need them to be equal, if they differ in length other validation is needed)
//n is the length of string
for(int i=0;i<n;i++)
{
if(string1[i]==string2[i])
{
//do something, make a counter that increments here...
//also save index i, so you can tell the position when a match occured
}else
{
//do something else if you need to do something when chars didnt match
}
}
Here you when i=0, you are comparing string1[0] with string2[0], when i=1, you compare string1[1] with string2[1] and so on.....
I'd recommend reading the two in as strings or converting to strings if you have the ability to. From there it's a simple string compare with a counter. Something like this:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_numeric(char *str)
{
while (*str)
if (!isdigit(*str++))
return (0);
return (1);
}
int main(void)
{
char num1[32];
char num2[32];
int count = 0;
printf("Digit 1\n>> ");
if (scanf("%5s", num1) != 1 || !is_numeric(num1))
return (0);
printf("Digit 2\n>> ");
if (scanf("%5s", num2) != 1 || !is_numeric(num2))
return (0);
if (strlen(num1) != 5 || strlen(num2) != 5)
return (0);
for (int i=0; i<5; ++i)
if (num1[i] == num2[i])
++count;
printf("%d\n", count);
return (0);
}
You can do it very easy using modulo (%) and divide (/). First you do % 10 to get the least significant digit and do the compare. Then you do / 10 to remove the least significant digit. Like:
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1 || i1 < 10000 || i1 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1 || i2 < 10000 || i2 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
for (i=0; i<5; ++i)
{
if ((i1 % 10) == (i2 % 10)) ++cnt; // Compare the digits
i1 = i1 / 10;
i2 = i2 / 10;
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
It can also be done using strings. Read the input as unsigned int and then convert the value to a string using snprintf and finally compare the two strings character by character.
Something like:
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[32];
char str2[32];
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str1, 32, "%u", i1);
if (strlen(str1) != 5) // Convert to string
{
printf("input error - not 5 digits\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str2, 32, "%u", i2); // Convert to string
if (strlen(str2) != 5)
{
printf("input error - not 5 digits\n");
return 0;
}
for (i=0; i<5; ++i)
{
if (str1[i] == str2[i]) ++cnt; // Compare the characters
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
The reason for taking the input into a unsigned int instead of directly to a string is that by doing that I don't have to check that the string are actually valid numbers (e.g. the user type 12W34). scanf did that for me.

Using Array Integer

I'm new in C programming language.
I need to get every digit separately that user have entered.
Here is my code:
#include <stdio.h>
int main()
{
int n[100];
printf("Enter a number: ");
scanf("%d",&n);
printf("%d %d %d",n[1],n[2],n[3]);
return 0;
} //i know that my code is not assigning like i want.
and now for example user entered a number like 123, i want the output like 1 2 3, How can i assign every digit to n[i] ? Without using string to int or int to string like atoi? Here is what Im going to do: User will enter a number and the program will search from Matrix 100x100 in row or column. i think i need to get the every digit separately to search.
No need to go to character array. The lats digit of a number n can be computed using n%10. Then you can remove the last digit using n /= 10. So this cycle would print the digits in reverse order:
void print_rev_digits(int n) {
while (n) {
printf("%d\n", n%10);
n /= 10;
}
}
And using a stack you can print the digits in the correct order. You can also use recursion for this(which will use stack for you). I am deliberately not posting a complete solution.
In this case you should read the user input character by character:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main()
{
char input[100];
int n[100];
printf("Enter a number: ");
if (fgets(input, sizeof(input), stdin)) { // attempt to read a line
int i;
for (i = 0; input[i]; i++) { // for each entered character
if (input[i] >= '0' && input[i] <= '9') { // is a digit
n[i] = input[i] - '0';
printf("%d ", input[i] - '0');
}
else if (isspace(input[i])) // end of entered integer
break;
else {
printf(stderr, "Input is not a number\n");
return -1;
}
}
printf("\n");
} else {
fprintf(stderr, "User did not enter valid input.\n");
}
return 0;
}

Resources