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

Lecture #8

The document provides an overview of repetition structures in programming, particularly focusing on while loops in C. It explains how to use loops to repeat actions based on conditions, including examples for displaying values and calculating averages. Additionally, it discusses the importance of initializing variables, using sentinel values, and ensuring proper loop control to avoid infinite loops.

Uploaded by

umit.gumus.mgm
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)
2 views

Lecture #8

The document provides an overview of repetition structures in programming, particularly focusing on while loops in C. It explains how to use loops to repeat actions based on conditions, including examples for displaying values and calculating averages. Additionally, it discusses the importance of initializing variables, using sentinel values, and ensuring proper loop control to avoid infinite loops.

Uploaded by

umit.gumus.mgm
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/ 85

Mühendi sl i k ve Mi marl ı k Fakül tesi

BİL1102
Programlamaya Giriş
Ders #7

Doç.Dr. Gonca Gökçe MENEKŞE DALVEREN

2024 Güz
•Repetition Structures
•While Loop
Loops
• Display “Turkey” three times on separate lines.
• We can solve this problem by writing 3 printf statements:
printf ("Turkey\n");
printf ("Turkey\n");
printf ("Turkey\n");

• What about if you were asked to display it 30 times?

1-3
Solution
• Repeat the statements you want in a controlled way
• Loop counter or control variable: count the number of repetitions
• Loop body: the group of instructions to be repeated
• Update the loop control variable and terminate the repetition when you do not
want to repeat the loop body anymore

1-4
Repetition Structure

• A repetition structure allows the programmer to specify that an action is to be


repeated while some condition remains true.
• There are three repetition structures in C, the while loop, the for loop, and the do-
while loop.
• Almost all programs use repetition!
Similar But Different

• Except for one special condition, all three forms of the loops are the same.
• Except for the one special condition, any loop can be replaced by either of other two
types of loop.
• The special condition requires the use of the do-while loop.
Will Loops Be Required?

1. Design your algorithm by drawing a flowchart.

2. Check the flowchart for the loop!

If there are any loops:


1. Find the loop enter and exit conditions.

2. Locate what to do in the loop?


Will Loops Be Required?

Consider the algorithm (flowchart or pseudocode)


1. Were there any steps I repeated as I solved the problem? If so, which ones?
2. If the answer to question 1 is yes, did I know in advance how many times to repeat
the step?
3. If the answer to question 2 is no, how did I know how long to keep repeating the
steps?
The while Repetition Structure
while ( condition )
{
statement(s);
}

The braces are not required if the loop body


contains only a single (simple or compound)
statement . However, it is a good idea and
required by the general Coding Standards.
The simplest example:

• Output numbers between 1 and 4, then “Bye” as shown below.

1
i=1; //initialization 2
while(i<5) //test 3
4
{ printf(“%d\n“, i); Bye
i=i+1; //update
}
printf(“Bye“); i < 5?
No

Yes

ii+1
The simplest example cont:

• Change the code to output: • Change the code to output:

10 10
11 12
12 14
13 16
Bye Bye
i=10;
while(i<14) i=10;
{ printf(“%d\n“, i); while(i<=16)
i=i+1; { printf(“%d\n“, i);
} i=i+2;
printf(“Bye“); }
printf(“Bye“);
The simplest example cont:

• Change the code to output • Change the code to


odd numbers between 51
and 61 (inclusive), 51
output: 100
53 90
then “Bye”: 55 80
57 70
59 60
61 Bye
i=51; Bye
while(i<=61)
i=100;
{ printf(“%d\n“, i); while(i>=60)
i=i+2; { printf(“%d\n“, i);
} i=i-10;
printf(“Bye“); }
printf(“Bye“);
A Simple Example

int children = 3;
int cookies = 0;
while ( children > 0 )
{
children = children - 1 ;
cookies = cookies + 2 ;
}
printf (“For %d children, we need %d cookies”, children, cookies);
Another while Loop Example

