0% found this document useful (0 votes)
6 views14 pages

Lab 4 CP (1)

This document outlines Lab #04 for CS-107: Computer Programming at NUST, focusing on control and iterative structures in C++. It covers key programming concepts such as switch-case statements, while loops, do-while loops, for loops, and nested loops, along with examples and syntax. Additionally, it includes lab tasks that require students to apply these concepts in practical programming scenarios.

Uploaded by

mohsinsubhani96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

Lab 4 CP (1)

This document outlines Lab #04 for CS-107: Computer Programming at NUST, focusing on control and iterative structures in C++. It covers key programming concepts such as switch-case statements, while loops, do-while loops, for loops, and nested loops, along with examples and syntax. Additionally, it includes lab tasks that require students to apply these concepts in practical programming scenarios.

Uploaded by

mohsinsubhani96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Department of Computer and Software Engineering

College of E&ME, NUST, Rawalpindi

CS – 107: Computer Programming

LAB # 04: Control and Iterative Structures in C++

Course Instructor: Assoc. Prof. Dr. Farhan Hussain

Lab Instructor:Engr. Ayesha Khanam

Sr. No. Student’s Name CMS ID

CS – 107: Computer Programming 1


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

LAB # 04: Control and Iterative Structures in C++

Software Requirement(s): MS Visual Studio

Lab Objectives:
Control and iterative structures are fundamental constructs in programming, allowing to control
the flow of execution and repeat tasks efficiently. This lab explores switch-case statements, loops
(while, do-while, for), nested loops, and loop control statements (break, continue). Mastering
these concepts shall enable students to develop efficient, structured, and well-organized code.

Switch Case Statements

The switch-case statement allows multi-way branching based on an integer, character, or


enumeration constant, presented as an argument. It is an efficient alternative to multiple if-else
statements and is often used in menu-driven programs.

Syntax:
switch (expression)
{
case caseLabel1:
// Code to execute if expression == constant1
break;
case caseLabel2:
// Code to execute if expression == constant2
break;
...
default:
// Code to execute if no case matches
}

1. Expression: The switch statement evaluates an expression that must result in an integer,
character, or enumeration constant. The result of this evaluation determines which case is
executed.
2. Case Labels: Each case label specifies a possible value of the expression. If the evaluated
expression matches a case, the statements inside that case block execute.

CS – 107: Computer Programming 2


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

3. Break Statement: The break statement ensures that execution exits the switch-case
structure once a match is found. Without break, execution will continue to the next case
(fall-through behavior), which is often undesirable unless explicitly needed.
4. Default Case: The default block executes if no matching case is found. It acts as a
fallback mechanism to handle unexpected inputs.

Example:
#include<iostream>
usingnamespace std;
intmain() {
int day;
cout<<"Enter day number (1-7): ";
cin>> day;

switch (day)
{
case 1:
cout<<"Monday"; break; // If day is 1, print Monday
case 2:
cout<<"Tuesday"; break; // If day is 2, print Tuesday
case 3:
cout<<"Wednesday"; break; // If day is 3, print Wednesday
case 4:
cout<<"Thursday"; break; // If day is 4, print Thursday
case 5:
cout<<"Friday"; break; // If day is 5, print Friday
case 6:
cout<<"Saturday"; break; // If day is 6, print Saturday
case 7:
cout<<"Sunday"; break; // If day is 7, print Sunday
default:
cout<<"Invalid input!"; // If input is not 1-7, print invalid message
}
return 0;
}

CS – 107: Computer Programming 3


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

While Loop

The while loop executes a block of code as long as a condition remains true. It is useful when the
number of iterations is unknown before runtime.

Syntax:

while (condition)
{
// Code to execute
}

1. Condition: A Boolean expression that determines whether the loop should continue
executing. If the condition evaluates to true, the loop body executes; otherwise, the loop
terminates.
2. Execution Flow: The condition is checked before the loop body runs. If it is false
initially, the loop never executes.
3. Indeterminate Iterations: The while loop is useful when the number of iterations is
unknown before execution, as it depends on real-time data or user input.
4. Common Use Cases:
a. Reading User Input: Continuously asking for valid input until a correct value is
entered.

CS – 107: Computer Programming 4


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

b. Processing Data Streams: Iterating over a file or network data until reaching an
end marker.
c. Waiting for Events: Continuously checking for an external event to occur before
proceeding.
5. Potential Pitfall: If the condition is always true, the loop becomes infinite, leading to a
program hang.

