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

Repetition in C

The document discusses different types of repetition structures in programming, including counting loops, while loops, for loops, and conditional loops. It provides examples of using while loops to calculate total payroll for employees and sum of input numbers. For loops can be used as an alternative to while loops for counting loops. Conditional loops like sentinel-controlled loops are used when the number of repetitions is unknown beforehand.

Uploaded by

Rahib ridoy
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)
41 views42 pages

Repetition in C

The document discusses different types of repetition structures in programming, including counting loops, while loops, for loops, and conditional loops. It provides examples of using while loops to calculate total payroll for employees and sum of input numbers. For loops can be used as an alternative to while loops for counting loops. Conditional loops like sentinel-controlled loops are used when the number of repetitions is unknown beforehand.

Uploaded by

Rahib ridoy
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/ 42

Repetition and Loop

Statements

Mirza Mohammad Lutfe Elahi


CSE 115 Programming Language I ECE@NSU
2

Outline
• Repetition in Programs
• Counting loops
• The while statement
• The for statement
• Conditional Loops
• Nested Loops
• The do-while statement
• How to debug and test programs
• Common Programming Errors

CSE 115 Programming Language I ECE@NSU


3

Recall: Control Structures


• Three kinds of control structures
– Sequence (Compound Statement)
– Selection (if and switch Statements)
– Repetition (discussed in this presentation)
• The repetition of steps in a program is called a loop
• Three loop control structures in C
– The while statement
– The for statement
– The do-while statement

CSE 115 Programming Language I ECE@NSU


4

Repetition in Programs
• Loop structure
– A control structure that repeats a group of steps in a program
• Loop body
– The statements that are repeated inside the loop
• Three questions to raise:
1. Are there any steps repeated in the problem?
2. If the answer to question 1 is yes, is the number of
repetitions know in advance?
3. If the answer to question 2 is no, then how long to keep
repeating the steps?

CSE 115 Programming Language I ECE@NSU


5

Flowchart of Loop Choice

CSE 115 Programming Language I ECE@NSU


6

Counting Loop
• Called a Counter-controlled loop
• A loop that can be controlled by a counter variable
• Number of iterations (repetitions) can be determined
before loop execution begins
• General format of a counting loop:
Set loop control variable to an initial value
while (loop control variable < final value) {
/* Do something multiple times */
Increase loop control variable by 1
}
CSE 115 Programming Language I ECE@NSU
7

The while Statement


• Syntax: Loop Repetition Condition
while (condition) {
statement1 ;
statement2 ; Loop Body:
Can be one statement, or
. . .
Compound statement
statementN ;
}
• As long as condition is true, the loop body is executed
• The condition is re-tested after each iteration
• The loop terminates when condition becomes false
CSE 115 Programming Language I ECE@NSU
8

Example of a while Loop


• Compute and display the gross pay for 7 employees
– Initialization: count_emp = 0;
– Testing: (count_emp < 7)
– Updating: count_emp = count_emp + 1;

CSE 115 Programming Language I ECE@NSU


9

Flowchart of a while Loop

Loop repetition condition

Loop body

If count_emp is not updated,


the loop will execute forever.
Such a loop is called infinite loop.

CSE 115 Programming Language I ECE@NSU


10

Total Payroll of a Company

CSE 115 Programming Language I ECE@NSU


11

Sample Run
Enter number of employees> 3
Hours> 50
Rate> $5.25
Pay is $262.50

Hours> 6
Rate> $5.0
Pay is $ 30.00

Hours> 15
Rate> $7.0
Pay is $105.00

All employees processed


Total payroll is $ 397.50

CSE 115 Programming Language I ECE@NSU


12

Sum of numbers using while Loop


#include<stdio.h>

int main(void) /* Compute Sum of numbers */


{
int i = 0; /* count number */
int a; /* current input number */
int sum = 0; /* Sum of inputs */

while(i < 10)


{
printf("Enter a number: ");
scanf("%d", &a);
sum = sum + a;
i++;
}
printf("Total is %d\n", sum);

return 0;
}

