0% found this document useful (0 votes)
41 views13 pages

MODULE 5b. Control Structure Loop Statements

credits sa prof ko. huhu sorry need ko lng talaga magdownload ng file
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views13 pages

MODULE 5b. Control Structure Loop Statements

credits sa prof ko. huhu sorry need ko lng talaga magdownload ng file
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Computer Programming

Lecture 5 CONTROL STRUCTURE

b) REPETITION AND LOOP STATEMENTS (ITERATIVE STATEMENTS)

Repetition is another type of program control structure. It allows a set of instructions to be


executed or performed several times until certain conditions are met.

The following questions should be asked to determine whether loops will be required in the general
algorithm.
1) Were there any steps repeated as the problem is solved? If so, which ones?
2) If the answer in #1 is yes, is it known in advance how many times should the steps be
repeated?
3) If the answer to #2 is no, how long should the steps be repeated?

Most repetition structures have three loop control components in addition to the loop body:
 Initialization of the loop control variable
 Test of the loop repetition condition
 Change (update) of the loop control variable

An important feature of the for loop statement in C is that it supplies a designated place for each of
these three components. The for statement can be used to count up or down by any interval.

loop – a control structure that repeats a group of steps in a program.


loop body – the statements that are repeated in a loop.

Any steps NO No loop


repeated? required

YES

Use one of the conditional


Know in advance NO loops:
how many times sentinel-controlled
to repeat?
endfile-controlled
input validation
general conditional
YES

Use a counting
loop

FIG. Flow Diagram of Loop Choice Process

1 |LESSON 5
Computer Programming

Kind When Used C Implementation


Structures
Counting Loop We can determine before loop while
execution exactly how many loop for
repetitions will be needed to solve the
problem.
Sentinel-controlled Loop Input of a list of data of any length while
ended by a special value for
Endfile-controlled Loop Input of a single list of data of any while
length from a data file for
Input validation Loop Repeated interactive input of a data do-while
value until a value within the valid
range is entered
General conditional Loop Repeated processing of data until a while
desired condition is met for
Table Comparison of Loop Kinds
1. The FOR Statement

The for statement or for loop is considered as a predefined loop because the number of times it
iterates to perform its body is predetermined in the loop’s definition.

The general form of the for statement is:

SYNTAX: for (initialization expression; condition; increment or update expression)


{
statement_sequence;
}
for ( i=0; i<=10; i++)
{
printf(“Hello World”);
}

EXAMPLE: /*Display N asterisks*/


for (count_star =0;
count_star <N;
count_star+=1)
printf(“*”);

The initialization expression is executed. Then, the loop repetition condition is tested. If it is true,
the statement is executed, and the update expression is evaluated. Then the loop repetition
condition is retested. The statement is repeated as long as the loop repetition condition is true.
When this condition is tested and found to be false, the for loop is exited, and the next
program statement after the for statement is executed.

Side effect
 A change in the value of a variable as a result of carrying out an operation

2 |LESSON 5
Computer Programming
 The side effect of applying the ++ operator is that the value of its operand is
incremented by one and when – operator is applied, the value of its operand is
decremented by one.

Increment and Decrement Operators:


j=i--/*i is decremented*/
j=i++ /*i is incremented*/

Prefix and Postfix Increments


j=++i /*Prefix increment. Increment i and then use it*/
j=i++ /*Postfix increment. Use i and then increment it*/

Note:
 Although C permits the use of fractional values for counting loop control variables of
type double, it is not recommended. Counting loops with type double control
variables will not always execute the same number of times on different computers.
 Never place a semi-colon right after the for header. This is a logical error.
 Never change the value of the for loop’s counter inside the body of the loop. This will
affect the result of the program.
 The increment part of the for loop is executed after the first iteration of the loop.

