Lect 09 Nested Loop Switch
Lect 09 Nested Loop Switch
return 0;
}
Home work1: Find some more elegant and efficient way to terminate the loop
Nested loop:
int main()
{
cout << "This program average the test score \n";
int noOfStds = 0;
int noOfTests = 0;
double score = 0.0;
double total;
double average = 0.0;
cout << "For how many student do you have scores: ";
cin >> noOfStds;
cout << "How many test scores does each student have: ";
cin >> noOfTests;
}
average = total / noOfTests;
cout << "Average score of student " << i + 1 << " is " << average << endl;
}
return 0;
}
Homework 2:
Homework 3:
Home work5: In a class of 15 students got the grade of each student, and then count how many
students got A, B, C, and D grades.
Homework 6: Write a program that reads an integer (5 digits or fewer) and determines and
prints how many digits in the integer are 7s.
Multiway decisions:
// multiway decisions
//1 only use if the condition
//2 use the nested if else
//3 use the if else if statement
//4 use the switch statement
char grade;
cout << "Enter the grades: ";
cin >> grade;
if (grade == 'A' || grade == 'a')
{
cout << "Excellent !";
}
if (grade == 'B' || grade == 'b')
{
cout << "very good !";
}
return 0;
}
Negative of just using if statement: It is very computationally expensive.
3.
// if else if statement
//3 use the if else if statement
//4 use the switch statement
char grade;
cout << "Enter the grades: ";
cin >> grade;
{
cout << "very good !";
else
{
cout << "Enter the valid grade";
}
;;;;;;;;;;;;;;;;;
case 'F':
case 'f':
printf("Fail !\n");
break;
default:
printf("Invalid grade, Please Enter the Grade A to D, and F\n");
}
- It is an elegant structure that makes a program more readable to handle the multiway
decisions
- It deals with the integral data (int, short, long or char=> ASCII codes)
- It is an optional statement as we may use if else if statement
// limitations of switch
Use of break.
- Switch statement
- Inside the loops
o Example of guess game, can use to exit from the loop
o In the case of a nested loop, it can be used to exit from the innermost loop
Use of continue.
- Unconditional jump
- Never use it
- It makes tracing and debugging and maintaining program
- Make a spaghetti program
- It is in C for completeness, but not use it
TIP
Sample ouput: