-->

C Programming: Iteration through different loops

C Programming: Iteration through different loops

    Suppose you are given a problem to display ‘C programming is fun’ 500 times.  One way of doing this problem is to display ‘C programming is fun’ 500 times using printf() functions. Think yourself, how it takes to display it using printf() 500 times?  Also how lengthy the program becomes? and how inefficient the program will be? Many problems arise and the solutions of these problems is solved by different types of Loops. Using loop, you can display the message as many as you want with only few lines of code. There are mainly 3 types of Loop in C programming which are discussed here,

    1. while Loop

    There are three steps in writing while loop, 1.  variable initialization  2. loop condition and 3. variable increment or decrement.

    General Syntax

    while(condition){
    statement
    }
    Example
      1: int i = 0; //variable initialization
      2: while(i <= 500){  // loop condition
      3:    printf("C programming is fun");
      4:    i++; //increment
      5: }


    While loop is also known as Entry Control loop because condition is checked at the entry of loop. Initially the value of i is assign with zero. Until the value of i becomes equal or less than 500, the statement within while loop executes.


    2.     do …while Loop



    General Syntax

    do{
    statements;
    }while(condition);
    Example
      1: int i = 0; //counter initialization
      2: do{
      3:   printf("C programming is fun");
      4:   i++;
      5: }while(i <= 500);


      do…while loop is also known as exit control loop because condition is checked at the exit of loop. If you supply false condition, statement is executed once.


      3.   for Loop



    General Syntax

    for(initialization;condition;update(increment/decrement)){
    statement;
    }





    Example

      1: int i;
      2: for(i = 0; i <= 500; i++){
      3:     printf("C programming is fun");
      4: }
    fardi zayden
    @مرسلة بواسطة
    كاتب ومحرر اخبار اعمل في موقع دراسات تقنية .

    إرسال تعليق