|
Understanding Loops in C++HomeLoops are basically means to do a task multiple times, without actually coding all statements over and over again. For example, loops can be used for displaying a string many times, for counting numbers and of course for displaying menus. Loops in C++ are mainly of three types :- 1. 'while' loop For those who have studied C or JAVA, this isn't very new, as the syntax for the loops are exactly same. So if you know the above languages, don't waste your time understanding loop syntax in C++.
The 'while' loop :- #include<iostream.h> void main() The output of the above code will be
:- A point to notice here is that, for making it more easy to understand, we could also write, int i=1; This would make our code more easy for a newbie, but in actuality it doesn't make a difference either way.
Example code for the same problem using a 'do while' loop would be :- void main() The output would once again be same as in the above example.
The 'for' loop :- The general syntax can be defined as :- To further explain the above code, we
will take an example. Suppose we had to print the numbers 1 to 5, using a 'for'
loop. The code for this #include<iostream.h> void main() The output for this code would be
:- Here variable 'i' is given an initial value of 1. The condition applied is till 'i' is less than or equal to 5. And for each iteration, the value of 'i' is also incremented by 1. Notice here that if we wanted to
print, we would change our 'for' loop to :-
1. Computer Science C++ by Sumita Arora 2. Object Oriented Programming using C++ 3. Using C++ by Rob McGregor Written by Rahul Batra Special Thanks to Ashish Kushwaha and Tanuj Kush |