• Problem: Write a program that calculates the average exam grade for a class of 10
students.
• What are the program inputs?
• the exam grades

• What are the program outputs?


• the average exam grade
The Pseudocode
total = 0
grade_counter = 0 //initial value important!

While (grade_counter < 10) //condition important!


Display “Enter a grade: ”
Read grade
total = total + grade
grade_counter = grade_counter + 1
End_while
average = total / 10
Display “Class average is: “, average
The C Code
#include <stdio.h>
int main ( void )
{
int counter, grade, total, average ;
total = 0 ;
counter = 1 ;
while ( counter <= 10 )
{
printf (“Enter a grade : “) ;
scanf (“%d”, &grade) ;
total = total + grade ;
counter = counter + 1 ;
}
average = total / 10 ;
printf (“Class average is: %d\n”, average) ;
return 0 ;
}
The Pseudocode
total = 0
grade_counter = 1

While (grade_counter ? 10) //what should be condition?


Display “Enter a grade: ”
Read grade
total = total + grade
grade_counter = grade_counter + 1
End_while
average = total / 10
Display “Class average is: “, average
What is wrong with that Pseudocode?

total = 0
grade_counter = 0
While (grade_counter < 10)
Display “Enter a grade: ”
Read grade
total = total + grade
End_while
average = total / 10
Display “Class average is: “, average
What is wrong with that Pseudocode? (solution)

total = 0
grade_counter = 0
While (grade_counter < 10)
Display “Enter a grade: ”
Read grade
total = total + grade
grade_counter = grade_counter + 1
//do not forget to update condition!
End_while
average = total / 10
Display “Class average is: “, average
Versatile?(çok yönlü?)
• How versatile is this program?
• It only works with class sizes of 10.
• We would like it to work with any class size.
• A better way :
• Ask the user how many students are in the class.
• Use that number in the condition of the while loop and when computing the
average.
New Pseudocode
total = 0
grade_counter = 0
num_students = 0
Display “Enter the number of students: “
Read num_students
While (grade_counter < num_students)
Display “Enter a grade: ”
Read grade
total = total + grade
grade_counter = grade_counter + 1
End_while
average = total / num_students
Display “Class average is: “, <average>
New C Code
#include <stdio.h>
int main ( )
{
int numStudents, counter, grade, total, average ;
total = 0 ;
counter = 1 ;
printf (“Enter the number of students: “) ;
scanf (“%d”, &numStudents) ;
while ( counter <= numStudents) {
printf (“Enter a grade : “) ;
scanf (“%d”, &grade) ;
total = total + grade ;
counter = counter + 1 ;
}
average = total / numStudents ;
printf (“Class average is: %d\n”, average) ;
return 0 ;
}
Using a Sentinel Value

• We could let the user keep entering grades and when he’s done enter
some special value that signals us that he’s done.

• This special signal value is called a sentinel value.


Using a Sentinel Value

• We have to make sure that the value we choose as the sentinel isn’t a
legal value.

• For example, we can’t use 0 as the sentinel in our example as it is a


legal value for an exam score.
The Priming Read

• When we use a sentinel value to control a while loop, we have to


get the first value from the user before we encounter the loop so
that it will be tested and the loop can be entered.

• This is known as a priming read.


The Priming Read

We have to give significant thought to:

• the initialization of variables,

• the sentinel value, and

• entering the loop.


New Pseudocode
total = 0
grade_counter = 0 //counts how many times loop is executed

Display “Enter a grade: “


