Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Decision making and looping

Introduction
• Suppose we want to calculate the sum of squares of all integers between 1 and 10.
• We can write the program using if statement:
-------------
-------------
Sum = 0; This program does the following things:
N =1; 1. Initializes the variable N.
Loop: 2. Computes the square of N and adds it to Sum.
Sum = Sum+ N*N; 3. Test the value of N to see whether it is equal to 10
if( N == 10) or not. If it is equal to 10, then the program prints
goto print;
the results.
else
{ 4. If n is less than 10, then it is incremented by one
N = N+1; and the control goes back to compute the sum
goto Loop; again.
}
print:
--------------
• These looping capabilities enable us to develop concise programs
containing repetitive processes without the use of goto statements.
• In looping, a sequence of statements are executed until some
conditions for termination of the loop are satisfied.
• A program loop therefore consists of two segments, one known as
the body of the loop and the other known as the control statement.
• The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the
loop.
• Depending on the position of the control statement in the loop, a
control structure may be classified either as the entry controlled loop
or as the exit controlled loop.
• A looping process, in general, would include the following four steps:
1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop.
3. Test for a specified value of the condition variable for execution of
the loop.
4. Incrementing or updating the control variable.
• The C language provides three loops:
1. The while loop
2. The do while loop
3. The for loop
The while loop
• The basic format of the while loop is:
while(test expression)
{
body of the loop;
}
• The while loop is an entry controlled loop statement.
• The test condition is evaluated and if the condition is true, then the
body of the loop is executed.
• After the execution of the body, the test condition is once again
evaluated and if it is true, the body is evaluated again.
• This process of repeated execution of the body continues until the
test condition finally becomes false and the control is transferred out
of the loop.
• On exit, the program continues with the statement immediately after
the body of the loop.
• // Print numbers from 1 to 5

#include <stdio.h>
int main() {
int i = 1; //Initialization

while (i <= 5) { // Testing


printf("%d\n", i);
++i; //Incrementing
}

return 0;
}
• Q1. Write a C program to find the sum of first n natural number using
while loop.
• Q2. Write a C program to evaluate y = xn when n is a non negative
integer using while loop.
• Q3. Write a C program to find the sum of digits of a number.
• Q4. Write a C program to find the factorial of a number.
• Q5. Write a C program to read the age of 100 persons and count the
number of persons in the age group 50 to 60.
The do while loop
• The while loop makes a test of condition before the loop is executed.
• Therefore, the body of the loop may not be executed at all if the
condition is not satisfied at the very first attempt.
• On some occasion it might be necessary to execute the body of the
loop before test is performed.
• Such situation is handled using do while loop.
• The general form of do while loop is:
do
{
body of the loop
}while(test expression);
• On reaching the do statement, the program proceeds to evaluate the
body of the loop first.
• At the end of the loop, the test condition in the while statement is
checked.
• If the condition is true, the program continues to evaluate the body of
the loop once again.
• This process continues as long as the condition is true.
• When the condition becomes false, the loop will be terminated and
the control goes to the statement that appears immediately after the
while statement.
• Since the test condition is evaluated at the bottom of the loop, the
do…while construct provides an exit controlled loop and therefore
the body of the loop executes atleast once.
• // Program to add numbers until the user enters zero

