## Want to keep learning?

This content is taken from the University of Reading's online course, Begin Programming: Build Your First Mobile Game. Join the course to learn more.
4.4

# Introduction to solving complex problems

So far we’ve looked at solving simple problems using conditional and looping constructs. But what if there is a complex problem where a combination of conditional and looping constructs have to be used? Or, multiple conditions and multiple looping constructs have to be used? In this tutorial we’ll cover how to tackle some of these problems by applying what you have learnt so far in the course.

Consider a grading system with four different grades: A, B, C and D - where A is the highest grade and D the lowest. The system of grades is defined as shown below:

A marks > 75
B 50 < marks <= 75
C 35 < marks <= 50
D marks <= 35

The algorithm to determine the grade when a mark is given should go something like this:

• Line 1: Begin
• Line 2: Check marks
• Line 3: If mark is greater than 75 then Grade A
• Line 4: Otherwise,
• Line 5: if mark is greater than 50 but less than or equal to 75, then Grade = B
• Line 6: Otherwise,
• Line 7: if mark is greater than 35 but less than or equal to 50, then Grade = C
• Line 8: Otherwise, Grade = D
• Line 9: End

This algorithm has several conditional statements. First it needs to be checked whether the mark is greater than 75. If the mark is not greater than 75, there are many possibilities. So there are two more conditional checks within the ‘Otherwise’ part of the first conditional statement. Because these conditional statements are inside one another they are described as nested conditions.

Implementing this in a Java program using ‘if’ statements would look like this:

int mark;
/*Assume mark is assigned the appropriate value here*/
if ( mark > 75 )
else {
if ( (mark <= 75) && (mark > 50) )
Grade = "B"; /*in the above condition you do not need to check (mark <= 75) as we only get to this point if it is so. We have shown it here for clarification*/
else {
if ( (mark <= 50) && (mark > 35) )
Grade = "C"; /*similar to previous condition check we do not need (mark<= 50) here as execution gets here only if that is true*/
else
}
}


Now can you improve this program to check whether the value of ‘mark’ is non-negative? Not greater than 100?

To check the non-negativity you will have to add an additional condition if ( mark >= 0 )

To check whether the mark is less than 100 you will have to add another condition if ( mark < 100 )

But if you want to make sure the mark is non-negative AND less than 100 you can use this condition:

if ( ( mark >= 0 ) && ( mark < 100 ) )

Move onto the next step for another example!