Home Classroom C++ C++ with Barney! Class 4

C++ with Barney! Class 4

1098

 

Loops

 

[You're Ted and you decide to learn some C++ from your friend Barney. This is the fourth day of the class]

 

You: Hi, Barney!

 

Barney: Hi, Ted! What’s up?

 

You: Don’t tell me that you weren’t expecting me to show up for the C++ lesson today!

 

Barney: Oh, almost forgot that. I was busy reading the novels I bought at the book fair. Bought some romance this time. So, so, what were we doing last time?

 

You: Mmm, we learned how to get the user input and how to use the if-else statements.

 

Barney: Okay, good. Then we will see how to use loops today. Computers become really useful when we want to repeat things over and over again. We will have to repeat certain instructions ten or fifteen times, and sometimes a million times, and even infinitely.

 

You: Infinitely?

 

Barney: Yes, in certain instances we have to run the programme indefinitely, may be until a certain event happens. That is when we need to use infinite loops. We’ll see how to code them soon.

 

You: Okay.

 

Barney: We call these repetitions loops in programming terms. There are three main kinds of loops. The while loop, the do-while loop and the for loop. Let’s first deal with the while loop. It’s syntax is like this:

 

while (condition) {

// statements

}

 

You: Oh, you’ll have to explain me this.

 

Barney: It’s simple. The compiler looks at the condition we have given, and executes the statements within the curly braces repeatedly until the condition becomes false. Let’s try an example.

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=0;

 

while (n<5) {

cout<<n<<endl;

n=n+1;

}

system(“pause”);

return 0;

}

 

You: Oh, that seems greek to me!

 

Barney: Only for now. Let’s run the programme and see first.

You: Hmm, that’s pretty interesting. How does that happen?

 

Barney: It’s like this. You have written a while loop that would run while n is lesser than 5. At the beginning n is set to 0 so the loop would run. First it will print 0 and the value of n is incremented. Now the loop checks the condition again and finds n is still less than 5. So the statements inside the loop are run again. This will repeat until n’s value is set to 5, when the loop will eventually stop.

 

You: Oh, I see, that’s wonderful!

 

Barney: The best things are yet to come. We have incremented n by one in this programme. Incrementing and decrementing variables by one is something we always have to do in our programmes. There are two more ways we can write the above incrementing statement.

 

n=n+1;

n+=1;

n++;

 

All these above statements are equivalent, they increment the value of n by one.

 

You: But the last one seems more convenient.

 

Barney: Yes. We almost never use the first statement. When we want to increment by one we almost always use the third option.

 

You: Then what about the second one?

 

Barney: The second one comes handy when we need to increment by a value different to one. For example, we can increment n by 5 by using:

n+=5;

 

You: I see.

 

Barney: And there is one more variant in incrementing. We could also ask the variable to increment like this:

++n;

To see how n++ and ++n work differently, let’s try another programme. Or, rather, let’s change our current programme like this:

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=0;

 

while (n<5) {

cout<<n++<<endl;

}

system(“pause”);

return 0;

}

 

 

What will happen?

 

You: Mmm, let’s see. N is printed and it is incremented. Perhaps it gives the same output as before?

 

Barney: Exactly.

This happens because n is incremented after it is printed in the screen, just as our previous programme did.

Now suppose we replaced it with ++n instead. What will happen now?

 

You: Wouldn’t it give the same result? Well, it will depend on whether n is incremented before or after n is printed, won’t it?

 

Barney: There! You get it! Yes, in ++n, n is incremented before anything happens. Let’s see what happens.

You: Hmm, exactly what I expected.

 

Barney: Yeah, it won’t need any explanation. Consider this programme:

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=5;

 

while (n<5) {

cout<<++n<<endl;

}

system(“pause”);

return 0;

}

 

We have set the initial value of n to 5. What will happen?

 

You: Mmm, now that the condition is not satisfied at the beginning, the loop won’t run?

 

Barney: Yes, since the while loop initially checks whether the condition is true or false, the statements inside the loop won’t be executed. However, there are certain times when you want your loop run at least once, no matter whether the condition is satisfied or not. This is when we’re going to use the do-while loop. It has a syntax like this:

 

do {

//statements

} while (condition);

 

As you can see, the statements are executed once first and then the condition is checked. If the condition is true, the loop will keep repeating until it becomes false. In this way, we can assure that the statements inside the loop are executed at least once. Let’s try an example:

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=10;

 

do {

cout<<n–<<endl;

} while (n>5);

system(“pause”);

return 0;

}

 

We have used the decrement operator – here. It works similar to the increment operator, except for the fact it reduces one from the variable. So, Ted, what do you think would be the output of this?

 

You: Well, n is 10 at the beginning. 10 is printed first, and decremented. Now n is 9. The condition is true. So the loop repeats. It should stop once n becomes 5. But by then 5 would not have printed. So the programme should print from 10 to 6.

 

Barney: Let’s see what happens:

 

 

 

Yes, you’re correct. This programme didn’t make much difference. We could have obtained the same from the while loop. Now suppose initially n was set to 0. What would have happned?

 

You: Sure enough, it would print 0 and terminate, because the condition is checked only after the statements are run for the first time.

 