Example (1)
Write a program that computes the factorial value of n (as input) and displays it.
#include<stdio.h>
#include<conio.h>
main()
{
int n, f, i;
clrscr();
printf(“\n Enter a number: “);
scanf(“%d”, &n);
f=1;
for (i=n; i>=1; i--)
{
f=f*i;
}
printf(“\nThe factorial value: %d”, f);
getch();
}

Example (2)
Write a program that will print the numbers 1 to 10 using a for statement.
#include<stdio.h>
#include<conio.h>
#include<dos.h>
int x;
main()
{
clrscr();
for (x=1; x<=10; x++)

3 |LESSON 5
Computer Programming
{
printf(“%d\n”,x);
delay(1000);
}
getch();
return(0);
}

Example (3)
Write a program that will get the sum of all integers from 1 to 10.
#include<stdio.h>
#include<conio.h>
int x,sum;
main()
{
clrscr();
sum=0;
for (x=1; x<=10; x++)
{
sum=sum+x;
}
printf(“The sum of 1 to 10 is %d\n”,sum);
getch();
}

2. The WHILE Statement

The while statement or while loop is an open-ended or event-controlled loop. The while loop
iterates while the condition is True (1). When it becomes False (0), the program control passes
to the line after the loop code.

The general form of the while statement is:

SYNTAX: while (loop repetition condition)


statement

EXAMPLE: /*Display N asterisks*/


count_star=0;
while (count_star < N)
{
printf(“*”);
count_star = count_star +1;
}

The loop repetition condition (a condition to control the loop process) is tested; if it is true the
statement (loop body) is executed, and the loop repetition condition is retested. The statement
is repeated as long as (while) the loop repetition is true. When this condition is tested and found
to be false, the while loop is exited and the next program statement is executed.

4 |LESSON 5
Computer Programming
Note: If loop repetition condition evaluates to false the first time it is tested, statement is not
executed.

counter-controlled loop (counting loop)


 A loop whose required number of iterations can be determined before loop execution
begins
loop repetition condition
 The condition that controls loop repetition

loop control variable


 The variable whose value controls loop repetition
infinite loop
 A loop that executes forever
accumulator
A variable used to store a value being computed in increments during the execution of a loop

Example (1)
Using while statement, write a program that computes the factorial value of n (as input) and
displays it.
#include<stdio.h>
#include<conio.h>
main()
{
int n, f, i;
clrscr();
printf(“\n Enter a number: “);
scanf(“%d”, &n);
f=1;
i=n;
while (i>=1)
{
f=f*i;
i--;
}
printf(“\nThe factorial value: %d”, f);
getch();
return 0;
}

Example (2)
Write a program that will print the numbers 1 to 10 using a while statement.

#include<stdio.h>
#include<conio.h>
int x;
main()
{
clrscr();
x=1;
while (x<=10)

5 |LESSON 5
Computer Programming
{
printf(“%d\n”,x);
x++;
}
getch();
return 0;
}

Example (3)
Write a program that generates the given sequence numbers using a while statement.
5
4
3
2
1
#include<stdio.h>
#include<conio.h>
#include<dos.h>
int n;
main()
{
clrscr();
n=5;
while (n>=1)
{
printf(“\n%d”,n);
delay(3000);
n--;
}
getch();
return 0;
}

3. The DO-WHILE Statement


The second type of open-ended or event-controlled loop is the do-while statement or do-while
loop.

The general form of the do-while statement is:

SYNTAX: do
statement
while (loop repetition condition);

EXAMPLE: /*Find first even number input*/


do
status = scanf(“%d”, &num);
while (status>0 && (num%2) !=0);

6 |LESSON 5
Computer Programming
First, the statement is executed. Then, the loop repetition condition is tested, and if it is true, the
statement is repeated and the condition retested. When this condition is retested and found to
be false, the loop is exited and the next statement after the do-while is executed.

Do-while is a variation of the while statement which checks the condition at the bottom/end of
the loop. This means that a do-while loop “always executes at least one”.

Note: If the loop body contains more than one statement, the group of statements must be
surrounded by braces {}.

