Thread: Can anyone explain clearly the logic of this program?

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    17

    Can anyone explain clearly the logic of this program?

    This program checks whether any of the digits in a number entered by the user appear more than once. What I still can't understand is the code inside "if" statement. What's the idea behind that? We get each of the digits at a time, then that digit is used as an index for the array named "digit_seen"... and then digit_seen[digit] = true... It's confusing to me. Can anyone please explain this program clearly??? Thanks a lot.

    Code:
    #include<stdio.h>
    #include<stdbool.h>
    
    int main(void)
    {
    	bool digit_seen[10] = {false};
       int digit;
       long n;
    
       printf("Enter a number: ");
       scanf("%ld", &n);
    
       while(n > 0) {
       	digit = n % 10;
          if(digit_seen[digit])
          	break;
          digit_seen[digit] = true;
          n /= 10;
       }
    
    	if(n > 0)
       	printf("Repeated digit\n");
       else
       	printf("No repeated digit\n");
    
       return 0;
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Let's say the first digit is a 3, so digitseen[3]'s value is checked, and it is zero (false). Since we had a 3, we set digitseen[3] to 1 or true.

    Now along comes another 3, and again, we check the value of digitseen[3]. Now the value is 1 (true), so we know that we've had a 3 already.

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    17
    Quote Originally Posted by Adak View Post
    Let's say the first digit is a 3, so digitseen[3]'s value is checked, and it is zero (false). Since we had a 3, we set digitseen[3] to 1 or true.

    Now along comes another 3, and again, we check the value of digitseen[3]. Now the value is 1 (true), so we know that we've had a 3 already.
    Thanks a lot, Ada... That makes sense to me now...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program Plan
    By Programmer_P in forum C++ Programming
    Replies: 0
    Last Post: 05-11-2009, 01:42 AM
  2. Replies: 5
    Last Post: 01-31-2006, 01:54 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. logic on a program
    By officegirl in forum C Programming
    Replies: 0
    Last Post: 10-13-2001, 10:41 PM