Loops
In programmingoften requires repeated execution of a sequence of
operations. A loop is a basic programming construct that allows
repeated execution of a fragment of source code. Depending on the
type of the loop, the code in it is repeated a fixed number of times or
repeats until a given condition is true (exists).
Loops that never end are called infinite loops. Using an infinite loop is
rarely needed except in cases where somewhere in the body of the
loop a break operator is used to terminate its execution prematurely.
3.
Loop Constructs
A loopingprocess, in general, would include the following steps:
1. Setting and initialization of a counter.
2. Test for a specified condition for execution of the loop.
3. Incrementing the counter.
The test may be either to determine whether the loop has been
repeated the specified number of times or to determine whether a
particular condition has been met with.
4.
Why use Loops
Eg:You need to add from 0 to 10
Solution not using loop: int answer; answer = 0 + 1 + 2 + 3 + 4 + 5 + 6
+ 7 + 8 + 9 + 10;
The above solution not suitable for very large numbers (says from 0
to 10000) , what would be a faster way to solve?
5.
The C languageprovides 3 constructs for performing loop
operations. They are:
1. The for loop
2. The while loop
3. The do loop
6.
for loop
For-loops area slightly more complicated than while and do-while loops but
on the other hand they can solve more complicated tasks with less code.
Here is the scheme describing for-loops:
Since none ofthe listed elements of the for-loops is mandatory, we can skip
them all and we will get an infinite loop:
9.
For-Loop – Example
Hereis a complete example of a for-loop:
Int i;
for (i = 0; i <= 5; i++)
{
printf(“%d“, i);
}
The result of its execution is :
0 1 2 3 4 5
Int i;
for (i = 0; i <= 10; i++)
{
printf(“n %d“, i);
}
The result of its execution is :
0
1
2
3
.
.
.
10
10.
int i;
for (i= 0; i <= 10; i = i + 2)
{
printf(“n %d“,i)
}
0
2
4
6
8
10
11.
Here is another,more complicated example of a for-loop, in which we have two variables
Example 1:
Example 2:
int i, j;
for (i = 0, j = 10; i <= 10 && j >= 0; i++, j--) {
printf("i = %d, j = %dn", i, j);
}
int i, sum;
for (i = 1, sum = 1; i <= 25; i=i*2,sum+=i) {
printf("i = %d, sum = %dn", i, sum);
}
Calculating N^M –Example
int m,n;
printf("n = ");
scanf("%d",&n);
printf("m = ");
scanf("%d", &m);
long int result = 1;
int i;
for (i = 0; i < m; i++)
{
result *= n;
}
printf("n^m = %ld" , result);
Here is how the outcome of the program for n = 2
and m = 10 looks like:
14.
Calculating Factorial ofany given no
int i, number;
int fact = 1;
printf("Enter any Number: ");
scanf("%d", &number);
for (i = 1; i <= number; i++) {
fact = fact * i;
}
printf("Factorial of %d is: %dn", number, fact);
Enter any number: 4
Factorial of 4 is 24
15.
While Loops
One ofthe simplest and most commonly used loops is while.
Syntax of For Loop
In the above code example, condition is any expression that returns a Boolean result – true
or false. It determines how long the loop body will be repeated and is called the loop
condition.
16.
In thewhile loop, first of all the Boolean expression is calculated and if it is true the
sequence of operations in the body of the loop is executed. Then again the input
condition is checked and if it is true again the body of the loop is executed. All this is
repeated again and again until at some point the conditional expression returns value
false. At this point the loop stops and the program continues to the next line, immediately
after the body of the loop.
The body of the while loop may not be executed even once if in the beginning the
condition of the cycle returns false. If the condition of the cycle is never broken the loop
will be executed indefinitely.
17.
Difference between Forand While
For While
Initialization may be either in loop statement or outside
the loop.
Initialization is always outside the loop.
Once the statement(s) is executed then after increment
is done.
Increment can be done before or after the execution of
the statement(s).
It is normally used when the number of iterations is
known.
It is normally used when the number of iterations is
unknown.
Condition is a relational expression. Condition may be expression or non-zero value.
It is used when initialization and increment is simple. It is used for complex initialization.
Use
While loop is used in situations where we do not know how many times loop needs to be executed
beforehand.
For loop is used where we already know about the number of times loop needs to be executed.
Typically for a index used in iteration.
18.
Summing the Numbersfrom 1 to N
int n;
printf("n = ");
scanf("%d", &n);
int num = 1;
int sum = 1;
printf("n nums are: %d" , num);
while (num < n)
{
num++;
sum += num;
printf("n nums are: %d" , num);
}
printf("n %d", sum);
19.
Calculating Factorial –Example
int n;
int fact=1;
printf("input n = ");
scanf("%d", &n);
while (n > 0)
{
fact *= n;
n--;
}
printf("n! = %d" ,fact);
20.
Check If aNumber Is Prime
int n, i = 2, isPrime = 1; // assume prime (isPrime = 1)
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
isPrime = 0; // 0 and 1 are not prime
} else {
while (i <= n / 2) {
if (n % i == 0) { // divisible by i
isPrime = 0; // not prime
break; }
i++; } }
if (isPrime)
printf("%d is a prime number.n", n);
else
printf("%d is not a prime number.n", n);
21.
Do-While Loops
The do-whileloop is similar to the while loop, but it checks the condition after each
execution of its loop body. This type of loops is called loops with condition at the end (post-
test loop). A do-while loop looks like this:
do
{
executable code;
}
while (condition);
22.
Difference between Whileand Do
While
The main difference between a while loop and do while loop is that while loop check condition before
iteration of the loop. On the other hand, the do-while loop verifies the condition after the execution of the
statements inside the loop. So do while will execute at least 1 even if condition is false
int a=1;
while(a>10)
{
printf("%d",a);
a++;
}
Output
Nothing will print because
condition a>10 is not true
int a=1;
do
{
printf("%d",a);
a++;
}
while(a>10);
}Output
This will print 1 first add 1and then
check the condition which is false
then loop will break.
23.
Calculating Factorial –Example
int n;
int fact = 1;
printf("input n = ");
scanf("%d", &n);
do {
fact *= n;
n--;
} while (n > 0);
printf("n! = %dn", fact);
24.
Product in theRange [N…M] –
Example
int N, M;
long long product = 1; // use long long to handle large results
printf("Enter starting number (N): ");
scanf("%d", &N);
printf("Enter ending number (M): ");
scanf("%d", &M);
if (N > M) {
printf("Invalid range! N should be <= M.n");
return 0;
}
int i = N; // start from N
do {
product *= i;
i++;
} while (i <= M);
printf("Product of numbers from %d to %d is: %lld
n", N, M, product);
25.
Break and Continuein Loops
Break and continue is a very basic concept of any programming language.
Break (breaks the loop/switch)
Break statement is used to terminate the current loop iteration or terminate the
switch statement in which it appears
Break statement can be used in the following scenarios:
o for loop (For loop & nested for loop)
o While (while loop & nested while loop)
o Do while (do while loop and nested while loop)
o Switch case (Switch cases and nested switch cases)
26.
int i;
for (i= 0; i < 10; i++)
{
if (i == 4)
{
break;
}
printf("n %d",i);
}
Output
0
1
2
3
27.
Continue
C Continue
The continuestatement breaks one iteration (in the loop), if a specified condition occurs, and continues with
the next iteration in the loop.
This example skips the value of 4:
int i;
for ( i= 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
printf("n %d",i);
}
Output
0
1
2
3
5
6
7
8
9
28.
Break and Continuein While Loop
Break
int i = 0;
while (i < 10)
{
printf(“%d”,i);
i++;
if (i == 4)
{
break;
}
}
29.
Continue
int i =0;
while (i < 10)
{
if (i == 4)
{
i++;
continue;
}
printf(“%d”,i);
i++;
}