Programming and Data Structures: Control Flow: Looping
Programming and Data Structures: Control Flow: Looping
Session 3
Control Flow: Looping
Condition Sentinel
Controlled Controlled
Counter Controlled
•1, 2, 3, 4, …
•…, 4, 3, 2, 1
Counter Controlled Loop
true
input n
sum ← sum + n
counter++
output sum
Condition-controlled Loop
input m
“WRONG INPUT”
true
m<0 || m>100
false
true
Condition-controlled m>49
loop with its condition “PASS”
being tested at the end false
“FAIL”
input m
false
m<0 || m>100
true
“WRONG INPUT”
input m
Condition-controlled true
loop with its m>49 “PASS”
condition being false
tested first
“FAIL”
Sentinel-Controlled Loop
•
Sum = 88
Average = 29.33
while loop
while (expression)
statement
F
expression
statement
while (i < n) { (loop body)
printf (“Line no : %d.\n”,i);
i++;
}
while Statement
COUNT = COUNT + 1
NO IS YES
COUNT > N? OUTPUT SUM
STOP
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);
Maximum of inputs
max = 0.0;
scanf(“%f”, &next);
while (next != -1.0) {
if (next > max)
max = next;
scanf(“%f”, &next);
}
printf (“The maximum number is %f\n”, max) ;
Printing a 2-D Figure
row=1;
#define ROWS 3 while (row <= ROWS) {
/* print a row of 5 *’s */
#define COLS 5 outer
... col=1;
loop
row=1; while (col <= COLS) {
while (row <= ROWS) { printf (“* “);
/* print a row of 5 *’s */ col++; inner
... } loop
row++; printf(“\n”);
} row++;
}
do-while statement
main () {
int digit=0; statement
do
printf(“%d\n”,digit++);
while (digit <= 9) ;
} F
expression
T
Example for do-while
do {
printf (“Please input month {1-12}”);
scanf (“%d”, &month);
} while ((month < 1) || (month > 12));
int main () {
char echo ;
do {
scanf (“%c”, &echo);
printf (“%c”,echo);
} while (echo != ‘\n’) ;
}
for Statement
expr1
(init) expr1;
while (expr2) {
statement
expr2 F
expr3;
(test)
}
T
statement
(body)
expr3
(update)
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;
}
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) ;
return 0; sum = 0;
} for (count=1; count<= N; count++)
sum = sum + count;
Print
***** #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
* #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
*****
****
***
**
*
Problem 4 : solution
Print
#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
• 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.
Specifying “Infinite Loop”
do {
statements
} while (1);
The break Statement
#include <stdio.h>
int main() {
int fact, i;
fact = 1; i = 1;
COUNT = COUNT + 1
NO IS YES
COUNT > N? OUTPUT SUM
STOP
Sum of first N natural numbers
int main () {
int N, count, sum;
START scanf (“%d”, &N) ;
sum = 0;
READ N count = 1;
for (count=1;count <= N;count++) {
SUM = 0 sum = sum + count;
COUNT = 1 printf (“Sum = %d\n”, sum) ;
return 0;
SUM = SUM + COUNT }
COUNT = COUNT + 1
NO IS YES
COUNT > N? OUTPUT SUM
STOP
Example 5: SUM = 1 + 2 + 3 + N
2 2 2 2
int main () {
int N, count, sum;
START scanf (“%d”, &N) ;
sum = 0;
READ N count = 1;
while (count <= N) {
SUM = 0
COUNT = 1 sum = sum + count*count;
count = count + 1;
SUM = SUM + COUNT * COUNT
}
printf (“Sum = %d\n”, sum) ;
COUNT = COUNT + 1 return 0;
}
NO IS YES
COUNT > N? OUTPUT SUM
STOP
Example: Computing Factorial
int main () {
START
int N, count, prod;
scanf (“%d”, &N) ;
READ N
prod = 1;
for (count=1;count <= N; count++) {
PROD = 1
COUNT = 1
prod =prod*count;
printf (“Factorial = %d\n”, prod) ;
return 0;
PROD = PROD * COUNT
}
COUNT = COUNT + 1
NO IS YES
COUNT > N? OUTPUT PROD
STOP
Example: Computing e series up to N terms
x
START 𝑥 𝑥 𝑥2 𝑥3
𝑒 =1+ + + + … ,− ∞ < 𝑥 <∞
1! 2 ! 3 !
READ X, N
TERM = 1
SUM = 0
COUNT = 1
COUNT = COUNT + 1
NO IS YES
COUNT > N? OUTPUT SUM
STOP
int main () {
float x, term, sum;
int n, count;
scanf (“%d”, &x) ;
scanf (“%d”, &n) ;
term = 1.0; sum = 0;
for (count = 1; count <= n; count++) {
sum += term;
term *= x/count;
}
printf (“%f\n”, sum) ;
}
Example 8: Computing e series up to 4 decimal places
x
START
READ X, N
TERM = 1
SUM = 0
COUNT = 1
COUNT = COUNT + 1
NO IS YES
TERM < 0.0001? OUTPUT SUM
STOP
int main () {
float x, term, sum;
int n, count;
scanf (“%d”, &x) ;
scanf (“%d”, &n) ;
term = 1.0; sum = 0;
for (count = 1; term >= 0.0001; count++) {
sum += term;
term *= x/count;
}
printf (“%f\n”, sum) ;
}
Example 1: Test if a number is prime or not
#include <stdio.h>
#include <stdlib.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);
return(0);
}
i++;
}
printf (“%d is a prime \n”, n);
}
More efficient??
#include <stdio.h>
main()
{
int n, i=2;
scanf (“%d”, &n); if(n == 2) { printf(“2 is prime\n”); return(0);}
while (i <= sqrt(n)) {
if (n % i == 0) {
printf (“%d is not a prime \n”, n);
retun(0);
}
i = i + 1;
}
printf (“%d is a prime \n”, n);
}
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);
}
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”);
}
Example 4: Compute GCD of two numbers
#include <stdio.h> 12 ) 45 ( 3
main()
{ 36
int A, B, temp;
9 ) 12 ( 1
scanf (%d %d”, &A, &B);
if (A > B) { temp = A; A = B; B = temp; } 9
while ((B % A) != 0) {
3 ) 9 ( 3
temp = B % A;
B = A; 9
A = temp;
} 0
printf (“The GCD is %d”, A);
} Initial: 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
More about scanf and printf
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.
– Commonly used conversion characters:
c single character
d decimal integer
f floating-point number
s string terminated by null character
X hexadecimal integer
– We can also specify the minimum field-width of a data item, by
specifying a number indicating the field width before the
conversion character.
Example: 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.
• 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);
symbol = ( i n t ) getchar();
f o r ( i = 0 ; i < 8 ; i++) {
i f ( s y m b o l < 128)
printf("0");
else {
printf("
1");
symbol
= symbol -
128;
}
symbol =
L e c t u r e s3 y()m b o l * 2 ;
G o o d P r a c t ices
One should include only simple statements inside the for loop
brackets. :
main()
{
int digit; int number;
printf("%d\n", number);
}
16
ESc Jan 13,
L e c t u r e 6 () /