C programming Q/A

Q5) You are given a non decreasing sorted sequence of non negative integers, ending with -1. That is if the sequence is a1,a2,…,an,−1 then ai≤ai+1 for all i from 1 to n-1. You can assume that are at least two numbers before the ending -1. You have to output the number of distinct elements in the sorted sequence.

    
    #include 

int main() {
  int n, last_number = -1, count = 0;
  while (scanf("%d", &n) && n != -1) {
    if (n != last_number) {
      count++;
      last_number = n;
    }
  }
  printf("%d\n", count);
  return 0;
}
     
Previous Post Next Post