First loop practice code with comments:
#include <iostream> //Initializing utilities
using namespace std;
int main() { //Initializes main function
int n=10; //Initializes integer type variable "n" with value=10
while(n>0) { //Begins loop that continues if the value of variable "n" is greater than 0.
cout<<"n is "<<n<<endl; //Prints "n is " followed by the value of variable n and ends the line
n--; //Subtracts 1 from the value of variable "n"
} //Ends (does not break) "while" loop
return 0; //Ends main function
}
Compiling and running:
[cms-opendata@localhost Programs]$ g++ -Wall loops.cpp -o loops
[cms-opendata@localhost Programs]$ ./loops
n is 10
n is 9
n is 8
n is 7
n is 6
n is 5
n is 4
n is 3
n is 2
n is 1
Uncommenting the line of code involving variable "n" outside of the loop generates an error because the variable is only used initialized within the loop.
Second loop practice code with comments:
#include <iostream> //Initializes utilities
using namespace std;
int main() { //Initializes main function
for (int n=10; n>0; n--) { //Starts "for" loop by initializing integer type variable "n" with value=10 inside the loop, continues the loop if the value of variable "n" is greater than 0, and subtracts 1 from the value of variable "n" at the start of each loop
cout<<"n is "<<n<<endl; //Prints "n is " followed by the value of variable "n" and ends the line
} //Ends (does not break) the "for" loop
return 0; //Ends main function
}
Compiling and running:
[cms-opendata@localhost Programs]$ g++ -Wall loops2.cpp -o loops2
[cms-opendata@localhost Programs]$ ./loops2
n is 10
n is 9
n is 8
n is 7
n is 6
n is 5
n is 4
n is 3
n is 2
n is 1
Third loop practice code with comments:
#include <iostream> //Initializes utilities
using namespace std;
int main() { //Initializes main function
for(int n=0; n<10; n++) { //Starts loop with integer counter variable "n" with value=0, continuing if the parameter "n<10" (variable "n" has a value less than 10"), and adds 1 to the value of "n" at the start of each loop
cout << "n is " << n << ": "; //Prints "n is " followed by the value of variable "n" followed by ": "
for(int m=0; m<=n; m++) { //Starts loop with integer counter variable "m" with value=0, continuing if the parameter "m<n" (variable "m" has a value less than that of variable "n"), and adds 1 to the value of "m" at the start of each loop
cout << m; //Prints the value of variable "m"
} //Ends (does not break) "for" loop within the primary "for" loop
cout << endl; //Ends the line
} //Ends (does not break) "for" loop
return 0 ; //Ends main function
}
Compiling and running:
[cms-opendata@localhost Programs]$ g++ -Wall loops3.cpp -o loops3
[cms-opendata@localhost Programs]$ ./loops3
n is 0: 0
n is 1: 01
n is 2: 012
n is 3: 0123
n is 4: 01234
n is 5: 012345
n is 6: 0123456
n is 7: 01234567
n is 8: 012345678
n is 9: 0123456789