0% found this document useful (0 votes)
18 views

BUE - Lec4 - Array Applications and Nested Loops

Good lectures for programming very important ti computer science students Arrays lecture

Uploaded by

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

BUE - Lec4 - Array Applications and Nested Loops

Good lectures for programming very important ti computer science students Arrays lecture

Uploaded by

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

1

23COMP02C
PROGRAMMING
AND SOFTWARE
DESIGN/
23ECE12C
COMPUTER
PROGRAMMING

LECTURE 3
AGENDA

 Problems on Arrays
 Jump Statements
 Nested Loops

2
LINEAR SEARCH

3
LINEAR SEARCH

Opening Problem:
If we have an array, how to find a certain value if exists
in the array?

List
Key

3
6 4 1 9 7 3 2 8

4
LINEAR SEARCH
Key List
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
5
LINEAR SEARCH

 Compare each element of array with key value


 Start at one end, go to other

 Useful for small and unsorted arrays


 Inefficient
 If search key not present in the array, examines every
element

6
Linear Search Pseudocode

7
Linear Search Code
void main()
{
const int size=5;
int m[size],key, foundIndex=-1;
//input
cout<<"Enter "<<size<<" elements:\n";
for(int i=0;i<=size-1;i++)
cin>>m[i]; Can you
solve it
cout<<"Enter the number you are searching for:";
differently
cin>>key; using a
//processing: Linear Search Boolean
for(int index=0;index<size;index++) flag?
{
if(m[index]==key)
{
foundIndex=index;
break;
}
}
//output
if(foundIndex==-1)
cout<<"Not found!";
else 8
cout<<"The key "<<key<<"is found in index "<<foundIndex<<endl;
}
Linear Search Code
void main()
{
const int size=5;
int m[size],key;
bool found=false;
//input
cout<<"Enter "<<size<<" elements:\n";
for(int i=0;i<=size-1;i++)
cin>>m[i];
cout<<"Enter the number you are searching for:";
cin>>key;
//processing: Linear Search
for(int index=0;index<size;index++)
{
if(m[index]==key)
{
found=true;
break;
}
}
//output
if(!found) //if(found==false)
cout<<"Not found!"; 9
else
cout<<"The key "<<key<<"is found in index "<<foundIndex<<endl;
SEARCH FOR MAXIMUM

List max 0 max

6 4 1 9 7 3 2 8 0 6

6 4 1 9 7 3 2 8 6

6 4 1 9 7 3 2 8 6

6 4 1 9 7 3 2 8 6 9

6 4 1 9 7 3 2 8 9

9
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8 9

6 4 1 9 7 3 2 8 9 10
*

PROBLEM: SEARCH MAXIMUM


const int size = 50;
int numbers[size];
Does it work
int max=0; for negative
numbers?
for (int i = 0; i < size; i++)
{
cout<< "Enter number: ";
cin>> numbers[i];
}

for (int i = 0; i < size; i++)


if (numbers[i] > max)
max = numbers[i];

11
cout<< "Maximum number: "<< max << endl;
SEARCH FOR MAXIMUM

List max

6 4 1 9 7 3 2 8 6

6 4 1 9 7 3 2 8 6

6 4 1 9 7 3 2 8 6

6 4 1 9 7 3 2 8 6 9

6 4 1 9 7 3 2 8 9

9
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8 9

6 4 1 9 7 3 2 8 9 12
PROBLEM: SEARCH MAXIMUM
const int size = 50;
int numbers[size];
int max;
for (int i = 0; i < size; i++)
{
cout<< "Enter number: ";
cin>> numbers[i];
}
max = numbers[0];
for (int i = 1; i < size; i++)
if (numbers[i] > max)
max = numbers[i];
cout<< "Maximum number: "<< max << endl;

13
const int size = 5;
PROBLEM
int scores[size];
SEARCH MAX
int max; INDEX
for (int i = 0; i < size; i++)
cin>> scores[i];

max = scores[0];
for (int i = 1; i < size; i++)
if (scores[i] > max)
max = scores[i];

cout<< "Maximum score: "<< max << endl;


cout<<"Achieved by Students:\n";
for (int i = 0; i < size; i++) Student 1 score is stored in index 0
14
if (scores[i] == max)
cout<< i+1 << endl;
PROBLEM: COUNT EVEN & ODD NUMBERS
const int size = 5;
int numbers[size];
int even=0, odd=0;

for (int i = 0; i < size; i++)


{ cout<< "Enter number: ";
cin>> numbers[i];
(numbers[i] % 2 == 0) ? even++ : odd++;
}
cout<< "You got " << even <<" even numbers and "<< odd <<" odd
numbers\n";
15
*

PROBLEM: DICE ROLL


If a dice is rolled 50 times, the user then enters a specific face number. The
program displays how many times this face appeared. (How?)
const int size = 50;
int faces[size];
int count=0, targetFace;

for (int i = 0; i < size; i++)


Generate numbers from 0-5
faces[i] = 1+ rand() % 6;
then add 1
cin>> targetFace;
for (int i = 0; i < size; i++)
if (faces[i] == targetFace)
count++; 16

cout<< targetFace << " appeared "<< count << " times\n";
17
Class Accumulative Project:
Employees Salary for Companies

18
Class Accumulative Project:
Employees Salary for Companies
Task1:for 1 employee

19
void main()
{ Task 1 Code
int hrs_worked,nDep,uDues=10;
float ssTax,fedTax,sIncome,grossPay,netPay,HInsurance=0;//6% , 14% ,5%
cout<<"Enter Weekly hours worked: ";
cin>>hrs_worked;
cout<<"\nHow many dependents? ";
cin>>nDep;
if(hrs_worked<=40)
grossPay=hrs_worked*16.78;
else
grossPay=40*16.78+((hrs_worked-40)*16.78*1.5);
cout<<"Gross Payment="<<grossPay<<"$\n";
ssTax=grossPay*0.06;
fedTax=grossPay*0.14;
sIncome=grossPay*0.05;
if(nDep>=3)
HInsurance=35;
cout<<"Withholding amount:"<<endl;
cout<<ssTax<<"\n"<<fedTax<<endl<<sIncome<<endl<<uDues<<endl<<HInsurance<<endl;
netPay=grossPay-ssTax-fedTax-sIncome-uDues-HInsurance; 20

cout<<"net pay="<<netPay<<"$"<<endl;
}
Take Home Exercise

Task2:
 Create a new version of your code to Calculate Net
Pay Salaries and taxes for 10 employees in your
company using 1D arrays.

21
EXTRA EXERCISES
 A factory has multiple production lines. Each production line has a
maximum price for its products.
 Each product belongs to a specific production line, has a base price,
taxes and net price.
 Write a C++ program that reads data of 3 products then computes the
net price and determines if the computed net price is accepted
compared with the maximum price of the corresponding production
line.
 N.B.
taxes
 net price = base price + base price x
100
 net price of each product should not exceed the maximum price of the
corresponding production line. 22
SAMPLE RUN

23
JUMP  Break
STATEMENTS  Continue

24
BREAK STATEMENT

 break statement
 Immediate exit from while, for, do/while, switch
 Program continues with the first statement after structure

 Common uses
 Escape early from a loop
Using break, we can leave a loop even if the condition for its end is not
fulfilled. It can be used to end an infinite loop, or to force it to end before
its natural end.

 Skip the remainder of switch 25


BREAK STATEMENT

26
BREAK STATEMENT

 Calculate the sum of integers starting from 0 until the sum is


an even number.
int sum = 0;
int number = 0;
while (true)
{
number++;
sum += number;
if (sum % 2 == 0)
break;
}
cout << "The number is " << number << endl;
cout << "The sum is " << sum << endl;

27
CONTINUE STATEMENT

 continue statement:
o Causes the program to skip the rest of the loop in the current
iteration as if the end of the statement block had been reached.
o Jumps to the start of the following iteration.

28
CONTINUE STATEMENT

29
CONTINUE STATEMENT

 continue statement
 Used in while, for, do/while
 Skips remainder of loop body for current iteration
 Proceeds with next iteration of loop
 while and do/while structure
 Loop-continuation test evaluated immediately after the
continue statement
 for structure
 Increment expression executed
 Next, loop-continuation test evaluated
30
CONTINUE STATEMENT

Display the sum of integers less than 20, do not include numbers 10 and 11 in the
summation process.

int sum = 0;

for (int number = 0; number < 20; number++)


{
if (number == 10 || number == 11)
continue;
sum += number;
}

cout << "The sum: " << sum << endl;


31
32
EXERCISE: COMPLETE

1. Every C++ program begins execution at function …


2. All variables must be given a … when they are declared.
3. The … statement is used to make a decision.
4. The … operator can be used as a prefix or as a suffix.
5. The … loop is sentinel-controlled.
6. In case statement, the … is optional.
7. … is the only ternary operator in C++.
8. The … statement causes the program to skip the rest of
the loop in the current iteration. 33
EXERCISE: CORRECT AND JUSTIFY

char done = 'Y'; char done = 'Y';


while (done == 'Y')
while (done = 'Y')
{
{
//...
//... cout << "Continue? (Y/N)";
cout << "Continue? (Y/N)"; cin >> done;
cin >> done; }
}
If you use a single equal sign to check
equality, your program will instead assign
the value on the right side of the
expression to the variable on the left hand
side, and the result of this statement is
"Why doesn't my loop ever end?" TRUE.Therefore, the loop will never end.

34
EXERCISE: CORRECT AND JUSTIFY

int x;
int x;
for (x = 0; x < 100; x++) ; for (x = 0; x < 100; x++)
cout << x; cout << x;

"Why does it just output 100?" Removed extra semicolon

Remember, semicolons don't go after


FOR loop definition.
If you put it, your program will function
improperly.

35
PROBLEM: BASKETBALL CHAMPIONSHIP

 Implement a program reads result of 4 basketball matches


(number of goals by two teams).
 For each match, the winner team gets 3 points. In case of
tie, each team gets 1 point. The program should display the
winner team.

36
int n=4, team1Goals, team2Goals, team1Points=0,team2Points=0;
for (int i=1; i<=n; i++)
{
BASKETBALL CHAMPIONSHIP
cout << "Enter result of match number "<< i <<": \n";
cin >> team1Goals >> team2Goals;
if (team1Goals == team2Goals)
{

team1Points++;
++team2Points;
}

else if (team1Goals > team2Goals)


team1Points += 3;
else
team2Points += 3;
}

if (team1Points > team2Points)


cout << "Team 1 wins\n";
else if (team1Points < team2Points)
cout << "Team 2 wins\n";
37
else
cout << "Tie\n";
PROBLEM: PRIME NUMBER

 Implement a Program that checks if an input number is prime or not.

38
PRIME NUMBER

int number; // Number to be tested


cout <<"Enter number: \n";
cin >> number;

// Test if number is prime


for (int divisor = 2; divisor < number; divisor++)
{
if (number % divisor == 0)
{
// If true, the number is not prime
cout<< "Not Prime\n";
break; // Exit the for loop
} 39

}
cout << "Prime\n";
?
PRIME NUMBER

int number; // Number to be tested


cout <<"Enter number: \n";
cin >> number;
// Test if number is prime
for (int divisor = 2; divisor < number; divisor++)
{
if (number % divisor == 0)
{
// If true, the number is not prime
cout<< "Not Prime\n"; ?
break; // Exit the for loop
}
else 40

cout << "Prime\n";


}
int number; // A number to be tested

PRIME NUMBER
cout <<"Enter number: \n";
Hint:When you
cin >> number;
find it, Raise a
bool isPrime = true; // Assume the current number flag ☺
prime
// Test if number is prime
for (int divisor = 2; divisor < number;
divisor++)
{
if (number % divisor == 0)
{
// If true, the number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
if (isPrime)
cout << "Prime Number\n"; 41

else
cout << "Not Prime\n";
PROBLEM: PRIME NUMBERS

 Write a program that checks 20 numbers and displays


whether prime or not.

42
int count = 0; // keep track of checked numbers
int number; // Number to be tested
PRIME
while (count < 20) NUMBERS
{
cout << "Enter a number: \n";
cin >> number;
bool isPrime = true; // Assume number is prime
// Test if number is prime
for (int divisor = 2; divisor < number; divisor++)
{
if (number % divisor == 0)
{
// If true, the number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}

if (isPrime)
cout << number << " is a prime number\n";
else
43
cout << number << " is not prime\n";
count++;
}
44
NESTED LOOPS

45
NESTED LOOPS

**********

for ( int lineNum = 1; lineNum <= 10; lineNum++)


cout << '*';

46
PROBLEM

for (int lineNum = 1; lineNum <= 5; lineNum++)


1
{ 2
cout << lineNum; 3
cout << endl; 4
} 5

47
PROBLEM: TRIANGLE OF NUMBERS

for (int lineNum = 1; lineNum <= 5; lineNum++)


{ 1
12
? 123
cout << lineNum; 1234
cout << endl; 12345
}
48
 Loops may be nested, with one loop sitting in the body of
NESTED
another. LOOPS
 The inner loop will be executed in full for every execution of
the outer loop.
i j
Ex:
for(int i = 0; i < 10; i++) 0 1
{ 2
for(int j = 1; j < 3; j++)
1 1
{
………… 2
………… 2 1
}
} 2
.. ..
9 1 49

2
for(int i = 1; i <=n; i++)
NESTED
{ LOOPS
//1st block of statements

for(int j = 1; j <=m ; j++)


{
//2nd block of statements
…………
…………
}
//3rd block of statements
}

How many times the 3 blocks of statements will be


executed?
• 1st block: Number of outer loop iterations (n times)
• 2nd block: Number of outer loop iterations x number
of inner loop iterations (nxm times) 50

• 3rd block: Number of outer loop iterations (n times)


NESTED LOOPS
(FLOWCHART)

51
NESTED LOOPS

 When you nest two loops, the outer loop takes control
of the number of complete repetitions of the inner loop.
 How it works?
The outer loop executes first (one iteration), and then
the inner loop will be executed until it terminates (many
iterations). The control is then returned to the outer
loop.

52
Iteration: for Loop (cont.)
Nested for Loop
for(start, bool_expression, action)
for(start, bool_expression, action)
statement;
Example

53
Iteration: for Loop (cont.)
Example

This statement is simply just a statement after the


loops and will execute sequentially. 54
Iteration: for Loop (cont.)
Example

55
Iteration: for Loop (cont.)
Example

56
DISPLAY OUTPUT

Output:
3 and 12 1st
iteration
for ( int i = 3; i <= 5; i++) 3 and 13 outer
loop
for (int j = 12; j <= 14; j++) 3 and 14
cout << i << " and " << j << endl; 2nd
4 and 12 iteration
outer
4 and 13 loop
4 and 14
3rd
5 and 12 iteration
outer
5 and 13 loop
57

5 and 14
PROBLEM: TRIANGLE OF NUMBERS

for (int lineNum = 1; lineNum <= 5; lineNum++)


{
for (int number = 1; number <= lineNum; number++)
cout << number; 1
cout << endl; //in theWhat
outerifloop 12
?
} cout<<
123
lineNum; 1234
12345
58
NESTED LOOPS

 Is there repetition in this output?


Yes → Many lines

 How many lines?


10
Lines: 1 .. 10

 How many stars in each line?


Line 1 has 1 star…
Line 2 has 2 stars….
Line 10 has 10 stars

59
PROBLEM: TRIANGLE OF NUMBERS

for (int lineNum = 1; lineNum <= 5; lineNum++)


{
for (int number = 1; number <= lineNum; number++)
cout << number << '\t'; 1
cout << endl; 12
} 123
1234
12345 60
PROBLEM: TRIANGLE OF NUMBERS

for (int lineNum = 1; lineNum <= 8; lineNum++)


{
for (int number = lineNum; number >= 1; number--)
cout << number;
cout << endl;
}

61
PROBLEM: TRIANGLE OF STARS

for (int numLines = 7; numLines >= 1; numLines--)


{
for (int stars = 1; stars <= numLines; stars++)
cout << '*';
cout << endl;
}

62
NESTING: TRIANGLE OF STARS

 Write C++ program that draws a triangle from ‘*’


with the following pattern.
 Note: the triangle size is determined by the user.

*
 Example: **
***
**** 63
NESTING: TRIANGLE OF STARS

* Line Spaces Stars


number (j) (k)
** (i)
1 3 1

*** 2 2 2
3 1 3
****
4 0 4
Total n=numb n-i i
(end of er of
loop lines
conditio 64
n)
SOLUTION

*
**
***
****
65
66

You might also like