0% found this document useful (0 votes)
7 views50 pages

Lec 3 Iteration1

The document provides an overview of iteration statements in C, focusing on while, for, and do-while loops. It includes examples of how to implement these loops for tasks such as summing natural numbers, reversing digits, and calculating the greatest common divisor. Additionally, it discusses the use of nested loops and jump statements like break and continue.

Uploaded by

Talha Zubair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views50 pages

Lec 3 Iteration1

The document provides an overview of iteration statements in C, focusing on while, for, and do-while loops. It includes examples of how to implement these loops for tasks such as summing natural numbers, reversing digits, and calculating the greatest common divisor. Additionally, it discusses the use of nested loops and jump statements like break and continue.

Uploaded by

Talha Zubair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Md.

Rony Ahmed
Add first 50 Add even
natural number How to do these in C ? numbers upto
50

wrong

mhdrony
• In C, and all other modern programming languages, iteration statements (also
called loops) allow a set of instructions to be repeatedly executed until a certain
condition is reached.

• There are three iteration statements in C


 while statement
 do-while statement
 for statement

mhdrony
While loop
• The general form of while:
while (expression){
statements; True(non-zero)
False(zero)
}

• where statement is either an empty statement, a single statement, or a block of


statements.
• The expression is evaluated. If it is non-zero(true), statement is executed and
expression is reevaluated.
• This cycle continues until expression becomes zero(false), at which point
execution resumes after statement.

mhdrony
Example: write a program to show 5 times.- I love programming!

int i=1;
while(i<=5)
{
printf("I love programming!\n");
i++;
}

second version:
int i=1;
while(i++<=5)
{
printf("I love programming!\n");
}

mhdrony
int i = 1 ; This is an indefinite loop, since i remains equal to 1 forever.
while (i <= 10 ) So the expression in while never becomes false.
printf ( "%d\n", i ) ;

Correct version:
int i = 1 ;
Why 2 to 11?
while (i++ <= 10 )
printf ( "%d\n", i ) ;

• ***so it seems you have to write statements so that expression in the


while becomes false(zero) after some iterations. Otherwise you will
have an infinite loop.
mhdrony
int sum=0,N=0; Solution of the first slide.
while(N<=50)
{
N++;
sum=sum+N;
}
printf("the sum of first 50 natural number: %d",sum);

look at this one: Why the difference??which one


int sum=0,N=0; is correct??
while(N<=50)
{
sum=sum+N;
N++;
}
printf("the sum of first 50 natural number: %d",sum);
mhdrony
Solution of the first slide.

int sum=0,N=0;
while(N<=50)
{
N=N+2;
sum=sum+N;
}
printf("the sum of even numbers upto 50: %d",sum);

mhdrony
• While loops check the test condition at the top of the loop, which means that the
body of the loop will not execute if the condition is false to begin with.

• The condition being tested may use relational or logical operators as shown in the
following examples:

• There need not be any statements in the body of the while loop. For example,
while((ch=getchar()) != 'A') ;
will simply loop until the user types A.
• *** remember that the equal sign is just an operator that evaluates to the value of
the right -hand operand.
mhdrony
Nested while
• A loop inside another loop is called a nested loop.

while(expression1)
{
statements;
While(expression2)
{
statements;
While(expression3)
……
……
}
}
• The depth of nested loop depends on the complexity of a problem.
• We can have any number of nested loops as required.
mhdrony
Flowchart of Nested while loop

while(condition1)
{
While(condition2)
{
statements;
}
}

mhdrony
int i=1,j,line;
printf("enter the no of line: ");
scanf("%d",&line);
while (i <= line)
{
j=1;
while (j <= i )
{
printf("*");
j++;
}
printf("\n");
i++;
}

mhdrony
Example:
main(void)
{
char ch;
ch = '\0'; /* initialize ch */
while(ch != 'A')
ch = getchar();
}
• First, ch is initialized to null.
• The while loop then checks to see if chis not equal to A.
• Because ch was initialized to null, the test is true and the loop begins.
• Each time you press a key, the condition is tested again.
• Once you enter an A, the condition becomes false because ch equals A, and the
loop terminates.
mhdrony
• The greatest common divisor (gcd) of two integers is the largest integer value that
evenly divides the two integers. For example, the gcd of 10 and 15 is 5 because 5
is the largest integer that evenly divides both 10 and 15.

#include <stdio.h>
int main (void)
{
int n1=7, n2=217, count;
count=n1;
while ( n1%count || n2%count ) {
count--;
}
printf ("%d\n", count);
return 0;
}

mhdrony
• another use of the while statement, the task of reversing the digits of an
integer that is entered from the terminal. For example, if the user types in
the number 1234, you want the program to reverse the digits of this number
and display the result of 4321.
• You can extract the rightmost digit from an integer number by taking the
remainder of the integer after it is divided by 10. For example, 1234 % 10
gives the value 4, which is the rightmost digit of 1234, and is also the first
digit of the reversed number.
• You can get the next digit of the number by using the same process if you
first divide the number by 10, bearing in mind the way integer division
works. Thus, 1234 /10 gives a result of 123, and 123 % 10 gives us 3, which
is the next digit of your reversed number.
• This procedure can be continued until the last digit has been extracted. In
the general case, you know that the last digit of the number has been
extracted when the result of the last integer division by 10 is 0.
mhdrony
int number, right_digit;
printf ("Enter a integer number.\n");
scanf ("%i", &number);
printf ("the number in reverse order:");
while ( number != 0 ) {
right_digit = number % 10;
printf ("%i", right_digit);
number = number / 10;
}
printf ("\n");

• **notice that you just printed the reversed number without saving it. So you
couldn’t use it further.
• Notice that you did not include a newline character inside the printf statement
contained in the while loop. mhdrony
Check your understanding!
#include <stdio.h>
int main (void)
{
int c,d;
c=3;
while (c>0) {
d=c;
while(d-->0)
printf(" ");
d=3-c;
d=2*d+1;
while(d-->0)
printf("*");
printf("\n");
c--;
}
return 0;
} mhdrony
For loop
• The general form of for statement
for (expr1; expr2; expr3)
{
Statement;
}

• Most commonly, expr1(initialization) and expr3(increment/decrement) are


assignments or function calls and expr2(condition) is a relational expression.

• Any of the three parts can be omitted, although the semicolons must remain.

mhdrony
For loop
• The for statement can also be showed as:
• for (initialization; true
condition; increment )
false
•{
• statement ;
•}

• The initialization is generally an assignment statement that is used to set the loop
control variable.
• The condition is generally a relational expression that determines when the loop exits.
• The increment defines how the loop control variable changes each time the loop is
repeated.
• The for loop continues to execute as long as the condition is true.
mhdrony
• The for statement is equivalent to while!
for (initialization; condition; increment ) initialization;
{ while (condition)
Statement; {
} Statement;
increment;
}

• The for is preferable when there is a simple initialization and increment since it
keeps the loop control statements close together and visible at the top of the loop.

mhdrony
example:
int i;
for(i=1 ; i<=5 ; i++)
{
printf("I love programming!\n");
}

More compact version:


for(int i=1 ; i<=5 ; i++)
{
printf("I love programming!\n");
}

mhdrony
Another example:
for(int i = 1 ; i++ <= 10; ) //what will be the output?
printf ( "%d\n", i ) ;

Infinite loop:
for(int i = 1 ; i ; )
printf ( "%d\n", i ) ;

mhdrony
Program to calculate sum of first 50 natural number:
for(int sum=0,N=0 ; N<=50 ; N++)
{
sum=sum+N;
}
printf("the sum of first 50 natural number: %d",sum);

• The initialization expression of the for loop can contain more than one
statement separated by a comma.

mhdrony
• Multiple statements can also be used in the increment and initialization
expression of for loop; i.e., you can increment (or decrement) two or more
variables at the same time.

• However, only one expression is allowed in the condition expression. This


expression may contain several conditions linked together using logical or
relational operators.
for(x=0, y=0; x+y < 10; ++x)

for(i=0, j=0; i<=j; i++, j--)

for(i=0, j=10; i<=j || j<5 ; i++, j--)


A pair of expressions separated by a comma operator is evaluated left to right,
and the type and value of the result are the type and value of the right operand.

mhdrony
• The greatest common divisor (gcd) problem again but with for loop:

int n1=79,n2=215,count;
for (count=n1; n1%count || n2%count ;count--) ;
printf ("GCD = %i\n", count);

Another solution: Try to understand the program.


Is there any problem?
int n1=75,n2=215,count;
for (count=2 ; !( (n1%count)==0 && (n2%count)==0 ) ;count++);
printf ("GCD = %i\n", count);

mhdrony
nested for
• A for loop inside another for loop is called nested for loop.

for (initialization; condition1; increment/decrement)


{
statement(s);
for (initialization; condition2; increment/decrement)
{
statement(s);
... ... ...
}
... ... ...
}

mhdrony
int i,j,line;
printf("enter the no of line: ");
scanf("%d",&line);
for ( i=1 ;i <= line; i++)
{
for(j=1;j <= i; j++) a smarter solution:
{ int i,j,line;
printf("*"); printf("enter the no of line: ");
} for ( scanf("%d",&line),i=1 ;i <= line; i++,printf("\n"))
printf("\n"); for(j=1;j <= i; printf("*"), j++);
}

mhdrony
• Reversing the digits of a number:

#include <stdio.h>
int main (void)
{
int number, right_digit;
printf ("Enter your number.\n");
scanf ("%i", &number);
for ( ; number != 0 ; number = number / 10)
{
right_digit = number % 10;
printf ("%i", right_digit);
}
printf ("\n");
return 0;
}
mhdrony
// Program to generate a table of triangular numbers
int n, triangularNumber;
printf ("TABLE OF TRIANGULAR NUMBERS\n\n");
printf (" n Sum from 1 to n\n");
printf ("--- ---------------\n");
triangularNumber = 0;
for ( n = 1; n <= 10; ++n )
{
triangularNumber += n;
printf (" %i %i\n", n, triangularNumber);
}

mhdrony
// Program to generate a table of triangular numbers

int n, triangularNumber;
printf ("TABLE OF TRIANGULAR NUMBERS\n\n");
printf (" n Sum from 1 to n\n");
printf ("--- ---------------\n");
triangularNumber = 0;
for ( n = 1; n <= 10; ++n ) {
triangularNumber += n;
printf (" %2i%8i\n", n, triangularNumber);
}

mhdrony
• The advantages of keeping loop control centralized are even more obvious when
there are several nested loops.

Program to show triangular pyramid:


int c,d,line;
printf("enter the no of line: ");
scanf("%d",&line);
c=line;
for(;c>0;c--)
{
for(d=c;d>1;d--)
printf(" ");
for(d=line-c,d=2*d+1;d>0;d--)
printf("*");
printf("\n");
}
mhdrony
Try to understand this one!
• A more compact one of previous version : it does exactly same task and in a
similar way!

int c,d,line;
for(printf("enter the no of line: "),scanf("%d",&line),c=line;c>0;c--,printf("\n"))
{
for(d=c;d>1;d--,printf(" "));
for(d=line-c,d=2*d+1;d>0;d--,printf("*"));
}

mhdrony
Loops - Do-While
• the while and for loops test the termination condition at the top.
• By contrast, the do-while, tests at the bottom after making each pass through the
loop body; the body is always executed at least once.
• The syntax of the do-while is:
do{
Statement
}while (econdition);

• First, the statement is executed,