CSE 115 Programming Language I ECE@NSU


13

The for Statement


• Better way to write a counting loop
for (initialization expression;
loop repetition condition;
update expression)
Statement ; /* Can be Compound */
• First, the initialization expression is executed
• Then, the loop repetition condition is tested
– If true, the Statement is executed , the update expression is computed,
and the repetition condition is re-tested
• Repeat as long as the repetition condition is true

CSE 115 Programming Language I ECE@NSU


14

Accumulating a Sum: total_pay

CSE 115 Programming Language I ECE@NSU


15

Compound Assignment Operator


variable op= expression ; is equivalent to
variable = variable op (expression) ;

Statement with Simple Equivalent with Compound


Assignment Operator Assignment Operator
count_emp = count_emp + 1; count_emp += 1;

time = time - 1; time -= 1;

product = product * item; product *= item;

total = total / number; total /= number;

n = n % (x+1); n %= x+1;

CSE 115 Programming Language I ECE@NSU


16

Prefix and Postfix Increments

C also provides the decrement operator -- that can be


used in either the prefix or postfix position

CSE 115 Programming Language I ECE@NSU


17

Computing Factorial

CSE 115 Programming Language I ECE@NSU


18

Conversion of Celsius to
Fahrenheit
Display a Table of Values

Decrement by 5

CSE 115 Programming Language I ECE@NSU


19

Conditional Loop
• Not able to determine the exact number of loop repetitions
before loop execution begins
• Example of a conditional loop: input validation
printf("Enter number of students> ");
scanf("%d", &num_students);
while (num_students < 0) {
printf("Invalid negative number; try again> ");
scanf("%d", &num_students);
}
• while loop rejects invalid (negative) input

CSE 115 Programming Language I ECE@NSU


20

Sentinel-Controlled Loop
• In many programs, we input a list of data values
• Often, we don’t know the length of the list
• We ask the user to enter a unique data value, called a
sentinel value, after the last data item
• Sentinel Value
– An end marker that follows the last value in a list of data
– For readability, we used #define to name the SENTINEL
• The loop repetition condition terminates a loop when
the sentinel value is read

CSE 115 Programming Language I ECE@NSU


21

Sentinel-Controlled while Loop


#include <stdio.h>
#define SENTINEL -1 /* Marking end of input */

int main(void) { /* Compute the sum of test scores */


int sum = 0; /* Sum of test scores */
int score; /* Current input score */

printf("Enter first score (%d to quit)> ", SENTINEL);


scanf("%d", &score);
while (score != SENTINEL) {
sum += score;
printf("Enter next score (%d to quit)> ", SENTINEL);
scanf("%d", &score);
}
printf("\nSum of exam scores is %d\n", sum);
return (0);
}

CSE 115 Programming Language I ECE@NSU


22

Sentinel-Controlled for Loop


#include <stdio.h>
#define SENTINEL -1 /* Marking end of input */

int main(void) { /* Compute the sum of test scores */


int sum = 0; /* Sum of test scores */
int score; /* Current input score */

printf("Enter first score (%d to quit)> ", SENTINEL);


for (scanf("%d", &score);
score != SENTINEL;
scanf("%d", &score)) {
sum += score;
printf("Enter next score (%d to quit)> ", SENTINEL);
}
printf("\nSum of exam scores is %d\n", sum);
return (0);
}

CSE 115 Programming Language I ECE@NSU


23

Infinite Loop on Faulty Input Data


• Reading faulty data can result in an infinite loop
scanf("%d", &score); /* read integer */
• Suppose the user enters the letter X
Enter next score (-1 to quit)> X
scanf fails to read variable score as letter X
• Variable score is not modified in the program
score != SENTINEL is always true
• Therefore, Infinite Loop

CSE 115 Programming Language I ECE@NSU


24

Detecting Faulty Input Data


• scanf can detect faulty input as follows:
status = scanf("%d", &score);
• If scanf successfully reads score then status is 1
• If scanf fails to read score then status is 0
• We can test status to detect faulty input
• This can be used to terminate the execution of a loop
• In general, scanf can read multiple variables
• It returns the number of successfully read inputs

