While Loop
Session No.: 12
Course Name: Problem Solving and Computer Programming
Course Code: E1PA103B
Instructor Name: Dr. Alok Singh Chauhan
Duration: 50 minutes
Date of Conduction of Class: 07-10-2025
Galgotias University 1
Recap
- Switch allows multi-way branching
- Syntax: switch(expression){ case value: ... }
- Example: Menu-driven calculator
- Limitation: Only works with discrete values
Galgotias University 2
Opening Question
• Scenario
Suppose we have to print the first 10 natural
numbers(1,2,3…10)
• Question for Students:
How can we print this?
• If we have to print the first N natural numbers,
where N is given by the user. How can we solve it?
Galgotias University 3
Learning Objective
At the end of this session students will be able
to
Understand the structure
and working of the while
loop in C.
Apply while loops to
solve real-world
repetitive problems.
Galgotias University 4
1. Why Loops?
Session 2. Structure
Outline of while
3. Activity 1
4. Summary
Galgotias University 5
Why do we use
loops?
• If we write the solution of an open question
without a loop, we have to write 10 times the
printf() function.
• Loops help execute code repeatedly without writing
it multiple times.
Galgotias University 6
courtesy – geeks for geeks
While Syntax
Syntax:
while (condition) {
// code block
}
• Condition is checked
before executing the
loop body.
Galgotias University 7
Example Program
#include <stdio.h>
int main(){
int i=1;
while(i<=5){
printf("%d\n", i);
i++;
}
return 0;
}
Galgotias University 8
Common Mistakes
- Infinite loops if the condition is never false
- Forgetting to update the loop variable
- Wrong condition placement
Galgotias University 9
Learning
Activity 1
GSCALE full form and date 10
Learning Activity 1
Problem Based Learning
• Problem: Write a program using a
while loop to calculate the sum of
the digits of a number entered by the
user
Galgotias University 11
Solution of Learning Activity
1 #include <stdio.h> while(num>0){
int main(){ digit=num%10;
sum+=digit;
int num, sum=0, num/=10;
digit; }
printf("Enter a return 0;
number: "); }
scanf("%d", &num);
Galgotias University 12
Summary
•- Loops avoid code repetition
•- While loop is entry-controlled
•- Use when iterations are unknown in advance
•- Avoid infinite loops
Galgotias University 13
Ensure attainment of LOs in
alignment to the learning
activities: outcomes (1-2)
Understand the structure
and working of the while
loop in C.
Apply while loops to
solve real-world
repetitive problems.
Galgotias University 14
Post session activities
•1. Print Fibonacci series up to n
terms using while loop
•2. Reverse a number
•3. Check palindrome number
Galgotias University 15
Next lesson
• Open Ended Question
• How can we design a loop that runs when we already know
the number of iterations in advance? (Leads to For Loop)
• Next Lecture: For Loop
Galgotias University 16
Review and
Reflection from
students
Galgotias University 17