0% found this document useful (0 votes)
26 views

CP Lecture 06 14102024 103325pm

Uploaded by

shayannshakeel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

CP Lecture 06 14102024 103325pm

Uploaded by

shayannshakeel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lab Manual Computer Programming

Lab Manual for Computer Programming

Lab No. 6
Looping Statements: For Loop

Objectives
To understand basic concept, implementation and usage of for loops.

Software Engineering Department


Bahria University (Karachi Campus)
Lab Manual Computer Programming

LAB # 06
Looping Statements: For Loop
Introduction
In computer programming, a loop is a sequence of instruction s that is continually repeated until a
certain condition is reached. Typically, a certain process is done, such as getting an item of data and
changing it, and then some condition is checked such as whether a counter has reached a prescribed
number or not. in this lab we discuss how to use FOR loop in C# programming.

For Loop
The FOR loop is found in many procedural languages which repeatedly executes some instructions
until given condition is true. In C++, the FOR loop is written in the form of expression in which
initialization, testing of condition and increment or decrement value is included.

For-loops are a slightly more complicated than while and do-while loops but on the other hand they
can solve more complicated tasks with less code. Here is the scheme describing for-loops:

They contain an initialization block (A), condition (B), body (D) and updating commands for the
loop variables (C). We will explain them in details shortly. Before that, let’s look at how the program
code of a for-loop looks like:

Software Engineering Department


Bahria University (Karachi Campus)
Lab Manual Computer Programming

Structure of the for loop:


1. Initialization expression:
In initializing of expression, the given variables initialize the starting value. It always executed as soon
as the loop is entered. We can start initialization at any number however in the given example variable
count initializing or count from 0.

Example:
int var;
( var = 5; )

2. Test expression:
In second part of the expression variable testing the given condition. In given example count is less
than 10, it test each time through the loop. If the test expression is true i.e. count<10 the body of the
loop will be go to prntf statement and if the expression is false i.e. count is equal to 10 or more, the
loop will be terminated.

Example:
int var;
( var >= 1;)

3. Increment / decrement expression:


In third part of the expression we use increment or decrement operators to make continuous counter.
In this example we use count ++ i.e. increment operator for increment in each step, the variable count
each time the loop and than execute.

Example:
Int var;
( var++ ) / ( var - - )

Detailed Explanation
1. Initialization of For Loops
For-loops can have an initialization block:

It is executed only once, just before entering the loop. Usually the initialization block is used to declare
the counter-variable (also called a loop variable) and to set its initial value. This variable is "visible"
and can be used only within the loop. In the initialization block is possible to declare and initialize
more than one variable.

Software Engineering Department


Bahria University (Karachi Campus)
Lab Manual Computer Programming

For-loops can have a loop condition:

The condition (loop condition) is evaluated once before each iteration of the loop, just like in the while
loops. For result true the loop’s body is executed, for result false it is skipped and the loop ends (the
program continues immediately after the last line of the loop’s body).

The last element of a for-loop contains code that updates the loop variable:

This code is executed at each iteration, after the loop’s body has been executed. It is most commonly
used to update the value of the countervariable.

The body of the loop contains a block with source code. The loop variables, declared in the
initialization block of the loop are available in it.

Here is a complete example of a for-loop:

Here is another, more complicated example of a for-loop, in which we have two variables i and sum,
that initially have the value of 1, but we update them consecutively at each iteration of the loop:

Software Engineering Department


Bahria University (Karachi Campus)
Lab Manual Computer Programming

For-Loop with Several Variables


As we have already seen, in the construct of a for-loop we can use multiple variables
at the same time. Here is an example in which we have two counters. One of the
counters moves up from 1 and the other moves down from 10:

Operator "continue"
The continue operator stops the current iteration of the inner loop, without terminating the loop. With
the following example we will examine how to use this operator. We will calculate the sum of all odd
integers in the range [1…n], which are not divisible by 7 by using the for-loop:

First we initialize the loop’s variable with a value of 1 as this is the first odd integer within the range
[1…n]. After each iteration of the loop we check if i has not yet exceeded n (i <= n). In the expression
for updating the variable we increase it by 2 in order to pass only through the odd numbers. Inside the
loop body we check whether the current number is divisible by 7. If so we call the operator continue,
which skips the rest of the loop’s body (it skips adding the current number to the sum). If the number
is not divisible by seven, it continues with updating of the sum with the current number.

Software Engineering Department


Bahria University (Karachi Campus)
Lab Manual Computer Programming

In this lab we will also examine the nested loops, these are programming constructs consisting of
several loops located into each other. The innermost loop is executed more times, and the outermost
less times. Let’s see how two nested loops look like:

for (initialization, verification, update) {


for (initialization, verification,update)
{executable code
}
…}

After initialization of the first for loop, the execution of its body will start, which contains the second
(nested) loop. Its variable will be initialized, its condition will be checked and the code within its body
will be executed, then the variable will be updated and execution will continue until the condition
returns false. After that the second iteration of the first for loop will continue, its variable will be
updated and the whole second loop will be performed once again. The inner loop will be fully executed
as many times as the body of the outer loop.

Let’s solve the following problem: for a given number n, to print on the console a triangle with n
number of lines, looking like this:

We will solve the problem with two for-loops. The outer loop will traverse the lines, and the inner one
the elements in them. When we are on the first line, we have to print "1" (1 element, 1 iteration of the
inner loop). On the second line we have to print "1 2" (2 elements, 2 iterations of the internal loop).
We see that there is a correlation between the line on which we are and the number of the elements
that we print. This tells us how to organize the inner loop’s structure:

 We initialize the loop variable with 1 (the first number that we will print): col = 1;
 The repetition condition depends on the line on which we are: col <= row;
 We increase the loop variable with one unit at each iteration of the internal loop.

Basically, we need to implement a for-loop (external) from 1 to n (for the lines) and put another for-
loop (internal) in it – for the numbers on the current line, which should spin from 1 to the number of
the current line. The external loop should go through the lines while the internal – through the columns
of the current line. Finally, we get the following code:

Software Engineering Department


Bahria University (Karachi Campus)
Lab Manual Computer Programming

If we execute it, we will make sure that it works correctly. Here is how the result for n=7 looks like:

Time Boxing
Activity Name Activity Time Total Time
Login Systems + Setting up Visual Studio Environment 3 mints + 5 mints 8 mints
Walk through Theory & Tasks 60 mints 60 mints
Implement Tasks 80 mints 80 mints
Evaluation Time 30 mints 30 mints
Total Duration 178 mints

Objectives/Outcomes
This Lab exercise delivers the idea/concept of:
- Creation and implementation of for loop.

Lab Tasks/Practical Work


1. Write a C# program that prints the following series:

 Odd series up to a limit defined by the user.


 Even series up to a limit defined by the user.
 1st 10 terms of an arithmetic series where a1 is -2 and d is 2.5,
 1st 10 terms of a geometric series where a1 is 3 and r is 2.

2. Write a C# program to print the Fibonacci series for N terms, where N is given by the user as input.

3. Write a C# program that prompts the user to input the number of subjects in which they have taken
exams, asks for the marks for each subject, calculates the total marks and percentage, and then
displays the corresponding grade.

4. Write a C# program to print the following patterns right-angled triangle, inverted right-angled
triangle, diamond, and pyramid star pattern, by using for loop.

5. Write a C# program that reads a positive integer number N (where N < 20) from the console and
prints a square matrix of numbers in a spiral order, as shown:

N=3 N=4

Software Engineering Department


Bahria University (Karachi Campus)

You might also like