AST 103
Programming with C/C++
Lecture-7: Repetition statement III
Tahmina Akter
Lecturer of Applied Statistics,
Institute of Statistical Research and Training (ISRT),
University of Dhaka, Bangladesh.
Email: takter2@isrt.ac.bd
January, 2018
ogramming with
Homework
Task 6.4: Write a C program to calculate n raised to
the x power. The program should have a while
repetition control statement.
Task 6.5: Write a C program that calculates the sum
of first 10 positive integers. Use while statement to
loop through the calculation and statements.
Sentinel-Controlled Statement
Let us develop a class averaging program that will process
an arbitrary number of grades each time the program is
run.
◮ no indication is given of how many grades
are to be entered.
◮ the program must process arbitrary
number of grades.
Solution: one way to solve this problem is to use a specific
value called a sentinel value (also called a signal value, a
dummy value, or a flag value)
Average with sentinel-controlled repetition I
#include <stdio.h>
int main (void)
{
unsigned int counter;
int grade;
int total;
float average;
total=0;
counter=0;
printf("Enter grade, -1 to end:");
scanf("%d", &grade);
Average with sentinel-controlled repetition I
while (grade!=-1){
total=total+grade;
counter=counter+1;
printf("Enter grade, -1 to end:");
scanf("%d", &grade);
}
if (counter!=0){
average=(float)total/counter;
printf("Class average is %.2f\n", average);
}
else{
printf("No grade were entered");
}
}
Dissecting the code of sentinel-controlled
statement
In line 4, unsigned int declares that counter is a positive
integer variable.
Average of integers is not always an integer, to declare
a variable that can contain a fractional part, float (line 7)
is used to declare average as a floating-point number.
To produce a floating-point calculation with integer
values, we must create temporary value that are floating
point numbers (line 19).
In line 20, f specifies that a floating-point value will be
printed, and 0.2 is the precision with which the value will
be displayed. For example,
◮ printf(“%0.2f\n”, 3.446) → prints 3.45
◮ printf(“%0.1f\n”, 3.446) → prints 3.4