Lecture #8
Lecture #8
BİL1102
Programlamaya Giriş
Ders #7
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");
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
• 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
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
ii+1
The simplest example cont:
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:
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
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.
• We have to make sure that the value we choose as the sentinel isn’t a
legal value.
/* 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) ;
}
return 0 ;
}
Example
Write a program such that :
• Program requests user to input a positive integer number
• 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;
#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:
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
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)
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.
• 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
#include <stdio.h>
int main ()
{
int i = 1 ;
#include <stdio.h>
int main ()
{
int i = 1 ;
for ( i = 1; i == 10; i = i + 2 )
{
printf (“%d\n”, i) ;
Output :
} Finish!
printf (“Finish!”) ;
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
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);
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 ) ;
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