CS 101 Lecture 3 PDF

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

Let Us C

1
CS 101
Computer Programming
Partha Pratim Paul
Lecturer, Dept. of ECE
Presidency University

2
Chapter 2

The Loop Control Structure

3
Introduction
Type of Flow Chart/Algorithm:

a) Simple Sequence/Sequential Instruction


b) Logical Sequence/Decision Control Instruction
c) Iteration/Loop

For first two types of programs, they were of limited nature, because
when executed, they always performed the same series of actions, in the
same way, exactly once. Almost always, if something is worth doing, it’s
worth doing more than once.

4
Iteration/Loop
The versatility of the computer lies in its ability to perform a set of
instructions repeatedly. This involves repeating some portion of the
program either a specified number of times or until a particular condition
is being satisfied.

There are three methods by way of which we can repeat a part of a


program. They are:

(a) Using a for statement


(b) Using a while statement
(c) Using a do-while statement

5
The while Loop
The while loop is is ideally suited for the such cases where you want to do
something a fixed number of times. Perhaps you want to calculate gross
salaries of ten different persons, or you want to convert temperatures from
centigrade to fahrenheit for 15 different cities.

The general form of while

initialise loop counter;


while (test loop counter using a condition)
{
do this;
and this;
increment loop counter;
}

6
The while Loop

7
The while Loop
Calculation of simple interest for 3 sets of p, n and r.

8
The while Loop
/* Calculation of simple interest for 3 sets of p, n and r */

#include<stdio.h>
int main( )
{
int p, n, count ;
float r, si ;
count = 1 ;

while ( count <= 3 )


{
printf ("\nEnter values of Principal, P = ") ;
scanf("%d", &p);

printf ("\nEnter values of Time, n = ") ;


scanf("%d", &n);

printf ("\nEnter values of Rate of Interest, r = ") ;


scanf("%f", &r);

si=(p*n*r)/100;
printf("\nSimple Interest = Tk %f", si);
count=count+1;
}
return 0;
}

9
The while Loop

10
The for Loop
The for allows us to specify three things about a loop in a single line

(a) Setting a loop counter to an initial value


(b) Testing the loop counter to determine whether its value has reached the number of
repetitions desired.
(c) Increasing the value of loop counter each time the program segment within the loop
has been executed.

The general form of for

for (initialise counter; test counter; increment counter)


{
do this;
and this;
and this;
}

11
The for Loop

12
The forLoop
Calculation of simple interest for 3 sets of p, n and r.

13
The for Loop
/* Calculation of simple interest for 3 sets of p, n and r */

#include<stdio.h>
main ( )
{
int p, n, count ;
float r, si ;
for ( count = 1 ; count <= 3 ; count = count + 1 )
{
printf ("\nEnter values of Principal, P = ") ;
scanf("%d", &p);

printf ("\nEnter values of Time, n = ") ;


scanf("%d", &n);

printf ("\nEnter values of Rate of Interest, r = ") ;


scanf("%f", &r);

si = p * n * r / 100 ;
printf ( "Simple Interest = Rs.%f\n", si ) ;
}
}

14
The for Loop
Let us now examine how the for statement gets executed:

− When the for statement is executed for the first time, the value of count is set to an initial value 1.

− Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body of the
loop is executed for the first time.

− Upon reaching the closing brace of for, control is sent back to the for statement, where the value of
count gets incremented by 1.

− Again the test is performed to check whether the new value of count exceeds 3.

− If the value of count is still within the range 1 to 3, the statements within the braces of for are
executed again.

− The body of the for loop continues to get executed till count doesn’t exceed the final value 3.

− When count reaches the value 4 the control exits from the loop and is transferred to the statement (if
any) immediately after the body of for.

15
while v/s for

If this program is compared with the one written using while,


it can be seen that the three steps—initialization, testing and
incrementation—required for the loop construct have now
been incorporated in the for statement.

16
The for Loop
//write down the program to print numbers from 1 to 10 in
different ways.

#include<stdio.h>
int main( )
{
int i ;
for ( i = 1 ; i <= 10 ; i = i + 1 )
printf ( "%d\n", i ) ;
}

17
Examples
//write down the program to print numbers from 1 to 10 using while loop

//write down the program to print numbers from 1 to 10 in different ways.

#include<stdio.h>
main( )
{
int i=1 ;
while(i<=10)
{
printf ( "%d\n", i ) ;
i=i+1;
}
return 0;
}

18
Examples
//write down the program to print numbers from 1 to 10 using
for loop

#include<stdio.h>
main( )
{
int i=1 ;
for ( i = 1 ; i <= 10 ; i = i + 1 )
printf ( "%d\n", i ) ;
}

19
Examples
//write down the program to print numbers from 10 to 1 using while loop

#include<stdio.h>
main( )
{
int i=10 ;
while (i >= 1 )
{
printf ( "Numbers are = %d\n", i ) ;
i=i-1;
}
return 0;
}