Example:
#include<iostream>
usingnamespace std;

intmain()
{
int count = 1;
while (count <= 5) // Loop continues while count is less than or equal to 5
{
cout<<"Iteration: "<< count <<endl;
count++; // Increment count to prevent infinite loop
}
return 0;
}
Do-While Loop

The do-while loop ensures execution at least once before checking the condition. It is useful for
scenarios like menu-driven programs and user input validation.

CS – 107: Computer Programming 5


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

Syntax:
do {
// Code to execute
} while (condition);

1. Guaranteed Execution: The loop body runs at least once, even if the condition is false.
2. Condition Checking: Occurs after execution, making it suitable for user-driven loops.
3. Common Use Cases:
a. Password validation
b. Retrying operations
c. User confirmation dialogs.

Example:
#include<iostream>
usingnamespace std;

intmain()
{
int num;
do
{
cout<<"Enter a positive number: ";
cin>> num; // User input
} while (num < 0); // Repeat loop if input is negative
return 0;
}

Difference between while and do-while loop:

Feature While Loop Do-While Loop

Condition Check Before execution After execution for once

Execution Guarantee Will not execute if condition is false Executes at least once

CS – 107: Computer Programming 6


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

For Loop

The for loop is used when the number of iterations is known beforehand and follows a structured
approach with an initialization, condition, and update.

Syntax:
for (initialization; condition; update)
{
// Code to execute
}
1. Initialization: Declares and initializes the loop control variable.
2. Condition: Evaluated before each iteration; if false, the loop terminates.
3. Update: Modifies the loop control variable.
4. Common Use Cases:
a. Counting loops
b. Iterating over arrays
c. Running a fixed number of repetitions

CS – 107: Computer Programming 7


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

Example:
#include<iostream>
usingnamespace std;

intmain()
{
for (inti = 1; i<= 5; i++) // Loop runs from 1 to 5
{
cout<<"Iteration: "<<i<<endl;
}
return 0;
}

Nested Loops:

A nested loop is a loop that exists within another loop. The inner loop executes completely for
each iteration of the outer loop.
Use Cases:
 Matrix Operations: Iterating over 2D arrays.
 Pattern Printing: Creating complex patterns using nested structures.
 Sorting Algorithms: Bubble sort, selection sort, etc.

Example: Printing a multiplication table.

#include<iostream>
usingnamespace std;

intmain()
{
for (inti = 1; i<= 5; i++) // Outer loop iterates through numbers 1 to 5

{
for (int j = 1; j <= 10; j++) // Inner loop iterates through 1 to 10

{
cout<<i<<" x "<< j <<" = "<<i * j <<endl;
}
cout<<endl; // Separate each table
}
return 0;
}

CS – 107: Computer Programming 8


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

Break and Continue Statements:

 Break

The breakstatement is used to exit a loop immediately when a specific condition is met.

Example:
#include<iostream>
usingnamespace std;

intmain()
{
for (inti = 1; i<= 10; i++)
{
if (i == 4)
break; // Exit loop when i is 4
cout<<i<<" ";
}
return 0;
}

 Continue

The continue statement skips the current iteration and proceeds to the next one.

Example:
#include<iostream>
usingnamespace std;

intmain()
{
//The loop prints numbers 1, 2, 4, 5, skipping 3.
for (inti = 1; i<= 5; i++)
{
if (i == 3)
continue; // Skip iteration when i is 3
cout<<i<<" ";
}
return 0;
}

CS – 107: Computer Programming 9


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

Lab Tasks
1. Simulate an ATM transaction system where the user can choose options such as
withdraw, deposit, check balance, and exitusing a switch-case statement. Ensure proper
input validation and error handling.

2. Create a car rental system where the user selects a car type (Economy, Standard, Luxury)
and enters the number of rental days. Use control structures to determine the rental price
and apply a surcharge for luxury cars.

3. Write a program that takes the severity level of a patient’s condition (Mild, Moderate,
Severe, Critical) and assigns them to an appropriate medical department using if-else
conditions. Additionally, determine if the patient needs immediate admission based on
their severity level.

4. Write a program that calculates the factorial of a number using ado-while loop. Ensure
that the user enters a non-negative integer.

5. Write a program where the user has to guess a randomly generated number between 1
and 100. The program should provide hints such as "Too high" or "Too low" and stop
when the correct number is guessed.

