Lec 3 Iteration1
Lec 3 Iteration1
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.
mhdrony
While loop
• The general form of while:
while (expression){
statements; True(non-zero)
False(zero)
}
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 ) ;
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;
}
• 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");
}
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.
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);
mhdrony
nested for
• A for loop inside another for loop is called nested for loop.
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.
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);
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;
}
mhdrony
Analysis of a problem:
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.
• 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
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.
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
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
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.
mhdrony