Skip to main content

The Loop Statements.

In this slide we try to figure out what are loops and why they are important and using them with a couple of examples. After that we will try to understand some other statements like Break, Continue and Goto statement.

Loops are used to perform some task repeatedly until some condition remains true. for e.g. take this blog, we will keep learning C++ until we don't get to a level, where we can write basic C++ program very easily.

Let's discuss these, one by one -

  1. for loop Statement.
  2. while loop Statement.
  3. do-while loop Statement.
Let's Start our discussion.

for loop

for loop is one of the most widely used loop, and I myself most of time use for loop.
for loop is used when you very  well know that how much repetitions you need to perform. For example, counting numbers upto 100, and the time we reach hundred we stop.
Syntax is shown in the below snippet - 

#include<iostream>
using namespace std;
int main()
{
	for( initialization ; condition ; increment/decrement ) { 
		Body;
	}
}

Here, in Initialization part we define our predicate/variable which going to be used in our loop. (We can modify these initialization, condition, increment/decrement statements according to need of the task)

let's see a program to find Sum of first 100 natural numbers, using For loop.

#include<iostream>
using namespace std;
int main()
{
	int sum = 0;		// Sum is initialized to 0;

	for(int i = 1; i<= 100; i++)
		sum += i;
	
	/*

	Other way we can write it, by doing the initialization in some other step, before loop.
	int i = 1; 
	for(;i <= 100 ;i++)
		sum += i

	*/
	cout << "Sum of first 100 natural numbers is : " << sum << endl;		

	/*
	Direct formula for calculating sum of first "n" natural numbers is
	n*(n+1)/2
	*/

	return 0;
}

Mostly, we use for loop in initializing the printing array, because there indices are consecutive it is very easy to use for loop, for example -

#include<iostream>
using namespace std;
int main()
{
	int sum = 0;		// Sum is initialized to 0;

	int *arr = new int[10];

	for(int i = 1; i<= 10; i++)
		arr[i] = 2*(i-1);			// Initializing array with some values.
							// Try to figure out what will be the values.

	for(int i = 0; i<10; i++)
		cout << arr[i] << " ";
	cout << endl;
	
	return 0;
}

Creating array of size dynamically and using for loop to initialize it.

Did you noticed, after for loop we have not used curly braces( { } ), because, if we are writing only one statement after this special statement like if, else, for, while etc. we don't need to use curly braces but writing more than one statements after these special statements and to make them lie inside these statement we have to use curly braces. around them.

There is a one more type of for loop, that C++ provide us on the go. 

Foreach loop

It resembles to the loop that we write in python and was included in C++11 ,For syntax, see below program - 

#include<iostream>
using namespace std;
int main()
{
	// We will iterate over the array using foreach loop.

	int arr[10] = {1,2,3,4,5,6,7,8,9,10};

	for(int x : arr)
		cout << x << " ";
	cout << endl;

	return 0;
}

You, can see that the syntax is very easy as compared to traditional for loop, The more important use of this loop, we will find in when we will be learning iterators and C++ STL.

Remember you can't modify the values of arr elements using this loop, until you don't define the "x" as a reference to array elements(If you didn't get it now don't worry, will be covering soon).

Now, we shall start our talk about while loop -

While loop

The While loop as the name suggests, repeat while a condition is true/false, depending on your condition. It is mostly used when you don't know the number of repetitions, But, we can also use for loop, even if you don't know number of repetitions. Let's see the Syntax - 
#include<iostream>
using namespace std;
int main()
{
	
	while(some condition)
	{
		// Do something;
	}
	
	return 0;
}

The syntax is very simple, Now let's take an example for or reference - 

#include<iostream>
using namespace std;
int main()
{
	int a = 10;

	while(a < 20)		// We don't know when "a" becomes 20.
	{
		cout << a << " ";
		++a;
	}
	cout << endl;

	return 0;
}

As, I already commented, we are not aware of when "a" will become greater than or equal to 20, but, until then keep iterating/looping.

do-While loop

It's almost same to the while loop, but, there is a little difference -
For and While loop are entry controlled statement, which simply means while entering in the for loop it first checks the condition written inside the loop is true or false, and if it is false at first step itself, we will not be able to enter inside the loop.
Do-while on the other hand is exit controlled statement, which means that it first enter inside the loop and then checks if the condition is true or false, and if it is false, the loop overs, we can clearly see that the do-while loop is iterating executing the statements inside the loop at-least once, regardless of the fact that condition is true or false.
Below program shows syntax - 

#include <iostream>
using namespace std;
int main()
{
	do{
		// Do Something
	}while(condition); // don't forget semicolon here

	return 0;
}

A simple program to see the virtue of using do-while loop - 

