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

Iterative Sentences C

The document discusses while loops in C# including syntax, examples, common mistakes, and exercises. It explains that while loops allow repeating a block of code while a condition is true. Key points covered include using while loops to iterate user input, counting iterations, and avoiding empty loops or those that never terminate.

Uploaded by

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

Iterative Sentences C

The document discusses while loops in C# including syntax, examples, common mistakes, and exercises. It explains that while loops allow repeating a block of code while a condition is true. Key points covered include using while loops to iterate user input, counting iterations, and avoiding empty loops or those that never terminate.

Uploaded by

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

Iterative Sentences

1. Objectives
At the end of this activity, you will be able to properly use the while sentence to generate
repetition in the execution of a sequence of sentences.

2. Motivation
Until now, each sentence in our program is executed only once. Execution starts at the first
sentence of the main program, and after it, the computer executes the second sentence which is
just in the bellow line, and so forth to the end. Only in case of finding a conditional sentence (if or
switch) the execution of an instruction would not happen. But, in any case, we always follow
forward and we never come back executing a sentence which had been executed before.
Using iterative sentences allow us to iterate a group of sentences, it means, to execute several
times the same group of sentences meanwhile a specific condition is true. These groups of
sentences are also called loops and the sentences that we repeat inside the loop are called the
body of the loop.

3. While sentence
In the C# language there are several types of iterative sentences, however we only will study the
while sentence, because it is the most standard and we could find it in all programming languages
with very similar syntax.

Syntax

Meanwhile the condition is true, sentences


while(condition)
inside the body of the loop will be executed.
{
Sentence 1;
Sentence 2;
Curly brackets indicate start and end points for the
. . . sequence of sentences that are going to be repeated.
Sentence 3; These sentences are the body of the loop.
}

If the body of the loop has only 1 sentence, then curly brackets are not necessary.

Example
We want to do a program that prints on the screen an integer number that will be the double of
the number that a user types on the keyboard. In order to end the program, the user will
introduce a 0 to indicate no more calculations.

static void Main(string[] args)


{
int num = Convert.ToInt32(Console.ReadLine());

while (num != 0)
{
Console.WriteLine("The double of " + num + " is " + 2 * num);
num = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("End of the program!");


}
The program declares an integer type variable (int) that we called num, then the program asks the
user to introduce by keyboard an integer value which is going to be stored in the variable num.
What follows is the evaluation of the loop condition (num != 0). If the condition is true then the
body of the loop is executed. First, the WriteLine displays the message on the screen and
later the ReadLine asks for the next number.
The next step is to evaluate again the loop condition (num != 0), if it is true, all instructions
inside of the body of the loop will be executed until the loop condition will be false (that is, when
a user writes a 0). In this case, the last WriteLine will be executed and the message “End of the
program” will be displayed.
Exercise 1: Write the program we have just described in the computer, compile and link it. Does
it work properly?
The loop condition could be as complex as necessary. In the previous case, condition checks only
that the value of a variable will be different from 0, but we could also join conditions using logic
operators (&&, ||).
Exercise 2: Modify the program so that the condition to end the program will be that the last
entered number will be equal to 0 or its double bigger than 100. Verify if it works correctly.
A priory, we do not know how many iterations the loop will do. In the previous example, it
depends on whether the user enters a 0. Besides, if the first evaluation of the condition is false,
the execution of the loop will not happen.

Another example
A very common situation occurs when we know in advance the number of turns that has to be
done by the loop. So, we will use a variable that counts the number of turns, and the loop
condition will check the predicted limit of the variable in each turn.
Look the next loop that writes the multiplication table of number 7:

Console.WriteLine("Multiplication table of number 7");

int i = 0; // This variable will be used as counter.


while (i <= 10)
{
Console.WriteLine("7 x " + i + " = " + i * 7);
i = i + 1; // We increase the counter variable
}

The counter variable starts on 0 and after each turn of the loop it will increase its value on 1. The
loop ends when the counter variable is equal to 11 (it is the first time when its value does not fulfil
the loop condition).

4. Tricks, advices and common mistakes


There are some recurring and very common mistakes when we work with iterative sentences. The
list bellow will help you to understand and to avoid making them.

 The body of the loop is empty


The body of the loop can be empty. It sounds an odd thing but the compiler does not detect as a
mistake because it is not a syntactic mistake, it is a logic mistake.
Look next example:

while (num != 0) ;
{
Console.WriteLine("The double of " + num + " is " + 2 * num);
num = Convert.ToInt32(Console.ReadLine());
}

You could think this loop looks like the first example presented in this paper, but if you look
carefully at it, you will notice there is a semicolon after the while condition, in the first line. It
means the loop ends just there, so there are no instructions to execute. This loop does not finish
at all because num never changes. Therefore, be careful with semicolons.

 Never ending loops


The previous common mistake shows a while that never ends because of a semicolon which is at
the end of the sentence by mistake.
Another common mistake when loops do not end occurs when we forget to increase the counter
variable inside the loop. Remember the multiplication table example. If inside the loop we would
not have put the sentence “i=i+1“, the loop would not have finished because the counter
variable would never reach the limit value (it would write endless times “7 x 0 = 0”).

 Bad written conditions


There are common mistakes on loop entry conditions as well, especially for compound conditions.
Look at the possible solution bellow for the example 2.

static void Main(string[] args)


{
int num, res;

num = Convert.ToInt32(Console.ReadLine());

while ((num != 0) || (res < 100))


{
res = 2 * num;
Console.WriteLine("The double of " + num + " is " + res);
num = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("End of the program!");


}

Remember that loop must end when num is 0 or the double of the last read number is bigger than
100. Can you see the mistakes?
 One iteration more or one iteration less
This kind of mistake occurs if we do not consider the first and/or the last turn of the loop. These
cases are special and we have to treat them properly.
For example, next program tries to calculate the power yx:

static void Main(string[] args)


{
int res, x, y, i;

y = Convert.ToInt32(Console.ReadLine());
x = Convert.ToInt32(Console.ReadLine());

if (x == 0)
Console.WriteLine("The power is 1");
else
{
res = y;
i = 0;
while (i <= x)
{
res = res * y;
i = i + 1;
}
Console.WriteLine("The power is " + res);
}
}
Write the program in the computer. Does it work? Why? Write it correctly and verify that it
works.

 To find the mistakes use the debugger


The best way to solve loop problems is the use of a debugger. In programming, it is a basic and
very useful tool to find mistakes.
Exercise 3: Next program asks for a number from keyboard and calculates its number of digits
considering those which are bigger than MAX. Type the program in the computer. Use the
debugger to determine why it does not work and sort out the mistakes.

const int MAX = 7;

static void Main(string[] args)


{
int original, num, cont;

num = Convert.ToInt32(Console.ReadLine());
original = num;

while (num / 10 != 0)
{
if (num % 10 > MAX)
cont++;
num = num / 10;
}

Console.WriteLine("The number " + original + " has " + cont +


"digits bigger than " + MAX);
}

Exercise 4: Write a program that calculates the sum of all numbers between 1 and 100 which are
multiple of 5 or 7. To verify that a number X is multiple of another number Y you only have to
check if the rest of the integer division of X divided by Y is 0.
Exercise 5: Write and test in the computer a program that reads a sequence of integers entered
by the keyboard. The program will sum values each time they are introduced, until the sum will be
bigger than a pre-established number by means of a constant of the program (just like we defined
constant MAX in the previous example). When it happens, the program prints on the screen the
value of the sum and it finishes.

You might also like