algorithmloopscounting

Counting numbers greater and less than input using 4 variables


I got a request for help with exercise (dedicated for primary school students) to prepare a program that counts numbers greater and less than input with limitation to using 4 int variables.

Write a program that reads one integer N. It will then read N integers and print out how many of these numbers were greater than N and how many were less than N.

I used kotlin for my attempts just for more readable example, but language doesn't matter.

val sc = Scanner(System.`in`)

println("N: ")
var A = sc.nextInt()
var B = 0
var C = 0
var D = 0

while (D < A){
    println("--> ")
    B = sc.nextInt()
    if (B > A) {
        C++
    }
    D++
}

println(C)

while (C > 0){
    C--
    A--
}

println(A)

Finally code must be describable by pseudocode like this.

1. load into A
2. if D < A jump to next otherwise jump to 8
3. Load to B
4. if B > A jump to next otherwise jump to 6
5. Increase C by 1
6. increase D by 1
7. jump to 2
8. write out box C
9. move to a new line
10. if C > 0 jump to next otherwise jump to 13
11. decrease C by 1
12. decrease A by 1
13. write out box A

I did some attempts to solve problem but I have no idea how to handle numbers that are equal that should not be counted.
I started to have some doubts that it is possible with restriction that not allowing more variables.


Solution

  • Usually you'd use five variables. So I combine the two counts in one variable.

    N = int(input())
    count = 0
    i = 0
    while i < N:
        i += 1
        number = int(input())
        if number > N:
            count += N+1
        if number < N:
            count += 1
    print(count // (N+1), 'were greater than', N)
    print(count % (N+1), 'were less than', N)
    

    Attempt This Online!

    Without division/modulo:

    N = int(input())
    count = 0
    i = 0
    while i < N:
        i += 1
        number = int(input())
        if number > N:
            count += N+1
        if number < N:
            count += 1
    i = 0
    while count > N:
        count -= N+1
        i += 1
    print(i, 'were greater than', N)
    print(count, 'were less than', N)
    

    Attempt This Online!