0% found this document useful (0 votes)
49 views53 pages

Control Flow: Looping Control Flow: Looping: Programming & Data Structures Programming & Data Structures

The document discusses different types of loops in C programming, including while, for, and do-while loops. It provides examples of using each loop type to iterate through operations like summing the first N natural numbers or printing patterns like stars. Key loop concepts covered include initialization, test conditions, updating, break and continue statements, and nested loops. Various looping applications are demonstrated, such as calculating factorials, finding maximum values, and printing 2D shapes.

Uploaded by

Paras Dorle
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)
49 views53 pages

Control Flow: Looping Control Flow: Looping: Programming & Data Structures Programming & Data Structures

The document discusses different types of loops in C programming, including while, for, and do-while loops. It provides examples of using each loop type to iterate through operations like summing the first N natural numbers or printing patterns like stars. Key loop concepts covered include initialization, test conditions, updating, break and continue statements, and nested loops. Various looping applications are demonstrated, such as calculating factorials, finding maximum values, and printing 2D shapes.

Uploaded by

Paras Dorle
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/ 53

Control Flow: Looping

CS10001: Programming & Data Structures

Pallab Dasgupta
Professor, Dept. of Computer Sc. & Engg.,
Engg.,
Indian Institute of Technology Kharagpur

Dept. of CSE, IIT KGP

Types of Repeated Execution


Loop: Group of instructions that are executed
repeatedly while some condition remains true.
How loops are controlled

Sentinel
Controlled

Condition

Controlled
Counter Controlled
1, 2, 3, 4,
, 4, 3, 2, 1
Dept. of CSE, IIT KGP

Counter Controlled Loop

Read 5 integers
and display the
value of their
summation.

counter 1, sum 0

counter < 6
true
input n
sum sum + n
counter++
output sum

Dept. of CSE, IIT KGP

false

Condition-controlled Loop

Given an exam marks as input, display the appropriate


message based on the rules below:
 If marks is greater than 49, display PASS, otherwise
display FAIL
 However, for input outside the 0-100 range, display
WRONG INPUT and prompt the user to input again
until a valid input is entered

Dept. of CSE, IIT KGP

Condition-Controlled Loop
input m
WRONG INPUT
true

m<0 || m>100
false
Condition-controlled
loop with its condition
being tested at the end

true

m>49
false

FAIL

Dept. of CSE, IIT KGP

PASS

input m
false

m<0 || m>100
true

WRONG INPUT
input m
Condition-controlled
Conditionloop with its
condition being
tested first

Dept. of CSE, IIT KGP

true

m>49
false

FAIL

PASS

Sentinel-Controlled Loop

Receive a number of positive


integers and display the
summation and average of
these integers.
A negative or zero input
indicates the end of input
process

Input: A set of integers


ending with a
negative integer or a zero

Output: Summation and


Average of these integers

Dept. of CSE, IIT KGP

Input Example:
30 16
42
Output Example:
Sum = 88
Average = 29.33

Dept. of CSE, IIT KGP

-9

Sentinel
Value

while loop
while (expression)
statement
expression
T

while (i < n) {
printf (Line no : %d.\n,i);
i++;
}

Dept. of CSE, IIT KGP

statement
(loop body)

while Statement
The while statement is used to carry out looping
operations, in which a group of statements is executed
repeatedly, as long as some condition remains
satisfied.
while (condition)
statement_to_repeat;

while (condition) {
statement_1;
...
statement_N;
}

Note:
The while-loop will not be entered if the loop-control
expression evaluates to false (zero) even before the first
iteration.
break can be used to come out of the while loop.
Dept. of CSE, IIT KGP

while :: Examples
int weight;
while ( weight > 65 ) {
printf ("Go, exercise, ");
printf ("then come back. \n");
printf ("Enter your weight: ");
scanf ("%d", &weight);
}

Dept. of CSE, IIT KGP

Sum of first N natural numbers int main () {

int N, count, sum;


scanf (%d, &N) ;
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count;
count = count + 1;
}
printf (Sum = %d\n, sum) ;
return 0;

START
READ N
SUM = 0
COUNT = 1
SUM = SUM + COUNT

COUNT = COUNT + 1

NO

IS
COUNT > N?

YES
OUTPUT SUM
STOP

Dept. of CSE, IIT KGP

Double your money


