Nothing Special   »   [go: up one dir, main page]

0% found this document useful (0 votes)
2 views62 pages

Week 09 (Repetition) (1)

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 62

Week-09

PROGRAMMING FOR BUSINESS


(CS2016)

Muhammad Nadeem Ghouri


muhammad.nadeem@nu.edu.pk
Control Structures II
(REPETITION OR
ITERATION OR LOOPING)
CONCEPT OF LOOPING (REPETITION)
STRUCTURE
 One of the basic structured programming
concepts
 The real power of computers is in their
ability to repeat an operation or a series of
operations many times
 When action is repeated many times,
the flow is called a loop
WHY IS REPETITION NEEDED?
 Suppose we want to add five numbers (say to find their
average).
 From what you have learned so far, you could proceed
as follows.

scanf(%d %d %d %d %d,
&num1,&num2,&num3,&num4,&num5);

sum = num1+num2+num3+num4+num5;

average = sum/5;
SUPPOSE WE WANT TO ADD FIVE
NUMBERS (SAY TO FIND THEIR AVERAGE).
WITHOUT LOOP
SOLUTION (WITH LOOP):
Suppose we wanted to add and
average 100, or 1000, or more
numbers.
We would have to declare that many

variables, and list them again in scanf


statement, and perhaps, again in the
output statement.
SEQUENCE PROGRAM
 Suppose the numbers we want to add are the
following:
5 3 7 9 4
Consider the following statements
(1) sum = 0;
(2) scanf(%d,&num);
(3) sum = sum + num;
 Assume sum and num are variables of the type int.
 The first statement initializes sum to 0.
 Execute statements 2 and 3.
 Statement 2 stores 5 in num and statement 3
updates the value of sum by adding num to it.
 After statement 3 the value of sum is 5.
SEQUENCE PROGRAM

 To add 10 numbers, you can repeat statements 2


and 3 10 times.
 To add 100 numbers we can repeat statements 2 and
3 100 times.
 You would not have to declare any addition variables
as in the first code.
 There are three repetition or looping structures in C
that lets us repeat statements over and over until
certain conditions are met.
 while Looping Structure

 for Looping Structure

 do…while Looping Structure


SUPPOSE THE NUMBERS WE WANT TO ADD ARE THE
FOLLOWING:

5 3 7 9 4
THERE ARE MAINLY TWO TYPES OF
LOOPS IN C PROGRAMMING:

 Entry Controlled loops: In Entry controlled


loops the test condition is checked before
entering the main body of the loop. For
Loop and While Loop is Entry-controlled
loops.

 Exit Controlled loops: In Exit controlled


loops the test condition is evaluated at the
end of the loop body. The loop body will
execute at least once, irrespective of whether
the condition is true or false. do-while
Loop is Exit Controlled loop.
Loop Type Description

for loop first Initializes, then condition


check, then executes the body and
at last, the update is done.

while loop first Initializes, then condition


checks, and then executes the
body, and updating can be inside
the body.

do-while loop do-while first executes the body


and then the condition check is
done.
WHAT IS A LOOP
 Loops repeat a statement, a
block, a function or a set of
a=0 any combination of these
construct a number of times

print a  The figure on the left


demonstrates the repetition
process of the statement printf
and a=a+1.
a=a+1
 The question about the figure
is that when this loop will
0 1 2 3 4 5 6 7 ……..? stop?
 The loop will never stop and
will infinitely repeat these
statements until the program
is forced to quit by the user
WHAT IS A LOOP
 A loop must be controlled by a
condition or an event in order
a=0 to limit the number of
iterations and prevent infinite
loops from occurring
print a  The figure to the left shows a
loop controlled by a condition.
a=a+1  If the condition is true the loop
will go on repeating the
statements otherwise it breaks
True the cycle and continues with
Cond
the rest of the program
false  The condition can be any
logical or relational expression
in C language
SELECTION STATEMENTS
REPETITION STATEMENT
THE WHILE LOOPING (REPETITION)
STRUCTURE
 The general form of the while statement is
