Sukkur Institute of Business Administration University
Department of Computer Science
Programming Fundamentals
Summer 2025
Instructor: Dr. Faheem Akhtar Rajput
Lab # 06: Mastering Loops: From Beginner to Pro with Exciting
Challenges
Objectives
After performing this lab, students will be able to:
• Use simple loops with increment/decrement operators
• Differentiate between for, while and do-while loop
• Identify the infinite loops
• Use loops with increment/decrement operators
• Use loop to print the series and shapes
• Use loops to print the sum, product, and average
• Use loop to validate the input
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Note: Use Multi-line and Single-line Comments in your programs as per the need
Unary operator
In C++, a unary operator is an operator that operates on a single operand. There are several
unary operators in C++, and I'll provide examples of some common ones:
The negation operator
changes the sign of a numeric value.
int a = 10;
int b = -a; // b is now -10
Increment/Decrement operator
These operators are used to increment or decrement the value of a variable by 1.
int x = 5;
x++; // Increment x by 1, x is now 6
x--; // Decrement x by 1, x is now 5 again
Negation Operator (-):
Practice Exercise 1 (Increment and Decrement operators)
Code is provided below, perform the following tasks:
a) Is there any logical error in code? (Mention error names and line numbers).
b) Resolve errors on paper and observe the output.
c) Execute code on the Machine/System and match the output, you noted/observed.
#include <iostream>
using namespace std;
int main(){
int x = 5, y = 9; // Initialize x and y with values 5 and 9
cout << x << ", " << "y" << endl; // Print x and y separated by a comma and a newline
cout << "x--"<< ", " << y << endl; // Post-decrement x and print x, then print y
cout << --y << ", " << --y << endl; // Pre-decrement y twice and print the result, then
print it again
cout << --x << ", " << y-- << endl; // Pre-decrement x and print it, then post-decrement
y and print y
x = x - 1; // Decrement x by 1 (equivalent to x--)
y -= 2; // Decrement y by 2 (equivalent to y = y - 2)
cout << y++ << ", " << "x" << endl; // Post-increment y and print it, then print the x
also
cout <<endl <<endl;
system("PAUSE");
return 0;
2
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
}
A unary operator ‘Not’ is covered with logical operator
Loop (Repetition statement)
Loops allow you to repeat a block of code multiple times.
The most commonly used loops in C++ are:
1. for Loop: It is used for iterating/repeating a task for specific number of times.
for (initialization; condition; update) {
// code to be executed repeatedly while the condition is true
}
2. while Loop: Repeats a block of code while a specified condition is true.
while (condition) {
// Code to repeat as long as the condition is true
}
3. do-while Loop: Similar to the while loop, but it guarantees that the code block is
executed at least once.
do {
// Code to repeat at least once
} while (condition);
Example 1: Loops
Write a program to print and sum 1 – 10 numbers.
Solution
FOR LOOP WHILE LOOP DO-WHILE LOOP
1. #include <iostream> 1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std; 2. using namespace std;
3. int main() 3. int main(){ 3. int main(){
4. { 4. int i=1; 4. int i=1;
5. int i; 5. int sum = 0; 5. int sum = 0;
6. int sum = 0; 6. while(i<=10) 6. do
7. for (i = 1; i <= 10; i++) 7. { 7. {
8. { 8. cout<<i<<" "; 8. cout<<i<<" ";
9. cout << i << " "; 9. sum = sum + I; 9. sum = sum + I;
10. sum = sum + i;
10. i++; 10. i++;
11. } 11. } 11. }
12. cout << endl; 12. cout<<endl<<sum; 12. while(i<=10);
3
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
13. cout << endl << sum; 14. 13. 13. cout<<endl<<sum; 14.
14. return 0;
15.
15. return 0; 15. return 0;
16. } 16. } 16. }
Practice Exercise 2 (Simple for loop)
#include <iostream>
using namespace std;
int main() {
//Loop to print the hello 10 times
for (int i=1; i<=10;i++){
cout <<”Hello”;
}
//Loop to print the * 10 times
for (int i=1; i<=10;i++){
cout <<”*”;
}
//Loop to print the * 10 times on different line
for (int i=1; i<=10;i++){
cout <<”*”<<endl;
}
//Loop to print the whole Numbers
for (int i=1; i<=10;i++){
cout <<i<<endl;
}
//Loop to print the Even Numbers
for (int i=0; i<=10;i+=2){
cout <<i<<endl;
}
Practice Exercise 3 (Input validation using if)
#include <iostream>
using namespace std;
int main() {
int height, marks;
//Height input and Validation
cout << "Enter the height : ";
cin >> height;
if (height <= 0) {
cout << "Please enter a positive integer for the height" << endl;
return 1; // Exit the program with an error code
}
4
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
//Marks input and validation
cout << "Enter the Marks : ";
cin >> marks;
if ( marks<0 || marks>100 ) {
cout << "Please enter the valid value of Marks" << endl;
return 1; // Exit the program with an error code
}
//ANother way to check the valid marks using negation
if ( !(marks>=0 && marks<=100) ) {
cout << "Please enter the valid value of Marks" << endl;
return 1; // Exit the program with an error code
}
Practice Exercise 4 (Input validation using while)
#include <iostream>
using namespace std;
int main() {
int height, marks;
//Height input and Validation
cout << "Enter the Marks: ";
cin >> marks;
//ANother way to check the valid marks using negation
while ( !(marks>=0 && marks<=100) ) {
cout << "Please enter the valid value of Marks" << endl;
cin >> marks;
}
cout <<"You entered " <<marks;
}
Practice Exercise 5 (Input validation using do-while)
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int height=-1, marks=-1;
//ANother way to check the valid marks using negation
do {
cout << "Please enter the valid value of Marks" << endl;
cin >> marks;
} while ( !(marks>=0 && marks<=100) );
cout <<"You entered " <<marks;
}
5
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Practice Exercise 6(CONTINUE/EXIT)
Write a program to ask user NAME and print “Welcome Dear [NAME]”, then ask user whether
user wants to continue or exit (y → continue, e → exit). Print an appropriate message to tell
user how to EXIT/CONTINUE.
Note: In following each task, you have to ask user whether CONTINUE/EXIT, if continues then
the program should RUN AGAIN otherwise TERMINATE.
Solutions
/*Practice Exercise 6(CONTINUE/EXIT)
Ask user whether CONTINUE/EXIT,
ask user whether user wants to continue or exit (y ' continue, e ' exit).
if continues then the program should RUN AGAIN otherwise TERMINATE.
*/
#include <iostream>
using namespace std;
int main(){
string name; //variable declaration for input name
char choice; //variable to take user choice for exit or continue
do{
cout << "Enter your name: ";
cin >> name;
cout << "Welcome Dear " << name << endl;
cout << "Do you want to continue, Press y to continue and e to exit ";
cin >> choice;
cout <<endl;
} while( choice == 'y'); //loop will continue when user choice is y
return 0;
}
6
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Practice Exercise 7(Continue, break, and exit keywords)
Write a program to demonstrate the use of continue, break, exit, and return keywords.
Solutions
#include <iostream>
using namespace std;
int main(){
//Use of continue keyword
for (int i=1; i<=10; i++){
cout <<endl;
cout <<"Hello";
if (i%4==0)
continue;//will skip the next statements of current iteration
cout << i;
}
cout << endl << "This statement is outside the first loop" << endl <<
endl;
//Use of break keyword
for (int i=1; i<=10; i++){
cout <<endl;
cout <<"Hello";
if (i%4==0)
break; //Continue will break the execution of loop and control
will be shifted to the lines afer loop body
cout << i;
}
cout << endl << "This statement is outside the second loop" << endl;
//Use of exit keyword
for (int i=1; i<=10; i++){
cout <<endl;
cout <<"Hello";
if (i%4==0)
exit(0); //Continue will break the execution of loop and control
will be shifted to the lines afer loop body
cout << i;
}
cout << endl << "This statement is outside the third loop" << endl;
//Use of exit keyword
for (int i=1; i<=10; i++){
cout <<endl;
cout <<"Hello" << endl;
}
cout << endl << "This statement is outside the fourth loop" << endl;
return 0;
}
7
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Practice Exercise 8: Table of Powers:
Generate a table of powers for a number, where you print the number raised to various powers
(e.g., 2^1, 2^2, 2^3, ...) using a for loop.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double base;
int n;
// Ask the user to input the base number
cout << "Enter the base number: ";
cin >> base;
// Ask the user to input the number of powers to calculate
cout << "Enter the number of powers to calculate: ";
cin >> n;
cout << "Table of Powers for " << base << ":" << endl;
for (int exponent = 1; exponent <= n; exponent++) {
// Calculate the result of base raised to the current exponent using
pow
double result = pow(base, exponent);
// Print the result in the format "base^exponent = result"
cout << base << "^" << exponent << " = " << result << endl;
}
return 0;
}
8
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Exercises (Class)
Refreshing Task01 (PRE/POST INCREMENT)
Code is provided below, perform following tasks:
a) Is there any syntax error in code? (Mention error names and line number).
b) Is there any logical error in code? (Mention error names and line number).
c) Resolve both errors on paper and observe the output.
d) Execute code on Machine/System and match the output, you noted/observed.
Note: Teacher can ask anyone to explain your observation.
Refreshing Task02 (PRE/POST DECREMENT)
Code is provided below, perform following tasks:
a) Is there any syntax error in code? (Mention error names and line number).
b) Is there any logical error in code? (Mention error names and line number).
c) Resolve both errors on paper and observe the output.
d) Execute code on Machine/System and match the output, you noted/observed.
1. cout<<x<<", "<<y<<endl;
2.
3. int x, y;
4. cout<<x<<", "<<y<<endl;
5.
6. x = 5, y = 9;
7. cout<<x<<", "<<y<<endl;
9
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
8.
9. cout<<x--<<", "<<y<<endl;
10. cout<<--y<<", "<<--y<<endl;
11. cout<<--x<<", "<<y--<<endl;
12.
13. --x;
14. y = 6;
15. cout<<y--<<", "<<x<<endl;
16. cout<<++y<<", "<<--y<<endl;
17.
18. x = x - 1 // x-- or x -= 1
19. y -= 2 // y = y - 2
20.
21. cout<<y++<<", "<<"x"<<endl;
22. cout<<x<<", "<<y<<endl;
Refreshing Task03 (OBSERVING FOR/WHILE/DO-WHILE BEHAVIOR)
Write a program to ask user input START/END and iterate loop from start to end and perform
following tasks:
a) Print numbers using FOR/WHILE/DO WHILE.
Sample output desired of program
b) Test on following values and observe output (You may be asked anytime during lab
regarding this observation).
Start End Observation
1 10
5 5
1 -10
10 1
c) While testing on last two inputs, it may work abnormally. Now modify above program so
that it should work t time where t is difference between start/end.
d) How for/while/do-while loop behaves?
10
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Exercise 01: Extend Practice Exercise 4 and Practice Exercise 5 to validate the input for height
as well, using while and do-while loop.
Exercise 02 (GRADE CALCULATION and input validation)
Write a program to ask the user to input n_courses (Total Courses), then iterate loop
n_courses time and ask user marks in each course and perform following tasks:
a) Make sure n_courses is between (3 to 8)
b) Calculate the average of all course marks.
c) Calculate the total percentage of all courses.
d) Tell the user whether s/he is PASS/FAIL, FAIL → less than 60, and
otherwise PASS.
Sample outputs:
11
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Exercise 03: Harmonic series
Write a program to output the N terms of HARMONIC series and their SUM.
Exercise 4: Print number series
(A). Write a program that print the starting 10 whole, natural, Even and odd numbers on the
same line.
The required output of the program:
Whole Numbers: 0 1 2 3 4 5 6 7 8 9
Natural Numbers: 1 2 3 4 5 6 7 8 9 10
Odd Numbers: 1 3 5 7 9 11 13 15 17 19
Even Numbers: 0 2 4 6 8 10 12 14 16 18 20
(B). Using loop, write a C++ program that displays a series of alphabets in ascending
order from ‘A’ to ‘Z’ and then in descending order from ‘Z’ to ‘A’.
(C). Print the first 10 multiples of 3 and 5 using two variables.
12
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Exercises (Weekly)
Bonus Exercise: (Guess the Number Game)
This is the bonus exercise. If you complete it and present it to your classmates on Monday. Then
you will be given some extra incentive in form of extra sessional points or some certificate. In
other case, I will explain it during class. Best of luck
Generate a random number between 0 and 100. Ask the user to guess the number using a while
loop until they guess correctly.
Sample output when the random number was 59:
Sample output when the random number was 51:
13
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Exercise 5: Input validation: Write a program that asks the user to input the marks in the
range of 0-50. If the user enters the value out of this range then the program will again ask the
user to input the valid number until the user enters the acceptable value.
Sample output
Exercise 6: Print number series in reverse
Write a program that prints the starting 10 whole, natural, Even, and odd numbers on the same
line in Reverse Order.
The required output of the program:
Exercise 7: Print number series
Write a program that ask user to input the start and the End of the series.
Then it prints whole, natural, Even and odd numbers between these ranges.
Let’s suppose the user enters value 3 for start, and value 9 for start End
Then the output of the program:
14
DEPARTMENT OF COMPUTER SCIENCE, SUKKUR IBA UNIVERSITY
Whole Numbers: 3 4 5 6 7 8 9
Natural Numbers: 3 4 5 6 7 8 9
Odd Numbers: 3 5 7 9
Even Numbers: 4 6 8
Exercise 8: Print number series
Generate and print the multiplication table (up to 10) for a given number using a for loop.
For Instance, if the user enters the value 5, then the table of 5 should be printed.
Exercise 9: Reverse Counting:
Create a program that counts down from N to 1 using the while and for loop.
‘N’ can be any integer value that the user will enter into the program.
[Link]
4
15