Example (1)
Using do-while statement, write a program that computes the factorial value of n (as input)
and displays it.
#include<stdio.h>
#include<conio.h>
main()
{
int n, f, i;
clrscr();
printf(“\n Enter a number: “);
scanf(“%d”, &n);
f=1;
i=n;
do
{
f=f*i;
i--;
}
while (i>=1);
printf(“\nThe factorial value of %d is: %d”, n, f);
getch();
return 0;
}

Example (2)
Write a program that will print the numbers 1 to 10 using do-while statement.
#include<stdio.h>
#include<conio.h>
int x;
main()
{
clrscr();
x=1;
do
{
printf(“%d\n”,x);
x++;
}
while (x<=10)
getch();

7 |LESSON 5
Computer Programming
return 0;
}

Example (3)
Write a program that will get the average of all integers from 1 to 10 using do-while loop.
#include<stdio.h>
#include<conio.h>
int x, sum;
float average;
main()
{
clrscr();

sum=0;
x=1;
do
{
sum=sum+x;
x++;
}
while (x<=10)
average=sum/10.00;
printf(“The computed average is %.2f\n”,average);
getch();
return 0;
}

Kinds of Loops
1) Counter-controlled Loop or Counting Loop
Pseudocode
Set loop control variable to an initial value of 0.
While loop control variable < final value

Increase loop control variable by 1.

2) Sentinel-controlled Loop
Pseudocode
Get a line of data.
While the sentinel value has not been encountered.
Process the data line.
Get another line of data.

3) Endfile-controlled Loop
Pseudocode
Get first data value and save input status
While input status does not indicate that end of file has been reached
Process data value
Get next data value and save input status

4) Input Validation Loop

8 |LESSON 5
Computer Programming
Pseudocode
Get a data value
If data value is not in the acceptable range
Go back to first step

5) General Conditional Loop


Another kind of repetition where the user is continuously prompted for a data value as long as
the response is unreasonable.

Pseudocode
Initialize loop control variable
As long as exit condition hasn’t been met
continue processing
Example: Program to Compute Company Payroll
#include <stdio.h>
#include<conio.h>
main ()
{
double total_pay, hours,rate,pay;
int count_emp,number_emp;

/*Get number of employees.*/


printf(“Enter number of employees> “);
scanf(“%d”, &number_emp);
/*Compute each employee’s pay and add it to the payroll.*/
total_pay=0.0;
count_emp=0;
while (count_emp<number_emp)
{
printf(“Hours> “);
scanf(“%f”,&hours);
printf(“Rate> $“);
scanf(”%f”, &rate);
pay=hours*rate;
printf(“Pay is $%6.2f \n”, pay);
total_pay=total_pay+pay; /*Add next pay*/
count_emp=count_emp+1;
}
printf(“All employees processed”);
printf(“Total payroll is $%8.2f\n”,total_pay);
getch ();
return 0;
}

Example: Using a for Statement in a Counting Loop


total_pay=0.0;
for (count_emp=0; /*initialization*/
count_emp<number_emp; /*loop repetition condition*/

9 |LESSON 5
Computer Programming
count_emp+=1) /*update*/
{
printf(“Hours> “);
scanf(“%lf”,&hours);
printf(“Rate> $“);
scanf(%lf”, &rate);
pay=hours*rate;
printf(“Pay is $%6.2f \n”, pay);
total_pay=total_pay+pay; }
printf(“All employees processed”);
printf(“Total payroll is $%8.2f\n”,total_pay);
getch();
return 0;
}

Example: Increments and Decrements Other than 1

Displaying a Celsius-to-Fahrenheit Conversion Table

#include<stdio.h>
/*Constant macros*/
OUTPUT:
#define CBEGIN 10
Celsius Fahrenheit
#define CLIMIT -5
10 50.00
#define CSTEP 5
5 41.00
main ()
0 32.00
{
-5 23.00
int celsius;
double fahrenheit;
printf(“ Celsius Fahrenheit\”);
for (celsius =CBEGIN;celsius>=CLIMIT;celsius-=CSTEP) {
fahrenheit=1.8*celsius+32.0;
printf(“%6c%3d%8c%7.2f\n”, ‘ ‘, celsius, ’ ‘,fahrenheit);
}
getch();
return 0;
}

