Loops in C++
Loops
In computer programming, loops are used to repeat a block of code.
For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our programs by making effective use of loops.
There are 3 types of loops in C++ :
for
loopwhile
loopdo...while
loop
While Loops
Syntax of While Loop
while(condition) {
// do something
}
- A
while
loop evaluates thecondition
- If the
condition
evaluates totrue
, the code inside thewhile
loop is executed. - The
condition
is evaluated again. - This process continues until the
condition
isfalse
. - When the
condition
evaluates tofalse
, the loop terminates.
Flow Chart of While Loop:
Example:
Print numbers 1 to n
on the stdout
#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int num = 1;
while( num <= n ) {
cout << num << endl; // Printing the number
num = num + 1 // Increasing number from 1 to 2 then 2 to 3 then 3 to 4 until it is equal to n
/* Can also be written like this:
* num += 1;
* num++;
* ++num;
*/
}
}
Example:
Print the sum of positive numbers entered by the user.
#include<iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << endl << "The sum is " << sum << endl;
}
Patterns:
Square:
Input: 4
Output:
****
****
****
****
Input: 5
Output:
*****
*****
*****
*****
*****
Solution:
- Check for
rows
andcolumns
- Here, 4 rows for 4 columns
rows == columns
#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int i = 1; // Starting position
while(i <= n) {
int j = 1;
while(j <= n) {
cout<<'*';
j++;
}
cout<<endl;
i++;
}
}
Numbered Square:
Input: 4
Output:
1111 -> 1st row
2222 -> 2nd row
3333 -> 3rd row
4444 -> 4th row
Solution:
- Check for
rows
andcolumns
- Here, 4 rows for 4 columns
rows == columns
- And, instead of
*
we need to print therow number
#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int row = 1; // Starting position
while(row <= n) {
int col = 1;
while(col <= n) {
cout<<row; // Notice what we're printing
col++;
}
cout<<endl;
row++;
}
}