then expression is evaluated.
• If it is true, statement is evaluated again, and so on.
• When the expression becomes false, the loop terminates.
mhdrony
example:
char another ;
int num ;
do
{
printf ( "Enter a number : " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number (y/n) : " ) ;
scanf ( " %c", &another ) ;
} while ( another == 'y' || another == 'Y' ) ;

 Try to enter a float number


and see what happens.
mhdrony
probable application
• the do –while loop is a good choice for showing menu of a software
because you will always want a menu function to execute at least
once.
• After the options have been displayed, the program will loop until a
valid option is selected.

mhdrony
Jump Statements
• C has four statements that perform an unconditional jump: return ,goto ,break,
and continue.

• Of these, you can use return and goto anywhere inside a function.(will be
discussed later)

• You can use the break and continue statements in conjunction with any of the
loop statements.

• You can also use the break inside the switch statement.

mhdrony
The break Statement
• The break statement has two uses.
1. You can use it to terminate a case in the switch statement
2. You can also use it to force immediate termination of a loop, bypassing
the normal loop conditional test.
• When the break statement is encountered inside a loop, the loop is immediately
terminated, and program control resumes at the next statement following the loop.
For example, the following code snippet
int t;
for(t=0; t < 100; t++) {
printf(''%d ", t);
if(t == 10) break;
}

• prints the numbers 0 through 10 on themhdrony


screen.
• A break causes an exit from only the innermost loop. For example,
int t=0,count;
for(t=0; t < 10; ++t) {
for(count = 1;;) {
printf("%d ", count);
count++;
if(count == 7) break;
}
printf("\n");
}
• prints the numbers 1 through 6 on the screen 10 times

mhdrony
Analysis of a problem:

• Write a program to determine whether a number is prime or not. A


prime number is one, which is divisible only by 1 or itself.

• All we have to divide the number successively by all numbers from 2


to one less than itself.

• If remainder of any of these divisions is zero, the number is not a


prime.

• If no division yields a zero then the number is a prime number.

mhdrony
int num, i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
i=2;
while ( i <= num - 1 )
{
if ( num % i == 0 )
{
printf ( "Not a prime number" ) ;
break ;
}
i++ ;
}
if ( i == num )
printf ( "Prime number" ) ;
mhdrony
• So, Why does the program require the if statement after the while loop at all?

• Well, there are two ways the control could have reached outside the while loop:
(a)It jumped out because the number proved to be not a prime.
(b)The loop came to an end because the value of i became equal to num.

• When the loop terminates in the second case, it means that there was no number
between 2 to num - 1 that could exactly divide num.
• That is, num is indeed a prime. If this is true, the program should print out the
message “Prime number”.

mhdrony
The continue Statement
• The continue statement works somewhat like the break statement.

• Instead of forcing termination, however, continue forces the next


iteration of the loop to take place skipping any code after it.

• For the for loop, continue causes the increment and then the
conditional test portions of the loop to execute.

• For the while and do -while loops, program control passes to the
conditional tests.

mhdrony
Flowchart indicating the operation of
continue statement

for (int j=0; j<=4; j++)


{
if (j==2)
continue;
printf("%d ", j);
}

mhdrony
Exercise
(try to solve them using all the loop statement)
1. Write a program in C to display the pattern like right angle triangle with a number. The
pattern like :
1
12
123
1234

2. Write a program in C to make such a pattern like right angle triangle with number
increased by 1The pattern like :
1
23
456
7 8 9 10

mhdrony
3. Write a program in C to make such a pattern like a pyramid with numbers increased by 1.
1
23
456
7 8 9 10

4. Write a program in C to display the n terms of harmonic series and their sum.
1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms. Take the value of n as input.

5. Write a program in C to find the sum of the series [ x - x^3 + x^5 + ......upto n th term].
Take the value of n as input.

6.Write a program in C to find the sum of the series 1 +11 + 111 + 1111 + .. n th terms.
Take the value of n as input.

7. Write a C program to check whether a given number is an armstrong number or not.

mhdrony
8. Write a C program to find the Armstrong number for a given range of number.
Test Data :
Input starting number of range: 1
Input ending number of range : 1000
Expected Output :
Armstrong numbers in given range are: 1 153 370 371 407

9. Write a program in C to display the pattern like a diamond.

mhdrony
10. Write a C program to display Pascal's triangle.
Test Data :
Input number of rows: 5
Expected Output :

11. Write a program in C to find the prime numbers within a range of numbers.
Test Data :
Input starting number of range: 1
Input ending number of range : 50
Expected Output :
The prime number between 1 and 50 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

mhdrony
12. Write a program in C to display the first n terms of Fibonacci series.
Fibonacci series 0 1 2 3 5 8 13 .....
Test Data :
Input number of terms to display : 10
Expected Output :
Here is the Fibonacci series upto to 10 terms :
0 1 1 2 3 5 8 13 21 34

13. Write a program in C to check whether a number is a palindrome or not.


Test Data :
Input a number: 121
Expected Output :
121 is a palindrome number.

mhdrony
14. Write a program in C to find LCM of any two numbers.
Test Data :
Input 1st number for LCM: 15
Input 2nd number for LCM: 20
Expected Output :
The LCM of 15 and 20 is : 60

15. Write a program in C to Check Whether a Number can be Express as Sum of Two Prime
Numbers.
Test Data :
Input a positive integer: 16
Expected Output : 3 13 or 5 11
(as 16 = 3 + 13 or
16 = 5 + 11 )

16. Write a program in C to calculate sum of the series (1) + (1+2) + (1+2+3) + (1+2+3+4)
+ ... + (1+2+3+4+...+n). Take n as input.

mhdrony
17. write a program in C to display the pattern using digits with right justified and
the highest columns appears in first row.

18. Write a C program to find all prime factors of a number.

19. Write a C program to find sum of all prime numbers between 1 to n.

20. Write a C program to show Pascal’s triangle of n line. Take n as input.

mhdrony

You might also like