#include <stdio.h>
int main() {
double number, sum = 0;

// the body of the loop is executed at least once


do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}
• Q1. Write a C program to find the sum of first n natural number using
do while loop.
• Q2. Write a C program to evaluate y = xn when n is a non negative
integer using do while loop.
• Q3. Write a C program to find the sum of digits of a number.
• Q4. Write a C program to find the factorial of a number.
• Q5. Write a C program to read the age of 100 persons and count the
number of persons in the age group 50 to 60.
The for loop
• The for loop is another entry controlled loop that provides a more
concise loop control structure.
• The general form of for loop is
for(initialisation; test condition; increment)
{
body of the loop;
}
• The execution of the for loop is as follows:
• The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables.
• Next, the condition is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop does not execute and the flow of control
jumps to the next statement just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows to update any loop control
variables. This statement can be left blank, as long as a semicolon appears
after the condition.
• The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates.
#include <stdio.h>
int main () {
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
return 0;
}
• Q1. Write a C program to find the sum of first n natural number using
for loop.
• Q2. Write a C program to evaluate y = xn when n is a non negative
integer using for loop.
• Q3. Write a C program to find the sum of digits of a number.
• Q4. Write a C program to find the factorial of a number.
• Q5. Write a C program to read the age of 100 persons and count the
number of persons in the age group 50 to 60.
Additional features of for loop
The for loop in C has several capabilities that are not found in other loop
constructs.
1.More than one variable can be initialized at a time in the for statement.
Ex:– for(p=1, n=0; n<10;++n )
2. The increment section may also have more than one part.
Ex:–for(n=1, m=50; n<=m;n=n+1, m =m–1)
The multiple arguments in initialization section & in the increment section are
separated by commas.
3. The test–condition may have any compound relation & the testing need not be
limited only to the loop control variable.
Ex:–for(i=1; i<10&&sum<100;i++)
4.It is also possible to use expressions in the assignment statements of initialization
& increment sections.
Ex:– for(x=(m+n)/2; x>0;x=x/2)
5. Another unique aspect of for loop is that one or more sections can
be omitted, if necessary.
Ex:–m=5;
for(;m!=100;)
{
printf(“%d\n”,m);
m=m+5;
}
6. We can set uptime delay loops using the null statement as follows.
Ex:– for (i=1000;j>0;j=j–1);
This loop is executed 1000 times without producing any output. It
simply causes a time delay.
7. Infinite loop can be obtain from for loop as
for(;;){ }
Nesting of for Loops
• One for statement within another for statement.
• Example:
for(i=1;i<10;i++)
{
-----------------
-----------------
for(j=1;j!=5;j++)
{
--------------------
--------------------
}
------------------
------------------
}
#include <stdio.h>
int main () {
/* local variable definition */
int i, j;
for(i = 2; i<100; i++) {
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}
• Q1. Write a C program to print all the even numbers from 1 to 100.
• Q2. Write a C program to display the following pattern:

1 1 1 2 3 4 1
2 2 2 3 1 2 3 2 3
3 3 3 4 5 6 1 2 4 5 6
4 4 4 4 7 8 9 10 1 7 8 9 10
Q3. Design the pyramid as given below:

1
2 2 2
3 3 3 3 3
4 4 4 4 4 4 4
Selecting a loop
• Given a problem, the programmer’s first concern is to decide the type of loop
structure to be used.
• To choose one of the three loop supported by C, certain strategy can be used.
1. Analyse the problem and see whether it required a pre-test or post test loop.
2. If it requires a post test loop, then do while loop can be used
3. If it requires a pre test loop, then while or for can be used
4. Decide whether the loop termination requires counter based or sentinel based
5. Use for loop if counter based
6. Use while loop for sentinel based
7. Note that both the counter and sentinel controlled loops can be implemented
by all the three types of loops.
Jumps in loops
• Skipping some part in body of the loop
• C permits a jump from one statement to another within a loop as well
as a jump out of a loop
• Break
• Continue
• Goto
• Break
• A break statement is used to terminate the execution of the rest of the block
where it is present and takes the control out of the block to the next
statement.
• Another point to be taken into consideration is that the break statement
when used in nested loops only terminates the inner loop where it is used
and not any of the outer loops.
• Let’s implement an example to understand how break statement works in C
language.

#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 15; i++) {
printf("%d\n", i);
if (i == 10)
break;
}
return 0;
}
• In this program, we see that as soon as the condition if(i==10) becomes true the
control flows out of the loop and the program ends.
• Continue
• The continue jump statement like any other jump statement interrupts or
changes the flow of control during the execution of a program. Continue is
mostly used in loops.
• Rather than terminating the loop it stops the execution of the statements
underneath and takes control to the next iteration.
• Similar to a break statement, in the case of a nested loop, the continue passes
the control to the next iteration of the inner loop where it is present and not
to any of the outer loops.
• Let’s implement an example to understand how continue statement works in C language.
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i < 3; i++) {
for (j = 1; j < 5; j++) {
if (j == 2)
continue;
printf("%d\n", j);
}
}
return 0;
}
• In this program, we see that the printf() instruction for the condition j=2 is skipped each
time during the execution because of continue. We also see that only the condition j=2 gets
affected by the continue. The outer loop runs without any disruption in its iteration.
• Goto
• goto jump statement is used to transfer the flow of control to any part of the
program desired. The programmer needs to specify a label or identifier with
the goto statement in the following manner:
goto label;
• This label indicates the location in the program where the control jumps to.
• Let’s implement an example to understand how goto statement works in C
language.
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i < 5; i++) {
if (i == 2)
goto there;
printf("%d\n", i);
}
there:
printf("Two");
return 0;
}
• In this program, we see that when the control goes to the goto there;
statement when i becomes equal to 2 then the control next goes out of the
loop to the label(there: ) and prints Two.

You might also like