#include <iostream>
using namespace std;
int main()
{
	int a = 10;

	do{
		cout << "A is less than 5" << endl;
	} 
	while ( a < 5 );	// False as 10 > 5

	return 0;
}

Try to copy and run this is your local environment and you will see that the program is still printing "A is less than 5", while the condition is false, this is because, the loop will execute at-least ones regardless of the false condition.

As of now we have covered the loops, Now, we will see some of the helping statements, that provide extra functionality for our loops.

Break Statement - This statement is used when you want to break the loop when a particular condition is satisfied, for example take this piece of code and read it thoroughly.

#include <iostream>
using namespace std;
int main()
{
	// We have lineraly search over this array to find 6
	int arr[] = {1,2,3,4,5,6,7,8,9,10};

	for(int i = 0; i< 10; i++)
	{
		if(arr[i] == 6)
		{
			cout << "Found at " << i << " index" << endl;
			break;			
		}
	}
	/*
	In the above loop I used break to save some time as
	if we already found the 6 there is no need to iterate 
	over other elements, so directly break the loop,
	otherwise it will keep iteraing over next elements
	even if there are million of elements next to it.
	*/

	return 0;
}

Continue Statement - The statement is used when you want to skip the loop when a particular condition is satisfied, for example take this piece of code and read it thoroughly - 

#include <iostream>
using namespace std;
int main()
{
	// We have to print number from 1 - 10 but not 6

	for(int i = 1; i<=10; i++)
	{
		if(i == 6)
			continue;		// this statement skips every statement occuring after it.
		cout << "Value is : " << i << endl;
	}

	return 0;
}

Goto Statement - The statement is used for directly jumping from one part of the program to another part of the program. See the below example for better understanding - 

#include <iostream>
using namespace std;
int main()
{
	
	cout << "First" << endl;
	cout << "Second" << endl;

	goto last;			// Jumps from here
	
	cout << "thrid" << endl;
	cout << "fourth" << endl;
	
	last:				// To here like.
	
	cout << "Fifth" << endl;
	cout << "sixth" << endl;
	
	return 0;
}

Try to execute this program in your environment, You will see that "third" and "fourth" will not be printed out, this is due to we jumped from above of those two statements.

You can jump in either direction of your program, it just depends on your program and you.

It sufficient for now, practicing will be done throughout the whole slides. Keep reading.

 Stay tuned for the upcoming content. For any query leave a comment below.

Click the Subscribe button at the top, to follow my every post regarding c++.

References -
  • Lippman, Stanley B. c++ primer, 3rd ed. April 2 , 1998.

Comments

Popular posts from this blog

Introduction to Computer Science.

 Before directly jumping deeply in c++, let's first start by creating the roots of computer science. In this post we will answer the following question. What is Computer and How it works? What is Program and Operating system? Low Level vs High Level Language? Compiler v/s Interpreter? By Knowing All these basic concepts You will be able to understand the upcoming more complex concepts easily. Let's start answering the above questions. What is Computer and How it works? What is computer? If I answer briefly,  what is computer?  then it is just a calculator used for doing simple calculations. If I have to answer where is computer used?, then I could probably say everywhere. We are surrounded by computer, for example mobile, smartwatches, and personal computer (obviously).  The below image is the first mechanical computer that we used for calculation.                                        Abacus How computer works? The computer's internal functionality is a whole separate bra

C-style strings vs String Class.

Here, we are going to learn about, what are C-Style Strings and what is String class . So, let's start by giving you the introduction. C-Style String is nothing but, an array of characters, and from the term array we can surely assume that these are static in size i.e. the size of these C-Style strings cannot be increased or decreased. String Class is a Built-in class that provide us much more functionality than C-Style String. C-STYLE STRINGS Before learning the String class, which is full-fledged feature of C++, we should rather start by taking a look at some important things about C-Style String. C-Style Strings are actually array of characters that are terminated by a null character "\0". If you are confused with, why null character? The reason is that, It helps us to define, upto which index we have some useful data present in our character array, and after null character there may or may not be some garbage values of characters. Let's first start by showing a

Algorithms, Pseduocodes and FlowCharts.

Some Basic Knowledge. C++ is a general purpose programming language, created by Bjarne Stroustrup and was firstly released in  1985. It is an extension to C language, Reason for that is if you are familiar with C language than you must be familiar with the fact that there are no classes, templates etc. present in C language. Due to which when classes are added to C language it is named as "C with Classes", but C++ is considered as default name now.  Extra thing to remember - In "C++" the symbol "++" after C is post increment symbol and therefore, "C++" means that In C additional features are added. Now, let's define, what are algorithms? Algorithms are nothing but set of rules that must be followed to accomplish some task. (Now, What that mean?😕) let's take an example of swapping two numbers, i.e. if a = 10 and b = 20 after swapping a = 20 and b = 10. How will you write the procedure for this?  (There are many such algorithms). Accordin