[go: up one dir, main page]

0% found this document useful (0 votes)
21 views51 pages

Lecture 4-11327

Uploaded by

elkinaniosman
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)
21 views51 pages

Lecture 4-11327

Uploaded by

elkinaniosman
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/ 51

CSE121: Computer Programming (2)

)2( ‫ برمجة الحاسب‬:121 ‫هحس‬


1st Year
Computer and Systems Engineering &
Power and Electrical Machines Engineering

Zagazig University

Fall 2023
Lecture #4
Dr. Ahmed Amer Shahin
Dept. of Computer & Systems Engineering

These slides are adapted from the slides accompanying the text “C How to Program, 8/e,” https://deitel.com/c-how-to-program-8-e/
Copyright Deitel 2016
Announcements
• Faculty Platform:
– Tutorial 1 Solution is uploaded (provided by Eng.
Mahmoud)
• Tutorials/Practical Sessions:
– Next week we will start a new round
Outline
• A C Program to Process User Data
• Iteration Essentials
• Iteration Structures in C
• The while Iteration Statement
• The do ... While Iteration Statement
• The for Iteration Statement
• Nested Loops
• break and continue Statements
• Infinite Loops

3
Lecture Map

4
A C PROGRAM TO PROCESS USER
DATA
A C Program to Process User Data

• A program that reads 4 integer numbers from


the user.
• Each data item entered should be incremented
by 3 and then printed.

6
A C Program to Process User Data
#include <stdio.h>

int main(void)
{
int n1, n2, n3, n4;

printf("Enter a number:\n");
scanf("%d", &n1);
n1 += 3;
printf("The number after processing is %d\n", n1);

printf("Enter a number:\n");
scanf("%d", &n2);
n2 += 3;
printf("The number after processing is %d\n", n2);

printf("Enter a number:\n");
scanf("%d", &n3);
n3 += 3;
printf("The number after processing is %d\n", n3);

printf("Enter a number:\n");
scanf("%d", &n4);
n4 += 3;
printf("The number after processing is %d\n", n4);

return 0;
}

7
A C Program to Process User Data

• What we notice is that


– The same four lines of code are rewritten four
times
• What happen if the number of data items is
1000 instead of 4?
– Not possible to rewrite the four line
• What about reading an unknown number of
data items?
– The user should decide when to stop

8
ITERATION ESSENTIALS

9
Iteration Essentials
• A loop is a group of instructions the computer
executes repeatedly while some loop-continuation
condition remains true.
• There are two means of iteration:
– Counter-controlled iteration
– Sentinel-controlled iteration
• Counter-controlled iteration is sometimes called
definite iteration because we know in advance
exactly how many times the loop will be executed.
• Sentinel-controlled iteration is sometimes called
indefinite iteration because it’s not known in
advance how many times the loop will be executed.

© 2016 Pearson Education, Ltd. All rights reserved. 10


Iteration Essentials (Cont.)

• In counter-controlled iteration, a control variable is


used to count the number of iterations.
• The control variable is incremented (or
decremented) each time the group of instructions is
performed.
– Usually, incremented (or decremented) by 1
• When the value of the control variable indicates that
the correct number of iterations has been
performed, the loop terminates
– execution continues with the statement after the
iteration statement.

© 2016 Pearson Education, Ltd. All rights reserved. 11


Iteration Essentials (Cont.)

• Sentinel values are used to control iteration


when:
– The precise number of iterations isn’t known in
advance, and
– The loop includes statements that obtain data each
time the loop is performed.
• The sentinel value indicates “end of data.”
– The sentinel is entered after all regular data items
have been supplied to the program.
– Sentinels must be distinct from regular data items.

© 2016 Pearson Education, Ltd. All rights reserved. 12


ITERATION STRUCTURES IN C

13
Iteration Structures In C

• C provides three types of iteration structures


in the form of statements, namely
– while → repeats some part of code while a
condition is satisfied.
– do…while → executes some part of code and
then repeats it while a condition is satisfied.
– for → repeat some part of code for a number
of times

© 2016 Pearson Education, Ltd. All rights reserved. 14


Iteration Structures In C
while (/* condition */)
{
/* code */
}
do
{
/* code */
} while (/* condition */);
for (i = 0; i < 10; i++)
{
/* code */
}
15
THE WHILE ITERATION
STATEMENT

16
The while Iteration Statement
• An iteration statement allows you to specify that an action is to
be repeated while some condition remains true.
• The pseudocode statement
While there are more assignment to do
do next assignment and submit it
• describes the iteration that occurs during a normal student week.
– The condition, “there are more assignment to do” may be true or
false.
– If it’s true, then the action, “do next assignment and submit it” is
performed.
– This action will be performed repeatedly while the condition
remains true.
– The condition will become false, if no more assignments.
– At this point, the iteration terminates, and the first statement after
the iteration structure is executed.

© 2016 Pearson Education, Ltd. All rights reserved. 17


The while Iteration Statement
(Cont.)
• As an example of a while statement, consider a
program segment designed to find the first product of 3
larger than 100.
• Suppose the integer variable product has been
initialized to 3.
• When the following while iteration statement finishes
executing, product will contain the desired answer:

product = 3;
while (product <= 100)
{
product = 3 * product;
} // end while

© 2016 Pearson Education, Ltd. All rights reserved. 18


The while Iteration Statement
(Cont.)
• When the while statement is entered, the value
of product is 3.
– The variable product is repeatedly multiplied by 3,
taking on the values 9, 27 and 81 successively.
– When product becomes 243, the condition in the
while statement, product <= 100, becomes
false.
– This terminates the iteration, and the final value of
– product is 243.
• Program execution continues with the next
statement after the while.
© 2016 Pearson Education, Ltd. All rights reserved. 19
#include <stdio.h>

int main(void)
{
int product;

product = 3;

while (product <= 100)


{
product = 3 * product;
}

printf("The first product of 3 greater than 100 is %d\n", product);

return 0;
}

© 2016 Pearson Education, Ltd. All rights reserved. 20


Counter-Controlled while Iteration
• To illustrate how algorithms are developed, we
solve a class-average problem.
• Consider the following problem statement:
– A class of ten students took a quiz. The grades
(integers in the range 0 to 100) for this quiz are
available to you. Determine the class average on the
quiz.
• The class average is equal to the sum of the grades
divided by the number of students.
– The algorithm for solving this problem on a
computer must input each of the grades, perform
the average calculation, and print the result.

© 2016 Pearson Education, Ltd. All rights reserved. 21


#include <stdio.h>

// function main begins program execution


int main(void)
{
unsigned int counter;
int grade
int total;
int average;

// initialization phase
total = 0; // initialize total
counter = 1; // initialize loop counter Pseudocode for the problem
// processing phase
while (counter <= 10)
{
printf("%s", "Enter grade: "); // prompt for input
scanf("%d", &grade); // read grade
total = total + grade; // add grade to total
counter = counter + 1; // increment counter
} // end while

// termination phase
average = total / 10; // integer division

printf("Class average is %d\n", average);


} // end function main The output
© 2016 Pearson Education, Ltd. All rights reserved. 22
Counter-Controlled while Iteration
(Cont.)
• The algorithm mentions a total and a
counter.
– A total is a variable used to accumulate the sum
of a series of values.
• A counter is a variable used to count
– in this case, to count the number of grades entered.
• Because the counter variable is used to count
positive values,
– we declared the variable as an unsigned int,
which can store only non-negative values

© 2016 Pearson Education, Ltd. All rights reserved. 23


Counter-Controlled while Iteration
(Cont.)
• Variables used to store totals should normally
be initialized to zero before being used in a
program;
– otherwise, the sum would include the previous
value stored in the total’s memory location.
• Counter variables are normally initialized to
zero or one, depending on their use
• An uninitialized variable contains a “garbage”
value—the value last stored in the memory
location reserved for that variable.
© 2016 Pearson Education, Ltd. All rights reserved. 24
Sentinel-Controlled While Iteration

• Let’s generalize the class-average problem.


• Consider the following problem:
– Develop a class-average program that will process an
arbitrary number of grades each time the program is run.
– In this example, the program must process an arbitrary
number of grades.
– How can the program determine when to stop the input
of grades? How will it know when to calculate and print
the class average?
• One way to solve this problem is to use a special value called a
sentinel value (also called a signal value, a dummy value, or a
flag value) to indicate “end of data entry.”

© 2016 Pearson Education, Ltd. All rights reserved. 25


Sentinel-Controlled While Iteration
(Cont.)
• Clearly, the sentinel value must be chosen so that it
cannot be confused with an acceptable input value.
– Because grades on a quiz are normally nonnegative
integers, –1 is an acceptable sentinel value for this
problem.
• Thus, a run of the class-average program might
process a stream of inputs such as 95, 96, 75, 74, 89
and –1.
– The program would then compute and print the class
average for the grades 95, 96, 75, 74, and 89 (– 1 is the
sentinel value, so it should not enter into the average
calculation).
© 2016 Pearson Education, Ltd. All rights reserved. 26
Pseudocode for the problem

© 2016 Pearson Education, Ltd. All rights reserved. 27


#include <stdio.h>

int main(void) {
unsigned int counter; // number of grades entered
int grade = 0; // grade value
int total = 0; // sum of grades
float average; // number with decimal point for average

// processing phase
// get first grade from user
printf("%s", "Enter grade, -1 to end: "); // prompt for input
scanf("%d", &grade); // read grade

// loop while sentinel value not yet read from user


while (grade != -1) {
total = total + grade; // add grade to total
counter = counter + 1; // increment counter

// get next grade from user


printf("%s", "Enter grade, -1 to end: "); // prompt for input
scanf("%d", &grade); // read next grade
} // end while

// termination phase
// if user entered at least one grade
if (counter != 0) {
// calculate average of all grades entered
average = (float)total / counter; // avoid truncation

// display average with two digits of precision


printf("Class average is %.2f\n", average);
} // end if
else { // if no grades were entered, output message
puts("No grades were entered");
} // end else
} // end function main © 2016 Pearson Education, Ltd. All rights reserved. 28
THE DO ... WHILE ITERATION
STATEMENT

29
do…while Iteration Statement
• The do…while iteration statement is similar
to the while statement.
• In the while statement, the loop-continuation
condition is tested at the beginning of the loop
before the body of the loop is performed.
• The do…while statement tests the loop-
continuation condition after the loop body is
performed.
• Therefore, the loop body will be executed at
least once.
© 2016 Pearson Education, Ltd. All rights reserved. 30
do…while Iteration Statement
(Cont.)
• Consider the following program that prints the numbers
from 1 to 10
#include <stdio.h>

int main(void)
{
unsigned int counter = 1;

do
{
printf("%u ", counter);
} while (++counter <= 10);
}

© 2016 Pearson Education, Ltd. All rights reserved. 31


THE FOR ITERATION STATEMENT

32
for Iteration Statement
• The for iteration statement handles all the details of
counter-controlled iteration.
• To illustrate its power, let’s rewrite the following
program using for iteration statement
#include <stdio.h>

int main(void)
{
unsigned int counter = 1; // initialization

while (counter <= 10)


{ // iteration condition
printf("%u\n", counter);
++counter; // increment
}
}
© 2016 Pearson Education, Ltd. All rights reserved. 33
#include <stdio.h>

int main(void)
{
// initialization, iteration condition, and increment
// are all included in the for statement header.
for (unsigned int counter = 1; counter <= 10; ++counter)
{
printf("%u\n", counter);
}
}

© 2016 Pearson Education, Ltd. All rights reserved. 34


for Iteration Statement (Cont.)
General Format of a forStatement
• The general format of the forstatement is
for (initialization; condition; increment) {
statement
}
where the initialization expression initializes the loop- control variable (and
might define it), the condition expression is the loop-continuation condition,
and the increment expression increments the control variable.

© 2016 Pearson Education, Ltd. All rights reserved. 35


for Iteration Statement (Cont.)
• Expressions in the for Statement’s Header
Are Optional
– The three expressions in the for statement are
optional.
– If the condition expression is omitted, C assumes
that the condition is true, thus creating an infinite
loop.
– You may omit the initialization expression if the
control variable is initialized elsewhere in the
program.
– The increment may be omitted if it’s calculated by
statements in the body of the for statement or if no
increment is needed.
© 2016 Pearson Education, Ltd. All rights reserved. 36
for Iteration Statement (Cont.)
• Off-By-One Errors
– Notice that in the previous program the loop-
continuation condition was counter <= 10.
– If you incorrectly wrote counter < 10, then the loop
would be executed only 9 times.
– This is a common logic error called an off-by-one error.

– However, we could write the loop as follows which will


execute for 10 times correctly

for (unsigned int counter = 0; counter < 10; ++counter)


{
printf("%u\n", counter);
}

© 2016 Pearson Education, Ltd. All rights reserved. 37


for Iteration Statement (Cont.)
• The following examples show methods of
varying the control variable in a for statement.

– Vary the control variable from 1 to 100 in increments


of 1.
• for (i = 1; i <= 100; ++ i)
– Vary the control variable from 100 to 1 in increments
of -1 (decrements of 1).
• for (i = 100; i >= 1; --i)
– Vary the control variable from 7 to 77 in steps of 7.
• for (i = 7; i <= 77; i += 7)
© 2016 Pearson Education, Ltd. All rights reserved. 38
for Iteration Statement (Cont.)

– Vary the control variable from 20 to 2 in steps of -2.


• for (i = 20; i >= 2; i -= 2)
– Vary the control variable over the following
sequence of values: 2, 5, 8, 11, 14, 17.
• for (j = 2; j <= 17; j += 3)
– Vary the control variable over the following
sequence of values: 44, 33, 22, 11, 0.
• for (j = 44; j >= 0; j -= 11)

© 2016 Pearson Education, Ltd. All rights reserved. 39


for Iteration Statement (Cont.)
• Application: Summing the Even Integers from 2 to 100

#include <stdio.h>

int main(void)
{
unsigned int sum = 0; // initialize sum

for (unsigned int number = 2; number <= 100; number += 2)


{
sum += number; // add number to sum
}

printf("Sum is %u\n", sum);


}

© 2016 Pearson Education, Ltd. All rights reserved. 40


NESTED LOOPS

41
Nested Loops

• Loops nesting is possible, which enables very


useful computations, especially with matrices.
• An example of generating the multiplication
table using two for loops, is shown
#include <stdio.h>

int main(void)
{
for (int i = 1; i <= 12; i++)
for (int j = 1; j <= 12; j++)
printf("%d * %d = %d\n", i, j, i * j);
}

Part of the output


© 2016 Pearson Education, Ltd. All rights reserved. 42
BREAK, AND CONTINUE
STATEMENTS

43
break and continue Statements
• The break and continue statements are
used to alter the flow of control.
• break Statement
– The break statement, when executed in a while,
for, do…while or switch statement, causes an
immediate exit from that statement.
– Program execution continues with the next
statement.
– Common uses of the break statement are to
escape early from a loop or to skip the remainder of
a switch statement
© 2016 Pearson Education, Ltd. All rights reserved. 44
break and continue Statements (Cont.)
#include <stdio.h>

int main(void)
{
unsigned int x; // declared here so it can be used after loop
// loop 10 times
for (x = 1; x <= 10; ++x)
{
// if x is 5, terminate loop
if (x == 5)
{
break; // break loop only if x is 5
}
printf("%u ", x);
}
printf("\nBroke out of loop at x == %u\n", x);
}

• break statement in a for iteration statement.


• When the if statement detects that x has become 5, break is executed.
• This terminates the for statement, and the program continues with the printf
after the for.
• The loop fully executes only four times.
© 2016 Pearson Education, Ltd. All rights reserved. 45
break and continue Statements (Cont.)

• continue Statement
– The continue statement, when executed in a while,
for or do…while statement, skips the remaining
statements in the body of that control statement and
performs the next iteration of the loop.
– In while and do…while statements, the loop-
continuation test is evaluated immediately after the
continue statement is executed.
– In the for statement, the increment expression is
executed, then the loop-continuation test is evaluated.
– A program that uses the continue statement in a for
statement to skip the printf statement and begin the
next iteration of the loop.

© 2016 Pearson Education, Ltd. All rights reserved. 99


break and continue Statements (Cont.)
#include <stdio.h>

int main(void)
{
// loop 10 times
for (unsigned int x = 1; x <= 10; ++x)
{
// if x is 5, continue with next iteration of loop
if (x == 5)
{
continue; // skip remaining code in loop body
}
printf("%u ", x); // display value of x
}
puts("\nUsed continue to skip printing the value 5");
}

© 2016 Pearson Education, Ltd. All rights reserved. 47


INFINITE LOOPS

48
Infinite Loops
• In some cases, we may need to let the loop run
without stopping
– A for loop without the loop-continuation condition will
run indefinitely.
for (int x = 1; ; ++x)

– A for loop without the increment expression may run


infinitely if the loop control variable is not updated
inside the loop
for (int x = 1; x <= 10;)
{
printf("x = %d", x);
}

© 2016 Pearson Education, Ltd. All rights reserved. 49


Infinite Loops

• We can use the while loop also to make an


infinite loop by providing it with a condition
that is always true.

while (1) while (2 < 6)


{ {
/* code */ /* code */
} }

© 2016 Pearson Education, Ltd. All rights reserved. 50


END OF LECTURE

51

You might also like