while(expression)
while(expression)
statement
statement

 The statement can be either a simple or compound


statement.
 The statement is called the body of the loop.
 The expression provides an entry condition.
WHILE LOOPS
while ( expression )
 The “loop body” can be either
{ a simple or compound
loop body statement.
}  The “expression” provides an

entry condition.
while ( a>b )  A while loop checks the
{
expression before entering
}
the loop body
while ( a>b && c<=78 )  The expression is evaluated

{ first (must produce true or


} false) then if the value is true
(none zero) the loop will
while ( 1 ) continue otherwise it exits the
{ This is an infinite loop body proceeding with the
} loop if 1 is true rest of the program.
WHILE LOOPS: EXAMPLES
start
(1)
int main()
count = 0
{
int count = 0;

while(count <= 5)
False
count <= 5? {
count = count + 1;
True
printf(“%d ”,count);
count = count + 1 }
}
output count

11 22 33 44 55 66

end
WHILE LOOPS: EXAMPLES
start (2)
int main()
input A
{
input B
int count, A, B;
scanf(“%d”,&A);
count = A scanf(“%d”,&B);
count = A;

False
while(count <= B)
count <= B? {
True count = count + 1;
count = count + 1 printf(“%d ”,count);
}
output count }

33 88

44 55 66 77 88 99
end
What is the output when:
A = 12 and B = 21
THE DO…WHILE LOOPING
(REPETITION) STRUCTURE
 The general form of a do...while statement is:

do
do
statement
statement
while(expression);
while(expression);

 The statement executes first,


and then the expression is
evaluated.
 If the expression evaluates to
true, the statement executes
again.
 As long as the expression in a
do...while statement is true,
the statement executes.
DO..WHILE LOOPS
do  A do...while loop will allow
{ the execution of the body
loop body
once then checks the
expression, if the expression
} while ( expression ); is true then it will repeat
again otherwise it exits the
do loop.
{
 The expression is evaluated
first (must produce true or
} while ( a>b ); false) then if the value is
true (none zero) the loop
do will continue otherwise it
exits the loop body
{ proceeding with the rest of
} while ( a>b && c<=7 ); the program.
This is an infinite
 To avoid an infinite loop,
do loop if 1 is true
make sure that the loop
body contains a statement
{
that ultimately makes the
} While ( 1 ); expression false and
assures that it exits.
WHILE LOOP AND DO..WHILE LOOP
 Loops in C language fall
a=0 a=0 under two major
categories, these are
 while , For loop
false
print a The while loop, has
Cond the condition checked
before entering the
True
a=a+1 loop
print a  do while loop
This type of loops will
True
Cond enter the loop body
a=a+1 at least once then
false checks the condition
 The two figures on the left
while do while show those two types
DO…WHILE LOOPING STRUCTURE
 Because the while and for loop has an entry
condition, it may never activate, whereas, the
do...while loop, which has an exit condition, always
goes through at least once.
i = 11; i = 11;
while(i <= 10) do
{ {
printf(“%d “,i); printf(“%d “,i);
i++; i++;
} }
while(i <= 10);

In the while loop, produces the do...while loop, outputs


nothing. the number 11.
DO WHILE EXAMPLE(3)
start int main()
{
count = 0
int count = 0;

do
{
count = count + 1;
count = count + 1 printf(“%d ”,count);
} while(count <= 5);
output count }

True
count <= 5? 11 22 33 44 55 66
False
end
start
DO WHILE EXAMPLE(4)
int main()
{
input A
int count, A, B;
scanf(“%d”,&A);
input B
scanf(“%d”,&B);
count = A;
count = A

do
{
output count count = count + 1;
printf(“%d ”,count);
count = count + 1 } while(count <= B)
}
True
count <= B?
33 88
False
end 44 55 66 77 88 99
What is the output when:
A = 11 and B = 33
THE FOR LOOPING (REPETITION)
STRUCTURE
 The general form of the for statement is

for(initial
for(initial statement;
statement; loop
loop condition;
condition; update
update statement)
statement)
statement
statement

 The initial statement,