CSE 115 Programming Language I ECE@NSU


25

Terminating Loop on Faulty Input


int main(void) { /* Compute the sum of test scores */
int sum = 0; /* Sum of test scores */
int score; /* Current input score */
int status; /* Input status of scanf */

printf("Enter first score (%d to quit)> ", SENTINEL);


status = scanf("%d", &score);
while (status != 0 && score != SENTINEL) {
sum += score;
printf("Enter next score (%d to quit)> ", SENTINEL);
status = scanf("%d", &score);
}
printf("\nSum of exam scores is %d\n", sum);
return (0);
}
CSE 115 Programming Language I ECE@NSU
26

Print number in reverse order


#include <stdio.h>
int main(void)
{
int number, digit;
printf("Enter a number: ");
scanf("%d", &number);
while(number > 0)
{
digit = number % 10;
printf("%d", digit);
number = number / 10;
}
return 0;
}

CSE 115 Programming Language I ECE@NSU


27

Nested Loops
• Consist of an outer loop with one or more inner loops
• Each time the outer loop is repeated, the inner loops are
reentered and executed
• Example:
int n = 5;
int i, j; *
for (i = 1; i <= n; i++) **
{
for (j = 1; j <= i; j++) ***
outer loop
inner loop

{ ****
printf("*");
} *****
printf("\n");
}
CSE 115 Programming Language I ECE@NSU
28

What is the Output


/* Illustrates nested for loops */
#include <stdio.h>

int main(void) { i j
int i, j; /* loop variables */ Outer 1
printf(" I J\n"); Inner 0
for (i = 1; i < 4; i++) { Outer 2
Inner 0
printf("Outer %6d\n", i);
Inner 1
for (j = 0; j < i; j++) { Outer 3
printf(" Inner%9d\n", j); Inner 0
} /* end of inner loop */ Inner 1
} /* end of outer loop */ Inner 2

return (0);
}
CSE 115 Programming Language I ECE@NSU
29

The do-while Statement


• The for and while statements evaluate the loop condition
before the execution of the loop body
• The do-while statement evaluates the loop condition after
the execution of the loop body
• Syntax:
do
statement; /* Can be compound */
while (loop repetition condition) ;
• The do-while must execute at least one time

CSE 115 Programming Language I ECE@NSU


30

Using do-while to repeat Program


int main(void) {
. . . /* Variable Declarations */
char ch; /* User response [y/n] */

do {
. . . /* Execute program */
printf("Repeat again [y/n]? ");
ch = getch(); /* read from keyboard */
printf("%c\n", ch); /* display character */
} while (ch=='y'|| ch=='Y’);
return 0;
}

CSE 115 Programming Language I ECE@NSU


31

Example: Selection Inside Loop


#include<stdio.h>

int main(void)
{
int number, i, flag = 1;
scanf("%d", &number);

for(i = 2; i < number; i++)


{
if(number % i == 0)
flag = 0;
}

if(flag == 1)
printf("%d is a prime number.\n", number);
else
printf("%d is not a prime number.\n", number);

return 0;
}
CSE 115 Programming Language I ECE@NSU
32

Using break Inside Loop


#include<stdio.h>

int main(void){
int number, i, flag = 1;
scanf("%d", &number);

for(i = 2; i < number; i++){


if(number % i == 0){
flag = 0;
break;
}
} The break statement makes the
loop terminate prematurely.
if(flag == 1)
printf("%d is a prime number",number);
else
printf("%d is not a prime number",number);

return 0;
}
CSE 115 Programming Language I ECE@NSU
33

Using continue Inside Loop


#include<stdio.h>

int main(void){
int number, i, sum = 0;

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


printf("Enter a number: ");
scanf("%d", &number);

if(number < 0) The continue statement forces


continue; next iteration of the loop,
skipping any remaining
sum += number; statements in the loop
printf("%d is added\n", number);
}

printf("Total = %d\n",sum);
return 0;
}

CSE 115 Programming Language I ECE@NSU


