C Programming

MAKING DECISIONS

SELECTION (IF STATEMENTS)
The if statements allows branching (decision making) depending upon the value or state of variables. This allows statements to be executed or skipped, depending upon decisions. The basic format is,


        if( expression )
                program statement;

Example;


        if( students < 65 )
                ++student_count;

In the above example, the variable student_count is incremented by one only if the value of the integer variable students is less than 65.


The following program uses an if statement to validate the users input to be in the range 1-10.


	#include <stdio.h>

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

		while( valid == 0 ) {
			printf("Enter a number between 1 and 10 -->");
			scanf("%d", &number);
			/* assume number is valid */
			valid = 1;
			if( number < 1 ) {
				printf("Number is below 1. Please re-enter\n");
				valid = 0;
			}
			if( number > 10 ) {
				printf("Number is above 10. Please re-enter\n");
				valid = 0;
			}
		}
		printf("The number is %d\n", number );
	}


	Sample Program Output
	Enter a number between 1 and 10 --> -78
	Number is below 1. Please re-enter
	Enter a number between 1 and 10 --> 4
	The number is 4


EXERCISE C10
Write a C program that allows the user to enter in 5 grades, ie, marks between 0 - 100. The program must calculate the average mark, and state the number of marks less than 65.

Answer


Consider the following program which determines whether a character entered from the keyboard is within the range A to Z.


	#include <stdio.h>

	main()
	{
		char letter;

		printf("Enter a character -->");
		scanf(" %c", &letter );

		if( letter >= 'A' ) {
			if( letter <= 'Z' )
				printf("The character is within A to Z\n");
		}
	}


	Sample Program Output
	Enter a character --> C
	The character is within A to Z

The program does not print any output if the character entered is not within the range A to Z. This can be addressed on the following pages with the if else construct.

Please note use of the leading space in the statement (before %c)


 	scanf(" %c", &letter );

This enables the skipping of leading TABS, Spaces, (collectively called whitespaces) and the ENTER KEY. If the leading space was not used, then the first entered character would be used, and scanf would not ignore the whitespace characters.


COMPARING float types FOR EQUALITY
Because of the way in which float types are stored, it makes it very difficult to compare float types for equality. Avoid trying to compare float variables for equality, or you may encounter unpredictable results.


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