Inner loop dependent on outer loop variable

Inner loop dependent on outer loop
#include <stdio.h>
variable
#include <conio.h>
int main()
{
int i,j;
for(i=1; i<=10; i++){
for(j=1; j<=i; j++){
printf("*");
}
printf("\n");
}
getch();
}
*
**
***
****
*****
******
*******
********
*********
**********
The Odd Loop
• The loops that we have used so far
executed the statements within them a
finite number of times.
• However, in real life programming one
comes across a situation when it is not
known beforehand how many times the
statements in the loop are to be executed.
• This situation can be programmed as shown
ahead.
Break Statement
• We often come across situations where we
want to jump out of a loop instantly, without
waiting to get back to the conditional test. The
keyword break allows us to do this.
• When break is encountered inside any loop,
control automatically passes to the first
statement after the loop.
• A break is usually associated with an if.
int i=1,j=1;
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==j)
break;
printf("%d %d\n", i, j);
}
}
int i=1,j=1;
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==j)
break;
printf("%d %d\n", i, j);
}
}
21
31
32
Continue Statement
• In some programming situations we want to
take the control to the beginning of the loop,
bypassing the statements inside the loop,
which have not yet been executed.
• The keyword continue allows us to do this.
• When continue is encountered inside any
loop, control automatically passes to the
beginning of the loop.
int i=1,j=1;
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==j)
continue;
printf("%d %d\n", i, j);
}
}
12
13
21
23
31
32
Examples
Computing the sum of N numbers
int n, i, number;
int sum=0;
printf("How many numbers would you like to sum: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Please enter the number: ");
scanf("%d",&number);
sum=sum+number;
}
printf("The sum is:%d",sum);
Practice Question: Write the above code using a while loop
Computing the Factorial
int n, i, f=1;
printf("Enter a number to get it's factorial: ");
scanf("%d",&n);
for(i=1;i<=n;i++){
f=f*i;
}
printf("The factorial of %d is = %d",n,f);
Practice Question: Write the above code using a decrementing for loop and a
while loop
Finding the Smallest Number
int i, n, min, number;
printf("How many numbers would you like to enter: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a number:");
scanf("%d",&number);
if(i==0){
min=number;
}
if(number<min)
min=number;
}
printf("Min. number is: %d",min);
Practice Question:
Modify the above code to
find the max. number