Lab 06 - Nested Loops and Conditions
Lab 06 - Nested Loops and Conditions
Lab # 06
Nested Loops, Break and Continue
OBJECTIVE:
Working on nested statements and control loop iteration using break and
continue.
THEORY:
Nested Statements:
It is possible to write one loop inside another loop. For example, we can write a
for loop inside a while loop or a for loop inside another for loop. Such loops are
called “nested loops”.
if:
A Nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement.
Syntax:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
Example: write a code that will take two numbers as input and check if x >= 10
then check (y>=20 then add these numbers, else subtract) and if x<10 then
multiply x and y
Code: Output:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[]
args)
{
int x, y;
Console.Write("Enter
First Number : ");
x =
Convert.ToInt16(Console.ReadL
ine());
Console.Write("Enter
Second Number : ");
y =
Convert.ToInt16(Console.ReadL
ine());
if(x>=10)
{
if (y >= 20)
{
Console.WriteLine("Addition of
two numbers is : "+ (x + y));
}
else
{
Console.WriteLine("Subtraction
of two number is : "+ (x - y));
}
}
else
{
Console.WriteLine("Subtraction
of two number is : " + (x - y));
}
}
}
}
for:
Syntax:
Syntax:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
Example: write a code to display number 0 in row 1 (10 times); 1 in row 2 (10
times); 2 in row 3 (10 times); 3 in row 4 (10 times); 4 in row 5 (10 times)
Code:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
int a, b, c=1;
for (a = 0; a < 5; a++)
{
for (b = 0; b < 10; b++)
{
Console.Write(a+"\t");
//c++;
}
Console.Write("\n");
}
}
}
}
Output:
{
for (b = 0; b < 10; b++)
{
Console.Write(c+"\t");
c++;
}
Console.Write("\n");
}
}
}
}
Output:
}
Output:
Example:
Code:
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
int a, b;
for (a = 0; a < 5; a++)
{
for (b = 0; b < 5; b++)
{
if (a == 0 || b == 0 || a == 4 || b == 4)
{
Console.Write("*\t");
}
else
{
Console.Write(" \t");
}
}
Console.Write("\n");
}
}
}
}
Output:
TASK:
• Perform all the examples with for loop and while loop.
• To print 20 x 20 table chart using nested for loop, While.
• To print prime numbers from 0 - 1000.
• Generate a game of rock – paper – Scissor.
• To print the following pattern.
+ + + + + A
+ + + + A B
+ + + A B C
+ +
A B C D
+
A B C D E
+ + + + * +
+ + + * * + +
+ + * * * + + +
+ * * * * + + + +
* * * * * + + + + +