Read grade
While ( grade != -1 ) // sentinel value is -1
total = total + grade
grade_counter = grade_counter + 1
Display “Enter another grade: ”
Read grade
End_while
average = total / grade_counter
Display “Class average is: “, average
Final “Clean” C Code
#include <stdio.h>
int main ( void )
{
int counter ; /* counts number of grades entered */
int grade ; /* individual grade */
int total; /* total of all grades */
int average ; /* average grade */

/* Initializations */
total = 0 ;
counter = 0 ;
Final “Clean” C Code (con’t)
/* Get grades from user */
/* Compute grade total and number of grades */

printf(“Enter a grade: “) ;
scanf(“%d”, &grade) ;
while (grade != -1) {
total = total + grade ;
counter = counter + 1 ;
printf(“Enter another grade: “) ;
scanf(“%d”, &grade) ;
}

/* Compute and display the average grade */


average = total / counter ;
printf (“Class average is: %d\n”, average) ;

return 0 ;
}
Example
Write a program such that :
• Program requests user to input a positive integer number

• If user inputs a negative integer number, program warns


and re-request a positive integer number

• Thus, program should loop for requesting positive number


unless user enters a positive integer number!

Draw the flowchart & write the pseudocode!


Using a while loop to check if user inputs
positive number
#include <stdio.h>
int main ( void )
{
int number ;
printf (“Enter a positive integer : “) ;
scanf (“%d”, &number) ;
while ( number <= 0 )
{
printf (“\nThat’s incorrect. Try again.\n”) ;
printf (“Enter a positive integer: “) ;
scanf (“%d”, &number) ;
}
printf (“You entered: %d\n”, number) ;
return 0 ;
}
What is Wrong with the below code for the given
problem?
#include <stdio.h>
int main ( void )
{
int number ;
printf (“Enter a positive integer : “) ;
scanf (“%d”, &number) ;
if ( number <= 0 )
{
printf (“\nThat’s incorrect. Try again.\n”) ;
printf (“Enter a positive integer: “) ;
scanf (“%d”, &number) ;
}
printf (“You entered: %d\n”, number) ;
return 0 ;
}
What is Wrong with the below code for the given
problem?
#include <stdio.h>
int main ( void )
{
int number ;
printf (“Enter a positive integer : “) ;
scanf (“%d”, &number) ;
if ( number <= 0 )
{
printf (“\nThat’s incorrect. Try again.\n”) ;
printf (“Enter a positive integer: “) ;
scanf (“%d”, &number) ;
}
printf (“You entered: %d\n”, number) ;
return 0 ;
}
Why Is It Wrong?

• If you use the if statement to do the error checking, you will force the error to correct it
once ( and only once)!
• But if the user repeats the same mistake, you let them continue.

• Usually, the user will try it three or four times before thinking about how to do it
correct.

• The while statement will not let them proceed until they do it correctly!
Use #define With Loops
What is the output of this code?
#define DAYS_IN_WEEK 7

int nr_days = 1;
float total = 0;
float sales;

while ( nr_days <= DAYS_IN_WEEK )


{
printf(“ Enter day %d sales: “ , nr_days );
scanf( “%f”, &sales );
total = total + sales;
nr_days = nr_days + 1;
}
What Is The Output?

#include <stdio.h>
int main( void )
{
int x = 13;
while ( x < 10 )
{
printf("x = %d\n", x);
x = x + 1;
}
return 0;
}
What Is The Output? (cont’d)

• Nothing!
• The reason is the condition was never true, so the body of the loop is never
executed.
What is the output?

