Write a program that reads in an integer number and checks whether any of the di
ID: 3621680 • Letter: W
Question
Write a program that reads in an integer number and checks whether any of the digits in the number appear more than once. Allow the user to repeat the process as many times as he likes. (allow for y/Y/n/N as responses)
Sample run:
Enter a number: 31345
It has a repeated digit
Do you want to enter another number? (y/n) : y
Enter a number: 12345678
No repeated digit
Do you want to enter another number? (y/n) : n
Plan: Use an array called digits_seen of size 10 whose base type is Boolean. It will be indexed from 0 to 9, which corresponds to the 10 possible digits a number can have.. Initially all the entries in the array should be set to false.
When the user enters his number n, the program reads in the entire integer and then examines each digit in n and sets the appropriate index entry in the array to true to indicate that it has been seen. If when it goes to do this, the entry is already true then you know you have encountered a duplicate!
HINT: use type long int to store the input number read in…so you can hold a lot of digits. Note that you reading a single integer and then dissecting it into digits.
Remember you can dissect the number read in by using % and integer division.
A quick example
Digit_seen is initially…..[false| false| false |false| false |false| false| false| false| false] remember the index runs from 0 to 9
Suppose the input number is 2131
You peel off the 1 and the array becomes
Digit_seen [false| true| false |false| false |false| false| false| false| false]
the true in position 1 indicates that you have seen a 1
Then peel off the 3
Digit_seen becomes [false| true| false |true| false |false| false| false| false| false]
the true in position 3 indicates that you have seen a 3
Then peel off the 1
When you look at Digit_seen [false|true| false |true| false |false| false| false| false| false]
When you go to pposition 1, you see that there is already a true there….that is you found a duplicate!
Explanation / Answer
#include<stdio.h>
#include<conio.h>
int main()
{
long int k;
int a[10];
int p;
int i;
char o;
do{
int rep=0;
printf(" Enter A Number :");
scanf("%ld",&k);
for(i=0; i<10;i++)
a[i]=0;
while(k>0)
{
p = k %10;
if(a[p]==1)
{
rep =1;
break;
}
a[p]=1;
k= k/10;
}
if(rep)
printf("It has a repeated digit");
else
printf("No repeated digit");
printf(" Do you want to enter another number? (y/n)");
o = getch();
}while(o=='y');
getch();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.