Types¶
while
- Entry-controlled loop
do...while
- Exit-controlled loops
for
Components¶
- Initialization
- \(n\)
- \(i\)
- Loop condition checked
- Code to execute is run
- Updation occurs
flowchart LR
i[Initialization] --> c[Condition] --> Code --> Updation --> c
/*
int n = 10;
int i = 1; // comesntenret
for (; ; )
{
if(i>n)
break;
// code
i++;
}
*/
for (int i = 1, n=10; i<=n; i++)
{
}
int i = 1, n=10;
for (; i<=n; i++)
{
;// nothing happens
}
printf("%d", i); 11
for (int i = 1, n=10; i<=n; i++)
printf("%d\n", i);
printf("%d\n", i);
for (int i = 1, n=10; i<=n; i++)
{
printf("%d\n", i);
}
printf("%d\n", i);
// here
int i, n;
for (i = 1, n=10; i<=n; i++);
printf("%d\n", i);
int i, n;
for (i = 1, n=10; i<=n; i++)
{
;
}
printf("%d\n", i);
Pyramid example¶
#include <stdio.h>
int main()
{
int n = 4; // no of lines
for (int i=1; i<=n; i++) // run the loop 4 times
{
printf("*\n");
}
return 0;
}
#include <stdio.h>
int main()
{
printf("*\n");
printf("**\n");
printf("***\n");
printf("****\n");
return 0;
}
- DUMB
- Not scalable
- Not elegant
Hence, we need loops (iterative statements)
#include <iostream.h>
int main()
{
for (int i=1; i<=n; i++)
{
for (int j=1; j<=i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
jump statements¶
- break
- exits the current loop
- continue
- skips the below code of the current iteration
- goes to the update segment of (for)loop
- in other loops, it goes to condition
- then continues as usual
int i=1;
do
{
if(i==3)
{
continue;
printf("%d\n", i);
}
printf("%d\n", i);
i++;
} while(i<=5); // has terminator
Loop Printining Questions¶
int n = 4; // no of lines
int j = 1;
for (int i=1; i<=n; i++) // controls no of lines
{
printf("%d", j);
j++;
}
int n = 4; // no of lines
for (int i=1; i<=n; i++) // controls no of lines
{
int j = 1;
printf("%d", j);
j++;
}