Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

(SP - 22) Lab 1 - Basics + Flow Control

The document provides instructions and examples for a structured programming lab on basics and flow control. It outlines lab rules including attendance, content availability, and quizzes. The document then provides examples and explanations of switch statements, if/else statements, loops, and type conversions in C++. Tracing examples are given to predict program output and identify bugs. Students are tasked with writing programs involving constants, conditionals, and calculations.

Uploaded by

Mohamed Mustafa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

(SP - 22) Lab 1 - Basics + Flow Control

The document provides instructions and examples for a structured programming lab on basics and flow control. It outlines lab rules including attendance, content availability, and quizzes. The document then provides examples and explanations of switch statements, if/else statements, loops, and type conversions in C++. Tracing examples are given to predict program output and identify bugs. Students are tasked with writing programs involving constants, conditionals, and calculations.

Uploaded by

Mohamed Mustafa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Lab #1

Basics + Flow Control

Structured Programming 2021/2022


Lab Rules

1. You MUST attend the lecture. The section is for practical work ONLY.
2. Attendance limited to student section. No EXCEPTIONS.
3. Attendance will be taken in each lab.

4. Lab Content will be uploaded weekly to your LMS.


5. Marks will be assigned to Hands-on.

6. Be ready for a QUIZ at anytime.


Today’s Lab

Switch
If/Else
Multiple conditions
in if
Break/
Continue

Revision

Some Basics

And More!
Loops
Tracing (1)

When does the following program output the word excellent?


What happens if we eliminate the else keyword?

#include <iostream>
using namespace std; It'll output very
int main() good then
The Program
{ excellent for the
will never
float grade; grades
cin>>grade; output
above 85
if(grade > 75) “Excellent”
cout<<"very good\n";
else if(grade > 85)
cout<<"excellent\n";
}
4
Tracing (1) – cont’d

To correct the program, we should swap the if and the else statements:

#include <iostream>
using namespace std;
int main()
{
float grade;
cin>>grade;
if(grade > 85)
cout<<"excellent\n";
else if(grade > 75)
cout<<"very good\n";
}

5
Tracing (2)

When does the following program output the word no?

#include <iostream> Never, the operator


using namespace std; used here is
int main() assignment not
{ comparison operator
int x = 1;
if ( x = 4 )
‘==’
cout << "yes";
else
cout << "no";
}

6
Tracing (3)

What happens if we enter 2 then 3 then 3 in the following program?


a. Would the else be invoked?
a= 2
  b=3
c = 3 not be
The else will
  int a,b,c;
invoked.
cout <<"enter 3 numbers a, b, and c \n";
cin>> a >> b >> c ; The else is matched
if ( a == b ) with the last if
if ( b == c )
cout <<"a, b and c are the same \n";
else
cout << "a and b are different \n";

7
Tracing (3) – cont’d

b. Correct the program such that the else matches the second if:

  int a,b,c;
cout <<"enter 3 numbers a, b, and c \n";
cin>> a >> b >> c ;
if ( a == b )
if ( b == c )
cout <<"a, b and c are the same \n";
elseelse
coutcout
<< "a
<< and b are
“b and different
c are \n";\n";
different

8
Tracing (3) – cont’d

c. Correct the program such that the else matches the first if:

 
int a,b,c;
cout <<"enter 3 numbers a, b, and c \n";
  int a,b,c;
cin>> a >> b >> c ;
cout <<"enter 3 numbers a, b, and c \n";
if ( a == b )
cin>> a >> b >> c ;
{
if ( a == b )
if ( b == c )
if ( b == c )
cout <<"a, b and c are the same \n";
cout <<"a, b and c are the same \n";
}
else
cout << "a and b are different \n";
else
cout << “a and b are different \n";
9
Tracing (4)

a. What is the output if we entered letter ‘B’?

 
char letter;
cout <<"enter a letter\n" ; You typed B.
cin>> letter ;
switch(letter)
Invalid Input
{
case 'A': cout<<"you typed A\n";
case 'B': cout<<"you typed B\n";
default: cout<<"Invalid input\n";
}

