Repetition and Looping in C Programming Language

Among the many things you can do in C Programming Language is Repetition and Looping

Repetition

  • When one or more operation is repeated over a certain amount of time
  • The number of repetition can be predefined or defined later during the run time
  • There are 3 types of Repetition/Looping Operator
    • for
    • while
    • do-while
For

  • A basic operator for repetition
  • Consists of three exponents
    • an initialization
    • a conditional
    • an increments or decrements
  • A for loop has no stop condition, meaning it is possible to loop operation infinitely by removing all the parameters.
  • It is also possible to create a nested loop by creating a loop inside the loop, the operation will start from the inner loop.
Example:
for(x=1;x<=10;x++) printf("%d\n", x);
This means the program will print the numbers 1 to 10

While and Do-While

  • while and do-while are also repetition operators
  • Despite their similar name, they are very different when it comes to operations, for example:
    • while loops checks the condition before entering the body, do-while enters the body at least once before checking the condition
    • while is an entry-based loop, do-while is an exit-based loop
    • In while, the conditions come before the body. In do-while, the conditions come after the body
Example of while:
while(x=1){
printf("%d\n", x);
++x;
}
This means the program will print the numbers 1 to 10

Example of do-while:
do{
printf("%d\n", x);
++x;
} while(counter<=10);
This means the program will print the numbers 1 to 10

Break and Continue

  • break
    • ends the loop
  • continue
    • if a condition is met, the operation will skip the rest of the statement inside the loop and move on to the next loop


Comments

Popular posts from this blog

Sorting & Searching

Pointer and Array in C Programming Language

Function and Recursion