C Programming

COMPOUND RELATIONALS ( AND, NOT, OR, EOR )

Range checking using Compound Relationals
Consider where a value is to be inputted from the user, and checked for validity to be within a certain range, lets say between the integer values 1 and 100.


	#include <stdio.h>

	main()
	{
		int number;
		int valid = 0;

		while( valid == 0 ) {
			printf("Enter a number between 1 and 100");
			scanf("%d", &number );
			if( (number < 1) || (number > 100) )
				printf("Number is outside legal range\n");
			else
				valid = 1;
		}
		printf("Number is %d\n", number );
	}


	Sample Program Output
	Enter a number between 1 and 100
	203
	Number is outside legal range
	Enter a number between 1 and 100
	-2
	Number is outside legal range
	Enter a number between 1 and 100
	37
	Number is 37

The program uses valid, as a flag to indicate whether the inputted data is within the required range of allowable values. The while loop continues whilst valid is 0.

The statement


	if( (number < 1) || (number > 100) )

checks to see if the number entered by the user is within the valid range, and if so, will set the value of valid to 1, allowing the while loop to exit.


Now consider writing a program which validates a character to be within the range A-Z, in other words alphabetic.


	#include <stdio.h>

	main()
	{
		char ch;
		int valid = 0;

		while( valid == 0 ) {
			printf("Enter a character A-Z");
			scanf(" %c", &ch );
			if( (ch >= 'A') && (ch <= 'Z') )
				valid = 1;
			else
				printf("Character is outside legal range\n");
		}
		printf("Character is %c\n", ch );
	}


	Sample Program Output
	Enter a character A-Z
	a
	Character is outside legal range
	Enter a character A-Z
	0
	Character is outside legal range
	Enter a character A-Z
	R
	Character is R

In this instance, the AND is used because we want validity between a range, that is all values between a low and high limit. In the previous case, we used an OR statement to test to see if it was outside or below the lower limit or above the higher limit.


ęCopyright B Brown. 1984-1999. All rights reserved.