10
Tracing (4) – cont’d

b. How to fix this bug?


Add break
after each
case
char letter;
cout <<"enter a letter\n" ;
cin>> letter ;
switch(letter)
{
case 'A': cout<<"you typed A\n"; break;
case 'B': cout<<"you typed B\n"; break;
default: cout<<"Invalid input\n";
}

11
Tracing (4) – cont’d

c. Modify the code to handle input of small letters ‘a’ and ‘b’:

char letter;
char
cout letter;
<<"enter a letter\n" ;
cout
cin>> letter ;a letter\n" ;
<<"enter
cin>> letter ;
switch(letter)
switch(letter)
{
{ case 'A':
case
case 'A':
'a': cout<<"you
cout<<"you typed
typed A\n";
A\n"; break;
break;
case 'B':
case 'B': cout<<"you typed B\n"; break;
default:
case 'b': cout<<"Invalid input\n";
cout<<"you typed B\n"; break;
} default: cout<<"Invalid input\n";
}
12
Type Conversion
A B
Tracing (5)

What will be the output?

#include <iostream>
Data Type Order
using namespace std;
long double Highest
int main()
double
{ float
int count = 7 ; long
float avgweight = 155.5; int
double totalweight = count * avgweight ; short
char Lowest
cout << “total weight =” << totalweight << endl ;
}

total weight =1088.5


Tracing (6)

What will be the output?

#include <iostream>
using namespace std;
int main()
{
int nValue1 = 10;
int nValue2 = 4;
float fValue = nValue1 / nValue2;
cout <<fValue; fValue = 2
}
Type Conversion

How can we correct this mistake?

#include <iostream>
using namespace std;
int main()
{
int nValue1 = 10;
int nValue2 = 4;
fValue = 2.5
float fValue = (float)nValue1 / nValue2;
cout <<fValue;
}
const
and

#define
Develop!

Write a program to output the area of a circle where PI is defined once as:

1. a const qualifier

2. a #define directive

18
Develop! Solution

1. const qualifier:

#include <iostream>
using namespace std;
int main()
{
const float PI = 3.14159;
float radius;
cout << "Enter the radius : ";
cin >> radius;
cout << "Area = " << PI * radius * radius <<endl;
}

19
Develop! Solution

2. #define directive:

#include <iostream>
using namespace std;
#define PI 3.14159 /* note: no datatype, no semicolon, no
equal*/

int main()
{
float radius;
cout << "Enter the radius : ";
cin >> radius;
cout << "Area = " << PI * radius * radius <<endl;
}
20
LOOPS
Loops
❑ Loop is a control structure that repeats a group of steps in a program.
• Loop body stands for the repeated statements

❑ Any Loop is composed of the following statements:


1- Counter Initialization.
2- Condition Checking.
3- Counter Increment/Decrement

❑ Three Types of Loops:


WHILE / DO..WHILE / FOR
22
while (condition) do for(initialization;
{ //statements; { condition;
} //statements; increment)
} while(condition); {
//statements;
Initialize the }
counter Initialize the
counter

Con NO
Body of Loop
ditio counter=start to NO
n stop STEP
Increment / increment
YES
Decrement YES
the counter
END
Body of Loop END
Body of Loop
YES Cond NO

Increment / ition
Decrement
the counter END
Problem (1)
Write a C++ program that calculate the square of n given numbers.

Enter a number: 3
10 -> 100
2 -> 4
6 -> 36
Solution (using For-Loop)
Solution (using While-Loop)
Solution (using Do-While-Loop)
Loop Tracing (1)

What is the output of the following program? There is ; after the


loop so the loop
will be executed
#include <iostream> 30 times
using namespace std;
int main()
{
int sum=0, index;
for(index = 0; index < 30; index++);
sum += index ;
cout <<sum ;
}
index now = 30 will
be added to sum, so
the output = 30
28
Loop Tracing (2)

