Lets write a C program to check if any digit in a user input number appears more than once.
Note: Any positive integer number can be formed using only 0-9 digits. So we take an array with length 10. i.e., 0 to 9
Page Contents
#include<stdio.h>
int main()
{
int a[10] = {0}, num, rem;
printf("Enter a positive number\n");
scanf("%d", &num);
while(num)
{
rem = num % 10;
if(a[rem] == 1)
break;
else
a[rem] = 1;
num = num / 10;
}
if(num)
printf("There are repetition of digits in the number\n");
else
printf("There are no repetition of digits in the number\n");
return 0;
}
Output 1:
Enter a positive number
123
There are no repetition of digits in the number
Output 2:
Enter a positive number
156
There are no repetition of digits in the number
Output 3:
Enter a positive number
1232
There are repetition of digits in the number
1. Since there are 10 digits i.e., 0 to 9 to form any number, we take array size as 10. We initialize all the elements of array to 0.
Related Read:
Basics of Arrays: C Program
2. We ask the user to input a positive number.
3. We iterate through the while loop until num is zero.
Related Read:
while loop in C programming
4. By modulo dividing user input number by 10, we fetch individual digits of number. We make use of this individual digit as index of the array. We over-write the initial value(which is zero) and assign 1 at that index position.
So presence of value 1 at an index specifies that the digit already exists in the number.
Related Read:
Modulus or Modulo Division In C Programming Language
5. So based on the presence of value 1 or 0 at particular index, our program decides if the digit is present more than once in a number or not.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert