Lecture 5
Lecture 5
Lecture 5
E-mail: mohmoawad@mans.edu.eg
Lecture 5
2. Looping statement
Loops in programming are used to repeat a block of code until the specified
condition is met. A loop statement allows programmers to execute a statement or
group of statements multiple times without repetition of code.
2
1. “for-loop” statement
“for loop” is a repetition control structure that allows programmers to write a loop
that will be executed a specific number of times.
3
Syntax:
4
Example 1:
Write a program to print the even numbers from 1 to 100.
6
Syntax:
7
Example 2:
Write a program to print the following figure:
*
**
***
****
*****
******
*******
8
#include <stdio.h>
void main()
{
int i,j;
for(i=1;i<=7;++i)
{
for(j=1,j<=i;++j)
{
printf(“*”);
}
printf(“\n”);
}
}
9
c. Infinite “for - loop ” statement
• Instead of giving true boolean value for the condition in for loop, you can also give
a condition that always evaluates to true. For example, the condition 1 is always
true.
• No matter how many times the loop runs, the condition is always true and the for
loop will run forever.
#include <stdio.h>
void main()
{
for( ; ; )
{
}
}
10
2. “while-loop” statement
• Loops can execute a block of code as long as a
specified condition is reached.
• Loops are handy because they save time,
reduce errors, and they make code more
readable.
11
Syntax:
while (condition)
{
Example Output
// body of the loop #include <stdio.h> 1
} void main() 2
{ 3
int i=1; 4
while(i<=10) 5
{ 6
printf(“%d\n“,i); 7
i++; 8
} 9
} 10
12
Example3
Write a C program that calculates the factorial مضروبusing a while loop.
n!=n∗(n−1)∗(n−2)∗...∗1
13
#include <stdio.h>
void main()
{
int num, fact = 1;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
while (num > 0)
{
fact *= num;
num--;
}
printf("The factorial is : %d\n",fact);
}
14
a. Nested “while - loop ” statement
Writing while loop inside another
while loop is called nested while
loop, or you can say defining one
while loop inside another while loop
is called nested while loop
15
Syntax #include <stdio.h>
void main()
{
// Outer while loop
while (condition1)
{
// Code to be executed as long as condition1 is true
// Inner while loop
while (condition2)
{
// Code to be executed as long as condition2 is true
}
// Rest of the code within the outer while loop
}
}
16
Example 4
17
#include <stdio.h>
void main()
{
int i = 1, j=1;
while (i <= 5)
{
while (j <= 10)
{
printf("%d * %d = %d\n", i, j, i * j);
j++;
}
i++;
}
}
18