Input:
#include <iostream>
using namespace std;

int main() {
// already defined "random" number to gues
int randomNumber = 57; // testing value
int userGuess;
int attempts = 0;

cout << "Welcome to the number guessing game!" << endl;

// Loop until the user guesses the correct number


while (true) {
cout << "Guess a number between 1 and 100: ";
cin >> userGuess;

attempts++;

if (userGuess > randomNumber) {


cout << "Too high! Try again." << endl;

CS – 107: Computer Programming 10


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

}
else if (userGuess < randomNumber) {
cout << "Too low! Try again." << endl;
}
else {
cout << "Congratulations! You guessed the correct number " <<
randomNumber << " in " << attempts << " attempts." << endl;
break; // Exit loop when the correct number is guessed
}
}

return 0;
}

6. Develop a program that takes vehicle speed as input and determines if the driver is within
the limit, overspeeding, or heavily overspeedingusing if-else conditions. Use aswitch-
case statement to apply fines based on the violation category. Implement a loop to check
multiple vehicles.

#include <iostream>
using namespace std;

int main() {
int limit = 80;
int vehicle_speed;
cout << "Enter the vehicle speed: ";
cin >> vehicle_speed;
if (vehicle_speed <= limit)
{
cout << "Speed is within the limit." << endl;
}
else if (vehicle_speed <= limit + 20)
{

CS – 107: Computer Programming 11


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

cout << "Overspeeding. Fine:1000Rs" << endl;


}
else {
cout << "Heavily overspeeding Fine: 2500Rs" << endl;
}
system("pause");
return 0;
}

7. Develop a program that simulates a restaurant ordering system. The user should be able
to choose a meal from a menu using a switch-case statement, enter the quantity, and
calculate the total bill. Use a loop to allow multiple orders and an if-else condition for
applying discounts on orders exceeding a specific amount.
8. #include <iostream>
9. using namespace std;
10.
11. int main() {
12. int choice, quantity;
13. float T_Bill = 0;
14. float price = 0;
15. char MoreOrder;
16.
17. // Loop to allow multiple orders
18. do {

CS – 107: Computer Programming 12


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

19. // Display menu


20. cout << "\n--- Welcome to to Ali Restaurant\n";
21. cout << "1. Burger - 550Rs\n";
22. cout << "2. Pizza - 1500Rs\n";
23. cout << "3. Pasta - 750Rs\n";
24. cout << "4. Salad - 300Rs\n";
25. cout << "Enter the number of the item you want to order:
";
26. cin >> choice;
27.
28. // Switch statement to handle the user's choice
29. switch (choice) {
30. case 1:
31. price = 550;
32. cout << "You selected Burger.\n";
33. break;
34. case 2:
35. price = 1500;
36. cout << "You selected Pizza.\n";
37. break;
38. case 3:
39. price = 750;
40. cout << "You selected Pasta.\n";
41. break;
42. case 4:
43. price = 300;
44. cout << "You selected Salad.\n";
45. break;
46. default:
47. cout << "Invalid choice. Please select from the
menu.\n";
48. continue; // Skip the rest and go back to the
menu if the choice is invalid
49. }
50.
51. // Enter quantity
52. cout << "Enter the quantity: ";
53. cin >> quantity;
54.
55. // total amount for the current order
56. T_Bill += price * quantity;
57.
58. // for more order
59. cout << "Do you want to order more items? (y/n): ";
60. cin >> MoreOrder;
61.
62. } while (MoreOrder == 'y' || MoreOrder == 'Y'); // more order
'n'
63.
64. // Apply discount if the total bill exceeds 2000 amount
65. if (T_Bill > 2000) {

CS – 107: Computer Programming 13


Department of Computer and Software Engineering
College of E&ME, NUST, Rawalpindi

66. T_Bill *= 0.9; // Apply 10% discount


67. cout << "You received a 10% discount!\n";
68. }
69.
70. // Display the total bill
71. cout << "\nTotal bill: Rs" << T_Bill << endl;
72.
73. return 0;
74. }

General Guidelines
 Properly comment and indent the code.
 Make the console intuitive.
 Attach the code and screenshot of the console for each task.
 Ensure originality in your documentation. Plagiarized reports get zero credit, whatsoever.
 Make submissions well in time to earn a maximum score.
 In case of any queries related to the lab, reach me out at [email protected] .

CS – 107: Computer Programming 14

You might also like