Example: Sentinel-controlled while Loop


/*Compute the sum of list of exam scores*/ SAMPLE OUTPUT:
#include<stdio.h> Enter first score (or -99 to quit)> 50
#include<conio.h> Enter first score (or -99 to quit)>45
int sum, score; Enter first score (or -99 to quit)>30
main() Enter first score (or -99 to quit)>42
{ Enter first score (or -99 to quit)>-99
/*Accumulate sum of all scores*/ Sum of exam scores is 167
sum=0;
printf(“\nEnter first score (or -99 to quit)> ”);

10 |LESSON 5
Computer Programming
scanf(“%d”, &score); /*Get first score */
while (score!=-99)
{
sum+=score;
printf(“\nEnter next score (or -99 to quit)> ”);
scanf(“%d”, &score); /*Get next score */
}
printf(“\nSum of exam scores is %d”,sum);
getch();
return 0;
}
Example: Program to Process Bald Eagle Sightings for a Year

/*Tally by month the bald eagle sightings for the year.


*Each month’s sightings are terminated by the sentinel zero*/
#include<stdio.h>
#include<conio.h>
#define SENTINEL 0
#define NUM_MONTHS 12
int month, /*number of month being processed */
mem_sight, /*one member’s sightings for this month*/
sightings; /*total sightings so far for this month */
main()
{
printf(“ BALD EAGLE SIGHTINGS\n”);
printf(“Input data for every month <Type 0 to terminate>: ”)
for (month=1;month<=NUM_MONTHS;month++)
{
sightings=0;
scanf(“%d”, &mem_sight);
while (mem_sight !=SENTINEL)
{
if (mem_sight>=0)
sightings+=mem_sight;
else
printf(“Warning, negative count %d ignored\n”,mem_sight);
scanf(“%d”,&mem_sight);
}
printf(“ month %2d: %2d\n, month, sightings);
} /*outer for*/
return (0);
}

11 |LESSON 5
Computer Programming
Example: A program to print Fibonacci series.
#include "stdio.h"
#include "conio.h"
void main()
{
int a,b,c,i,n;
clrscr();
a=0;
b=1;
printf("\n Please enter n for how many times generate series");
scanf("%d",&n);
printf("\n FIBONACCI SERIES in C Language \n");
printf("\t%d\t%d",a,b);
for(i=0;i<n;i++)
{
c=a+b;
a=b;
b=c;
printf("\t%d",c);
}
getch();
}

12 |LESSON 5
Computer Programming
Example:
A program is designed to assist in monitoring the gasoline supply in a storage tank at the Super
Oil Company refinery. The program is to alert the supervisor when the supply of the gasoline in
the tank falls below 10% of the tank’s 80,000-barrel storage capacity. Although the supervisor
always deals with the contents of the tank in terms of a number of barrels, the pump that is
used to fill water trucks gives its measurements in gallons. The barrel used in the petroleum
industry equals 42 US gallons.

Program to Monitor Gasoline’s Storage Tank

#include<stdio.h>
#include<conio.h>
#define CAPACITY 80000
#define GALS_PER_BRL 42.0

double monitor_gas, min_supply, start_supply;


double current;

main()
{

/*Compute minimum supply without warning*/


min_supply = 0.10*CAPACITY;
/*Get initial supply*/
printf(“Number of barrels currently in tank> “);
scanf(“%f”, &start_supply);
/*Subtract amounts removed and display amount remaining
as long as minimum supply remains*/
current=min_supply – start_supply;
/*Issue warning*/
printf(“only %.2f barrels are left.\n”, current);
printf(“***WARNING***\n”)

13 |LESSON 5

You might also like