Suppose your Rs 10000 is earning interest at 1% per
month. How many months until you double your money ?
my_money=10000.0;
n=0;
while (my_money < 20000.0) {
my_money = my_money*1.01;
n++;
}
printf (My money will double in %d months.\n,n);

Dept. of CSE, IIT KGP

Maximum of inputs
printf (Enter positive numbers to max, end with 1.0\n);
max = 0.0;
count = 0;
scanf(%f, &next);
while (next != 1.0) {
if (next > max)
max = next;
count++;
scanf(%f, &next);
}
printf (The maximum number is %f\n, max) ;

Dept. of CSE, IIT KGP

Printing a 2-D Figure

How would you print the following diagram?

*****
*****
*****

repeat 3 times
print a row of 5
stars

Dept. of CSE, IIT KGP

repeat 5 times
print *

Nested Loops

#define ROWS 3
#define COLS 5
...
row=1;
while (row <= ROWS) {
/* print a row of 5 *s */
...
row++;
}

Dept. of CSE, IIT KGP

row=1;
while (row <= ROWS) {
/* print a row of 5 *s */
col=1;
while (col <= COLS) {
printf (* );
col++;
}
printf(\n);
row++;
}

outer
loop
inner
loop

do-while statement

do statement while (expression)


main () {
int digit=0;
do
printf(%d\n,digit++);
while (digit <= 9) ;
}

statement

F
expression
T

Dept. of CSE, IIT KGP

Example for do-while


Usage: Prompt user to input month value, keep prompting until a
correct value of moth is input.
do {
printf (Please input month {1-12});
scanf (%d, &month);
} while ((month < 1) || (month > 12));

Dept. of CSE, IIT KGP

int main () {
char echo ;
do {
scanf (%c, &echo);
printf (%c,echo);
} while (echo != \n) ;
}

Dept. of CSE, IIT KGP

for Statement
The for statement is the most commonly
used looping structure in C.
General syntax:
for ( expr1; expr2; expr3) statement
expr1 (init) : initialize parameters
expr2 (test): test condition, loop continues if satisfied
expr3 (update): used to alter the value of the parameters
after each iteration
statement (body): body of the loop

Dept. of CSE, IIT KGP

for ( expression1; expression2; expression3)


statement
expr1
(init)
expr2
(test)
T
statement
(body)
expr3
(update)
Dept. of CSE, IIT KGP

expr1;
while (expr2) {
statement
expr3;
}

Sum of first N natural numbers


int main () {
int N, count, sum;
scanf (%d, &N) ;
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count;
count = count + 1;
}
printf (Sum = %d\n, sum) ;
return 0;
}

Dept. of CSE, IIT KGP

Sum of first N natural numbers


int main () {
int N, count, sum;
scanf (%d, &N) ;
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count;
int main () {
count = count + 1;
int N, count, sum;
}
printf (Sum = %d\n, sum) ; scanf (%d, &N) ;
sum = 0;
return 0;
}
for (count=1; count

<= N; count++)
sum = sum + count;

printf (Sum = %d\n, sum) ;


return 0;
}

Dept. of CSE, IIT KGP

2-D Figure
Print
*****
*****
*****

Dept. of CSE, IIT KGP

#define ROWS 3
#define COLS 5
....
for (row=1; row<=ROWS; row++) {
for (col=1; col<=COLS; col++) {
printf(*);
}
printf(\n);
}

Another 2-D Figure


Print
*
**
***
****
*****

Dept. of CSE, IIT KGP

#define ROWS 5
....
int row, col;
for (row=1; row<=ROWS; row++) {
for (col=1; col<=row; col++) {
printf(* );
}
printf(\n);
}

For - Examples

Problem 1: Write a For statement that computes the sum of all odd
numbers between 1000 and 2000.
Problem 2: Write a For statement that computes the sum of all
numbers between 1000 and 10000 that are divisible by 17.
Problem 3: Printing square problem but this time make the square
hollow.
Problem 4: Print
*****
****
***
**
*

Dept. of CSE, IIT KGP

Problem 4 : solution
Print
*****
****
***
**
*

Dept. of CSE, IIT KGP

#define ROWS 5
....
int row, col;
for (row=0; row<ROWS; row++) {
for (col=1; col<=row; col++)
printf(" ");
for (col=1; col<=ROWS-row; col++)
printf("* ");
printf ("\n");
}

The comma operator