20
Examples
//write down the program to print numbers from 10 to 1 using
for loop

#include<stdio.h>
main( )
{
int i=10 ;
for ( i = 10 ; i >= 1 ; i = i - 1 )
printf ( "%d\n", i ) ;
return 0;
}

21
Nested Loop
When the value of r varies from 1 to 3, and value of c varies
from 5 to 7, find the summation of r and c using nested loop.

22
Nested Loop
When the value of r varies from 1 to 3, and value of c varies from 5
to 7, find the summation of r and c using nested loop.

#include<stdio.h>
int main( )
{ int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{ for ( c = 5 ; c <= 7 ; c++ ) /* inner loop */
{ sum = r + c ;
printf ( "r=%d c=%d sum = %d\n", r, c, sum ) ;
}
}
}

23
Nested Loop
• Two for loops can be nested
• Similarly two while loops can also be nested.
• a for loop can occur within a while loop, or a while within a
for.

24
The break statement
We often come across situations where we want to jump out of a loop instantly,
without waiting to get back to the conditional test. The keyword break allows us to
do this. When break is encountered inside any loop, control automatically passes
to the first statement after the loop.

A break is usually associated with an if.

25
The break statement
// Write a program to determine whether a number is prime or not.

Hints:

A prime number is one, which is divisible only by 1 or itself.

All we have to do to test whether a number is prime or not, is to divide it


successively by all numbers from 2 to one less than itself. If remainder of any of
these divisions is zero, the number is not a prime. If no division yields a zero then
the number is a prime number. Following program implements this logic.

26
The break statement
// Write a program to determine whether a number is prime or not.

#include<stdio.h>
int main( )

{
int num, i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
i=2;
while ( i <= num - 1 )
{
if ( num % i == 0 )
{
printf ( "Not a prime number" ) ;
break ;
}
i++ ;
}
if ( i == num )
printf ( "Prime number" ) ;
}

27
The break statement
In this program the moment num % i turns out to be zero, (i.e. num is exactly divisible by i)
the message “Not a prime number” is printed and the control breaks out of the while loop.
Why does the program require the if statement after the while loop at all? Well, there are
two ways the control could have reached outside the while loop:

It jumped out because the number proved to be not a prime.


The loop came to an end because the value of i became equal to num.

When the loop terminates in the second case, it means that there was no number between 2
to num - 1 that could exactly divide num. That is, num is indeed a prime. If this is true, the
program should print out the message “Prime number”.

The keyword break, breaks the control only from the while in which it is placed. Consider the
following program, which illustrates this fact.

28
Odd Loop by Do while
The loops that we have used so far executed the statements
within them a finite number of times. However, in real life
programming one comes across a situation when it is not
known beforehand how many times the statements in the
loop are to be executed.

29
Odd Loop by Do while
// Find the square of a number

#include<stdio.h>
int main( )
{
char another ;
int num ;
do
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;

printf ( "\nWant to enter another number y/n " ) ;


scanf ( " %c", &another ) ;
} while ( another == 'y' ) ;
}

30
Odd Loop by Do while
In this program the do-while loop would keep getting
executed till the user continues to answer y. The moment he
answers n, the loop terminates, since the condition ( another
== 'y' ) fails. Note that this loop ensures that statements
within it are executed at least once even if n is supplied first
time itself.

Though it is simpler to program such a requirement using a


do-while loop, the same functionality if required, can also be
accomplished using for and while loops

31
Assignment-1
• company insures its drivers in the following cases:
− If the driver is married.
− If the driver is unmarried, male & above 30 years of age.
− If the driver is unmarried, female & above 25 years of age.

In all other cases the driver is not insured. If the marital


status, sex and age of the driver are the inputs, write a
program to determine whether the driver is to be insured or
not.

32
Assignment-1 Solution
/* Insurance of driver - without using logical operators */

#include<stdio.h>
int main( )
{
char sex, ms ;
int age ;
printf ( "Enter age, sex, marital status " ) ;
scanf ( "%d %c %c", &age, &sex, &ms ) ;

if ( ms == 'M' )
printf ( "Driver is insured" ) ;
else
{
if ( sex == 'M' )
{
if ( age > 30 )
printf ( "Driver is insured" ) ;
else
printf ( "Driver is not insured" ) ;
}
else
{
if ( age > 25 )
printf ( "Driver is insured" ) ;
else
printf ( "Driver is not insured" ) ;
}
}
}

33
Assignment-2
Using all the topics we have covered in this semester, find the
following output

0 1 1 2 3 5 8 13 21 34 45 79 ………

34
Assignment-2 Solution
/* Fibonacci Series c language */
#include<stdio.h>

int main()
{
int n, first = 0, second = 1, next, c;

printf("Enter the number of terms\n");


scanf("%d",&n);

printf("First %d terms of Fibonacci series are :-\n",n);

for ( c = 0 ; c < n ; c++ )


{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}

return 0;
}

35

You might also like