34

Using continue Inside Loop


#include<stdio.h>

int main(void){
int number, i, sum = 0;

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


printf("Enter a number: ");
scanf("%d", &number);

if(number < 0) The continue statement forces


continue; next iteration of the loop,
skipping any remaining
sum += number; statements in the loop
printf("%d is added\n", number);
}

printf("Total = %d\n",sum);
return 0;
}

CSE 115 Programming Language I ECE@NSU


35

Using continue Inside Loop


#include<stdio.h>

int main(void){
int number, i, sum = 0; Output:
Enter a number: 1
for(i = 0; i < 10; i++){ 1 is added
printf("Enter a number: "); Enter a number: 2
scanf("%d", &number); 2 is added
Enter a number: 3
3 is added
if(number < 0) Enter a number: -4
continue; Enter a number: -5
Enter a number: 6
sum += number; 6 is added
printf("%d is added\n", number); Enter a number: 7
} 7 is added
Enter a number: 8
printf("Total = %d\n",sum); 8 is added
Enter a number: -9
return 0;
Enter a number: 10
} 10 is added
Total = 37
CSE 115 Programming Language I ECE@NSU
36

Practice Series Problems

CSE 115 Programming Language I ECE@NSU


37

How to Debug and Test a Program


• Using a debugger program
– Debug option should be selected
– Execute program one statement at a time (Next line)
– Watch the value of variables at runtime (Add watch)
– Set breakpoints at selected statements
• Debugging without a debugger
– Insert extra printf statements that display intermediate results
at critical points in your program
if (DEBUG) printf(. . .);
– Turn ON diagnostic calls to printf
#define DEBUG 1
CSE 115 Programming Language I ECE@NSU
38

Example: Debugging using printf


#define DEBUG 1 /* turn on diagnostics */
#define DEBUG 0 /* turn off diagnostics */

int main(void) {
int score, sum=0;
printf("Enter first score (%d to quit)> ", SENTINEL);
scanf("%d", &score); /* get first score */
while (score != SENTINEL) {
sum += score;
if (DEBUG) printf("score=%d, sum=%d\n", score, sum);
printf("Enter next score (%d to quit)> ", SENTINEL);
scanf("%d", &score); /* get next score */
}
printf("Total score is %d\n", sum);
return 0;
}
CSE 115 Programming Language I ECE@NSU
39

Off-By-One Loop Errors


• A common logic error
• A loop executes one more time or one less time
• Example:
for (count = 0; count <= n; ++count)
sum += count; Executes n + 1 times

for (count = 1; count < n; ++count)


sum += count; Executes n – 1 times
• Checking loop boundaries
– Initial and final values of the loop control variable

CSE 115 Programming Language I ECE@NSU


40

Common Programming Errors


• Do not confuse if and while statements
– if statement implements a decision step
– while statement implements a loop
• for loop: remember to end the initialization step and
the loop repetition condition with semicolon (;)
• Remember to use braces { and } around a loop body
consisting of multiple statements
• Remember to provide a prompt for the user, when
using a sentinel-controlled loop
• Make sure the sentinel value cannot be confused with
a normal data input
CSE 115 Programming Language I ECE@NSU
41

Common Programming Errors


• Use do-while only when there is no possibility of
zero loop iterations
• Do not use increment, decrement, or compound
assignment as sub-expressions in complex expressions
a *= b + c; /* a = a*(b+c); */
There is no shorter way to write: a = a*b + c;
• Be sure that the operand of an increment/decrement
operator is a variable:
z = ++j * k--; /* ++j; z=j*k; k--; */

CSE 115 Programming Language I ECE@NSU


42

Chapter Review
• Two kinds of loops occur frequently in programming
• Counting loop: controlled by a counter
• Conditional loop: controlled by a condition
– Sentinel-controlled loop
– Input validation loop
– General conditional loop
• C provides three statements for implementing loops
– while statement (can have zero repetitions)
– for statement (can have zero repetitions)
– do-while statement (must execute at least once)

CSE 115 Programming Language I ECE@NSU

You might also like