Barney: Yeah, that’s how it works. Seems you understand thedo-while loop really well. By the way did you notice the semicolon at the end of the loop?

 

You: Oh, saw it only now. We didn’t use one in the while loop, did we?

 

Barney: Of course we didn’t. The do-while loop is not ending with curly braces so we need to tell the compiler that the line ends there by using the semicolon.

 

You: I get it.

 

Barney: Right, the next and final type of loop we’re going to look at is the for loop. It has a syntax similar to this:

 

for (initialization; condition; increment) {

//statements

}

 

You: Oops, that seems to be complex than the other two.

 

Barney: It may seem so, but it’s actually pretty simple. We’ll see about that in an example first.

 

include<iostream>

 

using namespace std;

 

int main()

{

int n=0, i;

 

for (i=1;i<=10;i++) {

n+=i;

}

 

cout<<n<<endl;

system(“pause”);

return 0;

}

You: Oh, you’ll have to explain me that from the beginning.

 

Barney: It’s like this. First you declare two integers n and i and initialize n to zero. Then comes the for loop. We’ll better understand that if we split that into parts and see. Can you split the statement inside these brackets according to the syntax?

 

You:

Initializer: i=1

Condition: i<=10

Increment: i++

Is that it?

 

Barney: Yes. As you can see, now the loop seems simpler than before. The initialize initializes i to one. The condition is i<=10 so the loop will run while is lesser than or equal to 10. The increment is i++, so each time the loop repeats, the value of i will be incremented by one.

 

You: Hmm, it is understandable when you dissect it like that. I think I understand what the rest of the programme does.

 

Barney: Yes, go ahead!

 

You: Each time the loop runs, the value of i is added to n. Since the loop runs while i=1,2,…,10, the final value of n will be equal to n=1+2+…+10

 

Barney: Exactly! You have always been a fast learner! So the programme should print that sum at the end. What exactly would it print?

 

You: Mmm, 55 of course. Good that I still remember high school math!

 

Barney: Let’s see.

 

 

 

you: There! Didn’t I tell ya? He he.

 

Barney: Good. When someone like you is around here, one don’t need to write a programme to find such a total. But I know you understand the significance of these loops in programming sure enough.

 

You: Yeah, yeah, I do. I was kidding!

 

Barney: Good. Now one more thing is that in the increment part, actually we can perform any mathematical operation, even decrementing. So something like this will also work:

 

for (i=10;i>=1;i–)

 

You: Hmm, I see.

 

Barney: And there are two more commands that I want to teach you now. They’re the break and continue statements. They’re really useful when dealing with loops. What do you think the break command does?

 

You: Mmm, perhaps it breaks the loop? Hehe.

 

Barney: Yes. If you want your loop to stop looping at some point, you can break it using this. This is really useful when you make use of infinite loops. What does this loop do?

 

int n=0, i=1;

 

while (true) {

n+=i;

i++;

}

 

You: Hmm, it will also calculate the sum 1+2+3+… but the condition is true, what happens then?

 

Barney: Well, since the condition remains true always, the loop will never stop. This is an example for an infinite loop.

 

You: What’s the use of that anyway, Barney?

 

Barney: Well, it’s like this. Suppose you need to find out when the sum 1+2+3+… reaches 1000. Then you can do some trick like this:

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=0, i=1;

 

while (true) {

n+=i;

if (n>=1000) break;

i++;

}

 

cout<<”The sum reaches 1000 when i=”<<i<<endl;

system(“pause”);

return 0;

}

 

cout<<”The sum reaches 1000 when i=”<<i<<endl;

 

system(“pause”);

return 0;

}

 

You check the value of n at each iteration, and once you find that it has exceeded 1000 you tell the loop to break. So what will be printed is the value of i required to make n>=100. So, genius, what will be printed as the output?

 

You: Oh, I’m not sure. Let’s run the programme and see.

 

Barney: Here we go!

 

 

 

You: Hmm, that’s interesting.

 

Barney: The continue statements asks the loop to go and start a new iteration without executing the rest of the code in the loop. An example will make this clear.

 

#include<iostream>

 

using namespace std;

 

int main()

{

for (int i=0;i<6;i++) {

if (i==2) continue;

cout<<i<<endl;

}

 

system(“pause”);

return 0;

}

 

 

Note that I have declared the integer i in the initialize itself. It is common practice to declare such temporary variables like this. Back to the programme, when i reaches 2, the continue statement asks the programme not to execute the following code an start a fresh iteration. So what will be the output?

 

You: It should print from 0 to 5, but since it continues at two, it should miss 2.

 

Barney: Okay, let’s see.

 

 

 

You: Yeah, I get that.

 

Barney: Good. Now you have a good understanding in the basics of loops. However to master it you need to practice. So keep writing different programmes to illustrate how loops can be used in different situations. And now since we have spent too much time on this I think it’s time we wind up for today.

 

You: Yeah, let’s break for today and continue the next day.

 

Barney: Okay, so bye then, Ted!

 

You: Bye, Barney!

Comments

comments

Engineer. Loves tic-tac.

NO COMMENTS

Leave a Reply