Building a Nest

22.04.2016 |

Episode #7 of the course Getting started with C programming by Sudeshna Das

 

In today’s lesson, we are going to learn how to use one if statement within another, and then follow it up with how to use one for looping within another for loop.

There are certain cases where we need to check for multiple conditions, as we have already seen with the AND (&&) operator. However, sometimes, the conditions themselves depend on other conditions. In such cases, we use one if statement within another. Let’s take an example.

 

#include<stdio.h>
void main()
{
int age=24, income=1000;
if(age>=18)
{
if(income<5000)
printf(“You are eligible to vote and are exempted from paying tax.”);
else
printf(“You are eligible to vote.”);
}
else
printf(“You are not eligible to vote.”);
}

http://codepad.org/8Rh5laje

 

The else on line number 9 is paired with the if in line number 7, and the else in line number 12 is paired with the if in line number 5.

Similarly, we can use one for loop within another for loop.

 

#include<stdio.h>
void main()
{
int column1, column2;
for(column1=1 ; column1<=5 ; column1=column1+1)
{
for(column2=1; column2<=4 ; column2=column2+1)
{
printf(“%i %i \n”,column1, column2);
}
}
}

http://codepad.org/kvDENIG5

 

See the output. At first, the value of column1 is assigned as 1, and now, the value of column2 changes from 1 to 4. Note that 4 is the maximum value that column2 is allowed to take. Now, column2 is again incremented and becomes 5. However, since column2 is not allowed to take a value of 5, the condition being checked by the second for is not satisfied. This makes us come out of the second for loop and go back to the first for loop. Here, the value of column1 is incremented by 1, and we move to the next statement.

In this next statement, the value 1 is again assigned to column2, and the same process of incrementing the value of column2 while the value of column1 remains unchanged continues until the result 2 4 is displayed. After this, the value of column1 is incremented again by 1. This process continues until the result 5 4 is displayed. After 5 4 is displayed, the value of column2 is incremented by 1, but we know that column2 cannot be 5. So this condition is not satisfied, and we move back to the first for loop. Here, the value of column1 is incremented by 1, but since column1 cannot hold the value 6, we come out of this for loop as well and move to the next statement, which, in this program, is the closing curly brackets that end the program.

The second for loop is inside the first for loop, so we call the second for loop the inner loop and the first for loop the outer loop.

The two programs we saw today had just one level of nesting, but you will probably use more than one level of nested statements as you progress to comparatively more advanced programs.

 

Recommended book

“Practical C Programming” by Steve Oualline

 

Share with friends