We can give several statements separated by commas
in place of expression1, expression2, and
expression3.
for (fact=1, i=1; i<=10; i++)
fact = fact * i;
for (sum=0, i=1; i<=N, i++)
sum = sum + i * i;

Dept. of CSE, IIT KGP

for :: Some Observations


Arithmetic expressions
Initialization, loop-continuation, and increment
can contain arithmetic expressions.
for ( k = x; k <= 4 * x * y; k += y / x )
"Increment" may be negative (decrement)
for (digit=9; digit>=0; digit--)
If loop continuation condition initially false:
Body of for structure not performed.
Control proceeds with statement after for structure.

Dept. of CSE, IIT KGP

Specifying Infinite Loop


for (; ;)
{
statements
}

while (1) {
statements
}

do {
statements
} while (1);

Dept. of CSE, IIT KGP

The break Statement

Break out of the loop { }


can use with
while
do while
for
switch
does not work with
if
else

Causes immediate exit from a while, do/while, for or switch


structure.
Program execution continues with the first statement after the
structure.

Dept. of CSE, IIT KGP

An Example
#include <stdio.h>
int main() {
int fact, i;
fact = 1; i = 1;
while ( i<10 ) {
/* run loop break when fact >100*/
fact = fact * i;
if ( fact > 100 ) {
printf ("Factorial of %d above 100", i);
break;
/* break out of the while loop */
}
i ++ ;
}
}

Dept. of CSE, IIT KGP

The continue Statement


Skips the remaining statements in the body of a
while, for or do/while structure.
Proceeds with the next iteration of the loop.

while and do/while


Loop-continuation test is evaluated immediately after the
continue statement is executed.

for structure
expression3 is evaluated, then expression2 is evaluated.

Dept. of CSE, IIT KGP

An Example with break & continue


fact = 1; i = 1;
while (1) {
fact = fact * i;
i ++ ;
if ( i<10 )
continue;
break;
}

Dept. of CSE, IIT KGP

/* a program segment to calculate 10 !

/* not done yet ! Go to loop and


perform next iteration*/

Some Examples

Dept. of CSE, IIT KGP

Sum of first N natural numbers int main () {

int N, count, sum;


scanf (%d, &N) ;
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count;
count = count + 1;
}
printf (Sum = %d\n, sum) ;
return 0;

START
READ N
SUM = 0
COUNT = 1
SUM = SUM + COUNT

COUNT = COUNT + 1

NO

IS
COUNT > N?

YES
OUTPUT SUM
STOP

Dept. of CSE, IIT KGP

Sum of first N natural numbers


