Home > OS >  Checking whether a number is smaller or greater without using an array
Checking whether a number is smaller or greater without using an array

Time:10-26

I am trying to check whether a number is greater or smaller in a while loop without using an array. I am trying to do it with the scanf() function, but have been unsuccesful so far.

I tried storing the initial value of the first number into a variable and then checking it at the next iteration of the loop, but I just don't know how. Any advice that helps me move with the code is appreciated greatly.

int number, nextNumber;

 while (...) {
        
        scanf("%d", &number)
        
        nextNumber = number;

        if (number >= nextNumber) {
            printf(...);

        }

CodePudding user response:

int number, nextNumber = INT_MIN;

while (...) {
        
    if(scanf("%d", &number) == 1)
        if (number > nextNumber) {
            nextNumber = number;
            /* ... */
        }
}

CodePudding user response:

An example that suggests the entries are correct:

#include <stdio.h>

int main(void)
{
    int result;
    scanf("%d", &result);
    
    int number;
    while(scanf("%d", &number)==1) // Type a character when you're done.
    {
        if (number > result) result=number;
    }

    printf("The largest number is: %d\n", result);

    return 0;
}
  • Related