You are on page 1of 25

CSE 1111

Computer Programming
while loop
While
• While Loop is just like for loop and can be used for similar
purpose.

• The syntax of while loop is different from for. And while loop
is faster than for.

• Inside while we only have to write the condition. Such as:


while(x<10)
While Loop

• Just like for, there is no ; in the line of while and there must
be second bracket to start new segment after the line of
while.

• Unlike for loop, the initialization must be done before the


start of the loop and increment is done inside the loop
Example:
• Suppose we have to print all the even integers from 1 to 200 by using
while loop:
Can You Tell what will happen if i=i+2 is not
written in the code above ?

Look at the code again and try to understand.


Example
• Suppose you want to print all the factors of an integer. It can be done
as shown below:
Example
• Suppose you want to print all the odd integers from 1 to 120. See the
code below:
Now Do the same thing using while loop.
Example
Break and continue
• If break is given inside a loop, then the program comes out of the
loop to the next line. It is used if we want to stop at some condition.

• If continue is given inside a loop, then the next loop will be executed
without completing the present loop.

• See the example below to understand better.


Example
• Suppose we want to print all the even integers from 1 to 100 except
38.
Example
• Suppose we want to print all the multiples of 5 but stop after 100
Problems
1. The input will be an integer. You will have to find out the factorial of
it.
2. The input will be an integer. Find out whether it is a prime number
or not.
3. Input will be an integer n. You will have to find out nth Fibonacci
number.
4. Input will be 2 integers n and r (n>=r). You will have to calculate npr
and ncr.
5. The input will be two integers. You will have to find the HCF
(Highest Common Factor) and LCM (Lowest Common Multiple) of
them.
Solve 1
Solve 2
Solve 3

• Do you know what is Fibonacci series ?


• The first two numbers of the series is 0 and 1.
• After that any number is the sum of the two previous numbers.
• So the series goes like this,
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ………… and so on
• So the 8th Fibonacci number is 13 and 10th is 34.
Solve 3
Solve 4
Solve 5
Write a C program to reverse a number. If 253 is the input, the output will be 352.
Write a C program to check whether a number is palindrome or not.
Write a C program to print all the prime numbers between a interval.

You might also like