int main () {
int N, count, sum;
scanf (%d, &N) ;
START
sum = 0;
count = 1;
READ N
for (count=1;count <= N;count++) {
sum = sum + count;
SUM = 0
printf (Sum = %d\n, sum) ;
COUNT = 1
return 0;
SUM = SUM + COUNT }
COUNT = COUNT + 1

NO

IS
COUNT > N?

YES
OUTPUT SUM
STOP

Dept. of CSE, IIT KGP

Example 5: SUM = 12 + 22 + 32 + N2
int main () {
int N, count, sum;
scanf (%d, &N) ;
sum = 0;
count = 1;
while (count <= N) {
sum = sum + count
count;
count = count + 1;
}
printf (Sum = %d\n, sum) ;
return 0;
}

START
READ N
SUM = 0
COUNT = 1
SUM = SUM + COUNT COUNT
COUNT = COUNT + 1

NO

IS
COUNT > N?

YES
OUTPUT SUM
STOP

Dept. of CSE, IIT KGP

Example: Computing Factorial


START
READ N
PROD = 1
COUNT = 1
PROD = PROD * COUNT

int main () {
int N, count, prod;
scanf (%d, &N) ;
prod = 1;
for (count=0;count < N; count++) {
prod =prod*count;
printf (Factorial = %d\n, prod) ;
return 0;
}

COUNT = COUNT + 1

NO

IS
COUNT > N?

YES
OUTPUT PROD
STOP

Dept. of CSE, IIT KGP

Example: Computing ex series up to N terms


START
READ X, N
TERM = 1
SUM = 0
COUNT = 1
SUM = SUM + TERM
TERM = TERM * X / COUNT
COUNT = COUNT + 1

NO

IS
COUNT > N?

YES
OUTPUT SUM
STOP

Dept. of CSE, IIT KGP

int main () {
float x, term, sum;
int n, count;
scanf (%d, &x) ;
scanf (%d, &n) ;
term = 1.0; sum = 0;
for (count = 0; count < n; count++) {
sum += term;
term = x/count;
}
printf (%f\n, sum) ;
}
Dept. of CSE, IIT KGP

Example 8: Computing ex series up to 4 decimal places


START
READ X, N
TERM = 1
SUM = 0
COUNT = 1
SUM = SUM + TERM
TERM = TERM * X / COUNT
COUNT = COUNT + 1

NO

IS
TERM < 0.0001?

YES
OUTPUT SUM
STOP

Dept. of CSE, IIT KGP

int main () {
float x, term, sum;
int n, count;
scanf (%d, &x) ;
scanf (%d, &n) ;
term = 1.0; sum = 0;
for (count = 0; term<0.0001; count++) {
sum += term;
term *= x/count;
}
printf (%f\n, sum) ;
}
Dept. of CSE, IIT KGP

Example 1: Test if a number is prime or not


#include <stdio.h>
int main() {
int n, i=2;
scanf (%d, &n);
while (i < n) {
if (n % i == 0) {
printf (%d is not a prime \n, n);
exit;
}
i++;
}
printf (%d is a prime \n, n);
}
Dept. of CSE, IIT KGP

More efficient??
#include <stdio.h>
main()
{
int n, i=3;
scanf (%d, &n);
while (i < sqrt(n)) {
if (n % i == 0) {
printf (%d is not a prime \n, n);
exit;
}
i = i + 2;
}
printf (%d is a prime \n, n);
}

Dept. of CSE, IIT KGP

Example 2: Find the sum of digits of a number


#include <stdio.h>
main()
{
int n, sum=0;
scanf (%d, &n);
while (n != 0) {
sum = sum + (n % 10);
n = n / 10;
}
printf (The sum of digits of the number is %d \n, sum);
}

Dept. of CSE, IIT KGP

Example 3: Decimal to binary conversion


#include <stdio.h>
main()
{
int dec;
scanf (%d, &dec);
do
{
printf (%2d, (dec % 2));
dec = dec / 2;
} while (dec != 0);
printf (\n);
}

Dept. of CSE, IIT KGP

Example 4: Compute GCD of two numbers


#include <stdio.h>
main()
{
int A, B, temp;
scanf (%d %d, &A, &B);
if (A > B) { temp = A; A = B; B = temp; }
while ((B % A) != 0) {
temp = B % A;
B = A;
A = temp;
}
printf (The GCD is %d, A);
}
Initial:

12 ) 45 ( 3
36
9 ) 12 ( 1
9
3 ) 9 ( 3
9
0

A=12, B=45
Iteration 1: temp=9, B=12,A=9
Iteration 2: temp=3, B=9, A=3
B % A = 0  GCD is 3

Dept. of CSE, IIT KGP

More about scanf and printf

Dept. of CSE, IIT KGP

Entering input data :: scanf function


General syntax:
scanf (control string, arg1, arg2, , argn);
control string refers to a string typically containing data
types of the arguments to be read in;
the arguments arg1, arg2, represent pointers to data
items in memory.
Example: scanf (%d %f %c, &a, &average, &type);

The control string consists of individual groups of characters,


with one character group for each input data item.
% sign, followed by a conversion character.

Dept. of CSE, IIT KGP

Commonly used conversion characters:


c
d
f
s
X

single character
decimal integer
floating-point number
string terminated by null character
hexadecimal integer

We can also specify the maximum field-width of a data item, by


specifying a number indicating the field width before the
conversion character.
Example:

Dept. of CSE, IIT KGP

scanf (%3d %5d, &a, &b);

Writing output data :: printf function


General syntax:
printf (control string, arg1, arg2, , argn);
control string refers to a string containing formatting
information and data types of the arguments to be output;
the arguments arg1, arg2, represent the individual output
data items.

The conversion characters are the same as in scanf.

Dept. of CSE, IIT KGP

Examples:
printf (The average of %d and %d is %f, a, b, avg);
printf (Hello \nGood \nMorning \n);
printf (%3d %3d %5d, a, b, a*b+2);
printf (%7.2f %5.1f, x, y);

Many more options are available:


Read from the book.
Practice them in the lab.

String I/O:
Will be covered later in the class.

Dept. of CSE, IIT KGP

You might also like