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

CS 114-Fundamentals of Programming

Loops in C language
Asma Majeed

1
Introduction to Loops
Agenda
To be followed in today’s lecture
While

Do while

For

Nested Loops
Fundamentals of computer programming 2
loop or iteration
• In a program, the repetition structure directs the computer to repeat a
set of instructions until some conditions are met
• Once the condition is met, the repetition should stop
• Repetition is also referred to as loop or iteration
• Loops are used in programming to repeat a specific block until some
end condition is met. There are three loops in C programming:
• while loop (pre-test)

• do...while loop (post-test)

• for loop (pre-test)

Fundamentals of computer programming 3


Looping Statements

• Looping statements allow the program to repeat a section of code


• any specific number of times
• Or
• until some condition occurs

• For example, loops are used to count the number of words in a document, or
• to count the number of accounts that have past-due balances.

Fundamentals of computer programming 4


Two types of Repetition
1. Counter-controlled repetition
is sometimes called definite repetition because we know in advance exactly
how many times the loop will be executed

2. Sentinel-controlled repetition
is sometimes called indefinite repetition because it’s not known in advance
how many times the loop will be executed.

Fundamentals of computer programming 5


while Statement
• The general form of a while statement is:
while (condition)
{
statement;
}
• The program will repeatedly execute the statement inside the while until the
condition becomes false (0).
• If the condition is initially false, the statement will not be executed

Fundamentals of computer programming 6


Example of a while statement:

while (i < n) /* controlling expression */

{
i = i * 2; /* loop body */

}
• When a while statement is executed, the controlling expression is
evaluated first.

• If its value is nonzero (true), the loop body is executed and the
expression is tested again.

• The process continues until the controlling expression eventually has the
value zero
Fundamentals of computer programming 7
Flowchart of while loop

Fundamentals of computer programming 8


Are you familiar with this sequence??

1 1 2 3 5 8

Fundamentals of computer programming 9


Fibonacci sequence
1
1
2=1+1
3=1+2
5=2+3
..
..
..
Fundamentals of computer programming 10
Fibonacci sequence

• In general

• In C style

• In C code, the equation is expressed as:


next_number = current_number + old_number;
• We want to loop until our current term is 100 or larger. The while loop
while (current_number < 100)

Fundamentals of computer programming 11


Fundamentals of computer programming 12
Exercises cont.…
• Print a table of squares. E.g
Enter number of entries in table: 5
1 1
2 4
3 9
4 16
5 25

Fundamentals of computer programming 14


Exercises cont.…
• Print all the powers of number 2 till the value is 64

Fundamentals of computer programming 15


Exercises cont.…
• Find next x multiples of a given number. X should also be
user input.

Fundamentals of computer programming 16


break Statement
• Loops can be exited at any point through the use of a break statement.

• Suppose we want to add a series of numbers, but we don’t know how


many numbers are to be added together.

• We need some way of letting the program know that we have reached
the end of our list.

Fundamentals of computer programming 17


Infinite loop

• Note that the while statement begins with:


while (1) {
}
• The program will loop forever because the while will exit only when the
expression 1 is 0.
• The only way to exit this loop is through a break statement.

Fundamentals of computer programming 18


Break in while loop

Fundamentals of computer programming 19


Example: break in while loop
int total;
int item; total+=item;
printf(“total%d \n”,total);
int main(){ }
total=0; printf(“final total %d \n”,total);
while(1){ return 0;
printf(“Enter 1 to add or 0 to stop\n”); }
scanf(“%d”,item); }

If (item==0)
break;

Fundamentals of computer programming 20


continue Statement
• The continue statement is very similar to the break statement

• except that instead of terminating the loop

• continue starts re-executing the body of the loop from the top

• Lets modify the previous program to total only numbers larger than 0

Fundamentals of computer programming 21


Fundamentals of computer programming 22
int total; if (item<0){
int item; ++minus_items;
int minus_items; continue;
int main(){ }
total=0; minus_items=0; total+=item;
while(1){ printf(“total%d \n”,total);
printf(“Enter 1 to add or 0 to }
stop\n”); printf(“final total %d \n”,total);
scanf(“%d”,item);
printf(“with %d –ve items
omitted”,minus_items);
If (item==0) return 0;
break; }

Fundamentals of computer programming 23


Repetition Structure
do - while
do while

CS 110 Fundamentals of Computer Programming

Fundamentals of computer programming 24


The do-while loop
• Similar to while loop
• Must execute at least one time (test is at the bottom)
• Has format:
do {

} while (condition) ; // A semi colon is placed after while statement in do-while

Fundamentals of computer programming 25


