Write a function which, given a string, returns 0 if all its letters are distinct otherwise returns 1.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <string.h>
#define MAX 100

void get_line(char *, int);
int check_string(char *, int);

int main(int argc, char ** argv) {
    char line[MAX];
    get_line(line, MAX);
    if(check_string(line, strlen(line)))
        printf("String has repeated letters\n");
        printf("All letters are distinct\n");

    return 0;

void get_line(char line[], int N) {
    char c;
    int i;
    for (i = 0; i < N-1 && (c = getchar()) != '\n'; i++)
        line[i] = c;
    line[i] = '\0';

int check_string(char line[], int N) {

    for (int i = 0; i < N-1; i++) {
        for(int j = i+1; j < N; j++) {
            if (line[i] == line[j])
                return 1;
    return 0;

When you compile and execute the above program it produces the following result on Linux:

Case 1: The word "Great" is used as input.

All letters are distinct

Case 2: The word "Good" is used as input

String has repeated letters

Brief Explanation

  • The program starts by using the function get_line to get the next input line and stores the result in the array line. It does so by using the function getchar to read a character at a time from input until it reaches a new line (\n). Each character read is stored in the array line. Once the for loop is exited, the variable i is one place after the last character in the array. The null character (\0) is assigned to this position to ensure termination.
  • The function check_string is then used to determine if all the letters in the string are distinct or not. The function takes two parameters (the line read and the length of the line). The function takes the first character in the string and compares with every other character, if there is a match, it returns 1 otherwise it takes the next character and compares it with every other character following it. It keeps doing the comparison and returns 1 as soon as a match is found or 0 once the outer loop is exited (meaning all the letters in the string are distinct).

Add comment

Security code