Sei sulla pagina 1di 26

Computer Programming TA C162

Repetition in Programs
Iterative Statements in C
for
While
Do-while

Second Semester 2008-2009


1
Computer Programming TA C162

Problem1: Adding first N integers


Algorithm Steps:
1. Initialize sum=0, term=0 and count=1
2. Input N from user
3. If count >N then goto Step 5
4. term =count
sum = sum + term
count=count+1
goto step 3
5. Print sum
6. Stop
Note: Step 4 will be repeated until condition at Step 3 not satisfied.
Need iterative construct to implement the algorithm

Second Semester 2008-2009


2
Computer Programming TA C162

for Statement
Structure: init
for (init; test-condn; incr/decr)
{
loop_body;
}
F
test
Executes loop body as long as test evaluates
to TRUE (non-zero). T
1. Initialization
2. Conditional Testing
loop_body
3. Updation of loop control variable

updation
Either 1 or 2 or 3 or ALL of them can be optional

Loop body can have a single statement or a group of statements.


Second Semester 2008-2009
3
Computer Programming TA C162

Loop Construct for series problems


/* 1+2+3+4+……..N terms */
for(count=1; count<=N; count++){
term = count;
sum = sum + term;}

/* 1+3+5+7+…….N terms */
for(count=1; count<=N; count++){
term = 2*count-1;
sum = sum + term;}

/* -1+2-3+4-5+6-……N terms */
for(count=1; count<=N; count++){
term = pow(-1,count)*count;
sum = sum + term;}

Second Semester 2008-2009


4
Computer Programming TA C162

Single statement in Loop Body


sum = 0;
for (i = 1; i <= 10; i++)
sum + = i;
i = 1;
sum = 0;
for ( ; i <= 10; i++)
sum + = i;
i = 1;
sum = 0
for ( ; i < 10 ; )
sum + = i++;
Second Semester 2008-2009
5
Computer Programming TA C162

More Examples
i=1;
sum = 0;
for( ; ; )
sum + = i++;
How many times loop statement will be
executed?
for (i = 0,j = 7; i < j; i++, j--)
printf(“%d %d”,i,j);
Output???
for (i = 0,j = 7; i < j; i++, j--);
printf(“%d %d”,i,j);
Output???
Second Semester 2008-2009
6
Computer Programming TA C162

Block of statement in Loop Body


Option1:
for (i = 0, sum = 0; i < 10; i++)
{
sum = sum + i;
printf(“%d”, sum);
}
Option2:
i = 0; sum = 0;
for ( ; i<10;i++)
{ sum + = i;
printf(“%d”, sum);
} Second Semester 2008-2009
7
Computer Programming TA C162

Few more Examples


/* -- what is the output of this loop? -- */

for (i = 1, sum = 0; i <= 10; i++) sum + = i*i;


printf("%d ", sum);

/* -- what is the output? -- */


letter = 'a';
for (c = 0; c < 26; c++)
printf("%c ", letter+c);

/* -- what does this loop do? -- */


sum = 0;
for (i = 0; i < 10 && sum < 50; i++)
{
sum = sum + i;
printf(“%d %d\n”, i, sum);
}

Second Semester 2008-2009


8
Computer Programming TA C162

Problem2:Generating Fibonacci Numbers


Definition:
The sequence of Fibonacci numbers is defined recursively
f0 = 0, f1 = 1, fi+1 = fi + fi-1
for i = 1, 2, 3, ……….
So the sequence is like
0, 1, 1, 2, 3, 5, 8, 13, 21, ……
Let f1 contains the value of the current Fibonacci number and f0
contains the value of the previous Fibonacci number.
Algorithm:
1. Save the value of f1 in a temporary.
2. Add f0 and f1, and store the value in f1, the new number.
3. Store the value of temporary in f0.
4. Print, and then repeat (1,2,3) till the required number of Fibonacci numbers.
5. End

Second Semester 2008-2009


9
Computer Programming TA C162

Program to print first 10 Fibonacci


Numbers
#include<stdio.h>
#define STEP 10
int main() /* To generate Fibonacci Numbers/
{ int f0 = 0,f1 = 1, i, temp;
printf(“%d, %d, ”,f0,f1);
/* Loop */
for(i = 0; i<STEP; i++)/* counter control loop */
{ temp = f1;
f1 += f0;
f0 = temp;
printf(“%d, ”,f1);
}
return 0;
}
Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

Second Semester 2008-2009


10
Computer Programming TA C162

Exercise: Modified Fibonacci Problem


Rewrite the Fibonacci series program to print the series till the Fibonacci
number fnum. User will enter the value of fnum.
Assume that fnum is a valid Fibonacci number
Example: fnum = 377
Hint: Set the appropriate condition in for loop to print the series till
Fibonacci number fnum.
for(; f1<=fnum ;) /* general condition loop */
{ temp = f1;
f1 += f0;
f0 = temp;
printf(“%d, ”,f1);
}

Second Semester 2008-2009


11
Computer Programming TA C162

Exercise: Using for Loops