• When a do statement is executed, the loop body is executed first, then
the controlling expression is evaluated.

• If the value of the expression is nonzero, the loop body is executed again
and then the expression is evaluated once more.

• The do statement is often indistinguishable from the while statement.

• The only difference is that the body of a do statement is always executed


at least once.

Fundamentals of computer programming 26


Fundamentals of computer programming 27
Simple Rules
• while and do-while good for when you don’t know how many times you
want to repeat the loop

• All loops must finish, or they become infinite loops

• All loops must have a test to continue, or they become infinite loops

Fundamentals of computer programming 28


Simple Rules
• It’s a good idea to use braces in all do statements, whether or not they’re
needed, because a do statement without braces can easily be mistaken
for a while statement:
do
printf("T minus %d and counting\n", i--);
while (i > 0);
• A careless reader might think that the word while was the beginning of a
while statement.

Fundamentals of computer programming 29


Example
• The numdigits.c program calculates the number of digits in an integer
entered by the user:
Enter a nonnegative integer: 60
The number has 2 digit(s).
• The program will divide the user’s input by 10 repeatedly until it
becomes 0; the number of divisions performed is the number of digits.
• Writing this loop as a do statement is better than using a while
statement, because every integer—even 0—has at least one digit

Fundamentals of computer programming 30


Exercise:
• Given an amount of money (less than $1.00), compute the number of quarters, dimes,
nickels, and pennies needed.
• A leap year is any year divisible by 4, unless the year is divisible by 100, but not 400.
Write a program to tell if a year is a leap year

Fundamentals of computer programming 31


Exercise:
• Finding Average grades of multiple classes
–We would like a program to compute the grade of each of a set of
classes.
–For each class, take marks inputs of few students and calculate the
class average.
–Need to be careful that the average grade for each class is computed
independently of other classes!
–After computing the average for a class, need to see if there is another
class.
• Draw a flowchart and write the program of the above exercise

Fundamentals of computer programming 32


Repetition Structure
For Loop

CS 110 Fundamentals of Computer Programming

Fundamentals of computer programming 33


For Syntax
• The syntax of for loop is:
for (expr1; expr2; expr3)
{

// codes

}
expr1= initializationStatement;
expr2= testExpression;
expr3= updateStatement;

Fundamentals of computer programming 34


How for loop works
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test
expression is false (0), for loop is terminated. But if the
test expression is true (nonzero), codes inside the body
of for loop is executed and the update expression is
updated.
• This process repeats until the test expression is false.
• The for loop is commonly used when the number of
iterations is known.
Fundamentals of computer programming 35
for loop Flowchart

Fundamentals of computer programming 36


Example
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num); // for loop terminates when num is less than count

for(count = 1; count <= num; ++count)


{
sum += count;
}
printf("Sum = %d", sum); return 0;
}
Fundamentals of computer programming 37
Example
• factorial of n (n!) = 1*2*3*4....n

Fundamentals of computer programming 38


Example
#include <stdio.h>
int main() {
int n, i;
unsigned long long factorial = 1;
printf("Enter an integer: ");
scanf("%d",&n); // show error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for(i=1; i<=n; ++i) {
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}
return 0;
}
Fundamentals of computer programming 39
While and for
• The for statement is closely related to the while
statement.
• Except in a few rare cases, a for loop can always be
replaced by an equivalent while loop:
expr1;
while ( expr2 ) {
statement
expr3;
}

Fundamentals of computer programming 40


The for Statement
• The for statement is usually the best choice for loops
that “count up” (increment a variable) or “count down”
(decrement a variable).

• A for statement that counts up or down a total of n times


will usually have one of the following forms:

Fundamentals of computer programming 41


For loops
• Counting up from 0 to n–1:
• for (i = 0; i < n; i++) …
• Counting up from 1 to n:
• for (i = 1; i <= n; i++) …
• Counting down from n–1 to 0:
• for (i = n - 1; i >= 0; i--) …
• Counting down from n to 1:
• for (i = n; i > 0; i--) …

Fundamentals of computer programming 42


for Statement Idioms
• Common “for” statement errors:
• Using < instead of > (or vice versa) in the controlling
expression. “Counting up” loops should use the < or <=
operator. “Counting down” loops should use > or >=.
• Using == in the controlling expression instead of <, <=, >,
or >=.
• “Off-by-one” errors such as writing the controlling
expression as i <= n instead of i < n.

Fundamentals of computer programming 43


Various forms of For loop
for (num=10; num<20; num=num+1)
• Here instead of num++, num=num+1 is used which is same as num++.

Fundamentals of computer programming 44


Various forms of For loop