loop condition and update
statement (called for loop
control statements) that are
enclosed with in the
parentheses controls the body
(the statement) of the for
statement.
FOR LOOPING STRUCTURE
 The for loop executes as follows:
1. The initial statement executes.
2. The loop condition is evaluated. If the loop
condition evaluates to true
1. Execute the for loop statement.
2. Execute the update statement.
3. Repeat Step 2 until the loop condition evaluates
to false.

 The initial statement


 usually initializes a variable
 is the first statement to be executed and is
executed only once.
THE FOR LOOPING (REPETITION)
STRUCTURE
 Problem: print numbers 1 through 10 on standard output
 Solution using for statement

11 22 33 44 55 66 77 88 99 10
10
int counter;

for (counter = 1; counter <= 10; counter++)


printf(“%d ”,counter);
control limiting value of
variable control variable

for (counter = 1; counter <= 10; counter++)

for initial value of updating


keyword control variable control variable
FOR LOOPING STRUCTURE
 The statement of a for loop may be a simple or a compound
statement.simple compound
for(i = 1; i <= 5; i++) for(i = 1; i <= 5; i++)
printf("Output of stars.\n“); {
printf("*“); printf("Output of stars.\n“);
printf("*\n“);
}

Output
Output aa line
line of
of stars.
stars. Output
Output aa line
line of
of stars.
stars.
Output
Output aa line
line of
of stars.
stars. **
Output a line of stars. Output
Output a line of stars. Output aa line
line of
of stars.
stars.
Output
Output aa line
line of
of stars.
stars. **
Output a line of stars. Output
Output a line of stars. Output aa line
line of
of stars.
stars.
** **
Output
Output aa line
line of
of stars.
stars.
for(i = 1; i <= 5; i++); **
printf("*“); Output
Output aa line
line of
of stars.
stars.
**
**
FOR LOOPING STRUCTURE
 All three statements can be omit—initial statement,
loop condition, and update statement.
HelloHello Infinite output;
for(;;) Hello
Hello press break to
printf("Hello\n“); stop the program
..
running
..

 Count backward
for(i = 10; i >= 1; i--)
printf(“%d “,i); 10
10 99 88 77 66 55 44 33 22 11

 Increment (or decrement) the loop control variable


for(i = 1; i <= 20; i = i + 2)
printf(“%d “,i); 1 3 5 7 9 11 13 15 17 19
1 3 5 7 9 11 13 15 17 19
Example
Example55

FOR LOOPING STRUCTURE


// reads five numbers and find their sum and average
#include <stdio.h>

int main()
{
int i, newNum, sum, average;
55 44 33 22 11
sum = 0; The
The sum
sum isis 15
15
for(i = 1; i <= 5; i++)
The
The average
average is is 33
{
scanf(“%d”,&newNum);
sum = sum + newNum;
}
average = sum / 5;
printf("The sum is %d\n”,sum);
printf(“The average is %d”,average);
return 0;
}
Scenario 1: Printing Multiples of a
Number
Problem: You are given a number N. Write a C program that uses a
for loop
to print the first 10 multiples of the number.

planation:

e program asks the user to input a number N.


e for loop runs from i = 1 to i = 10 and prints the multiplication result for each i.
Scenario 2: Sum of First N Even
Numbers
Problem: Write a C program that calculates the sum of the first N
even numbers
using a for loop. The value of N is input by the user.

Explanation:

The program first takes the input N, which defines how many even numbers to sum.
The for loop runs from i = 1 to N, and in each iteration, it adds the i-th even number
(calculated as 2 * i) to the sum. Finally, it prints the total sum.
Scenario 3: Calculating Factorial of a
Number
Problem: Write a C program to calculate the factorial of a given number N using
a for loop. The factorial of a number N is the product of all positive integers less
than or equal to N.

Explanation:

The program prompts the


user to input a number N.
The for loop multiplies all
integers from 1 to N to
compute the factorial.
It handles the special case
where N = 0, as 0! = 1.
BREAK STATEMENT
 A break and continue statement alters the flow of control.
 The break statement, when executed in a switch structure,
provides an immediate exit from the switch structure.
 You can use the break statement in while, for, and
do...while loops.
 When the break statement executes in a repetition
structure, it immediately exits from these structures.
 The break statement is typically used for two purposes:
 To exit early from a loop
 To skip the remainder of the switch structure
 After the break statement executes, the program continues
to execute with the first statement after the structure.
LOOPS AND BREAK KEYWORD
int i;
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
printf(“%d\t”,i);
}
EXAMPLE-01
EXAMPLE-02
CONTINUE STATEMENT
 The continue statement is used in while, for, and
do-while structures.
 When the continue statement is executed in a
loop, it skips the remaining statements in the loop
and proceeds with the next iteration of the loop.
 In a while and do-while structure, the expression
(that is, the loop-continue test) is evaluated
immediately after the continue statement.
 In a for structure, the update statement is
executed after the continue statement, and then
the loop condition (that is, the loop-continue
test) executes.
CONTINUE STATEMENT
EXAMPLE-01
NESTED LOOPING
 A loop (e.g., while, do-while, for) can be
placed within the body of another loop.
 When one loop is nested within another,

several iterations of the inner loop are


performed for every single iteration of the
outer loop.
 The inner and outer loops need not to be

generated by the same type of control


structures.
NESTED FOR LOOP (EXAMPLE 1)

for ( expr1a; expr2a; expr3a )


{
:
for ( expr1b; expr2b; expr3b
)
{
:
}
:
}
EXECUTION FLOW:

 The outer loop starts with i = 1. The inner loop


runs once (because j <= 1), printing 1 *,
followed by a newline (\n).

 The outer loop increments i to 2. The inner loop


now runs twice (because j <= 2), printing 2 *,
followed by a newline.

 This process continues until i = 5, at which point


the inner loop prints 5 *, and the outer loop
stops as the condition i <= 5 is no longer true.
EXAMPLE-02
OUTPUT

Explanation:
Outer Loop (for i): Controls the number of rows and runs n times.
Inner Loop (for j): Controls the number of columns and also runs n times
in each row.
Each iteration of the inner loop prints a # symbol. After printing n
symbols, the program moves to the next line (\n).
EXAMPLE-03
OUTPUT
NESTED WHILE (EXAMPLE 7)
#include<stdio.h>
int main()
while (expr1) {
int r,c,s;

r=1;
{ while(r<=5) /*outer loop*/
: {
while (expr2) c=1;
while(c<=2) /*inner loop*/
{ {
: s=r+c;
Update expr2; printf("r=%d c=%d sum=%d\n",r,c,s);
c++;
}
}
: printf("\n");
update expr1; r++;
} }
}
NESTED DO WHILE (EXAMPLE 8)
#include<stdio.h>
do int main()
{
int i=1,j=0,sum;
{ do {
: sum=0;
do do{
sum=sum+j;
{ printf("%d",j);
: j++;
Update expr; if(j<=i)
{
} printf("+");
while(expr); }
: }while(j<=i);
update expr; printf("=%d\n",sum);
j=1;
} i++;
while(expr); }while(i<=10);
}
EXERCISES
1. Find the persistence of a number. It is the
number, if times you can multiple the digits
(iteratively) before you get a single digit
number.
2. Given two numbers multiply them using the
following method. Successively divide the
smaller number by 2 (ignore any remainder)
until the quotient is 1 and multiple the
larger number by 2. Add to a total only
those multiples of the larger which
correspond to an odd quotient of the
smaller.
3. Find the digital root of a number (repeatedly
find the sum of the digits until you get a
number 1 to 9.
285:
2+8+5=15
1+5=6
4. A ball is dropped from a height of x. It
decreases 2/3 on height x at each bounce.
How many bounces the ball will have until
height is less than y? (Use while loop and if
condition to break, when height x becomes
less than y).
5. Write a C program that receives the total
number of integers (N). Then, the program
will ask for N real numbers. By applying for
loop, your program should find and display
the largest and the lowest of the numbers.
Give a proper message for invalid user input
(Don’t use arrays).

You might also like