write c program please

You are given a sequence of non-negative integers terminated by -1. You have to output 1 if there are atleast 2 distinct elements in the sequence and 0 if the sequence consists of only 1 integer. Note that -1 is not part of the sequence. The sequence is not necessarily sorted. Note: Don't use arrays to this question.


3 Answers
1-3 of  3
3 Answers
  • thank you..

  • The Question is not clear on "0 if the sequence consists of only 1 integer".
    1) Does this means that if there are same type of integers(duplicates) it should give 0 as output?
    2) If not then what needs be printed in the output if there are duplicate integers ?(This use case is not mentioned in the question)
    Below is th logic I have tried to write in C & java. Tested with the given input and output case sequence in both C & java.
    This logic holds true for the 2nd condition defined above and prints output as 2 if there are duplicates.

    C Implementation :

    int initial=0, num=0, output = 2;
    scanf("%d",&initial);
    scanf("%d",&num);
    if(num == -1)
    output = 0;
    else {
    initial = num;
    while(num != -1) {
    scanf("%d",&num);
    if(initial != num) {
    output = 1;
    break;
    }else if(initial == num) {
    scanf("%d",&num);
    }
    else {
    initial = num;
    }
    }
    }
    printf("%d",output);

    Java Implementation :

    int initial=0, num=0, output = 2;
    Scanner in = new Scanner(System.in);
    initial = in.nextInt();
    num = in.nextInt();
    if(num == -1)
    output = 0;
    else {
    initial = num;
    while(num != -1) {
    num = in.nextInt();
    if(initial != num) {
    output = 1;
    break;
    }else if(initial == num) {
    num = in.nextInt();
    }
    else {
    initial = num;
    }
    }
    }
    System.out.println(output);

    Test Cases :
    Input --> Output
    1 -1 --> 0
    1 2 -1 --> 1
    1 1 2 -1 --> 1
    1 2 3 -1 --> 1
    1 1 1 -1 --> 2

C Language

Didn't get the answer.
Contact people of Talent-C Language directly by clicking here