int num=10;
for (;num<20;num++)
Initialization part can be skipped from loop as shown below, the counter
variable is declared before the loop.
Note: Even though we can skip initialization part but semicolon (;) before condition is must, without which you will
get compilation error.

Fundamentals of computer programming 45


Various forms of For loop
for (num=10; num<20; )
{
//Statements
num++;
}

you can also skip the increment part as we did below. In this case semicolon (;) is must
after condition logic. In this case the increment or decrement part is done inside the
loop.

Fundamentals of computer programming 46


Various forms of For loop
int num=10;
for (;num<20;)
{
//Statements
num++;
}
This is also possible. The counter variable is initialized before the loop and incremented
inside the loop.

Fundamentals of computer programming 47


Multiple initialization inside for Loop in C

for (i=1,j=1; i<10 && j<10; i++, j++)


What’s the difference between above for loop and a simple for loop?

Fundamentals of computer programming 48


Infinite loop
We can also use infinite for loops like
for(;;)
which will never terminate except….?

Fundamentals of computer programming 49


Example: Break statement in for loop
int main( void )
{
int x; /* counter */
for ( x = 1; x <= 10; x++ )
{
if ( x == 5 )
{
break;
} /* end if */
printf( "%d ", x ); /* display value of x */
} /* end for */
printf( "\n Broke out of loop at x == %d \n", x );
return 0;
}
Fundamentals of computer programming 50
Example: continue statement in for loop

int main( void ){ printf( "%d ", x ); /* display


value of x */
int x; /* counter */ } /* end for */
for ( x = 1; x <= 10; x++ ) printf( "\n Used
{ continue to skip
if ( x == 5 ) printing the value 5\n"
);
{
return 0;
continue;
}
} /* end if */
Fundamentals of computer programming 51
Exercises
• Print All Prime Numbers between 1 to N
• Find All Factors of a Number
• Find Sum of All Odd Numbers Between 1 to N
• Find Sum of All Even Numbers Between 1 to N
• Print Odd Numbers Between 1 to 100
• Print Even Numbers Between 1 to 100
• Print Natural Numbers in Reverse Order from 1 to N

Fundamentals of computer programming 52


Repetition Structure
Nested Loops

Fundamentals of computer programming 53


Nested Loops
• A loop inside another loop is called a nested loop.
• We can have any number of nested loops as required.
• Consider a nested loop where the outer loop runs n times
and consists of another loop inside it.
• The inner loop runs m times.
• Then, the total number of times the inner loop runs
during the program execution is n*m.

Fundamentals of computer programming 54


Scenario-1

Fundamentals of computer programming 55


Fundamentals of computer programming 56
Scenario-2

Fundamentals of computer programming 57


customer
For each
Fundamentals of computer programming 58
Types of nested loops
• Nested while loop
• Nested do-while loop
• Nested for loop

• Note: There can be mixed type of nested loop i.e. a for loop inside a while
loop, or a while loop inside a do-while loop.

Fundamentals of computer programming 59


Repetition structure required?

• Is there a repetition? Do we need a loop?


• Nested?
• How many iterations?
• Loop counter/condition variable?

Fundamentals of computer programming 60


Repetition structure required?

Do we need a loop?
•Nested?
•How many iterations?
•Loop counter/condition variable?

Fundamentals of computer programming 61


Nested for loops
• A for loop can contain any kind of statement in its body, including another for loop.
• The inner loop must have a different name for its loop counter variable so that it will not conflict
with the outer loop.

for (int i = 1; i <= 3; i++)


{
for (int j = 1; j <= 2; j++)
{
printf(“seven \n");

Fundamentals of computer programming 62


Example 1: Nested for loops
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 10; j++)
{
printf(“%d ” , i * j);
}
printf(“\n”); // to end the line
}

Fundamentals of computer programming 63


Example 2: Nested for loops

for (int row = 1; row <= 6; row++;) {

for (int col = 1; col <= row; col++;) {

printf("*");

printf(“\n”);

Fundamentals of computer programming 64


Example of Nested while loop
int i=1, j;
while (i <= 5)
{
j=1;
while (j <= i )
{
printf("%d ",j);
j++;
}
printf("\n");
i++;
}
Fundamentals of computer programming 65
Example of Nested do-while loop
int main()
{
int i=1,j;
do
{
j=1;
do
{
printf("*");
j++;
}while(j <= i);
i++;
printf("\n");
}while(i <= 5);
return 0;
}

Fundamentals of computer programming 66


Exercises
• Write a program that prints factorial of all numbers from
1 to 15.

• Write a program to generate the Fibonacci series in c


• E.g. 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Fundamentals of computer programming 67

You might also like