After how many times will the following loop terminate?

#include <iostream>
using namespace std; Never… n is not
int main() modified
{ anywhere
int sum=0;
int n=10;
while (n<=100)
sum+= n*n ;
}

29
Problem (2)
Write a temperature-conversion program that converts from Celsius to
Fahrenheit .

Then ask the user if he/she needs more operations or not.


Solution
Break and continue
The break statement provides way for terminating the loop to terminate early.

The continue statement provides a convenient way to jump back to the top of
a loop earlier than normal, which can be used to bypass the remainder of the
loop for an iteration
Problem (3) (use break)
Write a program that accepts numbers from the user and counts the positive
and negative numbers. The results should be displayed when the user enters 0.
A sample run of the program should be like:

Enter numbers (0 to end): -1


4
-2
44
-5
0
You entered 2 positive numbers and 3 negative
ones.
Solution
Another Solution
Problem (5)

Write a program to determine whether a given number is a prime.


(A prime number is only divisible by 1 and itself)
Sample Execution:

Enter a number: 4 Use:


Not prime!
1- break in the loop body
 
Enter a number: 7 2- boolean variable as a flag
Prime!

36
int Number;
bool prime = true ;
cout<< "enter number: ";
cin>> Number;
if(Number==1)
cout<< " 1 is not prime " << endl;
else if (Number==2)
cout<< " 2 is prime " << endl;
else
{
for (int i=2;i<Number;i++)
{
if (Number%i==0)
{
prime= false;
break;
}
}
if (prime == true)
cout<<Number<<" is a prime\n";
else
cout<<Number<<" is not a prime\n";
}
Debugging Finding the Factorial of a Number
Example

38
Debugging Example

Write a program to
calculate the
factorial of a number
provided by the user.

39
Debugging Example – cont.
Wrong answer!

40
Debugging Example – cont.
Set a Breakpoint and start debugging!

41
Debugging Example – cont.

Create a Watch
and add all the
variables you
want to trace.

42
Debugging Example – cont.
Step Over the code and observe the values in the Watch
Window

43
Debugging Example – cont.

Find the problem in the following code:


for (int i = 0; i < number; i++)
{
factorial = factorial * i;
}

int i = 0
i can not start with 0;

(Multiplying by zero makes a wrong solution)

44
Debugging Example – cont.
Fix and Restart Debugging…

Wrong Answer -> Factorial of 4 = 24 not 6

45
Debugging Example – cont.
Trace the variable values in the
Watch window…

What is the problem?

The loop finishes before multiplying


the last number

for (int i = 1; i < number; i++)

• The loop condition must be less than or equal (<=) not


less than (<)

46
Debugging Example – cont.
Fix and retry…

Correct Answer!

47
Problem (6)

• A long time ago, the Egyptians figured


out that a triangle with sides of length 3,
4, and 5 had a right angle as its largest
angle.

• You must determine if other triangles


have a similar property.
Problem (6) – cont’d

Input:
• Input reads several test cases, followed by a line containing 0 0 0.

• Each test case has three positive integers, less than 30,000, denoting the
lengths of the sides of a triangle.
Output:

• For each test case, a line containing "right" if the triangle is a right triangle,
and a line containing "wrong" if the triangle is not a right triangle.
Problem (6) – cont’d

Sample Input: Output for Sample Input:


6 8 10 right
25 52 60 wrong

5 12 13 right

000
int s1, s2, s3;
while(true)
{
cin>>s1>>s2>>s3;
if(s1 == 0 && s2 == 0 && s3 == 0)
break;
if(s1 <= 0 || s2 <= 0 || s3 <= 0)
cout<<"wrong\n";
else if (s1*s1 + s2*s2 == s3*s3)
cout<<"right\n";
else if (s2*s2 + s3*s3 == s1*s1)
cout<<"right\n";
else if (s3*s3 + s1*s1 == s2*s2)
cout<<"right\n";
else
cout<<"wrong\n";
}

You might also like