Skip to main content

4. Loops and Functions



While Loop

  • When we want to repeatedly execute a statement as long as a condition is met, we can use the iteration statement called as while loop.
  • The while loop is used in the case where the number of iterations is not known in advance.
  • In while loop, the condition is checked first then the code under while loop is executed.
  1. Write a C program to convert a binary number to a decimal number.
  2. #include <stdio.h>
    int main()
    {
        int num = 1001;
        int ans = 0, x = 1;
        while (num > 0)
        {
            ans += x * (num % 10);
            x *= 2;
            num = num / 10;
        }
        printf("%d", ans);
        return 0;
    }

Do-while Loop

  • Do-while loop is similar to a while loop expect for the fact that it is guaranteed to execute at least once.
  • After executing a part of a program for once, the rest of the code gets executed on the basis of a Boolean condition.
  1. What is the output of the following C code?
  2. #include <stdio.h>
    int main()
    {
        int i = 11;
        do
        {
            printf("%d ", i);
            i++;
        } while (i <= 10);
        return 0;
    }

For Loop

  • For loop is used when the exact number of iterations needed is already known to us.
  • Syntax of for loop consists of 3 expressions:
    • Initializer: Initializes the value of a variable. This part is executed only once.
    • Checking_Boolean_Expression: The code inside the for loop is executed only when this condition returns true.
    • Update: Updates the value of the previous initial value.
  1. Write a C program to print first 10 elements of Fibonacci series.
  2. #include <stdio.h>
    int main()
    {
        int num = 10, i;
        int a = 0, b = 1, c;
        printf("%d %d", a, b);
        for (i = 2; i < num; i++)
        {
            c = a + b;
            printf(" %d", c);
            a = b;
            b = c;
        }
        return 0;
    }

Functions

  • A function is a block of code that performs a particular task.
  • Default return type is int.
  • void is used as type if do not want any return type.
  • expression can be constant, variable or function call.
  • return is optional and expression is also optional.
  • We cannot define one function within another function, we can only call a function within another function.
  • Only one value can be returned.
  • printf() is a built-in function in C whose return type is int and takes character pointer as argument.


Prev Next

Comments