#include <stdio.h>
int main( void )
{
int x = 1;
while ( x < 10 )
{
printf("x = %d\n“, x );
}
return 0;
}
Infinite Loop: Loop never stops!
WHY?

#include <stdio.h>
int main( void )
{
int x = 1;
while ( x < 10 )
{
printf("x = %d\n“, x );
}
return 0;
}
Infinite Loop: Loop never stops!
WHY?
#include <stdio.h>
int main( void )
{
int x = 1;
while ( x < 10 )
{
printf("x = %d\n“, x );
// no action for changing loop condition!
}
return 0;
}
Correct Loop: Loop stops!

#include <stdio.h>
int main( void )
{
int x = 1;
while ( x < 10 )
{
printf("x = %d\n“, x );
x++; // action for changing loop condition!
}
return 0;
}
Another Infinite Loop
WHY?

#include <stdio.h>
int main( void )
{
int x = 1;
while ( x != 10 )
{
printf("x = %d\n“, x );
x = x + 2;
}
return 0;
}
Example:

• Input n and find its factorial n!

printf(“Enter n value:”);
Enter n value: 5
scanf("%d", &n); 5 factorial is 120
count=1;
fact=1;
while(count<=n)
{ fact*=count;
count++;
}
printf(“%d factorial is %d", n, fact);
More Loops
Topics

• Counter-Controlled (Definite) Repetition


• Event-Controlled (Indefinite) Repetition
• for Loops
• do-while Loops
• Choosing an Appropriate Loop
Counter-Controlled Repetition
(Definite Repetition)
• If it is known in advance exactly how many times a loop will execute, it
is known as a counter-controlled loop.

int i = 0 ;
while ( i < 10 ) //we need a loop for 10 repetition
{
printf(“i = %d\n”, i) ;
i=i+1;
}
Counter-Controlled Repetition (con’t)

• Is the following loop a counter-controlled


loop?

while ( x != y )
{
printf(“x = %d”, x) ;
x=x+2;
}
Event-Controlled Repetition
(Indefinite Repetition)
• If it is NOT known in advance exactly how many times a loop will
execute, it is known as an event-controlled loop.

sum = 0 ;
printf(“Enter an integer value: “) ;
scanf(“%d”, &value) ;
while ( value != -1) {
sum = sum + value ;
printf(“Enter another value: “) ;
scanf(“%d”, &value) ;
}
Event-Controlled Repetition (con’t)
• An event-controlled loop will terminate when some event occurs.

• The event may be the occurrence of a sentinel value, as in the


previous example.

• There are other types of events that may occur, such as reaching
the end of a data file.
The 3 Parts of a Loop

#include <stdio.h>
int main ()
{
int i = 1 ; initialization of loop control variable

/* count from 1 to 100 */


while ( i < 101 )
{
printf (“%d “, i) ;
i=i+1;
}
return 0 ;
}
The 3 Parts of a Loop

#include <stdio.h>
int main ()
{
int i = 1 ;

/* count from 1 to 100 */


while ( i < 101 ) test/check of loop termination condition
{
printf (“%d “, i) ;
i=i+1;
}
return 0 ;
}
The 3 Parts of a Loop

#include <stdio.h>
int main ()
{
int i = 1 ;

/* count from 1 to 100 */


while ( i < 101 )
{
printf (“%d “, i) ;
i=i+1; modification of loop control variable
}
return 0 ;
}
The 3 Parts of a Loop
#include <stdio.h>
int main ()
{
int i = 1 ; initialization of loop control variable

/* count from 1 to 100 */


while ( i < 101 ) test/check of loop termination condition
{
printf (“%d “, i) ;
i=i+1; modification of loop control variable
}
return 0 ;
}
The for Loop Repetition Structure

• The for loop handles details of the counter-controlled loop


“automatically”.
• The initialization of the loop control variable, the termination condition
test, and control variable modification are handled in the for loop
structure.

for ( i = 1; i < 101; i = i + 1)


{
initialization modification
} test/check
You can declare and initialize counter in the for
statement

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


{
printf (“%d\n”, i) ;
}
printf (“Out of the loop i = %d”, i);
You can declare and initialize counter in the for
statement
for ( int i = 1; i < 10; i++ )
{
printf (“%d\n”, i) ;
}
printf (“Out of the loop i = %d”, i);
You can modify counter in the for statement

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


{
printf (“%d\n”, i) ;
i++;
}
printf (“i = %d”,i);
You can modify counter in the for statement

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


{
printf (“%d\n”, i) ;
i++;
}
printf (“i = %d”,i);
When Does a for Loop Initialize, Test and Modify?

• Just as with a while loop, a for loop


• initializes the loop control variable before beginning the first loop iteration,
• modifies the loop control variable at the very end of each iteration of the loop, and
• performs the loop termination test/check before each iteration of the loop.
• The for loop is easier to write and read for counter-controlled loops.
A for Loop That Counts From 0 to 9

for ( i = 0; i < 10; i = i + 1 )


{
printf (“%d\n”, i) ;
}

Which expressions are for Initialize, Test/Check and Modify ?


We Can Count Backwards, Too

for ( i = 10; i >0; i = i - 1 )


{
printf (“%d\n”, i) ;
}

Which expressions are for Initialize, Test/Check and Modify ?


We Can Count By 2’s ... or 7’s
… or Whatever

for ( i = 0; i < 10; i = i + 2 )


{
printf (“%d\n”, i) ;
}

Which expressions are for Initialize, Test/Check and Modify ?


Trace the code: What is the output?

for ( i = 1; i == 10; i = i + 2 )
{
printf (“%d\n”, i) ;
Output :
} Finish!
printf (“Finish!”) ;

Which expressions are for Initialize, Test and Modify ?


Trace the code: What is the output?

for ( i = 1; i < 10; i = i + 2 )


{
printf (“%d\n”, i) ;
}
printf (“i = %d”,i);

WHY?
More Example (Trace the code)
Output:

0 1
1 2
2 4
3 8
4 16
5 32
More Example (Trace the code)
Output:
for (k = 15; k > 0; k -= 3) 60
switch (k % 4) 12
24
{ 27
case 0: printf ("%d\n", k); 36
case 2: printf ("%d\n", k * 2); break; 12
12
case 1: printf ("%d\n", k * 3);
default: printf ("%d\n", k * 4);
}
More Example
• Write a program to find the sum of integers from 1
to n, for a given n value:

i
i =1
=1+2+3+…+n

• Accumulator variables: Variables that hold products or sums that


are cumulatively built on previous values as the loop iterates. Need
to be initialized.

79
// Summation with for
#include <stdio.h>

int main(void)
{
int n, // (input) given number
i, // loop counter
sum; // (output) sum of integers from 1 to n

// Get n
printf ("Enter n: ");
scanf ("%d", &n);

// Initialize sum to zero Accumulator


sum = 0; variable

// Calculate the sum


for (i = 1; i <= n; i++)
sum = sum + i; // or sum += i;

// Display the sum


printf (“Sum is %d\n”, sum);

return(0);
}
80
What does this program do?
// Find the average of 10 integers
#include <stdio.h>
int main (void)
{ int num, // (input) given integers
k, // loop counter
sum = 0; // sum of given integers
double avg; // (output) average of given integers

// Repeat 10 times
for (k = 1; k <= 10; k++)
{ // Get an integer
printf (“\nEnter integer %d: ”, k);
scanf (“%d”, &num);
// Add it to the sum
sum += num;
}
// Calculate and display the average
avg = sum / 10.0;
printf (“Average is %f\n”, avg);
return(0);
}
Can you modify it so that it finds the average of even and odd
numbers separately? 81
Do While Loop
The do-while Repetition Structure
do
{
statement(s)
} while ( condition ) ;

• The body of a do-while is ALWAYS executed at least once.


• Is this true of a while loop? What about a for loop?
Example
do
{
printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ;
if ( num <= 0 )
{
printf (“\nThat is not positive. Try again\n”) ;
}
} while ( num <= 0 ) ;
printf ("You entered a positive number: %d", num) ;

* Which expressions are for Initialize, Test/check and Modify?


Example
do
{
printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ;
if ( num <= 0 ) //is it test/check?
{
printf (“\nThat is not positive. Try again\n”) ;
}
} while ( num <= 0 ) ;
printf ("You entered a positive number: %d", num) ;
Example
do
{
printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ;
if ( num <= 0 ) //is it test/check? NOOOO!
{
printf (“\nThat is not positive. Try again\n”) ;
}
} while ( num <= 0 ) ;
printf ("You entered a positive number: %d", num) ;
Example
do
{
printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ;
if ( num <= 0 ) //is it test/check? NOOOO!
{
printf (“\nThat is not positive. Try again\n”) ;
}
} while ( num <= 0 ) ; //is it test/check? YES!
printf ("You entered a positive number: %d", num) ;

Which expressions are for Initialize?


Example
do
{
printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ; // Initialize?
if ( num <= 0 )
{
printf (“\nThat is not positive. Try again\n”) ;
}
} while ( num <= 0 ) ;
printf ("You entered a positive number: %d", num) ;
Example
Which expression is for Modify?
do
{
printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ; // Initialize? YES
if ( num <= 0 )
{
printf (“\nThat is not positive. Try again\n”) ;
}
} while ( num <= 0 ) ;
printf ("You entered a positive number: %d", num) ;
Example
Which expression is for Modify?
do
{
printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ; // Initialize? YES //MODIFY!
if ( num <= 0 )
{
printf (“\nThat is not positive. Try again\n”) ;
}
} while ( num <= 0 ) ;
printf ("You entered a positive number: %d", num) ;
Do while Loop An Equivalent while Loop
printf (“Enter a positive number: “) ;
do scanf (“%d”, &num) ;
{ while ( num <= 0 )
printf (“Enter a positive number: “) ; {
scanf (“%d”, &num) ; printf (“\nThat is not positive. Try again\n”) ;
if ( num <= 0 ) printf (“Enter a positive number: “) ;
{ scanf (“%d”, &num) ;
printf (“\nThat is not positive. Try }
again\n”) ; printf ("You entered a positive number: %d", num)
} ;
} while ( num <= 0 ) ;
printf ("You entered a positive number:
%d", num) ; • Notice that: using a while loop in this case
requires a priming read.

Which expressions are for Initialize, Test/Check and Modify?


Do while Loop An Equivalent For Loop
printf (“Enter a positive number: “) ;
do
{ scanf (“%d”, &num) ;
printf (“Enter a positive number: “) ; for ( ; num <= 0; )
scanf (“%d”, &num) ; {
if ( num <= 0 ) printf (“\nThat is not positive. Try again\n”)
{ ;
printf (“\nThat is not positive. Try printf (“Enter a positive number: “) ;
again\n”) ;
scanf (“%d”, &num) ;
}
} while ( num <= 0 ) ; }
printf ("You entered a positive number: printf ("You entered a positive number: %d",
%d", num) ; num) ;

Which expressions are for Initialize, Test/Check and Modify?


So, Which Type of Loop Should I Use?
• Use a for loop for counter-controlled repetition.
• Use a while or do-while loop for event-controlled repetition.
• Use a do-while loop when the loop must execute at least one time.
• Use a while loop when it is possible that the loop may never execute.
More Example (Trace the code)
Output:
int num = 1;
do{ 2
4
num *= 2;
8
printf ("%d\n", num); 16
}while (num <= 50); 32
64
More Example - Menu Entry
do .. while is a good choice to display a menu and get the choice of the
user, until the user enters a valid choice. It is usually followed with a switch
statement.

Example: Write a program that gets two numbers from user, and displays a
menu as below, and shows the result of the chosen operation:

1) Add
2) Subtract
3) Multiply
4) Divide
5) Exit
Enter your choice:

99
Solution of
Menu Entry

100
Loop Conversions between For loop and While loop

101
Loop Conversions between For loop and While loop

i=1;
for (i=1; i<=10; i++)
while (i<=10)
{
{
printf(‘’%d\n’’; i*5);
printf(‘’%d\n’’; i*5);
}
i++;
}

102

You might also like