1. Write a c program to calculate Factorial of an integer number. Factorial of N is
defined as
N*(N-1)*(N-2)*(N-3)….1
for(i=N, fact=1; i>=2; i--) /* counter controlled loop */
fact=fact*i;
2. Write a c program to calculate ab, a and b are inputs to
the program.
for(i=0, value=1; i<b; i++) /* counter controlled loop */
value = value*a;

3. Write a c program to print even/odd values between 0 to


100.
Try your self!!!

Second Semester 2008-2009


12
Computer Programming TA C162

Nested Loops
The statement of for is again a for statement
Loop body can (of course) be another loop.

/* print a multiplication table */


Loop
for (m1 = 1; m1 <= 10; m1++)
Statement
{
for (m2 = 1; m2 <= 10; m2++)
{
printf(“%d\t”, m1*m2);
}

printf(“\n”);
}
Braces aren’t necessary,
but they make the code easier to read.
Second Semester 2008-2009
13
Computer Programming TA C162

Problem : Finding Prime Numbers


Print all prime numbers less than 100.
• A number is prime if its only divisors are 1 and itself.
• All non-prime numbers less than 100 will have a divisor
between 2 and 10.

Start

Initialize

Print primes

Stop
Second Semester 2008-2009
14
Computer Programming TA C162

Primes: 1st refinement


Initialize
num = 2
Start

F
Initialize num < 100

Print primes Print num


if prime

Stop num = num + 1

Second Semester 2008-2009


15
Computer Programming TA C162

Primes: 2nd refinement


Initialize
num = 2
Divide num by
2 through 10
F
num < 100
no F
T divisors?

Print num T
if prime
Print num
num = num + 1

Second Semester 2008-2009


16
Computer Programming TA C162

Primes: 3rd refinement


Initialize
Divide num by divisor = 2
2 through 10

F
divisor <= 10
no F
divisors?
T
T Clear flag if
num%divisor == 0
Print num
divisor =
divisor + 1

Second Semester 2008-2009


17
Computer Programming TA C162

Algorithm: Using a Flag Variable


To keep track of whether number was divisible, we use a "flag" variable.
• Set prime = TRUE, assuming that this number is prime.
• If any divisor divides number evenly, set prime = FALSE.
Once it is set to FALSE, it stays FALSE.
• After all divisors are checked, number is prime if the flag variable is
still TRUE.

Macros can be used for readability.


#define TRUE 1
#define FALSE 0

Second Semester 2008-2009


18
Computer Programming TA C162

Primes: Complete Code


#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main () {
int num, divisor, prime;
/* start with 2 and go up to 100 */
for (num = 2; num < 100; num ++ ) {
prime = TRUE; /* assume num is prime */

/* test whether divisible by 2 through 10 */


for (divisor = 2; divisor <= 10; divisor++)
if ((num % divisor) == 0) && (num != divisor))

prime = FALSE; /* not prime */

if (prime) /* if prime, print it */


printf("The number %d is prime\n", num);
}
return;
}
Second Semester 2008-2009
19
Computer Programming TA C162

While
while (test)
{ F
test
loop_body;
}
T
loop_body

Loop body can contain block of statements.


Executes loop body as long as test evaluates to TRUE (non-zero).

Note: Test is evaluated before executing loop body.


Second Semester 2008-2009
20
Computer Programming TA C162

While loop: Examples


x = 0;
while (x < 10) {
printf(“%d ”, x);
x = x + 1; }

scanf(“%d”,&num);
while(num!=-1){
sum = sum + num;
scanf(“%d”,&num);} /*sentinel control loop*/

Second Semester 2008-2009


21
Computer Programming TA C162

Infinite Loops
The following loop will never terminate: Why???
x = 0;
while (x < 10)
printf(“%d ”, x);

for(;;){
loop body;}

Inference:
Loop body does not change condition, so test never fails.
This is a common programming error that can be difficult to find.

Second Semester 2008-2009


22
Computer Programming TA C162

For vs. While


In general:

For loop is preferred for counter-based loops.


• Explicit counter variable
• Easy to see how counter is modified each loop

While loop is preferred for sentinel-based loops.


• Test checks for sentinel value.

Note:
Either kind of loop can be expressed as the other, so it’s really a matter of
style and readability.

Second Semester 2008-2009


23
Computer Programming TA C162

Do-While
do
{ loop_body
loop_body;
}while (test);

test
T
F

Loop body can contain block of statements.


Executes loop body as long as test evaluates to TRUE (non-zero).

Note: Test is evaluated after executing loop body.


Second Semester 2008-2009
24
Computer Programming TA C162

More Examples:
digit = 0;
while(digit <= 9)
printf(“%d\n”,digit++);

digit = 0;
do
printf(“%d\n”,digit++);
while(digit <= 9);

What is the output in both the cases?


Initially if digit value is 10 then what will happen?

Second Semester 2008-2009


25
Computer Programming TA C162

Loop Basics
1. Initialization of a condition variable.
2. Execution of the loop statements.
3. Test for a specified value of the condition variable.
4. Updating the condition variable.

Types of loops
• Counter controlled Loops
• Sentinel controlled Loops
• Input validation Loop
• General condition Loop

Second Semester 2008-2009


26

Potrebbero piacerti anche