Lab 3
Lab 3
Programming I (C++)
Lab 3
Purpose:
This lab aims at providing a thorough understanding of the control flow of programs. This includes: loops
with while, for, and do-while. In addition, conditionals are also considered (if statement). This lab can
extend to two lab lectures to cover these topics.
Tools:
Visual Studio (at least 2017). Edition 2010 is NOT accepted.
To Do:
1. Write a complete C++ program that prompts the user to enter 20 float numbers. The program then
finds the average of the entered numbers and prints the result out on screen.
Steps of Solution:
- Help students to think how to solve this problem.
- Concentrate on defining the three main steps: Input-Processing-Output.
- The program is to be written using while loop and for loop.
//Using While Loop to calculate the average of 20 numbers
#include <iostream>
using namespace std;
int main() {
float number, sum=0.0, avg;
return 0;
}
Prepared by: Ashraf Bourawy Omar AL-Mukhtar University, Albayda, Libya Page 1 of 3
CSCI 131: C++ Programming Language Fall 2024
int main() {
float number, sum=0.0, avg;
int i;
return 0;
}
int main() {
float number, sum=0.0, avg;
int counter=0; //intialize the counter
cout << "Enter numbers: ";
do {
cin >> number;
sum += number;
counter++;
} while (counter < 3);
return 0;
}
Prepared by: Ashraf Bourawy Omar AL-Mukhtar University, Albayda, Libya Page 2 of 3
CSCI 131: C++ Programming Language Fall 2024
2. Write a program that asks the user to enter an integer number. The program then checks if the
entered number is prime or not.
#include <iostream>
using namespace std;
int main()
{
int num;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> num;
if (num == 0 || num == 1)
{
isPrime = false;
}
else {
if (isPrime)
cout << num << " is a prime number";
else
cout << num << " is not a prime number";
return 0;
}
Learning outcome:
By the completion of this lab, student should know:
1. How to solve a given problem using loops.
2. The logic behind while and for loops.
3. One statement versus a block of statements after while and for.
4. How to initialize, re-initialize (increment or decrement) the counter.
5. How to avoid infinite loops.
6. The logic of the conditional if-else statement.
Prepared by: Ashraf Bourawy Omar AL-Mukhtar University, Albayda, Libya Page 3 of 3