Search code examples
arrayscinputcomparison

How to store user input of round numbers in an Array


I have a problem to solve which is. I have to make a program which will take 2 numbers from the sequence of numbers and compare them if it's '<' '>' or '=' and the list of numbers needs to end with number 0. So basically I have a sequence of numbers {5, 7, 8, 4, 3, 3, 0} and the program have to check by couples 5,7 (it is 5 < 7) then it will go to 8, 4 (it is 8 > 4) then 3, 3 so it is 3 = 3. And the 0 is basically as the exit.

So far I wrote down the comparison of the numbers but now I only have a program which takes 2 inputs from the user and compares them. But I kinda need to specify for the user let's say to enter 11 numbers which will end with 0 (as 0 will not be counted to the comparison) and store those numbers in an array and then let the program to compare the 2 numbers after each other (in a sequence) with <, > or =.

Thanks in advance guys. I'm kinda new to C and these arrays and specially malloc, calloc, realloc are really complicated for me.

So far my code looks like this:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define post 10
int main(){

    int a, b;


    printf("Enter two numbers: ");
    scanf("%d%d", &a, &b);

    if (a > b)
    {
        printf("%d > %d\n", a, b);
    }
    else if(a < b)
    {
        printf("%d < %d\n", a, b);
    }
    else
    {
        printf("%d = %d\n", a, b);
    }


    system("pause");
    return 0;
}

Solution

  • You can create large array and then input how many number you want to compare. Then you can use for to walk through the numbers in the array and compare them.

    Here is exemple:

    #include <stdio.h>
    
    #define SIZE 100
    
    int main()
    {
        int arr[SIZE] = {0};
    
        printf("Enter number: ");
        
        int number;
        int counter = 0;   
        
        while (1)
        {
            if (scanf("%d", &number) != 1)
            {
                printf("Invalid number!");
                return 1;
            }
            arr[counter] = number;
            if(number == 0) {break;}
            counter++;
        }
    
        for (int i = 0; i < counter; i+=2)
        {
            if (arr[i] > arr[i + 1])
            {
                printf("%d > %d\n", arr[i], arr[i + 1]);
            }
            else if(arr[i] < arr[i + 1])
            {
                printf("%d < %d\n", arr[i], arr[i + 1]);
            }
            else
            {
                printf("%d = %d\n", arr[i], arr[i + 1]);
            }      
        }
        
        return 0;
    }
    

    Output:

    Enter number: 1 2 3 4 5 5 0
    1 < 2
    3 < 4
    5 = 5